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 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 let stalled_on = match certainty {
498 Certainty::Yes => None,
499 Certainty::Maybe(stalled_cause) => match has_changed {
500 HasChanged::Yes => None,
505 HasChanged::No => {
506 let mut stalled_vars = orig_values;
507
508 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 ty::GenericArgKind::Lifetime(_) => false,
516 });
517
518 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 #[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 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 fn evaluate_added_goals_step(&mut self) -> Result<Option<Certainty>, NoSolution> {
646 let cx = self.cx();
647 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 if let Some(pred) = goal.predicate.as_normalizes_to() {
672 let pred = pred.no_bound_vars().unwrap();
674 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 trace!(?nested_goals);
691 self.nested_goals.extend(nested_goals.into_iter().map(|(s, g)| (s, g, None)));
692
693 self.eq_structurally_relating_aliases(
708 goal.param_env,
709 pred.term,
710 unconstrained_rhs,
711 )?;
712
713 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 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 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 #[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 #[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 if term.is_infer() {
963 let cx = self.cx();
964 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 #[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 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 #[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 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 self.delegate.sub_regions(b, a, self.origin_span);
1103 }
1104
1105 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 pub(super) fn probe_existing_opaque_ty(
1163 &mut self,
1164 key: ty::OpaqueTypeKey<I>,
1165 ) -> Option<(ty::OpaqueTypeKey<I>, I::Ty)> {
1166 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 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
1220struct 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}