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#[derive(Debug, Copy, Clone)]
41enum CurrentGoalKind {
42 Misc,
43 CoinductiveTrait,
48 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 delegate: &'a D,
95
96 variables: I::CanonicalVarKinds,
99
100 current_goal_kind: CurrentGoalKind,
103 pub(super) var_values: CanonicalVarValues<I>,
104
105 pub(super) max_input_universe: ty::UniverseIndex,
115 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 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 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 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 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 pub(super) fn step_kind_for_source(&self, source: GoalSource) -> PathKind {
258 match source {
259 GoalSource::Misc => PathKind::Unknown,
267 GoalSource::NormalizeGoal(path_kind) => path_kind,
268 GoalSource::ImplWhereBound => match self.current_goal_kind {
269 CurrentGoalKind::CoinductiveTrait => PathKind::Coinductive,
272 CurrentGoalKind::NormalizesTo => PathKind::Inductive,
280 CurrentGoalKind::Misc => PathKind::Unknown,
284 },
285 GoalSource::TypeRelating => PathKind::Inductive,
289 GoalSource::InstantiateHigherRanked => PathKind::Inductive,
292 GoalSource::AliasBoundConstCondition | GoalSource::AliasWellFormed => PathKind::Unknown,
296 }
297 }
298
299 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 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 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 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 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 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 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 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 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 (orig_values, canonical_goal) = self.canonicalize_goal(goal, opaque_types);
463 let mut goal_evaluation =
464 self.inspect.new_goal_evaluation(goal, &orig_values, goal_evaluation_kind);
465 let canonical_result = self.search_graph.evaluate_goal(
466 self.cx(),
467 canonical_goal,
468 self.step_kind_for_source(source),
469 &mut goal_evaluation,
470 );
471 goal_evaluation.query_result(canonical_result);
472 self.inspect.goal_evaluation(goal_evaluation);
473 let response = match canonical_result {
474 Err(e) => return Err(e),
475 Ok(response) => response,
476 };
477
478 let has_changed =
479 if !has_only_region_constraints(response) { HasChanged::Yes } else { HasChanged::No };
480
481 let (normalization_nested_goals, certainty) =
482 self.instantiate_and_apply_query_response(goal.param_env, &orig_values, response);
483
484 let stalled_on = match certainty {
495 Certainty::Yes => None,
496 Certainty::Maybe(stalled_cause) => match has_changed {
497 HasChanged::Yes => None,
502 HasChanged::No => {
503 let mut stalled_vars = orig_values;
504
505 stalled_vars.retain(|arg| match arg.kind() {
507 ty::GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Infer(_)),
508 ty::GenericArgKind::Const(ct) => {
509 matches!(ct.kind(), ty::ConstKind::Infer(_))
510 }
511 ty::GenericArgKind::Lifetime(_) => false,
513 });
514
515 if let Some(normalizes_to) = goal.predicate.as_normalizes_to() {
517 let normalizes_to = normalizes_to.skip_binder();
518 let rhs_arg: I::GenericArg = normalizes_to.term.into();
519 let idx = stalled_vars
520 .iter()
521 .rposition(|arg| *arg == rhs_arg)
522 .expect("expected unconstrained arg");
523 stalled_vars.swap_remove(idx);
524 }
525
526 Some(GoalStalledOn {
527 num_opaques: canonical_goal
528 .canonical
529 .value
530 .predefined_opaques_in_body
531 .opaque_types
532 .len(),
533 stalled_vars,
534 stalled_cause,
535 })
536 }
537 },
538 };
539
540 Ok((
541 normalization_nested_goals,
542 GoalEvaluation { goal, certainty, has_changed, stalled_on },
543 ))
544 }
545
546 pub(super) fn compute_goal(&mut self, goal: Goal<I, I::Predicate>) -> QueryResult<I> {
547 let Goal { param_env, predicate } = goal;
548 let kind = predicate.kind();
549 if let Some(kind) = kind.no_bound_vars() {
550 match kind {
551 ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
552 self.compute_trait_goal(Goal { param_env, predicate }).map(|(r, _via)| r)
553 }
554 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
555 self.compute_host_effect_goal(Goal { param_env, predicate })
556 }
557 ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) => {
558 self.compute_projection_goal(Goal { param_env, predicate })
559 }
560 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(predicate)) => {
561 self.compute_type_outlives_goal(Goal { param_env, predicate })
562 }
563 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(predicate)) => {
564 self.compute_region_outlives_goal(Goal { param_env, predicate })
565 }
566 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
567 self.compute_const_arg_has_type_goal(Goal { param_env, predicate: (ct, ty) })
568 }
569 ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
570 self.compute_unstable_feature_goal(param_env, symbol)
571 }
572 ty::PredicateKind::Subtype(predicate) => {
573 self.compute_subtype_goal(Goal { param_env, predicate })
574 }
575 ty::PredicateKind::Coerce(predicate) => {
576 self.compute_coerce_goal(Goal { param_env, predicate })
577 }
578 ty::PredicateKind::DynCompatible(trait_def_id) => {
579 self.compute_dyn_compatible_goal(trait_def_id)
580 }
581 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
582 self.compute_well_formed_goal(Goal { param_env, predicate: term })
583 }
584 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => {
585 self.compute_const_evaluatable_goal(Goal { param_env, predicate: ct })
586 }
587 ty::PredicateKind::ConstEquate(_, _) => {
588 panic!("ConstEquate should not be emitted when `-Znext-solver` is active")
589 }
590 ty::PredicateKind::NormalizesTo(predicate) => {
591 self.compute_normalizes_to_goal(Goal { param_env, predicate })
592 }
593 ty::PredicateKind::AliasRelate(lhs, rhs, direction) => self
594 .compute_alias_relate_goal(Goal {
595 param_env,
596 predicate: (lhs, rhs, direction),
597 }),
598 ty::PredicateKind::Ambiguous => {
599 self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
600 }
601 }
602 } else {
603 self.enter_forall(kind, |ecx, kind| {
604 let goal = goal.with(ecx.cx(), ty::Binder::dummy(kind));
605 ecx.add_goal(GoalSource::InstantiateHigherRanked, goal);
606 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
607 })
608 }
609 }
610
611 #[instrument(level = "trace", skip(self))]
614 pub(super) fn try_evaluate_added_goals(&mut self) -> Result<Certainty, NoSolution> {
615 let mut response = Ok(Certainty::overflow(false));
616 for _ in 0..FIXPOINT_STEP_LIMIT {
617 match self.evaluate_added_goals_step() {
620 Ok(Some(cert)) => {
621 response = Ok(cert);
622 break;
623 }
624 Ok(None) => {}
625 Err(NoSolution) => {
626 response = Err(NoSolution);
627 break;
628 }
629 }
630 }
631
632 if response.is_err() {
633 self.tainted = Err(NoSolution);
634 }
635
636 response
637 }
638
639 fn evaluate_added_goals_step(&mut self) -> Result<Option<Certainty>, NoSolution> {
643 let cx = self.cx();
644 let mut unchanged_certainty = Some(Certainty::Yes);
646 for (source, goal, stalled_on) in mem::take(&mut self.nested_goals) {
647 if let Some(certainty) = self.delegate.compute_goal_fast_path(goal, self.origin_span) {
648 match certainty {
649 Certainty::Yes => {}
650 Certainty::Maybe(_) => {
651 self.nested_goals.push((source, goal, None));
652 unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
653 }
654 }
655 continue;
656 }
657
658 if let Some(pred) = goal.predicate.as_normalizes_to() {
669 let pred = pred.no_bound_vars().unwrap();
671 let unconstrained_rhs = self.next_term_infer_of_kind(pred.term);
674 let unconstrained_goal =
675 goal.with(cx, ty::NormalizesTo { alias: pred.alias, term: unconstrained_rhs });
676
677 let (
678 NestedNormalizationGoals(nested_goals),
679 GoalEvaluation { goal, certainty, stalled_on, has_changed: _ },
680 ) = self.evaluate_goal_raw(
681 GoalEvaluationKind::Nested,
682 source,
683 unconstrained_goal,
684 stalled_on,
685 )?;
686 trace!(?nested_goals);
688 self.nested_goals.extend(nested_goals.into_iter().map(|(s, g)| (s, g, None)));
689
690 self.eq_structurally_relating_aliases(
705 goal.param_env,
706 pred.term,
707 unconstrained_rhs,
708 )?;
709
710 let with_resolved_vars = self.resolve_vars_if_possible(goal);
717 if pred.alias
718 != with_resolved_vars
719 .predicate
720 .as_normalizes_to()
721 .unwrap()
722 .no_bound_vars()
723 .unwrap()
724 .alias
725 {
726 unchanged_certainty = None;
727 }
728
729 match certainty {
730 Certainty::Yes => {}
731 Certainty::Maybe(_) => {
732 self.nested_goals.push((source, with_resolved_vars, stalled_on));
733 unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
734 }
735 }
736 } else {
737 let GoalEvaluation { goal, certainty, has_changed, stalled_on } =
738 self.evaluate_goal(GoalEvaluationKind::Nested, source, goal, stalled_on)?;
739 if has_changed == HasChanged::Yes {
740 unchanged_certainty = None;
741 }
742
743 match certainty {
744 Certainty::Yes => {}
745 Certainty::Maybe(_) => {
746 self.nested_goals.push((source, goal, stalled_on));
747 unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
748 }
749 }
750 }
751 }
752
753 Ok(unchanged_certainty)
754 }
755
756 pub(crate) fn record_impl_args(&mut self, impl_args: I::GenericArgs) {
758 self.inspect.record_impl_args(self.delegate, self.max_input_universe, impl_args)
759 }
760
761 pub(super) fn cx(&self) -> I {
762 self.delegate.cx()
763 }
764
765 #[instrument(level = "debug", skip(self))]
766 pub(super) fn add_goal(&mut self, source: GoalSource, mut goal: Goal<I, I::Predicate>) {
767 goal.predicate =
768 goal.predicate.fold_with(&mut ReplaceAliasWithInfer::new(self, source, goal.param_env));
769 self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
770 self.nested_goals.push((source, goal, None));
771 }
772
773 #[instrument(level = "trace", skip(self, goals))]
774 pub(super) fn add_goals(
775 &mut self,
776 source: GoalSource,
777 goals: impl IntoIterator<Item = Goal<I, I::Predicate>>,
778 ) {
779 for goal in goals {
780 self.add_goal(source, goal);
781 }
782 }
783
784 pub(super) fn next_region_var(&mut self) -> I::Region {
785 let region = self.delegate.next_region_infer();
786 self.inspect.add_var_value(region);
787 region
788 }
789
790 pub(super) fn next_ty_infer(&mut self) -> I::Ty {
791 let ty = self.delegate.next_ty_infer();
792 self.inspect.add_var_value(ty);
793 ty
794 }
795
796 pub(super) fn next_const_infer(&mut self) -> I::Const {
797 let ct = self.delegate.next_const_infer();
798 self.inspect.add_var_value(ct);
799 ct
800 }
801
802 pub(super) fn next_term_infer_of_kind(&mut self, term: I::Term) -> I::Term {
805 match term.kind() {
806 ty::TermKind::Ty(_) => self.next_ty_infer().into(),
807 ty::TermKind::Const(_) => self.next_const_infer().into(),
808 }
809 }
810
811 #[instrument(level = "trace", skip(self), ret)]
816 pub(super) fn term_is_fully_unconstrained(&self, goal: Goal<I, ty::NormalizesTo<I>>) -> bool {
817 let universe_of_term = match goal.predicate.term.kind() {
818 ty::TermKind::Ty(ty) => {
819 if let ty::Infer(ty::TyVar(vid)) = ty.kind() {
820 self.delegate.universe_of_ty(vid).unwrap()
821 } else {
822 return false;
823 }
824 }
825 ty::TermKind::Const(ct) => {
826 if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
827 self.delegate.universe_of_ct(vid).unwrap()
828 } else {
829 return false;
830 }
831 }
832 };
833
834 struct ContainsTermOrNotNameable<'a, D: SolverDelegate<Interner = I>, I: Interner> {
835 term: I::Term,
836 universe_of_term: ty::UniverseIndex,
837 delegate: &'a D,
838 cache: HashSet<I::Ty>,
839 }
840
841 impl<D: SolverDelegate<Interner = I>, I: Interner> ContainsTermOrNotNameable<'_, D, I> {
842 fn check_nameable(&self, universe: ty::UniverseIndex) -> ControlFlow<()> {
843 if self.universe_of_term.can_name(universe) {
844 ControlFlow::Continue(())
845 } else {
846 ControlFlow::Break(())
847 }
848 }
849 }
850
851 impl<D: SolverDelegate<Interner = I>, I: Interner> TypeVisitor<I>
852 for ContainsTermOrNotNameable<'_, D, I>
853 {
854 type Result = ControlFlow<()>;
855 fn visit_ty(&mut self, t: I::Ty) -> Self::Result {
856 if self.cache.contains(&t) {
857 return ControlFlow::Continue(());
858 }
859
860 match t.kind() {
861 ty::Infer(ty::TyVar(vid)) => {
862 if let ty::TermKind::Ty(term) = self.term.kind()
863 && let ty::Infer(ty::TyVar(term_vid)) = term.kind()
864 && self.delegate.root_ty_var(vid) == self.delegate.root_ty_var(term_vid)
865 {
866 return ControlFlow::Break(());
867 }
868
869 self.check_nameable(self.delegate.universe_of_ty(vid).unwrap())?;
870 }
871 ty::Placeholder(p) => self.check_nameable(p.universe())?,
872 _ => {
873 if t.has_non_region_infer() || t.has_placeholders() {
874 t.super_visit_with(self)?
875 }
876 }
877 }
878
879 assert!(self.cache.insert(t));
880 ControlFlow::Continue(())
881 }
882
883 fn visit_const(&mut self, c: I::Const) -> Self::Result {
884 match c.kind() {
885 ty::ConstKind::Infer(ty::InferConst::Var(vid)) => {
886 if let ty::TermKind::Const(term) = self.term.kind()
887 && let ty::ConstKind::Infer(ty::InferConst::Var(term_vid)) = term.kind()
888 && self.delegate.root_const_var(vid)
889 == self.delegate.root_const_var(term_vid)
890 {
891 return ControlFlow::Break(());
892 }
893
894 self.check_nameable(self.delegate.universe_of_ct(vid).unwrap())
895 }
896 ty::ConstKind::Placeholder(p) => self.check_nameable(p.universe()),
897 _ => {
898 if c.has_non_region_infer() || c.has_placeholders() {
899 c.super_visit_with(self)
900 } else {
901 ControlFlow::Continue(())
902 }
903 }
904 }
905 }
906
907 fn visit_predicate(&mut self, p: I::Predicate) -> Self::Result {
908 if p.has_non_region_infer() || p.has_placeholders() {
909 p.super_visit_with(self)
910 } else {
911 ControlFlow::Continue(())
912 }
913 }
914
915 fn visit_clauses(&mut self, c: I::Clauses) -> Self::Result {
916 if c.has_non_region_infer() || c.has_placeholders() {
917 c.super_visit_with(self)
918 } else {
919 ControlFlow::Continue(())
920 }
921 }
922 }
923
924 let mut visitor = ContainsTermOrNotNameable {
925 delegate: self.delegate,
926 universe_of_term,
927 term: goal.predicate.term,
928 cache: Default::default(),
929 };
930 goal.predicate.alias.visit_with(&mut visitor).is_continue()
931 && goal.param_env.visit_with(&mut visitor).is_continue()
932 }
933
934 #[instrument(level = "trace", skip(self, param_env), ret)]
935 pub(super) fn eq<T: Relate<I>>(
936 &mut self,
937 param_env: I::ParamEnv,
938 lhs: T,
939 rhs: T,
940 ) -> Result<(), NoSolution> {
941 self.relate(param_env, lhs, ty::Variance::Invariant, rhs)
942 }
943
944 #[instrument(level = "trace", skip(self, param_env), ret)]
950 pub(super) fn relate_rigid_alias_non_alias(
951 &mut self,
952 param_env: I::ParamEnv,
953 alias: ty::AliasTerm<I>,
954 variance: ty::Variance,
955 term: I::Term,
956 ) -> Result<(), NoSolution> {
957 if term.is_infer() {
960 let cx = self.cx();
961 let identity_args = self.fresh_args_for_item(alias.def_id);
970 let rigid_ctor = ty::AliasTerm::new_from_args(cx, alias.def_id, identity_args);
971 let ctor_term = rigid_ctor.to_term(cx);
972 let obligations = self.delegate.eq_structurally_relating_aliases(
973 param_env,
974 term,
975 ctor_term,
976 self.origin_span,
977 )?;
978 debug_assert!(obligations.is_empty());
979 self.relate(param_env, alias, variance, rigid_ctor)
980 } else {
981 Err(NoSolution)
982 }
983 }
984
985 #[instrument(level = "trace", skip(self, param_env), ret)]
989 pub(super) fn eq_structurally_relating_aliases<T: Relate<I>>(
990 &mut self,
991 param_env: I::ParamEnv,
992 lhs: T,
993 rhs: T,
994 ) -> Result<(), NoSolution> {
995 let result = self.delegate.eq_structurally_relating_aliases(
996 param_env,
997 lhs,
998 rhs,
999 self.origin_span,
1000 )?;
1001 assert_eq!(result, vec![]);
1002 Ok(())
1003 }
1004
1005 #[instrument(level = "trace", skip(self, param_env), ret)]
1006 pub(super) fn sub<T: Relate<I>>(
1007 &mut self,
1008 param_env: I::ParamEnv,
1009 sub: T,
1010 sup: T,
1011 ) -> Result<(), NoSolution> {
1012 self.relate(param_env, sub, ty::Variance::Covariant, sup)
1013 }
1014
1015 #[instrument(level = "trace", skip(self, param_env), ret)]
1016 pub(super) fn relate<T: Relate<I>>(
1017 &mut self,
1018 param_env: I::ParamEnv,
1019 lhs: T,
1020 variance: ty::Variance,
1021 rhs: T,
1022 ) -> Result<(), NoSolution> {
1023 let goals = self.delegate.relate(param_env, lhs, variance, rhs, self.origin_span)?;
1024 for &goal in goals.iter() {
1025 let source = match goal.predicate.kind().skip_binder() {
1026 ty::PredicateKind::Subtype { .. } | ty::PredicateKind::AliasRelate(..) => {
1027 GoalSource::TypeRelating
1028 }
1029 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => GoalSource::Misc,
1031 p => unreachable!("unexpected nested goal in `relate`: {p:?}"),
1032 };
1033 self.add_goal(source, goal);
1034 }
1035 Ok(())
1036 }
1037
1038 #[instrument(level = "trace", skip(self, param_env), ret)]
1044 pub(super) fn eq_and_get_goals<T: Relate<I>>(
1045 &self,
1046 param_env: I::ParamEnv,
1047 lhs: T,
1048 rhs: T,
1049 ) -> Result<Vec<Goal<I, I::Predicate>>, NoSolution> {
1050 Ok(self.delegate.relate(param_env, lhs, ty::Variance::Invariant, rhs, self.origin_span)?)
1051 }
1052
1053 pub(super) fn instantiate_binder_with_infer<T: TypeFoldable<I> + Copy>(
1054 &self,
1055 value: ty::Binder<I, T>,
1056 ) -> T {
1057 self.delegate.instantiate_binder_with_infer(value)
1058 }
1059
1060 pub(super) fn enter_forall<T: TypeFoldable<I>, U>(
1063 &mut self,
1064 value: ty::Binder<I, T>,
1065 f: impl FnOnce(&mut Self, T) -> U,
1066 ) -> U {
1067 self.delegate.enter_forall(value, |value| f(self, value))
1068 }
1069
1070 pub(super) fn resolve_vars_if_possible<T>(&self, value: T) -> T
1071 where
1072 T: TypeFoldable<I>,
1073 {
1074 self.delegate.resolve_vars_if_possible(value)
1075 }
1076
1077 pub(super) fn eager_resolve_region(&self, r: I::Region) -> I::Region {
1078 if let ty::ReVar(vid) = r.kind() {
1079 self.delegate.opportunistic_resolve_lt_var(vid)
1080 } else {
1081 r
1082 }
1083 }
1084
1085 pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
1086 let args = self.delegate.fresh_args_for_item(def_id);
1087 for arg in args.iter() {
1088 self.inspect.add_var_value(arg);
1089 }
1090 args
1091 }
1092
1093 pub(super) fn register_ty_outlives(&self, ty: I::Ty, lt: I::Region) {
1094 self.delegate.register_ty_outlives(ty, lt, self.origin_span);
1095 }
1096
1097 pub(super) fn register_region_outlives(&self, a: I::Region, b: I::Region) {
1098 self.delegate.sub_regions(b, a, self.origin_span);
1100 }
1101
1102 pub(super) fn well_formed_goals(
1104 &self,
1105 param_env: I::ParamEnv,
1106 term: I::Term,
1107 ) -> Option<Vec<Goal<I, I::Predicate>>> {
1108 self.delegate.well_formed_goals(param_env, term)
1109 }
1110
1111 pub(super) fn trait_ref_is_knowable(
1112 &mut self,
1113 param_env: I::ParamEnv,
1114 trait_ref: ty::TraitRef<I>,
1115 ) -> Result<bool, NoSolution> {
1116 let delegate = self.delegate;
1117 let lazily_normalize_ty = |ty| self.structurally_normalize_ty(param_env, ty);
1118 coherence::trait_ref_is_knowable(&**delegate, trait_ref, lazily_normalize_ty)
1119 .map(|is_knowable| is_knowable.is_ok())
1120 }
1121
1122 pub(super) fn fetch_eligible_assoc_item(
1123 &self,
1124 goal_trait_ref: ty::TraitRef<I>,
1125 trait_assoc_def_id: I::DefId,
1126 impl_def_id: I::DefId,
1127 ) -> Result<Option<I::DefId>, I::ErrorGuaranteed> {
1128 self.delegate.fetch_eligible_assoc_item(goal_trait_ref, trait_assoc_def_id, impl_def_id)
1129 }
1130
1131 pub(super) fn register_hidden_type_in_storage(
1132 &mut self,
1133 opaque_type_key: ty::OpaqueTypeKey<I>,
1134 hidden_ty: I::Ty,
1135 ) -> Option<I::Ty> {
1136 self.delegate.register_hidden_type_in_storage(opaque_type_key, hidden_ty, self.origin_span)
1137 }
1138
1139 pub(super) fn add_item_bounds_for_hidden_type(
1140 &mut self,
1141 opaque_def_id: I::DefId,
1142 opaque_args: I::GenericArgs,
1143 param_env: I::ParamEnv,
1144 hidden_ty: I::Ty,
1145 ) {
1146 let mut goals = Vec::new();
1147 self.delegate.add_item_bounds_for_hidden_type(
1148 opaque_def_id,
1149 opaque_args,
1150 param_env,
1151 hidden_ty,
1152 &mut goals,
1153 );
1154 self.add_goals(GoalSource::AliasWellFormed, goals);
1155 }
1156
1157 pub(super) fn probe_existing_opaque_ty(
1160 &mut self,
1161 key: ty::OpaqueTypeKey<I>,
1162 ) -> Option<(ty::OpaqueTypeKey<I>, I::Ty)> {
1163 let duplicate_entries = self.delegate.clone_duplicate_opaque_types();
1166 assert!(duplicate_entries.is_empty(), "unexpected duplicates: {duplicate_entries:?}");
1167 let mut matching = self.delegate.clone_opaque_types_lookup_table().into_iter().filter(
1168 |(candidate_key, _)| {
1169 candidate_key.def_id == key.def_id
1170 && DeepRejectCtxt::relate_rigid_rigid(self.cx())
1171 .args_may_unify(candidate_key.args, key.args)
1172 },
1173 );
1174 let first = matching.next();
1175 let second = matching.next();
1176 assert_eq!(second, None);
1177 first
1178 }
1179
1180 pub(super) fn evaluate_const(
1184 &self,
1185 param_env: I::ParamEnv,
1186 uv: ty::UnevaluatedConst<I>,
1187 ) -> Option<I::Const> {
1188 self.delegate.evaluate_const(param_env, uv)
1189 }
1190
1191 pub(super) fn is_transmutable(
1192 &mut self,
1193 dst: I::Ty,
1194 src: I::Ty,
1195 assume: I::Const,
1196 ) -> Result<Certainty, NoSolution> {
1197 self.delegate.is_transmutable(dst, src, assume)
1198 }
1199
1200 pub(super) fn replace_bound_vars<T: TypeFoldable<I>>(
1201 &self,
1202 t: T,
1203 universes: &mut Vec<Option<ty::UniverseIndex>>,
1204 ) -> T {
1205 BoundVarReplacer::replace_bound_vars(&**self.delegate, universes, t).0
1206 }
1207
1208 pub(super) fn may_use_unstable_feature(
1209 &self,
1210 param_env: I::ParamEnv,
1211 symbol: I::Symbol,
1212 ) -> bool {
1213 may_use_unstable_feature(&**self.delegate, param_env, symbol)
1214 }
1215}
1216
1217struct ReplaceAliasWithInfer<'me, 'a, D, I>
1232where
1233 D: SolverDelegate<Interner = I>,
1234 I: Interner,
1235{
1236 ecx: &'me mut EvalCtxt<'a, D>,
1237 param_env: I::ParamEnv,
1238 normalization_goal_source: GoalSource,
1239 cache: HashMap<I::Ty, I::Ty>,
1240}
1241
1242impl<'me, 'a, D, I> ReplaceAliasWithInfer<'me, 'a, D, I>
1243where
1244 D: SolverDelegate<Interner = I>,
1245 I: Interner,
1246{
1247 fn new(
1248 ecx: &'me mut EvalCtxt<'a, D>,
1249 for_goal_source: GoalSource,
1250 param_env: I::ParamEnv,
1251 ) -> Self {
1252 let step_kind = ecx.step_kind_for_source(for_goal_source);
1253 ReplaceAliasWithInfer {
1254 ecx,
1255 param_env,
1256 normalization_goal_source: GoalSource::NormalizeGoal(step_kind),
1257 cache: Default::default(),
1258 }
1259 }
1260}
1261
1262impl<D, I> TypeFolder<I> for ReplaceAliasWithInfer<'_, '_, D, I>
1263where
1264 D: SolverDelegate<Interner = I>,
1265 I: Interner,
1266{
1267 fn cx(&self) -> I {
1268 self.ecx.cx()
1269 }
1270
1271 fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1272 match ty.kind() {
1273 ty::Alias(..) if !ty.has_escaping_bound_vars() => {
1274 let infer_ty = self.ecx.next_ty_infer();
1275 let normalizes_to = ty::PredicateKind::AliasRelate(
1276 ty.into(),
1277 infer_ty.into(),
1278 ty::AliasRelationDirection::Equate,
1279 );
1280 self.ecx.add_goal(
1281 self.normalization_goal_source,
1282 Goal::new(self.cx(), self.param_env, normalizes_to),
1283 );
1284 infer_ty
1285 }
1286 _ => {
1287 if !ty.has_aliases() {
1288 ty
1289 } else if let Some(&entry) = self.cache.get(&ty) {
1290 return entry;
1291 } else {
1292 let res = ty.super_fold_with(self);
1293 assert!(self.cache.insert(ty, res).is_none());
1294 res
1295 }
1296 }
1297 }
1298 }
1299
1300 fn fold_const(&mut self, ct: I::Const) -> I::Const {
1301 match ct.kind() {
1302 ty::ConstKind::Unevaluated(..) if !ct.has_escaping_bound_vars() => {
1303 let infer_ct = self.ecx.next_const_infer();
1304 let normalizes_to = ty::PredicateKind::AliasRelate(
1305 ct.into(),
1306 infer_ct.into(),
1307 ty::AliasRelationDirection::Equate,
1308 );
1309 self.ecx.add_goal(
1310 self.normalization_goal_source,
1311 Goal::new(self.cx(), self.param_env, normalizes_to),
1312 );
1313 infer_ct
1314 }
1315 _ => ct.super_fold_with(self),
1316 }
1317 }
1318
1319 fn fold_predicate(&mut self, predicate: I::Predicate) -> I::Predicate {
1320 if predicate.allow_normalization() { predicate.super_fold_with(self) } else { predicate }
1321 }
1322}