rustc_next_trait_solver/solve/eval_ctxt/
mod.rs

1use std::mem;
2use std::ops::ControlFlow;
3
4#[cfg(feature = "nightly")]
5use rustc_macros::HashStable_NoContext;
6use rustc_type_ir::data_structures::{HashMap, HashSet};
7use rustc_type_ir::inherent::*;
8use rustc_type_ir::relate::Relate;
9use rustc_type_ir::relate::solver_relating::RelateExt;
10use rustc_type_ir::search_graph::{CandidateHeadUsages, PathKind};
11use rustc_type_ir::{
12    self as ty, CanonicalVarValues, InferCtxtLike, Interner, TypeFoldable, TypeFolder,
13    TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
14    TypingMode,
15};
16use tracing::{debug, instrument, trace};
17
18use super::has_only_region_constraints;
19use crate::coherence;
20use crate::delegate::SolverDelegate;
21use crate::placeholder::BoundVarReplacer;
22use crate::resolve::eager_resolve_vars;
23use crate::solve::search_graph::SearchGraph;
24use crate::solve::ty::may_use_unstable_feature;
25use crate::solve::{
26    CanonicalInput, Certainty, FIXPOINT_STEP_LIMIT, Goal, GoalEvaluation, GoalSource,
27    GoalStalledOn, HasChanged, NestedNormalizationGoals, NoSolution, QueryInput, QueryResult,
28    inspect,
29};
30
31pub(super) mod canonical;
32mod probe;
33
34/// The kind of goal we're currently proving.
35///
36/// This has effects on cycle handling handling and on how we compute
37/// query responses, see the variant descriptions for more info.
38#[derive(Debug, Copy, Clone)]
39enum CurrentGoalKind {
40    Misc,
41    /// We're proving an trait goal for a coinductive trait, either an auto trait or `Sized`.
42    ///
43    /// These are currently the only goals whose impl where-clauses are considered to be
44    /// productive steps.
45    CoinductiveTrait,
46    /// Unlike other goals, `NormalizesTo` goals act like functions with the expected term
47    /// always being fully unconstrained. This would weaken inference however, as the nested
48    /// goals never get the inference constraints from the actual normalized-to type.
49    ///
50    /// Because of this we return any ambiguous nested goals from `NormalizesTo` to the
51    /// caller when then adds these to its own context. The caller is always an `AliasRelate`
52    /// goal so this never leaks out of the solver.
53    NormalizesTo,
54}
55
56impl CurrentGoalKind {
57    fn from_query_input<I: Interner>(cx: I, input: QueryInput<I, I::Predicate>) -> CurrentGoalKind {
58        match input.goal.predicate.kind().skip_binder() {
59            ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
60                if cx.trait_is_coinductive(pred.trait_ref.def_id) {
61                    CurrentGoalKind::CoinductiveTrait
62                } else {
63                    CurrentGoalKind::Misc
64                }
65            }
66            ty::PredicateKind::NormalizesTo(_) => CurrentGoalKind::NormalizesTo,
67            _ => CurrentGoalKind::Misc,
68        }
69    }
70}
71
72pub struct EvalCtxt<'a, D, I = <D as SolverDelegate>::Interner>
73where
74    D: SolverDelegate<Interner = I>,
75    I: Interner,
76{
77    /// The inference context that backs (mostly) inference and placeholder terms
78    /// instantiated while solving goals.
79    ///
80    /// NOTE: The `InferCtxt` that backs the `EvalCtxt` is intentionally private,
81    /// because the `InferCtxt` is much more general than `EvalCtxt`. Methods such
82    /// as  `take_registered_region_obligations` can mess up query responses,
83    /// using `At::normalize` is totally wrong, calling `evaluate_root_goal` can
84    /// cause coinductive unsoundness, etc.
85    ///
86    /// Methods that are generally of use for trait solving are *intentionally*
87    /// re-declared through the `EvalCtxt` below, often with cleaner signatures
88    /// since we don't care about things like `ObligationCause`s and `Span`s here.
89    /// If some `InferCtxt` method is missing, please first think defensively about
90    /// the method's compatibility with this solver, or if an existing one does
91    /// the job already.
92    delegate: &'a D,
93
94    /// The variable info for the `var_values`, only used to make an ambiguous response
95    /// with no constraints.
96    variables: I::CanonicalVarKinds,
97
98    /// What kind of goal we're currently computing, see the enum definition
99    /// for more info.
100    current_goal_kind: CurrentGoalKind,
101    pub(super) var_values: CanonicalVarValues<I>,
102
103    /// The highest universe index nameable by the caller.
104    ///
105    /// When we enter a new binder inside of the query we create new universes
106    /// which the caller cannot name. We have to be careful with variables from
107    /// these new universes when creating the query response.
108    ///
109    /// Both because these new universes can prevent us from reaching a fixpoint
110    /// if we have a coinductive cycle and because that's the only way we can return
111    /// new placeholders to the caller.
112    pub(super) max_input_universe: ty::UniverseIndex,
113    /// The opaque types from the canonical input. We only need to return opaque types
114    /// which have been added to the storage while evaluating this goal.
115    pub(super) initial_opaque_types_storage_num_entries:
116        <D::Infcx as InferCtxtLike>::OpaqueTypeStorageEntries,
117
118    pub(super) search_graph: &'a mut SearchGraph<D>,
119
120    nested_goals: Vec<(GoalSource, Goal<I, I::Predicate>, Option<GoalStalledOn<I>>)>,
121
122    pub(super) origin_span: I::Span,
123
124    // Has this `EvalCtxt` errored out with `NoSolution` in `try_evaluate_added_goals`?
125    //
126    // If so, then it can no longer be used to make a canonical query response,
127    // since subsequent calls to `try_evaluate_added_goals` have possibly dropped
128    // ambiguous goals. Instead, a probe needs to be introduced somewhere in the
129    // evaluation code.
130    tainted: Result<(), NoSolution>,
131
132    pub(super) inspect: inspect::EvaluationStepBuilder<D>,
133}
134
135#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
136#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
137pub enum GenerateProofTree {
138    Yes,
139    No,
140}
141
142pub trait SolverDelegateEvalExt: SolverDelegate {
143    /// Evaluates a goal from **outside** of the trait solver.
144    ///
145    /// Using this while inside of the solver is wrong as it uses a new
146    /// search graph which would break cycle detection.
147    fn evaluate_root_goal(
148        &self,
149        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
150        span: <Self::Interner as Interner>::Span,
151        stalled_on: Option<GoalStalledOn<Self::Interner>>,
152    ) -> Result<GoalEvaluation<Self::Interner>, NoSolution>;
153
154    /// Check whether evaluating `goal` with a depth of `root_depth` may
155    /// succeed. This only returns `false` if the goal is guaranteed to
156    /// not hold. In case evaluation overflows and fails with ambiguity this
157    /// returns `true`.
158    ///
159    /// This is only intended to be used as a performance optimization
160    /// in coherence checking.
161    fn root_goal_may_hold_with_depth(
162        &self,
163        root_depth: usize,
164        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
165    ) -> bool;
166
167    // FIXME: This is only exposed because we need to use it in `analyse.rs`
168    // which is not yet uplifted. Once that's done, we should remove this.
169    fn evaluate_root_goal_for_proof_tree(
170        &self,
171        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
172        span: <Self::Interner as Interner>::Span,
173    ) -> (
174        Result<NestedNormalizationGoals<Self::Interner>, NoSolution>,
175        inspect::GoalEvaluation<Self::Interner>,
176    );
177}
178
179impl<D, I> SolverDelegateEvalExt for D
180where
181    D: SolverDelegate<Interner = I>,
182    I: Interner,
183{
184    #[instrument(level = "debug", skip(self))]
185    fn evaluate_root_goal(
186        &self,
187        goal: Goal<I, I::Predicate>,
188        span: I::Span,
189        stalled_on: Option<GoalStalledOn<I>>,
190    ) -> Result<GoalEvaluation<I>, NoSolution> {
191        EvalCtxt::enter_root(self, self.cx().recursion_limit(), span, |ecx| {
192            ecx.evaluate_goal(GoalSource::Misc, goal, stalled_on)
193        })
194    }
195
196    fn root_goal_may_hold_with_depth(
197        &self,
198        root_depth: usize,
199        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
200    ) -> bool {
201        self.probe(|| {
202            EvalCtxt::enter_root(self, root_depth, I::Span::dummy(), |ecx| {
203                ecx.evaluate_goal(GoalSource::Misc, goal, None)
204            })
205        })
206        .is_ok()
207    }
208
209    #[instrument(level = "debug", skip(self))]
210    fn evaluate_root_goal_for_proof_tree(
211        &self,
212        goal: Goal<I, I::Predicate>,
213        span: I::Span,
214    ) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
215        evaluate_root_goal_for_proof_tree(self, goal, span)
216    }
217}
218
219impl<'a, D, I> EvalCtxt<'a, D>
220where
221    D: SolverDelegate<Interner = I>,
222    I: Interner,
223{
224    pub(super) fn typing_mode(&self) -> TypingMode<I> {
225        self.delegate.typing_mode()
226    }
227
228    /// Computes the `PathKind` for the step from the current goal to the
229    /// nested goal required due to `source`.
230    ///
231    /// See #136824 for a more detailed reasoning for this behavior. We
232    /// consider cycles to be coinductive if they 'step into' a where-clause
233    /// of a coinductive trait. We will likely extend this function in the future
234    /// and will need to clearly document it in the rustc-dev-guide before
235    /// stabilization.
236    pub(super) fn step_kind_for_source(&self, source: GoalSource) -> PathKind {
237        match source {
238            // We treat these goals as unknown for now. It is likely that most miscellaneous
239            // nested goals will be converted to an inductive variant in the future.
240            //
241            // Having unknown cycles is always the safer option, as changing that to either
242            // succeed or hard error is backwards compatible. If we incorrectly treat a cycle
243            // as inductive even though it should not be, it may be unsound during coherence and
244            // fixing it may cause inference breakage or introduce ambiguity.
245            GoalSource::Misc => PathKind::Unknown,
246            GoalSource::NormalizeGoal(path_kind) => path_kind,
247            GoalSource::ImplWhereBound => match self.current_goal_kind {
248                // We currently only consider a cycle coinductive if it steps
249                // into a where-clause of a coinductive trait.
250                CurrentGoalKind::CoinductiveTrait => PathKind::Coinductive,
251                // While normalizing via an impl does step into a where-clause of
252                // an impl, accessing the associated item immediately steps out of
253                // it again. This means cycles/recursive calls are not guarded
254                // by impls used for normalization.
255                //
256                // See tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.rs
257                // for how this can go wrong.
258                CurrentGoalKind::NormalizesTo => PathKind::Inductive,
259                // We probably want to make all traits coinductive in the future,
260                // so we treat cycles involving where-clauses of not-yet coinductive
261                // traits as ambiguous for now.
262                CurrentGoalKind::Misc => PathKind::Unknown,
263            },
264            // Relating types is always unproductive. If we were to map proof trees to
265            // corecursive functions as explained in #136824, relating types never
266            // introduces a constructor which could cause the recursion to be guarded.
267            GoalSource::TypeRelating => PathKind::Inductive,
268            // Instantiating a higher ranked goal can never cause the recursion to be
269            // guarded and is therefore unproductive.
270            GoalSource::InstantiateHigherRanked => PathKind::Inductive,
271            // These goal sources are likely unproductive and can be changed to
272            // `PathKind::Inductive`. Keeping them as unknown until we're confident
273            // about this and have an example where it is necessary.
274            GoalSource::AliasBoundConstCondition | GoalSource::AliasWellFormed => PathKind::Unknown,
275        }
276    }
277
278    /// Creates a root evaluation context and search graph. This should only be
279    /// used from outside of any evaluation, and other methods should be preferred
280    /// over using this manually (such as [`SolverDelegateEvalExt::evaluate_root_goal`]).
281    pub(super) fn enter_root<R>(
282        delegate: &D,
283        root_depth: usize,
284        origin_span: I::Span,
285        f: impl FnOnce(&mut EvalCtxt<'_, D>) -> R,
286    ) -> R {
287        let mut search_graph = SearchGraph::new(root_depth);
288
289        let mut ecx = EvalCtxt {
290            delegate,
291            search_graph: &mut search_graph,
292            nested_goals: Default::default(),
293            inspect: inspect::EvaluationStepBuilder::new_noop(),
294
295            // Only relevant when canonicalizing the response,
296            // which we don't do within this evaluation context.
297            max_input_universe: ty::UniverseIndex::ROOT,
298            initial_opaque_types_storage_num_entries: Default::default(),
299            variables: Default::default(),
300            var_values: CanonicalVarValues::dummy(),
301            current_goal_kind: CurrentGoalKind::Misc,
302            origin_span,
303            tainted: Ok(()),
304        };
305        let result = f(&mut ecx);
306        assert!(
307            ecx.nested_goals.is_empty(),
308            "root `EvalCtxt` should not have any goals added to it"
309        );
310        assert!(search_graph.is_empty());
311        result
312    }
313
314    /// Creates a nested evaluation context that shares the same search graph as the
315    /// one passed in. This is suitable for evaluation, granted that the search graph
316    /// has had the nested goal recorded on its stack. This method only be used by
317    /// `search_graph::Delegate::compute_goal`.
318    ///
319    /// This function takes care of setting up the inference context, setting the anchor,
320    /// and registering opaques from the canonicalized input.
321    pub(super) fn enter_canonical<R>(
322        cx: I,
323        search_graph: &'a mut SearchGraph<D>,
324        canonical_input: CanonicalInput<I>,
325        proof_tree_builder: &mut inspect::ProofTreeBuilder<D>,
326        f: impl FnOnce(&mut EvalCtxt<'_, D>, Goal<I, I::Predicate>) -> R,
327    ) -> R {
328        let (ref delegate, input, var_values) = D::build_with_canonical(cx, &canonical_input);
329        for &(key, ty) in &input.predefined_opaques_in_body.opaque_types {
330            let prev = delegate.register_hidden_type_in_storage(key, ty, I::Span::dummy());
331            // It may be possible that two entries in the opaque type storage end up
332            // with the same key after resolving contained inference variables.
333            //
334            // We could put them in the duplicate list but don't have to. The opaques we
335            // encounter here are already tracked in the caller, so there's no need to
336            // also store them here. We'd take them out when computing the query response
337            // and then discard them, as they're already present in the input.
338            //
339            // Ideally we'd drop duplicate opaque type definitions when computing
340            // the canonical input. This is more annoying to implement and may cause a
341            // perf regression, so we do it inside of the query for now.
342            if let Some(prev) = prev {
343                debug!(?key, ?ty, ?prev, "ignore duplicate in `opaque_types_storage`");
344            }
345        }
346
347        let initial_opaque_types_storage_num_entries = delegate.opaque_types_storage_num_entries();
348        let mut ecx = EvalCtxt {
349            delegate,
350            variables: canonical_input.canonical.variables,
351            var_values,
352            current_goal_kind: CurrentGoalKind::from_query_input(cx, input),
353            max_input_universe: canonical_input.canonical.max_universe,
354            initial_opaque_types_storage_num_entries,
355            search_graph,
356            nested_goals: Default::default(),
357            origin_span: I::Span::dummy(),
358            tainted: Ok(()),
359            inspect: proof_tree_builder.new_evaluation_step(var_values),
360        };
361
362        let result = f(&mut ecx, input.goal);
363        ecx.inspect.probe_final_state(ecx.delegate, ecx.max_input_universe);
364        proof_tree_builder.finish_evaluation_step(ecx.inspect);
365
366        // When creating a query response we clone the opaque type constraints
367        // instead of taking them. This would cause an ICE here, since we have
368        // assertions against dropping an `InferCtxt` without taking opaques.
369        // FIXME: Once we remove support for the old impl we can remove this.
370        // FIXME: Could we make `build_with_canonical` into `enter_with_canonical` and call this at the end?
371        delegate.reset_opaque_types();
372
373        result
374    }
375
376    pub(super) fn ignore_candidate_head_usages(&mut self, usages: CandidateHeadUsages) {
377        self.search_graph.ignore_candidate_head_usages(usages);
378    }
379
380    /// Recursively evaluates `goal`, returning whether any inference vars have
381    /// been constrained and the certainty of the result.
382    fn evaluate_goal(
383        &mut self,
384        source: GoalSource,
385        goal: Goal<I, I::Predicate>,
386        stalled_on: Option<GoalStalledOn<I>>,
387    ) -> Result<GoalEvaluation<I>, NoSolution> {
388        let (normalization_nested_goals, goal_evaluation) =
389            self.evaluate_goal_raw(source, goal, stalled_on)?;
390        assert!(normalization_nested_goals.is_empty());
391        Ok(goal_evaluation)
392    }
393
394    /// Recursively evaluates `goal`, returning the nested goals in case
395    /// the nested goal is a `NormalizesTo` goal.
396    ///
397    /// As all other goal kinds do not return any nested goals and
398    /// `NormalizesTo` is only used by `AliasRelate`, all other callsites
399    /// should use [`EvalCtxt::evaluate_goal`] which discards that empty
400    /// storage.
401    pub(super) fn evaluate_goal_raw(
402        &mut self,
403        source: GoalSource,
404        goal: Goal<I, I::Predicate>,
405        stalled_on: Option<GoalStalledOn<I>>,
406    ) -> Result<(NestedNormalizationGoals<I>, GoalEvaluation<I>), NoSolution> {
407        // If we have run this goal before, and it was stalled, check that any of the goal's
408        // args have changed. Otherwise, we don't need to re-run the goal because it'll remain
409        // stalled, since it'll canonicalize the same way and evaluation is pure.
410        if let Some(stalled_on) = stalled_on
411            && !stalled_on.stalled_vars.iter().any(|value| self.delegate.is_changed_arg(*value))
412            && !self
413                .delegate
414                .opaque_types_storage_num_entries()
415                .needs_reevaluation(stalled_on.num_opaques)
416        {
417            return Ok((
418                NestedNormalizationGoals::empty(),
419                GoalEvaluation {
420                    goal,
421                    certainty: Certainty::Maybe(stalled_on.stalled_cause),
422                    has_changed: HasChanged::No,
423                    stalled_on: Some(stalled_on),
424                },
425            ));
426        }
427
428        // We only care about one entry per `OpaqueTypeKey` here,
429        // so we only canonicalize the lookup table and ignore
430        // duplicate entries.
431        let opaque_types = self.delegate.clone_opaque_types_lookup_table();
432        let (goal, opaque_types) = eager_resolve_vars(self.delegate, (goal, opaque_types));
433
434        let (orig_values, canonical_goal) =
435            Self::canonicalize_goal(self.delegate, goal, opaque_types);
436        let canonical_result = self.search_graph.evaluate_goal(
437            self.cx(),
438            canonical_goal,
439            self.step_kind_for_source(source),
440            &mut inspect::ProofTreeBuilder::new_noop(),
441        );
442        let response = match canonical_result {
443            Err(e) => return Err(e),
444            Ok(response) => response,
445        };
446
447        let has_changed =
448            if !has_only_region_constraints(response) { HasChanged::Yes } else { HasChanged::No };
449
450        let (normalization_nested_goals, certainty) = Self::instantiate_and_apply_query_response(
451            self.delegate,
452            goal.param_env,
453            &orig_values,
454            response,
455            self.origin_span,
456        );
457
458        // FIXME: We previously had an assert here that checked that recomputing
459        // a goal after applying its constraints did not change its response.
460        //
461        // This assert was removed as it did not hold for goals constraining
462        // an inference variable to a recursive alias, e.g. in
463        // tests/ui/traits/next-solver/overflow/recursive-self-normalization.rs.
464        //
465        // Once we have decided on how to handle trait-system-refactor-initiative#75,
466        // we should re-add an assert here.
467
468        let stalled_on = match certainty {
469            Certainty::Yes => None,
470            Certainty::Maybe(stalled_cause) => match has_changed {
471                // FIXME: We could recompute a *new* set of stalled variables by walking
472                // through the orig values, resolving, and computing the root vars of anything
473                // that is not resolved. Only when *these* have changed is it meaningful
474                // to recompute this goal.
475                HasChanged::Yes => None,
476                HasChanged::No => {
477                    let mut stalled_vars = orig_values;
478
479                    // Remove the canonicalized universal vars, since we only care about stalled existentials.
480                    stalled_vars.retain(|arg| match arg.kind() {
481                        ty::GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Infer(_)),
482                        ty::GenericArgKind::Const(ct) => {
483                            matches!(ct.kind(), ty::ConstKind::Infer(_))
484                        }
485                        // Lifetimes can never stall goals.
486                        ty::GenericArgKind::Lifetime(_) => false,
487                    });
488
489                    // Remove the unconstrained RHS arg, which is expected to have changed.
490                    if let Some(normalizes_to) = goal.predicate.as_normalizes_to() {
491                        let normalizes_to = normalizes_to.skip_binder();
492                        let rhs_arg: I::GenericArg = normalizes_to.term.into();
493                        let idx = stalled_vars
494                            .iter()
495                            .rposition(|arg| *arg == rhs_arg)
496                            .expect("expected unconstrained arg");
497                        stalled_vars.swap_remove(idx);
498                    }
499
500                    Some(GoalStalledOn {
501                        num_opaques: canonical_goal
502                            .canonical
503                            .value
504                            .predefined_opaques_in_body
505                            .opaque_types
506                            .len(),
507                        stalled_vars,
508                        stalled_cause,
509                    })
510                }
511            },
512        };
513
514        Ok((
515            normalization_nested_goals,
516            GoalEvaluation { goal, certainty, has_changed, stalled_on },
517        ))
518    }
519
520    pub(super) fn compute_goal(&mut self, goal: Goal<I, I::Predicate>) -> QueryResult<I> {
521        let Goal { param_env, predicate } = goal;
522        let kind = predicate.kind();
523        if let Some(kind) = kind.no_bound_vars() {
524            match kind {
525                ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
526                    self.compute_trait_goal(Goal { param_env, predicate }).map(|(r, _via)| r)
527                }
528                ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
529                    self.compute_host_effect_goal(Goal { param_env, predicate })
530                }
531                ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) => {
532                    self.compute_projection_goal(Goal { param_env, predicate })
533                }
534                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(predicate)) => {
535                    self.compute_type_outlives_goal(Goal { param_env, predicate })
536                }
537                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(predicate)) => {
538                    self.compute_region_outlives_goal(Goal { param_env, predicate })
539                }
540                ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
541                    self.compute_const_arg_has_type_goal(Goal { param_env, predicate: (ct, ty) })
542                }
543                ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
544                    self.compute_unstable_feature_goal(param_env, symbol)
545                }
546                ty::PredicateKind::Subtype(predicate) => {
547                    self.compute_subtype_goal(Goal { param_env, predicate })
548                }
549                ty::PredicateKind::Coerce(predicate) => {
550                    self.compute_coerce_goal(Goal { param_env, predicate })
551                }
552                ty::PredicateKind::DynCompatible(trait_def_id) => {
553                    self.compute_dyn_compatible_goal(trait_def_id)
554                }
555                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
556                    self.compute_well_formed_goal(Goal { param_env, predicate: term })
557                }
558                ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => {
559                    self.compute_const_evaluatable_goal(Goal { param_env, predicate: ct })
560                }
561                ty::PredicateKind::ConstEquate(_, _) => {
562                    panic!("ConstEquate should not be emitted when `-Znext-solver` is active")
563                }
564                ty::PredicateKind::NormalizesTo(predicate) => {
565                    self.compute_normalizes_to_goal(Goal { param_env, predicate })
566                }
567                ty::PredicateKind::AliasRelate(lhs, rhs, direction) => self
568                    .compute_alias_relate_goal(Goal {
569                        param_env,
570                        predicate: (lhs, rhs, direction),
571                    }),
572                ty::PredicateKind::Ambiguous => {
573                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
574                }
575            }
576        } else {
577            self.enter_forall(kind, |ecx, kind| {
578                let goal = goal.with(ecx.cx(), ty::Binder::dummy(kind));
579                ecx.add_goal(GoalSource::InstantiateHigherRanked, goal);
580                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
581            })
582        }
583    }
584
585    // Recursively evaluates all the goals added to this `EvalCtxt` to completion, returning
586    // the certainty of all the goals.
587    #[instrument(level = "trace", skip(self))]
588    pub(super) fn try_evaluate_added_goals(&mut self) -> Result<Certainty, NoSolution> {
589        let mut response = Ok(Certainty::overflow(false));
590        for _ in 0..FIXPOINT_STEP_LIMIT {
591            // FIXME: This match is a bit ugly, it might be nice to change the inspect
592            // stuff to use a closure instead. which should hopefully simplify this a bit.
593            match self.evaluate_added_goals_step() {
594                Ok(Some(cert)) => {
595                    response = Ok(cert);
596                    break;
597                }
598                Ok(None) => {}
599                Err(NoSolution) => {
600                    response = Err(NoSolution);
601                    break;
602                }
603            }
604        }
605
606        if response.is_err() {
607            self.tainted = Err(NoSolution);
608        }
609
610        response
611    }
612
613    /// Iterate over all added goals: returning `Ok(Some(_))` in case we can stop rerunning.
614    ///
615    /// Goals for the next step get directly added to the nested goals of the `EvalCtxt`.
616    fn evaluate_added_goals_step(&mut self) -> Result<Option<Certainty>, NoSolution> {
617        let cx = self.cx();
618        // If this loop did not result in any progress, what's our final certainty.
619        let mut unchanged_certainty = Some(Certainty::Yes);
620        for (source, goal, stalled_on) in mem::take(&mut self.nested_goals) {
621            if let Some(certainty) = self.delegate.compute_goal_fast_path(goal, self.origin_span) {
622                match certainty {
623                    Certainty::Yes => {}
624                    Certainty::Maybe(_) => {
625                        self.nested_goals.push((source, goal, None));
626                        unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
627                    }
628                }
629                continue;
630            }
631
632            // We treat normalizes-to goals specially here. In each iteration we take the
633            // RHS of the projection, replace it with a fresh inference variable, and only
634            // after evaluating that goal do we equate the fresh inference variable with the
635            // actual RHS of the predicate.
636            //
637            // This is both to improve caching, and to avoid using the RHS of the
638            // projection predicate to influence the normalizes-to candidate we select.
639            //
640            // Forgetting to replace the RHS with a fresh inference variable when we evaluate
641            // this goal results in an ICE.
642            if let Some(pred) = goal.predicate.as_normalizes_to() {
643                // We should never encounter higher-ranked normalizes-to goals.
644                let pred = pred.no_bound_vars().unwrap();
645                // Replace the goal with an unconstrained infer var, so the
646                // RHS does not affect projection candidate assembly.
647                let unconstrained_rhs = self.next_term_infer_of_kind(pred.term);
648                let unconstrained_goal =
649                    goal.with(cx, ty::NormalizesTo { alias: pred.alias, term: unconstrained_rhs });
650
651                let (
652                    NestedNormalizationGoals(nested_goals),
653                    GoalEvaluation { goal, certainty, stalled_on, has_changed: _ },
654                ) = self.evaluate_goal_raw(source, unconstrained_goal, stalled_on)?;
655                // Add the nested goals from normalization to our own nested goals.
656                trace!(?nested_goals);
657                self.nested_goals.extend(nested_goals.into_iter().map(|(s, g)| (s, g, None)));
658
659                // Finally, equate the goal's RHS with the unconstrained var.
660                //
661                // SUBTLE:
662                // We structurally relate aliases here. This is necessary
663                // as we otherwise emit a nested `AliasRelate` goal in case the
664                // returned term is a rigid alias, resulting in overflow.
665                //
666                // It is correct as both `goal.predicate.term` and `unconstrained_rhs`
667                // start out as an unconstrained inference variable so any aliases get
668                // fully normalized when instantiating it.
669                //
670                // FIXME: Strictly speaking this may be incomplete if the normalized-to
671                // type contains an ambiguous alias referencing bound regions. We should
672                // consider changing this to only use "shallow structural equality".
673                self.eq_structurally_relating_aliases(
674                    goal.param_env,
675                    pred.term,
676                    unconstrained_rhs,
677                )?;
678
679                // We only look at the `projection_ty` part here rather than
680                // looking at the "has changed" return from evaluate_goal,
681                // because we expect the `unconstrained_rhs` part of the predicate
682                // to have changed -- that means we actually normalized successfully!
683                // FIXME: Do we need to eagerly resolve here? Or should we check
684                // if the cache key has any changed vars?
685                let with_resolved_vars = self.resolve_vars_if_possible(goal);
686                if pred.alias
687                    != with_resolved_vars
688                        .predicate
689                        .as_normalizes_to()
690                        .unwrap()
691                        .no_bound_vars()
692                        .unwrap()
693                        .alias
694                {
695                    unchanged_certainty = None;
696                }
697
698                match certainty {
699                    Certainty::Yes => {}
700                    Certainty::Maybe(_) => {
701                        self.nested_goals.push((source, with_resolved_vars, stalled_on));
702                        unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
703                    }
704                }
705            } else {
706                let GoalEvaluation { goal, certainty, has_changed, stalled_on } =
707                    self.evaluate_goal(source, goal, stalled_on)?;
708                if has_changed == HasChanged::Yes {
709                    unchanged_certainty = None;
710                }
711
712                match certainty {
713                    Certainty::Yes => {}
714                    Certainty::Maybe(_) => {
715                        self.nested_goals.push((source, goal, stalled_on));
716                        unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
717                    }
718                }
719            }
720        }
721
722        Ok(unchanged_certainty)
723    }
724
725    /// Record impl args in the proof tree for later access by `InspectCandidate`.
726    pub(crate) fn record_impl_args(&mut self, impl_args: I::GenericArgs) {
727        self.inspect.record_impl_args(self.delegate, self.max_input_universe, impl_args)
728    }
729
730    pub(super) fn cx(&self) -> I {
731        self.delegate.cx()
732    }
733
734    #[instrument(level = "debug", skip(self))]
735    pub(super) fn add_goal(&mut self, source: GoalSource, mut goal: Goal<I, I::Predicate>) {
736        goal.predicate =
737            goal.predicate.fold_with(&mut ReplaceAliasWithInfer::new(self, source, goal.param_env));
738        self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
739        self.nested_goals.push((source, goal, None));
740    }
741
742    #[instrument(level = "trace", skip(self, goals))]
743    pub(super) fn add_goals(
744        &mut self,
745        source: GoalSource,
746        goals: impl IntoIterator<Item = Goal<I, I::Predicate>>,
747    ) {
748        for goal in goals {
749            self.add_goal(source, goal);
750        }
751    }
752
753    pub(super) fn next_region_var(&mut self) -> I::Region {
754        let region = self.delegate.next_region_infer();
755        self.inspect.add_var_value(region);
756        region
757    }
758
759    pub(super) fn next_ty_infer(&mut self) -> I::Ty {
760        let ty = self.delegate.next_ty_infer();
761        self.inspect.add_var_value(ty);
762        ty
763    }
764
765    pub(super) fn next_const_infer(&mut self) -> I::Const {
766        let ct = self.delegate.next_const_infer();
767        self.inspect.add_var_value(ct);
768        ct
769    }
770
771    /// Returns a ty infer or a const infer depending on whether `kind` is a `Ty` or `Const`.
772    /// If `kind` is an integer inference variable this will still return a ty infer var.
773    pub(super) fn next_term_infer_of_kind(&mut self, term: I::Term) -> I::Term {
774        match term.kind() {
775            ty::TermKind::Ty(_) => self.next_ty_infer().into(),
776            ty::TermKind::Const(_) => self.next_const_infer().into(),
777        }
778    }
779
780    /// Is the projection predicate is of the form `exists<T> <Ty as Trait>::Assoc = T`.
781    ///
782    /// This is the case if the `term` does not occur in any other part of the predicate
783    /// and is able to name all other placeholder and inference variables.
784    #[instrument(level = "trace", skip(self), ret)]
785    pub(super) fn term_is_fully_unconstrained(&self, goal: Goal<I, ty::NormalizesTo<I>>) -> bool {
786        let universe_of_term = match goal.predicate.term.kind() {
787            ty::TermKind::Ty(ty) => {
788                if let ty::Infer(ty::TyVar(vid)) = ty.kind() {
789                    self.delegate.universe_of_ty(vid).unwrap()
790                } else {
791                    return false;
792                }
793            }
794            ty::TermKind::Const(ct) => {
795                if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
796                    self.delegate.universe_of_ct(vid).unwrap()
797                } else {
798                    return false;
799                }
800            }
801        };
802
803        struct ContainsTermOrNotNameable<'a, D: SolverDelegate<Interner = I>, I: Interner> {
804            term: I::Term,
805            universe_of_term: ty::UniverseIndex,
806            delegate: &'a D,
807            cache: HashSet<I::Ty>,
808        }
809
810        impl<D: SolverDelegate<Interner = I>, I: Interner> ContainsTermOrNotNameable<'_, D, I> {
811            fn check_nameable(&self, universe: ty::UniverseIndex) -> ControlFlow<()> {
812                if self.universe_of_term.can_name(universe) {
813                    ControlFlow::Continue(())
814                } else {
815                    ControlFlow::Break(())
816                }
817            }
818        }
819
820        impl<D: SolverDelegate<Interner = I>, I: Interner> TypeVisitor<I>
821            for ContainsTermOrNotNameable<'_, D, I>
822        {
823            type Result = ControlFlow<()>;
824            fn visit_ty(&mut self, t: I::Ty) -> Self::Result {
825                if self.cache.contains(&t) {
826                    return ControlFlow::Continue(());
827                }
828
829                match t.kind() {
830                    ty::Infer(ty::TyVar(vid)) => {
831                        if let ty::TermKind::Ty(term) = self.term.kind()
832                            && let ty::Infer(ty::TyVar(term_vid)) = term.kind()
833                            && self.delegate.root_ty_var(vid) == self.delegate.root_ty_var(term_vid)
834                        {
835                            return ControlFlow::Break(());
836                        }
837
838                        self.check_nameable(self.delegate.universe_of_ty(vid).unwrap())?;
839                    }
840                    ty::Placeholder(p) => self.check_nameable(p.universe())?,
841                    _ => {
842                        if t.has_non_region_infer() || t.has_placeholders() {
843                            t.super_visit_with(self)?
844                        }
845                    }
846                }
847
848                assert!(self.cache.insert(t));
849                ControlFlow::Continue(())
850            }
851
852            fn visit_const(&mut self, c: I::Const) -> Self::Result {
853                match c.kind() {
854                    ty::ConstKind::Infer(ty::InferConst::Var(vid)) => {
855                        if let ty::TermKind::Const(term) = self.term.kind()
856                            && let ty::ConstKind::Infer(ty::InferConst::Var(term_vid)) = term.kind()
857                            && self.delegate.root_const_var(vid)
858                                == self.delegate.root_const_var(term_vid)
859                        {
860                            return ControlFlow::Break(());
861                        }
862
863                        self.check_nameable(self.delegate.universe_of_ct(vid).unwrap())
864                    }
865                    ty::ConstKind::Placeholder(p) => self.check_nameable(p.universe()),
866                    _ => {
867                        if c.has_non_region_infer() || c.has_placeholders() {
868                            c.super_visit_with(self)
869                        } else {
870                            ControlFlow::Continue(())
871                        }
872                    }
873                }
874            }
875
876            fn visit_predicate(&mut self, p: I::Predicate) -> Self::Result {
877                if p.has_non_region_infer() || p.has_placeholders() {
878                    p.super_visit_with(self)
879                } else {
880                    ControlFlow::Continue(())
881                }
882            }
883
884            fn visit_clauses(&mut self, c: I::Clauses) -> Self::Result {
885                if c.has_non_region_infer() || c.has_placeholders() {
886                    c.super_visit_with(self)
887                } else {
888                    ControlFlow::Continue(())
889                }
890            }
891        }
892
893        let mut visitor = ContainsTermOrNotNameable {
894            delegate: self.delegate,
895            universe_of_term,
896            term: goal.predicate.term,
897            cache: Default::default(),
898        };
899        goal.predicate.alias.visit_with(&mut visitor).is_continue()
900            && goal.param_env.visit_with(&mut visitor).is_continue()
901    }
902
903    pub(super) fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
904        self.delegate.sub_unify_ty_vids_raw(a, b)
905    }
906
907    #[instrument(level = "trace", skip(self, param_env), ret)]
908    pub(super) fn eq<T: Relate<I>>(
909        &mut self,
910        param_env: I::ParamEnv,
911        lhs: T,
912        rhs: T,
913    ) -> Result<(), NoSolution> {
914        self.relate(param_env, lhs, ty::Variance::Invariant, rhs)
915    }
916
917    /// This should be used when relating a rigid alias with another type.
918    ///
919    /// Normally we emit a nested `AliasRelate` when equating an inference
920    /// variable and an alias. This causes us to instead constrain the inference
921    /// variable to the alias without emitting a nested alias relate goals.
922    #[instrument(level = "trace", skip(self, param_env), ret)]
923    pub(super) fn relate_rigid_alias_non_alias(
924        &mut self,
925        param_env: I::ParamEnv,
926        alias: ty::AliasTerm<I>,
927        variance: ty::Variance,
928        term: I::Term,
929    ) -> Result<(), NoSolution> {
930        // NOTE: this check is purely an optimization, the structural eq would
931        // always fail if the term is not an inference variable.
932        if term.is_infer() {
933            let cx = self.cx();
934            // We need to relate `alias` to `term` treating only the outermost
935            // constructor as rigid, relating any contained generic arguments as
936            // normal. We do this by first structurally equating the `term`
937            // with the alias constructor instantiated with unconstrained infer vars,
938            // and then relate this with the whole `alias`.
939            //
940            // Alternatively we could modify `Equate` for this case by adding another
941            // variant to `StructurallyRelateAliases`.
942            let identity_args = self.fresh_args_for_item(alias.def_id);
943            let rigid_ctor = ty::AliasTerm::new_from_args(cx, alias.def_id, identity_args);
944            let ctor_term = rigid_ctor.to_term(cx);
945            let obligations = self.delegate.eq_structurally_relating_aliases(
946                param_env,
947                term,
948                ctor_term,
949                self.origin_span,
950            )?;
951            debug_assert!(obligations.is_empty());
952            self.relate(param_env, alias, variance, rigid_ctor)
953        } else {
954            Err(NoSolution)
955        }
956    }
957
958    /// This sohuld only be used when we're either instantiating a previously
959    /// unconstrained "return value" or when we're sure that all aliases in
960    /// the types are rigid.
961    #[instrument(level = "trace", skip(self, param_env), ret)]
962    pub(super) fn eq_structurally_relating_aliases<T: Relate<I>>(
963        &mut self,
964        param_env: I::ParamEnv,
965        lhs: T,
966        rhs: T,
967    ) -> Result<(), NoSolution> {
968        let result = self.delegate.eq_structurally_relating_aliases(
969            param_env,
970            lhs,
971            rhs,
972            self.origin_span,
973        )?;
974        assert_eq!(result, vec![]);
975        Ok(())
976    }
977
978    #[instrument(level = "trace", skip(self, param_env), ret)]
979    pub(super) fn sub<T: Relate<I>>(
980        &mut self,
981        param_env: I::ParamEnv,
982        sub: T,
983        sup: T,
984    ) -> Result<(), NoSolution> {
985        self.relate(param_env, sub, ty::Variance::Covariant, sup)
986    }
987
988    #[instrument(level = "trace", skip(self, param_env), ret)]
989    pub(super) fn relate<T: Relate<I>>(
990        &mut self,
991        param_env: I::ParamEnv,
992        lhs: T,
993        variance: ty::Variance,
994        rhs: T,
995    ) -> Result<(), NoSolution> {
996        let goals = self.delegate.relate(param_env, lhs, variance, rhs, self.origin_span)?;
997        for &goal in goals.iter() {
998            let source = match goal.predicate.kind().skip_binder() {
999                ty::PredicateKind::Subtype { .. } | ty::PredicateKind::AliasRelate(..) => {
1000                    GoalSource::TypeRelating
1001                }
1002                // FIXME(-Znext-solver=coinductive): should these WF goals also be unproductive?
1003                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => GoalSource::Misc,
1004                p => unreachable!("unexpected nested goal in `relate`: {p:?}"),
1005            };
1006            self.add_goal(source, goal);
1007        }
1008        Ok(())
1009    }
1010
1011    /// Equates two values returning the nested goals without adding them
1012    /// to the nested goals of the `EvalCtxt`.
1013    ///
1014    /// If possible, try using `eq` instead which automatically handles nested
1015    /// goals correctly.
1016    #[instrument(level = "trace", skip(self, param_env), ret)]
1017    pub(super) fn eq_and_get_goals<T: Relate<I>>(
1018        &self,
1019        param_env: I::ParamEnv,
1020        lhs: T,
1021        rhs: T,
1022    ) -> Result<Vec<Goal<I, I::Predicate>>, NoSolution> {
1023        Ok(self.delegate.relate(param_env, lhs, ty::Variance::Invariant, rhs, self.origin_span)?)
1024    }
1025
1026    pub(super) fn instantiate_binder_with_infer<T: TypeFoldable<I> + Copy>(
1027        &self,
1028        value: ty::Binder<I, T>,
1029    ) -> T {
1030        self.delegate.instantiate_binder_with_infer(value)
1031    }
1032
1033    /// `enter_forall`, but takes `&mut self` and passes it back through the
1034    /// callback since it can't be aliased during the call.
1035    pub(super) fn enter_forall<T: TypeFoldable<I>, U>(
1036        &mut self,
1037        value: ty::Binder<I, T>,
1038        f: impl FnOnce(&mut Self, T) -> U,
1039    ) -> U {
1040        self.delegate.enter_forall(value, |value| f(self, value))
1041    }
1042
1043    pub(super) fn resolve_vars_if_possible<T>(&self, value: T) -> T
1044    where
1045        T: TypeFoldable<I>,
1046    {
1047        self.delegate.resolve_vars_if_possible(value)
1048    }
1049
1050    pub(super) fn eager_resolve_region(&self, r: I::Region) -> I::Region {
1051        if let ty::ReVar(vid) = r.kind() {
1052            self.delegate.opportunistic_resolve_lt_var(vid)
1053        } else {
1054            r
1055        }
1056    }
1057
1058    pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
1059        let args = self.delegate.fresh_args_for_item(def_id);
1060        for arg in args.iter() {
1061            self.inspect.add_var_value(arg);
1062        }
1063        args
1064    }
1065
1066    pub(super) fn register_ty_outlives(&self, ty: I::Ty, lt: I::Region) {
1067        self.delegate.register_ty_outlives(ty, lt, self.origin_span);
1068    }
1069
1070    pub(super) fn register_region_outlives(&self, a: I::Region, b: I::Region) {
1071        // `'a: 'b` ==> `'b <= 'a`
1072        self.delegate.sub_regions(b, a, self.origin_span);
1073    }
1074
1075    /// Computes the list of goals required for `arg` to be well-formed
1076    pub(super) fn well_formed_goals(
1077        &self,
1078        param_env: I::ParamEnv,
1079        term: I::Term,
1080    ) -> Option<Vec<Goal<I, I::Predicate>>> {
1081        self.delegate.well_formed_goals(param_env, term)
1082    }
1083
1084    pub(super) fn trait_ref_is_knowable(
1085        &mut self,
1086        param_env: I::ParamEnv,
1087        trait_ref: ty::TraitRef<I>,
1088    ) -> Result<bool, NoSolution> {
1089        let delegate = self.delegate;
1090        let lazily_normalize_ty = |ty| self.structurally_normalize_ty(param_env, ty);
1091        coherence::trait_ref_is_knowable(&**delegate, trait_ref, lazily_normalize_ty)
1092            .map(|is_knowable| is_knowable.is_ok())
1093    }
1094
1095    pub(super) fn fetch_eligible_assoc_item(
1096        &self,
1097        goal_trait_ref: ty::TraitRef<I>,
1098        trait_assoc_def_id: I::DefId,
1099        impl_def_id: I::ImplId,
1100    ) -> Result<Option<I::DefId>, I::ErrorGuaranteed> {
1101        self.delegate.fetch_eligible_assoc_item(goal_trait_ref, trait_assoc_def_id, impl_def_id)
1102    }
1103
1104    #[instrument(level = "debug", skip(self), ret)]
1105    pub(super) fn register_hidden_type_in_storage(
1106        &mut self,
1107        opaque_type_key: ty::OpaqueTypeKey<I>,
1108        hidden_ty: I::Ty,
1109    ) -> Option<I::Ty> {
1110        self.delegate.register_hidden_type_in_storage(opaque_type_key, hidden_ty, self.origin_span)
1111    }
1112
1113    pub(super) fn add_item_bounds_for_hidden_type(
1114        &mut self,
1115        opaque_def_id: I::DefId,
1116        opaque_args: I::GenericArgs,
1117        param_env: I::ParamEnv,
1118        hidden_ty: I::Ty,
1119    ) {
1120        let mut goals = Vec::new();
1121        self.delegate.add_item_bounds_for_hidden_type(
1122            opaque_def_id,
1123            opaque_args,
1124            param_env,
1125            hidden_ty,
1126            &mut goals,
1127        );
1128        self.add_goals(GoalSource::AliasWellFormed, goals);
1129    }
1130
1131    // Try to evaluate a const, or return `None` if the const is too generic.
1132    // This doesn't mean the const isn't evaluatable, though, and should be treated
1133    // as an ambiguity rather than no-solution.
1134    pub(super) fn evaluate_const(
1135        &self,
1136        param_env: I::ParamEnv,
1137        uv: ty::UnevaluatedConst<I>,
1138    ) -> Option<I::Const> {
1139        self.delegate.evaluate_const(param_env, uv)
1140    }
1141
1142    pub(super) fn is_transmutable(
1143        &mut self,
1144        dst: I::Ty,
1145        src: I::Ty,
1146        assume: I::Const,
1147    ) -> Result<Certainty, NoSolution> {
1148        self.delegate.is_transmutable(dst, src, assume)
1149    }
1150
1151    pub(super) fn replace_bound_vars<T: TypeFoldable<I>>(
1152        &self,
1153        t: T,
1154        universes: &mut Vec<Option<ty::UniverseIndex>>,
1155    ) -> T {
1156        BoundVarReplacer::replace_bound_vars(&**self.delegate, universes, t).0
1157    }
1158
1159    pub(super) fn may_use_unstable_feature(
1160        &self,
1161        param_env: I::ParamEnv,
1162        symbol: I::Symbol,
1163    ) -> bool {
1164        may_use_unstable_feature(&**self.delegate, param_env, symbol)
1165    }
1166}
1167
1168/// Eagerly replace aliases with inference variables, emitting `AliasRelate`
1169/// goals, used when adding goals to the `EvalCtxt`. We compute the
1170/// `AliasRelate` goals before evaluating the actual goal to get all the
1171/// constraints we can.
1172///
1173/// This is a performance optimization to more eagerly detect cycles during trait
1174/// solving. See tests/ui/traits/next-solver/cycles/cycle-modulo-ambig-aliases.rs.
1175///
1176/// The emitted goals get evaluated in the context of the parent goal; by
1177/// replacing aliases in nested goals we essentially pull the normalization out of
1178/// the nested goal. We want to treat the goal as if the normalization still happens
1179/// inside of the nested goal by inheriting the `step_kind` of the nested goal and
1180/// storing it in the `GoalSource` of the emitted `AliasRelate` goals.
1181/// This is necessary for tests/ui/sized/coinductive-1.rs to compile.
1182struct ReplaceAliasWithInfer<'me, 'a, D, I>
1183where
1184    D: SolverDelegate<Interner = I>,
1185    I: Interner,
1186{
1187    ecx: &'me mut EvalCtxt<'a, D>,
1188    param_env: I::ParamEnv,
1189    normalization_goal_source: GoalSource,
1190    cache: HashMap<I::Ty, I::Ty>,
1191}
1192
1193impl<'me, 'a, D, I> ReplaceAliasWithInfer<'me, 'a, D, I>
1194where
1195    D: SolverDelegate<Interner = I>,
1196    I: Interner,
1197{
1198    fn new(
1199        ecx: &'me mut EvalCtxt<'a, D>,
1200        for_goal_source: GoalSource,
1201        param_env: I::ParamEnv,
1202    ) -> Self {
1203        let step_kind = ecx.step_kind_for_source(for_goal_source);
1204        ReplaceAliasWithInfer {
1205            ecx,
1206            param_env,
1207            normalization_goal_source: GoalSource::NormalizeGoal(step_kind),
1208            cache: Default::default(),
1209        }
1210    }
1211}
1212
1213impl<D, I> TypeFolder<I> for ReplaceAliasWithInfer<'_, '_, D, I>
1214where
1215    D: SolverDelegate<Interner = I>,
1216    I: Interner,
1217{
1218    fn cx(&self) -> I {
1219        self.ecx.cx()
1220    }
1221
1222    fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1223        match ty.kind() {
1224            ty::Alias(..) if !ty.has_escaping_bound_vars() => {
1225                let infer_ty = self.ecx.next_ty_infer();
1226                let normalizes_to = ty::PredicateKind::AliasRelate(
1227                    ty.into(),
1228                    infer_ty.into(),
1229                    ty::AliasRelationDirection::Equate,
1230                );
1231                self.ecx.add_goal(
1232                    self.normalization_goal_source,
1233                    Goal::new(self.cx(), self.param_env, normalizes_to),
1234                );
1235                infer_ty
1236            }
1237            _ => {
1238                if !ty.has_aliases() {
1239                    ty
1240                } else if let Some(&entry) = self.cache.get(&ty) {
1241                    return entry;
1242                } else {
1243                    let res = ty.super_fold_with(self);
1244                    assert!(self.cache.insert(ty, res).is_none());
1245                    res
1246                }
1247            }
1248        }
1249    }
1250
1251    fn fold_const(&mut self, ct: I::Const) -> I::Const {
1252        match ct.kind() {
1253            ty::ConstKind::Unevaluated(..) if !ct.has_escaping_bound_vars() => {
1254                let infer_ct = self.ecx.next_const_infer();
1255                let normalizes_to = ty::PredicateKind::AliasRelate(
1256                    ct.into(),
1257                    infer_ct.into(),
1258                    ty::AliasRelationDirection::Equate,
1259                );
1260                self.ecx.add_goal(
1261                    self.normalization_goal_source,
1262                    Goal::new(self.cx(), self.param_env, normalizes_to),
1263                );
1264                infer_ct
1265            }
1266            _ => ct.super_fold_with(self),
1267        }
1268    }
1269
1270    fn fold_predicate(&mut self, predicate: I::Predicate) -> I::Predicate {
1271        if predicate.allow_normalization() { predicate.super_fold_with(self) } else { predicate }
1272    }
1273}
1274
1275/// Do not call this directly, use the `tcx` query instead.
1276pub fn evaluate_root_goal_for_proof_tree_raw_provider<
1277    D: SolverDelegate<Interner = I>,
1278    I: Interner,
1279>(
1280    cx: I,
1281    canonical_goal: CanonicalInput<I>,
1282) -> (QueryResult<I>, I::Probe) {
1283    let mut inspect = inspect::ProofTreeBuilder::new();
1284    let canonical_result = SearchGraph::<D>::evaluate_root_goal_for_proof_tree(
1285        cx,
1286        cx.recursion_limit(),
1287        canonical_goal,
1288        &mut inspect,
1289    );
1290    let final_revision = inspect.unwrap();
1291    (canonical_result, cx.mk_probe(final_revision))
1292}
1293
1294/// Evaluate a goal to build a proof tree.
1295///
1296/// This is a copy of [EvalCtxt::evaluate_goal_raw] which avoids relying on the
1297/// [EvalCtxt] and uses a separate cache.
1298pub(super) fn evaluate_root_goal_for_proof_tree<D: SolverDelegate<Interner = I>, I: Interner>(
1299    delegate: &D,
1300    goal: Goal<I, I::Predicate>,
1301    origin_span: I::Span,
1302) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
1303    let opaque_types = delegate.clone_opaque_types_lookup_table();
1304    let (goal, opaque_types) = eager_resolve_vars(delegate, (goal, opaque_types));
1305
1306    let (orig_values, canonical_goal) = EvalCtxt::canonicalize_goal(delegate, goal, opaque_types);
1307
1308    let (canonical_result, final_revision) =
1309        delegate.cx().evaluate_root_goal_for_proof_tree_raw(canonical_goal);
1310
1311    let proof_tree = inspect::GoalEvaluation {
1312        uncanonicalized_goal: goal,
1313        orig_values,
1314        final_revision,
1315        result: canonical_result,
1316    };
1317
1318    let response = match canonical_result {
1319        Err(e) => return (Err(e), proof_tree),
1320        Ok(response) => response,
1321    };
1322
1323    let (normalization_nested_goals, _certainty) = EvalCtxt::instantiate_and_apply_query_response(
1324        delegate,
1325        goal.param_env,
1326        &proof_tree.orig_values,
1327        response,
1328        origin_span,
1329    );
1330
1331    (Ok(normalization_nested_goals), proof_tree)
1332}