1use std::mem;
2use std::ops::ControlFlow;
3
4#[cfg(feature = "nightly")]
5use rustc_macros::HashStable_NoContext;
6use rustc_type_ir::data_structures::{HashMap, HashSet};
7use rustc_type_ir::inherent::*;
8use rustc_type_ir::relate::Relate;
9use rustc_type_ir::relate::solver_relating::RelateExt;
10use rustc_type_ir::search_graph::{CandidateHeadUsages, PathKind};
11use rustc_type_ir::{
12 self as ty, CanonicalVarValues, InferCtxtLike, Interner, TypeFoldable, TypeFolder,
13 TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
14 TypingMode,
15};
16use tracing::{debug, instrument, trace};
17
18use super::has_only_region_constraints;
19use crate::coherence;
20use crate::delegate::SolverDelegate;
21use crate::placeholder::BoundVarReplacer;
22use crate::resolve::eager_resolve_vars;
23use crate::solve::search_graph::SearchGraph;
24use crate::solve::ty::may_use_unstable_feature;
25use crate::solve::{
26 CanonicalInput, Certainty, FIXPOINT_STEP_LIMIT, Goal, GoalEvaluation, GoalSource,
27 GoalStalledOn, HasChanged, NestedNormalizationGoals, NoSolution, QueryInput, QueryResult,
28 inspect,
29};
30
31pub(super) mod canonical;
32mod probe;
33
34#[derive(Debug, Copy, Clone)]
39enum CurrentGoalKind {
40 Misc,
41 CoinductiveTrait,
46 NormalizesTo,
54}
55
56impl CurrentGoalKind {
57 fn from_query_input<I: Interner>(cx: I, input: QueryInput<I, I::Predicate>) -> CurrentGoalKind {
58 match input.goal.predicate.kind().skip_binder() {
59 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
60 if cx.trait_is_coinductive(pred.trait_ref.def_id) {
61 CurrentGoalKind::CoinductiveTrait
62 } else {
63 CurrentGoalKind::Misc
64 }
65 }
66 ty::PredicateKind::NormalizesTo(_) => CurrentGoalKind::NormalizesTo,
67 _ => CurrentGoalKind::Misc,
68 }
69 }
70}
71
72pub struct EvalCtxt<'a, D, I = <D as SolverDelegate>::Interner>
73where
74 D: SolverDelegate<Interner = I>,
75 I: Interner,
76{
77 delegate: &'a D,
93
94 variables: I::CanonicalVarKinds,
97
98 current_goal_kind: CurrentGoalKind,
101 pub(super) var_values: CanonicalVarValues<I>,
102
103 pub(super) max_input_universe: ty::UniverseIndex,
113 pub(super) initial_opaque_types_storage_num_entries:
116 <D::Infcx as InferCtxtLike>::OpaqueTypeStorageEntries,
117
118 pub(super) search_graph: &'a mut SearchGraph<D>,
119
120 nested_goals: Vec<(GoalSource, Goal<I, I::Predicate>, Option<GoalStalledOn<I>>)>,
121
122 pub(super) origin_span: I::Span,
123
124 tainted: Result<(), NoSolution>,
131
132 pub(super) inspect: inspect::EvaluationStepBuilder<D>,
133}
134
135#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
136#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
137pub enum GenerateProofTree {
138 Yes,
139 No,
140}
141
142pub trait SolverDelegateEvalExt: SolverDelegate {
143 fn evaluate_root_goal(
148 &self,
149 goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
150 span: <Self::Interner as Interner>::Span,
151 stalled_on: Option<GoalStalledOn<Self::Interner>>,
152 ) -> Result<GoalEvaluation<Self::Interner>, NoSolution>;
153
154 fn root_goal_may_hold_with_depth(
162 &self,
163 root_depth: usize,
164 goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
165 ) -> bool;
166
167 fn evaluate_root_goal_for_proof_tree(
170 &self,
171 goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
172 span: <Self::Interner as Interner>::Span,
173 ) -> (
174 Result<NestedNormalizationGoals<Self::Interner>, NoSolution>,
175 inspect::GoalEvaluation<Self::Interner>,
176 );
177}
178
179impl<D, I> SolverDelegateEvalExt for D
180where
181 D: SolverDelegate<Interner = I>,
182 I: Interner,
183{
184 #[instrument(level = "debug", skip(self))]
185 fn evaluate_root_goal(
186 &self,
187 goal: Goal<I, I::Predicate>,
188 span: I::Span,
189 stalled_on: Option<GoalStalledOn<I>>,
190 ) -> Result<GoalEvaluation<I>, NoSolution> {
191 EvalCtxt::enter_root(self, self.cx().recursion_limit(), span, |ecx| {
192 ecx.evaluate_goal(GoalSource::Misc, goal, stalled_on)
193 })
194 }
195
196 fn root_goal_may_hold_with_depth(
197 &self,
198 root_depth: usize,
199 goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
200 ) -> bool {
201 self.probe(|| {
202 EvalCtxt::enter_root(self, root_depth, I::Span::dummy(), |ecx| {
203 ecx.evaluate_goal(GoalSource::Misc, goal, None)
204 })
205 })
206 .is_ok()
207 }
208
209 #[instrument(level = "debug", skip(self))]
210 fn evaluate_root_goal_for_proof_tree(
211 &self,
212 goal: Goal<I, I::Predicate>,
213 span: I::Span,
214 ) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
215 evaluate_root_goal_for_proof_tree(self, goal, span)
216 }
217}
218
219impl<'a, D, I> EvalCtxt<'a, D>
220where
221 D: SolverDelegate<Interner = I>,
222 I: Interner,
223{
224 pub(super) fn typing_mode(&self) -> TypingMode<I> {
225 self.delegate.typing_mode()
226 }
227
228 pub(super) fn step_kind_for_source(&self, source: GoalSource) -> PathKind {
237 match source {
238 GoalSource::Misc => PathKind::Unknown,
246 GoalSource::NormalizeGoal(path_kind) => path_kind,
247 GoalSource::ImplWhereBound => match self.current_goal_kind {
248 CurrentGoalKind::CoinductiveTrait => PathKind::Coinductive,
251 CurrentGoalKind::NormalizesTo => PathKind::Inductive,
259 CurrentGoalKind::Misc => PathKind::Unknown,
263 },
264 GoalSource::TypeRelating => PathKind::Inductive,
268 GoalSource::InstantiateHigherRanked => PathKind::Inductive,
271 GoalSource::AliasBoundConstCondition | GoalSource::AliasWellFormed => PathKind::Unknown,
275 }
276 }
277
278 pub(super) fn enter_root<R>(
282 delegate: &D,
283 root_depth: usize,
284 origin_span: I::Span,
285 f: impl FnOnce(&mut EvalCtxt<'_, D>) -> R,
286 ) -> R {
287 let mut search_graph = SearchGraph::new(root_depth);
288
289 let mut ecx = EvalCtxt {
290 delegate,
291 search_graph: &mut search_graph,
292 nested_goals: Default::default(),
293 inspect: inspect::EvaluationStepBuilder::new_noop(),
294
295 max_input_universe: ty::UniverseIndex::ROOT,
298 initial_opaque_types_storage_num_entries: Default::default(),
299 variables: Default::default(),
300 var_values: CanonicalVarValues::dummy(),
301 current_goal_kind: CurrentGoalKind::Misc,
302 origin_span,
303 tainted: Ok(()),
304 };
305 let result = f(&mut ecx);
306 assert!(
307 ecx.nested_goals.is_empty(),
308 "root `EvalCtxt` should not have any goals added to it"
309 );
310 assert!(search_graph.is_empty());
311 result
312 }
313
314 pub(super) fn enter_canonical<R>(
322 cx: I,
323 search_graph: &'a mut SearchGraph<D>,
324 canonical_input: CanonicalInput<I>,
325 proof_tree_builder: &mut inspect::ProofTreeBuilder<D>,
326 f: impl FnOnce(&mut EvalCtxt<'_, D>, Goal<I, I::Predicate>) -> R,
327 ) -> R {
328 let (ref delegate, input, var_values) = D::build_with_canonical(cx, &canonical_input);
329 for &(key, ty) in &input.predefined_opaques_in_body.opaque_types {
330 let prev = delegate.register_hidden_type_in_storage(key, ty, I::Span::dummy());
331 if let Some(prev) = prev {
343 debug!(?key, ?ty, ?prev, "ignore duplicate in `opaque_types_storage`");
344 }
345 }
346
347 let initial_opaque_types_storage_num_entries = delegate.opaque_types_storage_num_entries();
348 let mut ecx = EvalCtxt {
349 delegate,
350 variables: canonical_input.canonical.variables,
351 var_values,
352 current_goal_kind: CurrentGoalKind::from_query_input(cx, input),
353 max_input_universe: canonical_input.canonical.max_universe,
354 initial_opaque_types_storage_num_entries,
355 search_graph,
356 nested_goals: Default::default(),
357 origin_span: I::Span::dummy(),
358 tainted: Ok(()),
359 inspect: proof_tree_builder.new_evaluation_step(var_values),
360 };
361
362 let result = f(&mut ecx, input.goal);
363 ecx.inspect.probe_final_state(ecx.delegate, ecx.max_input_universe);
364 proof_tree_builder.finish_evaluation_step(ecx.inspect);
365
366 delegate.reset_opaque_types();
372
373 result
374 }
375
376 pub(super) fn ignore_candidate_head_usages(&mut self, usages: CandidateHeadUsages) {
377 self.search_graph.ignore_candidate_head_usages(usages);
378 }
379
380 fn evaluate_goal(
383 &mut self,
384 source: GoalSource,
385 goal: Goal<I, I::Predicate>,
386 stalled_on: Option<GoalStalledOn<I>>,
387 ) -> Result<GoalEvaluation<I>, NoSolution> {
388 let (normalization_nested_goals, goal_evaluation) =
389 self.evaluate_goal_raw(source, goal, stalled_on)?;
390 assert!(normalization_nested_goals.is_empty());
391 Ok(goal_evaluation)
392 }
393
394 pub(super) fn evaluate_goal_raw(
402 &mut self,
403 source: GoalSource,
404 goal: Goal<I, I::Predicate>,
405 stalled_on: Option<GoalStalledOn<I>>,
406 ) -> Result<(NestedNormalizationGoals<I>, GoalEvaluation<I>), NoSolution> {
407 if let Some(stalled_on) = stalled_on
411 && !stalled_on.stalled_vars.iter().any(|value| self.delegate.is_changed_arg(*value))
412 && !self
413 .delegate
414 .opaque_types_storage_num_entries()
415 .needs_reevaluation(stalled_on.num_opaques)
416 {
417 return Ok((
418 NestedNormalizationGoals::empty(),
419 GoalEvaluation {
420 goal,
421 certainty: Certainty::Maybe(stalled_on.stalled_cause),
422 has_changed: HasChanged::No,
423 stalled_on: Some(stalled_on),
424 },
425 ));
426 }
427
428 let opaque_types = self.delegate.clone_opaque_types_lookup_table();
432 let (goal, opaque_types) = eager_resolve_vars(self.delegate, (goal, opaque_types));
433
434 let (orig_values, canonical_goal) =
435 Self::canonicalize_goal(self.delegate, goal, opaque_types);
436 let canonical_result = self.search_graph.evaluate_goal(
437 self.cx(),
438 canonical_goal,
439 self.step_kind_for_source(source),
440 &mut inspect::ProofTreeBuilder::new_noop(),
441 );
442 let response = match canonical_result {
443 Err(e) => return Err(e),
444 Ok(response) => response,
445 };
446
447 let has_changed =
448 if !has_only_region_constraints(response) { HasChanged::Yes } else { HasChanged::No };
449
450 let (normalization_nested_goals, certainty) = Self::instantiate_and_apply_query_response(
451 self.delegate,
452 goal.param_env,
453 &orig_values,
454 response,
455 self.origin_span,
456 );
457
458 let stalled_on = match certainty {
469 Certainty::Yes => None,
470 Certainty::Maybe(stalled_cause) => match has_changed {
471 HasChanged::Yes => None,
476 HasChanged::No => {
477 let mut stalled_vars = orig_values;
478
479 stalled_vars.retain(|arg| match arg.kind() {
481 ty::GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Infer(_)),
482 ty::GenericArgKind::Const(ct) => {
483 matches!(ct.kind(), ty::ConstKind::Infer(_))
484 }
485 ty::GenericArgKind::Lifetime(_) => false,
487 });
488
489 if let Some(normalizes_to) = goal.predicate.as_normalizes_to() {
491 let normalizes_to = normalizes_to.skip_binder();
492 let rhs_arg: I::GenericArg = normalizes_to.term.into();
493 let idx = stalled_vars
494 .iter()
495 .rposition(|arg| *arg == rhs_arg)
496 .expect("expected unconstrained arg");
497 stalled_vars.swap_remove(idx);
498 }
499
500 Some(GoalStalledOn {
501 num_opaques: canonical_goal
502 .canonical
503 .value
504 .predefined_opaques_in_body
505 .opaque_types
506 .len(),
507 stalled_vars,
508 stalled_cause,
509 })
510 }
511 },
512 };
513
514 Ok((
515 normalization_nested_goals,
516 GoalEvaluation { goal, certainty, has_changed, stalled_on },
517 ))
518 }
519
520 pub(super) fn compute_goal(&mut self, goal: Goal<I, I::Predicate>) -> QueryResult<I> {
521 let Goal { param_env, predicate } = goal;
522 let kind = predicate.kind();
523 if let Some(kind) = kind.no_bound_vars() {
524 match kind {
525 ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
526 self.compute_trait_goal(Goal { param_env, predicate }).map(|(r, _via)| r)
527 }
528 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
529 self.compute_host_effect_goal(Goal { param_env, predicate })
530 }
531 ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) => {
532 self.compute_projection_goal(Goal { param_env, predicate })
533 }
534 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(predicate)) => {
535 self.compute_type_outlives_goal(Goal { param_env, predicate })
536 }
537 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(predicate)) => {
538 self.compute_region_outlives_goal(Goal { param_env, predicate })
539 }
540 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
541 self.compute_const_arg_has_type_goal(Goal { param_env, predicate: (ct, ty) })
542 }
543 ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
544 self.compute_unstable_feature_goal(param_env, symbol)
545 }
546 ty::PredicateKind::Subtype(predicate) => {
547 self.compute_subtype_goal(Goal { param_env, predicate })
548 }
549 ty::PredicateKind::Coerce(predicate) => {
550 self.compute_coerce_goal(Goal { param_env, predicate })
551 }
552 ty::PredicateKind::DynCompatible(trait_def_id) => {
553 self.compute_dyn_compatible_goal(trait_def_id)
554 }
555 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
556 self.compute_well_formed_goal(Goal { param_env, predicate: term })
557 }
558 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => {
559 self.compute_const_evaluatable_goal(Goal { param_env, predicate: ct })
560 }
561 ty::PredicateKind::ConstEquate(_, _) => {
562 panic!("ConstEquate should not be emitted when `-Znext-solver` is active")
563 }
564 ty::PredicateKind::NormalizesTo(predicate) => {
565 self.compute_normalizes_to_goal(Goal { param_env, predicate })
566 }
567 ty::PredicateKind::AliasRelate(lhs, rhs, direction) => self
568 .compute_alias_relate_goal(Goal {
569 param_env,
570 predicate: (lhs, rhs, direction),
571 }),
572 ty::PredicateKind::Ambiguous => {
573 self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
574 }
575 }
576 } else {
577 self.enter_forall(kind, |ecx, kind| {
578 let goal = goal.with(ecx.cx(), ty::Binder::dummy(kind));
579 ecx.add_goal(GoalSource::InstantiateHigherRanked, goal);
580 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
581 })
582 }
583 }
584
585 #[instrument(level = "trace", skip(self))]
588 pub(super) fn try_evaluate_added_goals(&mut self) -> Result<Certainty, NoSolution> {
589 let mut response = Ok(Certainty::overflow(false));
590 for _ in 0..FIXPOINT_STEP_LIMIT {
591 match self.evaluate_added_goals_step() {
594 Ok(Some(cert)) => {
595 response = Ok(cert);
596 break;
597 }
598 Ok(None) => {}
599 Err(NoSolution) => {
600 response = Err(NoSolution);
601 break;
602 }
603 }
604 }
605
606 if response.is_err() {
607 self.tainted = Err(NoSolution);
608 }
609
610 response
611 }
612
613 fn evaluate_added_goals_step(&mut self) -> Result<Option<Certainty>, NoSolution> {
617 let cx = self.cx();
618 let mut unchanged_certainty = Some(Certainty::Yes);
620 for (source, goal, stalled_on) in mem::take(&mut self.nested_goals) {
621 if let Some(certainty) = self.delegate.compute_goal_fast_path(goal, self.origin_span) {
622 match certainty {
623 Certainty::Yes => {}
624 Certainty::Maybe(_) => {
625 self.nested_goals.push((source, goal, None));
626 unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
627 }
628 }
629 continue;
630 }
631
632 if let Some(pred) = goal.predicate.as_normalizes_to() {
643 let pred = pred.no_bound_vars().unwrap();
645 let unconstrained_rhs = self.next_term_infer_of_kind(pred.term);
648 let unconstrained_goal =
649 goal.with(cx, ty::NormalizesTo { alias: pred.alias, term: unconstrained_rhs });
650
651 let (
652 NestedNormalizationGoals(nested_goals),
653 GoalEvaluation { goal, certainty, stalled_on, has_changed: _ },
654 ) = self.evaluate_goal_raw(source, unconstrained_goal, stalled_on)?;
655 trace!(?nested_goals);
657 self.nested_goals.extend(nested_goals.into_iter().map(|(s, g)| (s, g, None)));
658
659 self.eq_structurally_relating_aliases(
674 goal.param_env,
675 pred.term,
676 unconstrained_rhs,
677 )?;
678
679 let with_resolved_vars = self.resolve_vars_if_possible(goal);
686 if pred.alias
687 != with_resolved_vars
688 .predicate
689 .as_normalizes_to()
690 .unwrap()
691 .no_bound_vars()
692 .unwrap()
693 .alias
694 {
695 unchanged_certainty = None;
696 }
697
698 match certainty {
699 Certainty::Yes => {}
700 Certainty::Maybe(_) => {
701 self.nested_goals.push((source, with_resolved_vars, stalled_on));
702 unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
703 }
704 }
705 } else {
706 let GoalEvaluation { goal, certainty, has_changed, stalled_on } =
707 self.evaluate_goal(source, goal, stalled_on)?;
708 if has_changed == HasChanged::Yes {
709 unchanged_certainty = None;
710 }
711
712 match certainty {
713 Certainty::Yes => {}
714 Certainty::Maybe(_) => {
715 self.nested_goals.push((source, goal, stalled_on));
716 unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
717 }
718 }
719 }
720 }
721
722 Ok(unchanged_certainty)
723 }
724
725 pub(crate) fn record_impl_args(&mut self, impl_args: I::GenericArgs) {
727 self.inspect.record_impl_args(self.delegate, self.max_input_universe, impl_args)
728 }
729
730 pub(super) fn cx(&self) -> I {
731 self.delegate.cx()
732 }
733
734 #[instrument(level = "debug", skip(self))]
735 pub(super) fn add_goal(&mut self, source: GoalSource, mut goal: Goal<I, I::Predicate>) {
736 goal.predicate =
737 goal.predicate.fold_with(&mut ReplaceAliasWithInfer::new(self, source, goal.param_env));
738 self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
739 self.nested_goals.push((source, goal, None));
740 }
741
742 #[instrument(level = "trace", skip(self, goals))]
743 pub(super) fn add_goals(
744 &mut self,
745 source: GoalSource,
746 goals: impl IntoIterator<Item = Goal<I, I::Predicate>>,
747 ) {
748 for goal in goals {
749 self.add_goal(source, goal);
750 }
751 }
752
753 pub(super) fn next_region_var(&mut self) -> I::Region {
754 let region = self.delegate.next_region_infer();
755 self.inspect.add_var_value(region);
756 region
757 }
758
759 pub(super) fn next_ty_infer(&mut self) -> I::Ty {
760 let ty = self.delegate.next_ty_infer();
761 self.inspect.add_var_value(ty);
762 ty
763 }
764
765 pub(super) fn next_const_infer(&mut self) -> I::Const {
766 let ct = self.delegate.next_const_infer();
767 self.inspect.add_var_value(ct);
768 ct
769 }
770
771 pub(super) fn next_term_infer_of_kind(&mut self, term: I::Term) -> I::Term {
774 match term.kind() {
775 ty::TermKind::Ty(_) => self.next_ty_infer().into(),
776 ty::TermKind::Const(_) => self.next_const_infer().into(),
777 }
778 }
779
780 #[instrument(level = "trace", skip(self), ret)]
785 pub(super) fn term_is_fully_unconstrained(&self, goal: Goal<I, ty::NormalizesTo<I>>) -> bool {
786 let universe_of_term = match goal.predicate.term.kind() {
787 ty::TermKind::Ty(ty) => {
788 if let ty::Infer(ty::TyVar(vid)) = ty.kind() {
789 self.delegate.universe_of_ty(vid).unwrap()
790 } else {
791 return false;
792 }
793 }
794 ty::TermKind::Const(ct) => {
795 if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
796 self.delegate.universe_of_ct(vid).unwrap()
797 } else {
798 return false;
799 }
800 }
801 };
802
803 struct ContainsTermOrNotNameable<'a, D: SolverDelegate<Interner = I>, I: Interner> {
804 term: I::Term,
805 universe_of_term: ty::UniverseIndex,
806 delegate: &'a D,
807 cache: HashSet<I::Ty>,
808 }
809
810 impl<D: SolverDelegate<Interner = I>, I: Interner> ContainsTermOrNotNameable<'_, D, I> {
811 fn check_nameable(&self, universe: ty::UniverseIndex) -> ControlFlow<()> {
812 if self.universe_of_term.can_name(universe) {
813 ControlFlow::Continue(())
814 } else {
815 ControlFlow::Break(())
816 }
817 }
818 }
819
820 impl<D: SolverDelegate<Interner = I>, I: Interner> TypeVisitor<I>
821 for ContainsTermOrNotNameable<'_, D, I>
822 {
823 type Result = ControlFlow<()>;
824 fn visit_ty(&mut self, t: I::Ty) -> Self::Result {
825 if self.cache.contains(&t) {
826 return ControlFlow::Continue(());
827 }
828
829 match t.kind() {
830 ty::Infer(ty::TyVar(vid)) => {
831 if let ty::TermKind::Ty(term) = self.term.kind()
832 && let ty::Infer(ty::TyVar(term_vid)) = term.kind()
833 && self.delegate.root_ty_var(vid) == self.delegate.root_ty_var(term_vid)
834 {
835 return ControlFlow::Break(());
836 }
837
838 self.check_nameable(self.delegate.universe_of_ty(vid).unwrap())?;
839 }
840 ty::Placeholder(p) => self.check_nameable(p.universe())?,
841 _ => {
842 if t.has_non_region_infer() || t.has_placeholders() {
843 t.super_visit_with(self)?
844 }
845 }
846 }
847
848 assert!(self.cache.insert(t));
849 ControlFlow::Continue(())
850 }
851
852 fn visit_const(&mut self, c: I::Const) -> Self::Result {
853 match c.kind() {
854 ty::ConstKind::Infer(ty::InferConst::Var(vid)) => {
855 if let ty::TermKind::Const(term) = self.term.kind()
856 && let ty::ConstKind::Infer(ty::InferConst::Var(term_vid)) = term.kind()
857 && self.delegate.root_const_var(vid)
858 == self.delegate.root_const_var(term_vid)
859 {
860 return ControlFlow::Break(());
861 }
862
863 self.check_nameable(self.delegate.universe_of_ct(vid).unwrap())
864 }
865 ty::ConstKind::Placeholder(p) => self.check_nameable(p.universe()),
866 _ => {
867 if c.has_non_region_infer() || c.has_placeholders() {
868 c.super_visit_with(self)
869 } else {
870 ControlFlow::Continue(())
871 }
872 }
873 }
874 }
875
876 fn visit_predicate(&mut self, p: I::Predicate) -> Self::Result {
877 if p.has_non_region_infer() || p.has_placeholders() {
878 p.super_visit_with(self)
879 } else {
880 ControlFlow::Continue(())
881 }
882 }
883
884 fn visit_clauses(&mut self, c: I::Clauses) -> Self::Result {
885 if c.has_non_region_infer() || c.has_placeholders() {
886 c.super_visit_with(self)
887 } else {
888 ControlFlow::Continue(())
889 }
890 }
891 }
892
893 let mut visitor = ContainsTermOrNotNameable {
894 delegate: self.delegate,
895 universe_of_term,
896 term: goal.predicate.term,
897 cache: Default::default(),
898 };
899 goal.predicate.alias.visit_with(&mut visitor).is_continue()
900 && goal.param_env.visit_with(&mut visitor).is_continue()
901 }
902
903 pub(super) fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
904 self.delegate.sub_unify_ty_vids_raw(a, b)
905 }
906
907 #[instrument(level = "trace", skip(self, param_env), ret)]
908 pub(super) fn eq<T: Relate<I>>(
909 &mut self,
910 param_env: I::ParamEnv,
911 lhs: T,
912 rhs: T,
913 ) -> Result<(), NoSolution> {
914 self.relate(param_env, lhs, ty::Variance::Invariant, rhs)
915 }
916
917 #[instrument(level = "trace", skip(self, param_env), ret)]
923 pub(super) fn relate_rigid_alias_non_alias(
924 &mut self,
925 param_env: I::ParamEnv,
926 alias: ty::AliasTerm<I>,
927 variance: ty::Variance,
928 term: I::Term,
929 ) -> Result<(), NoSolution> {
930 if term.is_infer() {
933 let cx = self.cx();
934 let identity_args = self.fresh_args_for_item(alias.def_id);
943 let rigid_ctor = ty::AliasTerm::new_from_args(cx, alias.def_id, identity_args);
944 let ctor_term = rigid_ctor.to_term(cx);
945 let obligations = self.delegate.eq_structurally_relating_aliases(
946 param_env,
947 term,
948 ctor_term,
949 self.origin_span,
950 )?;
951 debug_assert!(obligations.is_empty());
952 self.relate(param_env, alias, variance, rigid_ctor)
953 } else {
954 Err(NoSolution)
955 }
956 }
957
958 #[instrument(level = "trace", skip(self, param_env), ret)]
962 pub(super) fn eq_structurally_relating_aliases<T: Relate<I>>(
963 &mut self,
964 param_env: I::ParamEnv,
965 lhs: T,
966 rhs: T,
967 ) -> Result<(), NoSolution> {
968 let result = self.delegate.eq_structurally_relating_aliases(
969 param_env,
970 lhs,
971 rhs,
972 self.origin_span,
973 )?;
974 assert_eq!(result, vec![]);
975 Ok(())
976 }
977
978 #[instrument(level = "trace", skip(self, param_env), ret)]
979 pub(super) fn sub<T: Relate<I>>(
980 &mut self,
981 param_env: I::ParamEnv,
982 sub: T,
983 sup: T,
984 ) -> Result<(), NoSolution> {
985 self.relate(param_env, sub, ty::Variance::Covariant, sup)
986 }
987
988 #[instrument(level = "trace", skip(self, param_env), ret)]
989 pub(super) fn relate<T: Relate<I>>(
990 &mut self,
991 param_env: I::ParamEnv,
992 lhs: T,
993 variance: ty::Variance,
994 rhs: T,
995 ) -> Result<(), NoSolution> {
996 let goals = self.delegate.relate(param_env, lhs, variance, rhs, self.origin_span)?;
997 for &goal in goals.iter() {
998 let source = match goal.predicate.kind().skip_binder() {
999 ty::PredicateKind::Subtype { .. } | ty::PredicateKind::AliasRelate(..) => {
1000 GoalSource::TypeRelating
1001 }
1002 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => GoalSource::Misc,
1004 p => unreachable!("unexpected nested goal in `relate`: {p:?}"),
1005 };
1006 self.add_goal(source, goal);
1007 }
1008 Ok(())
1009 }
1010
1011 #[instrument(level = "trace", skip(self, param_env), ret)]
1017 pub(super) fn eq_and_get_goals<T: Relate<I>>(
1018 &self,
1019 param_env: I::ParamEnv,
1020 lhs: T,
1021 rhs: T,
1022 ) -> Result<Vec<Goal<I, I::Predicate>>, NoSolution> {
1023 Ok(self.delegate.relate(param_env, lhs, ty::Variance::Invariant, rhs, self.origin_span)?)
1024 }
1025
1026 pub(super) fn instantiate_binder_with_infer<T: TypeFoldable<I> + Copy>(
1027 &self,
1028 value: ty::Binder<I, T>,
1029 ) -> T {
1030 self.delegate.instantiate_binder_with_infer(value)
1031 }
1032
1033 pub(super) fn enter_forall<T: TypeFoldable<I>, U>(
1036 &mut self,
1037 value: ty::Binder<I, T>,
1038 f: impl FnOnce(&mut Self, T) -> U,
1039 ) -> U {
1040 self.delegate.enter_forall(value, |value| f(self, value))
1041 }
1042
1043 pub(super) fn resolve_vars_if_possible<T>(&self, value: T) -> T
1044 where
1045 T: TypeFoldable<I>,
1046 {
1047 self.delegate.resolve_vars_if_possible(value)
1048 }
1049
1050 pub(super) fn eager_resolve_region(&self, r: I::Region) -> I::Region {
1051 if let ty::ReVar(vid) = r.kind() {
1052 self.delegate.opportunistic_resolve_lt_var(vid)
1053 } else {
1054 r
1055 }
1056 }
1057
1058 pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
1059 let args = self.delegate.fresh_args_for_item(def_id);
1060 for arg in args.iter() {
1061 self.inspect.add_var_value(arg);
1062 }
1063 args
1064 }
1065
1066 pub(super) fn register_ty_outlives(&self, ty: I::Ty, lt: I::Region) {
1067 self.delegate.register_ty_outlives(ty, lt, self.origin_span);
1068 }
1069
1070 pub(super) fn register_region_outlives(&self, a: I::Region, b: I::Region) {
1071 self.delegate.sub_regions(b, a, self.origin_span);
1073 }
1074
1075 pub(super) fn well_formed_goals(
1077 &self,
1078 param_env: I::ParamEnv,
1079 term: I::Term,
1080 ) -> Option<Vec<Goal<I, I::Predicate>>> {
1081 self.delegate.well_formed_goals(param_env, term)
1082 }
1083
1084 pub(super) fn trait_ref_is_knowable(
1085 &mut self,
1086 param_env: I::ParamEnv,
1087 trait_ref: ty::TraitRef<I>,
1088 ) -> Result<bool, NoSolution> {
1089 let delegate = self.delegate;
1090 let lazily_normalize_ty = |ty| self.structurally_normalize_ty(param_env, ty);
1091 coherence::trait_ref_is_knowable(&**delegate, trait_ref, lazily_normalize_ty)
1092 .map(|is_knowable| is_knowable.is_ok())
1093 }
1094
1095 pub(super) fn fetch_eligible_assoc_item(
1096 &self,
1097 goal_trait_ref: ty::TraitRef<I>,
1098 trait_assoc_def_id: I::DefId,
1099 impl_def_id: I::ImplId,
1100 ) -> Result<Option<I::DefId>, I::ErrorGuaranteed> {
1101 self.delegate.fetch_eligible_assoc_item(goal_trait_ref, trait_assoc_def_id, impl_def_id)
1102 }
1103
1104 #[instrument(level = "debug", skip(self), ret)]
1105 pub(super) fn register_hidden_type_in_storage(
1106 &mut self,
1107 opaque_type_key: ty::OpaqueTypeKey<I>,
1108 hidden_ty: I::Ty,
1109 ) -> Option<I::Ty> {
1110 self.delegate.register_hidden_type_in_storage(opaque_type_key, hidden_ty, self.origin_span)
1111 }
1112
1113 pub(super) fn add_item_bounds_for_hidden_type(
1114 &mut self,
1115 opaque_def_id: I::DefId,
1116 opaque_args: I::GenericArgs,
1117 param_env: I::ParamEnv,
1118 hidden_ty: I::Ty,
1119 ) {
1120 let mut goals = Vec::new();
1121 self.delegate.add_item_bounds_for_hidden_type(
1122 opaque_def_id,
1123 opaque_args,
1124 param_env,
1125 hidden_ty,
1126 &mut goals,
1127 );
1128 self.add_goals(GoalSource::AliasWellFormed, goals);
1129 }
1130
1131 pub(super) fn evaluate_const(
1135 &self,
1136 param_env: I::ParamEnv,
1137 uv: ty::UnevaluatedConst<I>,
1138 ) -> Option<I::Const> {
1139 self.delegate.evaluate_const(param_env, uv)
1140 }
1141
1142 pub(super) fn is_transmutable(
1143 &mut self,
1144 dst: I::Ty,
1145 src: I::Ty,
1146 assume: I::Const,
1147 ) -> Result<Certainty, NoSolution> {
1148 self.delegate.is_transmutable(dst, src, assume)
1149 }
1150
1151 pub(super) fn replace_bound_vars<T: TypeFoldable<I>>(
1152 &self,
1153 t: T,
1154 universes: &mut Vec<Option<ty::UniverseIndex>>,
1155 ) -> T {
1156 BoundVarReplacer::replace_bound_vars(&**self.delegate, universes, t).0
1157 }
1158
1159 pub(super) fn may_use_unstable_feature(
1160 &self,
1161 param_env: I::ParamEnv,
1162 symbol: I::Symbol,
1163 ) -> bool {
1164 may_use_unstable_feature(&**self.delegate, param_env, symbol)
1165 }
1166}
1167
1168struct ReplaceAliasWithInfer<'me, 'a, D, I>
1183where
1184 D: SolverDelegate<Interner = I>,
1185 I: Interner,
1186{
1187 ecx: &'me mut EvalCtxt<'a, D>,
1188 param_env: I::ParamEnv,
1189 normalization_goal_source: GoalSource,
1190 cache: HashMap<I::Ty, I::Ty>,
1191}
1192
1193impl<'me, 'a, D, I> ReplaceAliasWithInfer<'me, 'a, D, I>
1194where
1195 D: SolverDelegate<Interner = I>,
1196 I: Interner,
1197{
1198 fn new(
1199 ecx: &'me mut EvalCtxt<'a, D>,
1200 for_goal_source: GoalSource,
1201 param_env: I::ParamEnv,
1202 ) -> Self {
1203 let step_kind = ecx.step_kind_for_source(for_goal_source);
1204 ReplaceAliasWithInfer {
1205 ecx,
1206 param_env,
1207 normalization_goal_source: GoalSource::NormalizeGoal(step_kind),
1208 cache: Default::default(),
1209 }
1210 }
1211}
1212
1213impl<D, I> TypeFolder<I> for ReplaceAliasWithInfer<'_, '_, D, I>
1214where
1215 D: SolverDelegate<Interner = I>,
1216 I: Interner,
1217{
1218 fn cx(&self) -> I {
1219 self.ecx.cx()
1220 }
1221
1222 fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1223 match ty.kind() {
1224 ty::Alias(..) if !ty.has_escaping_bound_vars() => {
1225 let infer_ty = self.ecx.next_ty_infer();
1226 let normalizes_to = ty::PredicateKind::AliasRelate(
1227 ty.into(),
1228 infer_ty.into(),
1229 ty::AliasRelationDirection::Equate,
1230 );
1231 self.ecx.add_goal(
1232 self.normalization_goal_source,
1233 Goal::new(self.cx(), self.param_env, normalizes_to),
1234 );
1235 infer_ty
1236 }
1237 _ => {
1238 if !ty.has_aliases() {
1239 ty
1240 } else if let Some(&entry) = self.cache.get(&ty) {
1241 return entry;
1242 } else {
1243 let res = ty.super_fold_with(self);
1244 assert!(self.cache.insert(ty, res).is_none());
1245 res
1246 }
1247 }
1248 }
1249 }
1250
1251 fn fold_const(&mut self, ct: I::Const) -> I::Const {
1252 match ct.kind() {
1253 ty::ConstKind::Unevaluated(..) if !ct.has_escaping_bound_vars() => {
1254 let infer_ct = self.ecx.next_const_infer();
1255 let normalizes_to = ty::PredicateKind::AliasRelate(
1256 ct.into(),
1257 infer_ct.into(),
1258 ty::AliasRelationDirection::Equate,
1259 );
1260 self.ecx.add_goal(
1261 self.normalization_goal_source,
1262 Goal::new(self.cx(), self.param_env, normalizes_to),
1263 );
1264 infer_ct
1265 }
1266 _ => ct.super_fold_with(self),
1267 }
1268 }
1269
1270 fn fold_predicate(&mut self, predicate: I::Predicate) -> I::Predicate {
1271 if predicate.allow_normalization() { predicate.super_fold_with(self) } else { predicate }
1272 }
1273}
1274
1275pub fn evaluate_root_goal_for_proof_tree_raw_provider<
1277 D: SolverDelegate<Interner = I>,
1278 I: Interner,
1279>(
1280 cx: I,
1281 canonical_goal: CanonicalInput<I>,
1282) -> (QueryResult<I>, I::Probe) {
1283 let mut inspect = inspect::ProofTreeBuilder::new();
1284 let canonical_result = SearchGraph::<D>::evaluate_root_goal_for_proof_tree(
1285 cx,
1286 cx.recursion_limit(),
1287 canonical_goal,
1288 &mut inspect,
1289 );
1290 let final_revision = inspect.unwrap();
1291 (canonical_result, cx.mk_probe(final_revision))
1292}
1293
1294pub(super) fn evaluate_root_goal_for_proof_tree<D: SolverDelegate<Interner = I>, I: Interner>(
1299 delegate: &D,
1300 goal: Goal<I, I::Predicate>,
1301 origin_span: I::Span,
1302) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
1303 let opaque_types = delegate.clone_opaque_types_lookup_table();
1304 let (goal, opaque_types) = eager_resolve_vars(delegate, (goal, opaque_types));
1305
1306 let (orig_values, canonical_goal) = EvalCtxt::canonicalize_goal(delegate, goal, opaque_types);
1307
1308 let (canonical_result, final_revision) =
1309 delegate.cx().evaluate_root_goal_for_proof_tree_raw(canonical_goal);
1310
1311 let proof_tree = inspect::GoalEvaluation {
1312 uncanonicalized_goal: goal,
1313 orig_values,
1314 final_revision,
1315 result: canonical_result,
1316 };
1317
1318 let response = match canonical_result {
1319 Err(e) => return (Err(e), proof_tree),
1320 Ok(response) => response,
1321 };
1322
1323 let (normalization_nested_goals, _certainty) = EvalCtxt::instantiate_and_apply_query_response(
1324 delegate,
1325 goal.param_env,
1326 &proof_tree.orig_values,
1327 response,
1328 origin_span,
1329 );
1330
1331 (Ok(normalization_nested_goals), proof_tree)
1332}