diff --git a/compiler/rustc_middle/src/ty/context/impl_interner.rs b/compiler/rustc_middle/src/ty/context/impl_interner.rs index e849f3076a9f3..d8fb3ad998cfd 100644 --- a/compiler/rustc_middle/src/ty/context/impl_interner.rs +++ b/compiler/rustc_middle/src/ty/context/impl_interner.rs @@ -160,6 +160,26 @@ impl<'tcx> Interner for TyCtxt<'tcx> { // See trait-system-refactor-initiative#234. } + fn erase_and_anonymize_regions>(self, value: T) -> T { + self.erase_and_anonymize_regions(value) + } + + fn const_eval_resolve_for_typeck( + self, + typing_env: Self::TypingEnv, + ct: ty::AliasConst<'tcx>, + span: Self::Span, + ) -> ty::ConstEvalResult { + use crate::mir::interpret::ErrorHandled; + + match self.const_eval_resolve_for_typeck(typing_env, ct, span) { + Ok(Ok(vt)) => Ok(vt), + Ok(Err(ty)) => Err(ty::ConstEvalErr::NonValtreeable(ty)), + Err(ErrorHandled::Reported(e, _)) => Err(ty::ConstEvalErr::Reported(e.into())), + Err(ErrorHandled::TooGeneric(_)) => Err(ty::ConstEvalErr::TooGeneric), + } + } + fn expand_abstract_consts>>(self, t: T) -> T { self.expand_abstract_consts(t) } @@ -211,6 +231,10 @@ impl<'tcx> Interner for TyCtxt<'tcx> { } } + fn anon_const_kind(self, def_id: DefId) -> ty::AnonConstKind { + self.anon_const_kind(def_id) + } + fn def_span(self, def_id: DefId) -> Span { self.def_span(def_id) } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index e6321fadd0701..87b2d232c51c1 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1119,6 +1119,10 @@ impl<'tcx> rustc_type_ir::inherent::TypingEnv> for TypingEnv<'tcx> .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}")) .size } + + fn post_analysis(tcx: TyCtxt<'tcx>, def_id: DefId) -> TypingEnv<'tcx> { + Self::post_analysis(tcx, def_id) + } } impl<'tcx> TypingEnv<'tcx> { diff --git a/compiler/rustc_next_trait_solver/src/delegate.rs b/compiler/rustc_next_trait_solver/src/delegate.rs index 630e1dd68e041..c029199e906f3 100644 --- a/compiler/rustc_next_trait_solver/src/delegate.rs +++ b/compiler/rustc_next_trait_solver/src/delegate.rs @@ -56,6 +56,9 @@ pub trait SolverDelegate: Deref + Sized { // FIXME: Uplift the leak check into this crate. fn leak_check(&self, max_input_universe: ty::UniverseIndex) -> Result<(), NoSolution>; + /// FIXME: Only used in `evaluate_const` on `EvalCtxt` to delegate evaluation of GCE consts and + /// should be removed once GCE is gone. + /// /// Evaluate a const, normalizing the type of the resulting value with `normalize_ty`. /// Returns `Ok(None)` if the const is too generic, and `Err(_)` only if `normalize_ty` /// failed. diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index 54f5a196b4154..0ceeaca9a48cd 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -1494,47 +1494,132 @@ where Ok(()) } - // Try to evaluate a const and normalize the type of the resulting value, or return `None` if - // the const is too generic. This doesn't mean the const isn't evaluatable, though, and should - // be treated as an ambiguity rather than no-solution. + // Try to evaluate a const and normalize the type of the resulting value and make a response. pub(super) fn evaluate_const( - &mut self, - param_env: I::ParamEnv, - alias_const: ty::AliasConst, - ) -> Result>, NoSolutionOrRerunNonErased> { - if self.typing_mode().is_erased_not_coherence() { - let resolved = self.deeply_resolve_ignoring_regions(alias_const); - // FIXME: get rid of this once GCE is removed - let is_gce = self.cx().features().generic_const_exprs(); - if resolved.has_opaque_types() || is_gce { - match self.opaque_accesses.rerun_always(RerunReason::EvaluateConst)? {} - } - } - - self.delegate.evaluate_const(param_env, alias_const, |ty| self.normalize(param_env, ty)) - } - - pub(super) fn evaluate_const_and_instantiate_projection_term( &mut self, param_env: I::ParamEnv, projection_term: ty::AliasTerm, expected_term: I::Term, alias_const: ty::AliasConst, ) -> QueryResultOrRerunNonErased { - match self.evaluate_const(param_env, alias_const)? { + let alias_const = self.deeply_resolve_ignoring_regions(alias_const); + let cx = self.cx(); + + // FIXME: get rid of this once GCE is removed + let is_gce = cx.features().generic_const_exprs(); + + if self.typing_mode().is_erased_not_coherence() + && (alias_const.has_opaque_types() || is_gce) + { + match self.opaque_accesses.rerun_always(RerunReason::EvaluateConst)? {} + } + + let evaluated_const = if is_gce { + self.delegate + .evaluate_const(param_env, alias_const, |ty| self.normalize(param_env, ty))? + } else { + // Postpone evaluation of constants that depend on generic parameters or + // inference variables. + // + // We use `TypingMode::PostAnalysis` here which is not *technically* correct + // to be revealing opaque types here as borrowcheck has not run yet. However, + // CTFE itself uses `TypingMode::PostAnalysis` unconditionally even during + // typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821). + // As a result we always use a revealed env when resolving the instance to evaluate. + // + // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself + // instead of having this logic here + let evaluation_input = match alias_const.kind { + // Generic params are allowed in `AnonConstKind::RepeatExprCount` for backcompat + // reasons as long as evaluation doesn't rely on them to succeed. + ty::AliasConstKind::Anon { def_id } + if matches!( + cx.anon_const_kind(def_id.into()), + ty::AnonConstKind::RepeatExprCount + ) => + { + if alias_const.has_non_region_infer() { + // Diagnostics will sometimes replace the identity args of anon consts in + // array repeat expr counts with inference variables so we have to handle this + // even though it is not something we should ever actually encounter. + // + // Array repeat expr counts are allowed to syntactically use generic parameters + // but must not actually depend on them in order to evalaute successfully. This means + // that it is actually fine to evalaute them in their own environment rather than with + // the actually provided generic arguments. + cx.delay_bug("AnonConst with infer args but no error reported"); + } + + // The generic args of repeat expr counts under `min_const_generics` are not supposed to + // affect evaluation of the constant as this would make it a "truly" generic const arg. + // To prevent this we discard all the generic arguments and evalaute with identity args + // and in its own environment instead of the current environment we are normalizing in. + let args = GenericArgs::identity_for_item(cx, def_id.into()); + let typing_env = TypingEnv::post_analysis(cx, def_id.into()); + + Ok((typing_env, args)) + } + _ => { + // We are only dealing with "truly" generic/uninferred constants here: + // - GCEConsts have been handled separately + // - Repeat expr count back compat consts have also been handled separately + // So we are free to simply defer evaluation here. + // + // FIXME: This assumes that `args` are normalized which is not necessarily true + // + // Const patterns are converted to type system constants before being + // evaluated. However, we don't care about them here as pattern evaluation + // logic does not go through type system normalization. If it did this would + // be a backwards compatibility problem as we do not enforce "syntactic" non- + // usage of generic parameters like we do here. + if alias_const.args.has_non_region_param() + || alias_const.args.has_non_region_placeholders() + || alias_const.args.has_non_region_infer() + { + Err(ty::ConstEvalErr::TooGeneric) + } else { + // Since there is no generic parameter, we can just drop the environment + // to prevent query cycle. + let typing_env = TypingEnv::fully_monomorphized(); + let args = alias_const.args; + + Ok((typing_env, args)) + } + } + }; + + // FIXME: `def_span` will point at the definition of this const; ideally, we'd point at + // where it gets used as a const generic. + let span = alias_const.kind.def_span(cx); + + let evaluated = evaluation_input.and_then(|(typing_env, args)| { + let alias_const = ty::AliasConst::new(cx, alias_const.kind, args); + let erased_alias_const = cx.erase_and_anonymize_regions(alias_const); + cx.const_eval_resolve_for_typeck(typing_env, erased_alias_const, span) + }); + + match evaluated { + Ok(val) => { + let ty = self.normalize(param_env, alias_const.type_of(cx))?; + Some(Const::new(cx, ty::ConstKind::Value(ValueConst::new(ty, val)))) + } + + Err(ty::ConstEvalErr::Reported(e)) => Some(Const::new_error(cx, e)), + Err(ty::ConstEvalErr::TooGeneric) => None, + Err(ty::ConstEvalErr::NonValtreeable(_)) => { + cx.delay_bug("Type system constant with non valtree'able type evaluated but no error emitted"); + None + } + } + }; + + match evaluated_const { Some(evaluated) => { self.eq(param_env, expected_term, evaluated.into())?; self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) } - None if self.cx().features().gca_const_items() => { - // HACK(khyperia): calling `deeply_resolve_ignoring_regions` here shouldn't be necessary, - // `try_evaluate_const` calls `deeply_resolve_ignoring_regions` already. However, we want - // to check `has_non_region_infer` against the type with vars resolved (i.e. check - // if there are vars we failed to resolve), so we need to call it again here. - // Perhaps we could split EvaluateConstErr::HasGenericsOrInfers into HasGenerics and - // HasInfers or something, make evaluate_const return that, and make this branch be - // based on that, rather than checking `has_non_region_infer`. - if self.deeply_resolve_ignoring_regions(alias_const).has_non_region_infer() { + None if cx.features().gca_const_items() => { + if alias_const.has_non_region_infer() { self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS) } else { // Evaluation failed because the const was too generic or was an invalid type @@ -1548,7 +1633,7 @@ where // original DefId on the trait itself. self.eq( param_env, - projection_term.to_term(self.cx(), ty::IsRigid::Yes), + projection_term.to_term(cx, ty::IsRigid::Yes), expected_term, )?; self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index 3da905741c03b..08ad1b81fae8e 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -253,20 +253,9 @@ where self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS) } - ty::ConstKind::Alias(ty::IsRigid::No, alias_const) => { - // We never return `NoSolution` here as `evaluate_const` emits an - // error itself when failing to evaluate, so emitting an additional fulfillment - // error in that case is unnecessary noise. This may change in the future once - // evaluation failures are allowed to impact selection, e.g. generic const - // expressions in impl headers or `where`-clauses. - - // FIXME(generic_const_exprs): Implement handling for generic - // const expressions here. - if let Some(_normalized) = self.evaluate_const(param_env, alias_const)? { - self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) - } else { - self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS) - } + ty::ConstKind::Alias(ty::IsRigid::No, _) => { + self.normalize(param_env, ty::Unnormalized::new(ct))?; + self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) } // We can freely ICE here as: diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs index 49e5744cfe46c..873c44b402315 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs @@ -459,7 +459,7 @@ where }, target_args, ); - return ecx.evaluate_const_and_instantiate_projection_term( + return ecx.evaluate_const( goal.param_env, goal.predicate.alias, goal.predicate.term, diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals/anon_const.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals/anon_const.rs index 5c6e9cc2045c2..59d2dbb136b91 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals/anon_const.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals/anon_const.rs @@ -16,7 +16,7 @@ where goal: Goal>, ) -> QueryResultOrRerunNonErased { let alias_const = goal.predicate.projection_term.expect_ct(); - self.evaluate_const_and_instantiate_projection_term( + self.evaluate_const( goal.param_env, goal.predicate.projection_term, goal.predicate.term, diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals/free_alias.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals/free_alias.rs index dfcc89b91a4f2..f041001fd0632 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals/free_alias.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals/free_alias.rs @@ -46,7 +46,7 @@ where free.into() } ty::AliasTermKind::FreeConst { .. } => { - return self.evaluate_const_and_instantiate_projection_term( + return self.evaluate_const( goal.param_env, free_alias, goal.predicate.term, diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals/inherent.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals/inherent.rs index 45ece5a0589fb..c0ef3160ac083 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals/inherent.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals/inherent.rs @@ -64,7 +64,7 @@ where // NOTE: we intentionally pass in the `InherentConstImpl` form as the term to // instantiate to upon too-generic CTFE failure, as we ought to consistently compare // identities via `InherentConstImpl` rather than `InherentConstSelf`. - return self.evaluate_const_and_instantiate_projection_term( + return self.evaluate_const( goal.param_env, term, goal.predicate.term, diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index c0cd3160b98ba..c28121df6f3ad 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -204,6 +204,19 @@ impl StableHash for InferConst { } } +pub type ConstEvalResult = Result<::ValTree, ConstEvalErr>; + +/// Errors from CTFE we care about in next-solver. +#[derive_where(Clone, Copy, Debug; I: Interner)] +pub enum ConstEvalErr { + /// Unsupported type encountered while constructing valtree after evaluation. + NonValtreeable(I::Ty), + /// Already reported error. + Reported(I::ErrorGuaranteed), + /// Too generic or otherwise failed CTFE. + TooGeneric, +} + /// This datastructure is used to represent the value of constants used in the type system. /// /// We explicitly choose a different datastructure from the way values are processed within diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index 4fd92194c5d81..c9fef82be7b9e 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -759,4 +759,5 @@ pub trait ScalarInt: Copy + Debug + Hash + Eq { pub trait TypingEnv: Copy + Clone + Debug + PartialEq + Eq + Hash { fn fully_monomorphized() -> Self; fn layout_size(self, interner: I, ty: I::Ty) -> Size; + fn post_analysis(interner: I, def_id: I::DefId) -> Self; } diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 159c2939875b0..6780c66183aa1 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -293,6 +293,7 @@ pub trait Interner: self, alias: ty::AliasConstKind, ) -> Option>>; + fn anon_const_kind(self, def_id: Self::DefId) -> ty::AnonConstKind; fn def_span(self, def_id: Self::DefId) -> Self::Span; @@ -352,6 +353,15 @@ pub trait Interner: fn renormalize_rigid_aliases(self) -> bool; + fn erase_and_anonymize_regions>(self, value: T) -> T; + + fn const_eval_resolve_for_typeck( + self, + typing_env: Self::TypingEnv, + ct: ty::AliasConst, + span: Self::Span, + ) -> ty::ConstEvalResult; + fn coroutine_hidden_types( self, def_id: Self::CoroutineId, diff --git a/tests/ui/const-generics/generic_const_exprs/unevaluated-const-ice-119731.rs b/tests/ui/const-generics/generic_const_exprs/unevaluated-const-ice-119731.rs index 99130689d7ce2..81ff69919cb7a 100644 --- a/tests/ui/const-generics/generic_const_exprs/unevaluated-const-ice-119731.rs +++ b/tests/ui/const-generics/generic_const_exprs/unevaluated-const-ice-119731.rs @@ -30,7 +30,6 @@ mod v20 { //~| ERROR: maximum number of nodes exceeded in constant v20::v17::::{constant#0} //~| ERROR: maximum number of nodes exceeded in constant v20::v17::::{constant#0} //~| ERROR: maximum number of nodes exceeded in constant v20::v17::::{constant#0} - //~| ERROR: maximum number of nodes exceeded in constant v20::v17::::{constant#0} //~| ERROR: maximum number of nodes exceeded in constant v20::v17::::{constant#0} pub const fn v21() -> v18 { //~^ ERROR cannot find type `v18` in this scope diff --git a/tests/ui/const-generics/generic_const_exprs/unevaluated-const-ice-119731.stderr b/tests/ui/const-generics/generic_const_exprs/unevaluated-const-ice-119731.stderr index cf40269afc3dc..1b97917143888 100644 --- a/tests/ui/const-generics/generic_const_exprs/unevaluated-const-ice-119731.stderr +++ b/tests/ui/const-generics/generic_const_exprs/unevaluated-const-ice-119731.stderr @@ -1,5 +1,5 @@ error[E0432]: unresolved import `v20::v13` - --> $DIR/unevaluated-const-ice-119731.rs:42:15 + --> $DIR/unevaluated-const-ice-119731.rs:41:15 | LL | pub use v20::{v13, v17}; | ^^^ no `v13` in `v20` @@ -34,7 +34,7 @@ LL + pub const fn v21() -> v11 {} | error[E0425]: cannot find type `v18` in this scope - --> $DIR/unevaluated-const-ice-119731.rs:35:31 + --> $DIR/unevaluated-const-ice-119731.rs:34:31 | LL | pub const fn v21() -> v18 { | ^^^ not found in this scope @@ -51,7 +51,7 @@ LL + pub const fn v21() -> v11 { | error[E0422]: cannot find struct, variant or union type `v18` in this scope - --> $DIR/unevaluated-const-ice-119731.rs:37:13 + --> $DIR/unevaluated-const-ice-119731.rs:36:13 | LL | v18 { _p: () } | ^^^ not found in this scope @@ -137,14 +137,6 @@ LL | impl v17 { | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: maximum number of nodes exceeded in constant v20::v17::::{constant#0} - --> $DIR/unevaluated-const-ice-119731.rs:28:37 - | -LL | impl v17 { - | ^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - error[E0592]: duplicate definitions with name `v21` --> $DIR/unevaluated-const-ice-119731.rs:23:9 | @@ -154,7 +146,7 @@ LL | pub const fn v21() -> v18 {} LL | pub const fn v21() -> v18 { | ------------------------- other definition for `v21` -error: aborting due to 14 previous errors; 2 warnings emitted +error: aborting due to 13 previous errors; 2 warnings emitted Some errors have detailed explanations: E0422, E0425, E0432, E0592. For more information about an error, try `rustc --explain E0422`. diff --git a/tests/ui/consts/too_generic_eval_ice.next.stderr b/tests/ui/consts/too_generic_eval_ice.next.stderr index 01da33241c810..f0e80b7e1bba7 100644 --- a/tests/ui/consts/too_generic_eval_ice.next.stderr +++ b/tests/ui/consts/too_generic_eval_ice.next.stderr @@ -1,8 +1,10 @@ -error[E0284]: type annotations needed: cannot satisfy `the constant `Self::HOST_SIZE` can be evaluated` +error[E0284]: type annotations needed --> $DIR/too_generic_eval_ice.rs:11:13 | LL | [5; Self::HOST_SIZE] == [6; 0] - | ^^^^^^^^^^^^^^^ cannot satisfy `the constant `Self::HOST_SIZE` can be evaluated` + | ^^^^^^^^^^^^^^^ cannot infer the value of the constant `_` + | + = note: cannot satisfy `Foo::crash::{constant#0} == _` error: aborting due to 1 previous error diff --git a/tests/ui/traits/next-solver/canonical/const-region-infer-to-static-in-binder.stderr b/tests/ui/traits/next-solver/canonical/const-region-infer-to-static-in-binder.stderr index 07eddd8c87c3d..bb56d43c0cb5a 100644 --- a/tests/ui/traits/next-solver/canonical/const-region-infer-to-static-in-binder.stderr +++ b/tests/ui/traits/next-solver/canonical/const-region-infer-to-static-in-binder.stderr @@ -1,8 +1,10 @@ -error[E0284]: type annotations needed: cannot satisfy `the constant `{ || {} }` can be evaluated` +error[E0284]: type annotations needed --> $DIR/const-region-infer-to-static-in-binder.rs:4:10 | LL | struct X; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot satisfy `the constant `{ || {} }` can be evaluated` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer the value of the constant `_` + | + = note: cannot satisfy `X::{constant#0} == _` error[E0284]: type annotations needed --> $DIR/const-region-infer-to-static-in-binder.rs:4:10