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