Skip to content

alias-relate: add fast reject optimization #124852

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 144 additions & 2 deletions compiler/rustc_next_trait_solver/src/solve/alias_relate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,20 @@
//! (3.) Otherwise, if we end with two rigid (non-projection) or infer types,
//! relate them structurally.

use rustc_type_ir::data_structures::HashSet;
use rustc_type_ir::inherent::*;
use rustc_type_ir::{self as ty, Interner};
use rustc_type_ir::{
self as ty, Interner, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
};
use tracing::{instrument, trace};

use crate::delegate::SolverDelegate;
use crate::solve::{Certainty, EvalCtxt, Goal, QueryResult};
use crate::solve::{Certainty, EvalCtxt, Goal, NoSolution, QueryResult};

enum IgnoreAliases {
Yes,
No,
}

impl<D, I> EvalCtxt<'_, D>
where
Expand All @@ -46,6 +54,12 @@ where
|| rhs.is_error()
);

if self.alias_cannot_name_placeholder_in_rigid(param_env, lhs, rhs)
|| self.alias_cannot_name_placeholder_in_rigid(param_env, rhs, lhs)
{
return Err(NoSolution);
}

// Structurally normalize the lhs.
let lhs = if let Some(alias) = lhs.to_alias_term() {
let term = self.next_term_infer_of_kind(lhs);
Expand Down Expand Up @@ -106,4 +120,132 @@ where
}
}
}

/// In case a rigid term refers to a placeholder which is not referenced by the
/// alias, the alias cannot be normalized to that rigid term unless it contains
/// either inference variables or these placeholders are referenced in a term
/// of a `Projection`-clause in the environment.
fn alias_cannot_name_placeholder_in_rigid(
&mut self,
param_env: I::ParamEnv,
rigid_term: I::Term,
alias: I::Term,
) -> bool {
// Check that the rigid term is actually rigid.
if rigid_term.to_alias_term().is_some() || alias.to_alias_term().is_none() {
return false;
}

// If the alias has any type or const inference variables,
// do not try to apply the fast path as these inference variables
// may resolve to something containing placeholders.
if alias.has_non_region_infer() {
return false;
}

let mut referenced_placeholders = Default::default();
self.collect_placeholders_in_term(
rigid_term,
IgnoreAliases::Yes,
&mut referenced_placeholders,
);
if referenced_placeholders.is_empty() {
return false;
}

let mut alias_placeholders = Default::default();
self.collect_placeholders_in_term(alias, IgnoreAliases::No, &mut alias_placeholders);
loop {
let mut has_changed = false;
for clause in param_env.caller_bounds().iter() {
match clause.kind().skip_binder() {
ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_term,
term,
}) => {
let mut required_placeholders = Default::default();
for term in projection_term.args.iter().filter_map(|arg| arg.as_term()) {
self.collect_placeholders_in_term(
term,
IgnoreAliases::Yes,
&mut required_placeholders,
);
}

if !required_placeholders.is_subset(&alias_placeholders) {
continue;
}

if term.has_non_region_infer() {
return false;
}

has_changed |= self.collect_placeholders_in_term(
term,
IgnoreAliases::No,
&mut alias_placeholders,
);
}
ty::ClauseKind::Trait(_)
| ty::ClauseKind::HostEffect(_)
| ty::ClauseKind::TypeOutlives(_)
| ty::ClauseKind::RegionOutlives(_)
| ty::ClauseKind::ConstArgHasType(..)
| ty::ClauseKind::WellFormed(_)
| ty::ClauseKind::ConstEvaluatable(_) => continue,
}
}

if !has_changed {
break;
}
}
// If the rigid term references a placeholder not mentioned by the alias,
// they can never unify.
!referenced_placeholders.is_subset(&alias_placeholders)
}

fn collect_placeholders_in_term(
&mut self,
term: I::Term,
ignore_aliases: IgnoreAliases,
placeholders: &mut HashSet<I::Term>,
) -> bool {
// Fast path to avoid walking the term.
if !term.has_placeholders() {
return false;
}

struct PlaceholderCollector<'a, I: Interner> {
ignore_aliases: IgnoreAliases,
has_changed: bool,
placeholders: &'a mut HashSet<I::Term>,
}
impl<I: Interner> TypeVisitor<I> for PlaceholderCollector<'_, I> {
type Result = ();

fn visit_ty(&mut self, t: I::Ty) {
match t.kind() {
ty::Placeholder(_) => self.has_changed |= self.placeholders.insert(t.into()),
ty::Alias(..) if matches!(self.ignore_aliases, IgnoreAliases::Yes) => {}
_ => t.super_visit_with(self),
}
}

fn visit_const(&mut self, ct: I::Const) {
match ct.kind() {
ty::ConstKind::Placeholder(_) => {
self.has_changed |= self.placeholders.insert(ct.into())
}
ty::ConstKind::Unevaluated(_) | ty::ConstKind::Expr(_)
if matches!(self.ignore_aliases, IgnoreAliases::Yes) => {}
_ => ct.super_visit_with(self),
}
}
}

let mut visitor = PlaceholderCollector { ignore_aliases, has_changed: false, placeholders };
term.visit_with(&mut visitor);
visitor.has_changed
}
}
8 changes: 8 additions & 0 deletions compiler/rustc_type_ir/src/inherent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,14 @@ pub trait GenericArg<I: Interner<GenericArg = Self>>:
+ From<I::Region>
+ From<I::Const>
{
fn as_term(&self) -> Option<I::Term> {
match self.kind() {
ty::GenericArgKind::Lifetime(_) => None,
ty::GenericArgKind::Type(ty) => Some(ty.into()),
ty::GenericArgKind::Const(ct) => Some(ct.into()),
}
}

fn as_type(&self) -> Option<I::Ty> {
if let ty::GenericArgKind::Type(ty) = self.kind() { Some(ty) } else { None }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ error[E0308]: mismatched types
LL | fn func<const N: u32>() -> [(); { () }] {
| ^^ expected `usize`, found `()`

error[E0271]: type mismatch resolving `N == { () }`
--> $DIR/const-in-impl-fn-return-type.rs:20:5
|
LL | fn func<const N: u32>() -> [(); { () }] {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ
|
note: the requirement `N == { () }` appears on the `impl`'s method `func` but not on the corresponding trait's method
--> $DIR/const-in-impl-fn-return-type.rs:12:8
|
LL | trait Trait {
| ----- in this trait
LL | fn func<const N: u32>() -> [(); N];
| ^^^^ this trait's method doesn't have the requirement `N == { () }`

error: the constant `N` is not of type `usize`
--> $DIR/const-in-impl-fn-return-type.rs:12:32
|
Expand All @@ -12,6 +26,7 @@ LL | fn func<const N: u32>() -> [(); N];
|
= note: the length of array `[(); N]` must be type `usize`

error: aborting due to 2 previous errors
error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0308`.
Some errors have detailed explanations: E0271, E0308.
For more information about an error, try `rustc --explain E0271`.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ struct S {}
impl Trait for S {
fn func<const N: u32>() -> [(); { () }] {
//~^ ERROR mismatched types
//[next]~| ERROR type mismatch resolving `N == { () }`
N
}
}
Expand Down
Loading