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 #[instrument(level = "trace", skip(self, param_env), ret)]
904 pub(super) fn eq<T: Relate<I>>(
905 &mut self,
906 param_env: I::ParamEnv,
907 lhs: T,
908 rhs: T,
909 ) -> Result<(), NoSolution> {
910 self.relate(param_env, lhs, ty::Variance::Invariant, rhs)
911 }
912
913 #[instrument(level = "trace", skip(self, param_env), ret)]
919 pub(super) fn relate_rigid_alias_non_alias(
920 &mut self,
921 param_env: I::ParamEnv,
922 alias: ty::AliasTerm<I>,
923 variance: ty::Variance,
924 term: I::Term,
925 ) -> Result<(), NoSolution> {
926 if term.is_infer() {
929 let cx = self.cx();
930 let identity_args = self.fresh_args_for_item(alias.def_id);
939 let rigid_ctor = ty::AliasTerm::new_from_args(cx, alias.def_id, identity_args);
940 let ctor_term = rigid_ctor.to_term(cx);
941 let obligations = self.delegate.eq_structurally_relating_aliases(
942 param_env,
943 term,
944 ctor_term,
945 self.origin_span,
946 )?;
947 debug_assert!(obligations.is_empty());
948 self.relate(param_env, alias, variance, rigid_ctor)
949 } else {
950 Err(NoSolution)
951 }
952 }
953
954 #[instrument(level = "trace", skip(self, param_env), ret)]
958 pub(super) fn eq_structurally_relating_aliases<T: Relate<I>>(
959 &mut self,
960 param_env: I::ParamEnv,
961 lhs: T,
962 rhs: T,
963 ) -> Result<(), NoSolution> {
964 let result = self.delegate.eq_structurally_relating_aliases(
965 param_env,
966 lhs,
967 rhs,
968 self.origin_span,
969 )?;
970 assert_eq!(result, vec![]);
971 Ok(())
972 }
973
974 #[instrument(level = "trace", skip(self, param_env), ret)]
975 pub(super) fn sub<T: Relate<I>>(
976 &mut self,
977 param_env: I::ParamEnv,
978 sub: T,
979 sup: T,
980 ) -> Result<(), NoSolution> {
981 self.relate(param_env, sub, ty::Variance::Covariant, sup)
982 }
983
984 #[instrument(level = "trace", skip(self, param_env), ret)]
985 pub(super) fn relate<T: Relate<I>>(
986 &mut self,
987 param_env: I::ParamEnv,
988 lhs: T,
989 variance: ty::Variance,
990 rhs: T,
991 ) -> Result<(), NoSolution> {
992 let goals = self.delegate.relate(param_env, lhs, variance, rhs, self.origin_span)?;
993 for &goal in goals.iter() {
994 let source = match goal.predicate.kind().skip_binder() {
995 ty::PredicateKind::Subtype { .. } | ty::PredicateKind::AliasRelate(..) => {
996 GoalSource::TypeRelating
997 }
998 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => GoalSource::Misc,
1000 p => unreachable!("unexpected nested goal in `relate`: {p:?}"),
1001 };
1002 self.add_goal(source, goal);
1003 }
1004 Ok(())
1005 }
1006
1007 #[instrument(level = "trace", skip(self, param_env), ret)]
1013 pub(super) fn eq_and_get_goals<T: Relate<I>>(
1014 &self,
1015 param_env: I::ParamEnv,
1016 lhs: T,
1017 rhs: T,
1018 ) -> Result<Vec<Goal<I, I::Predicate>>, NoSolution> {
1019 Ok(self.delegate.relate(param_env, lhs, ty::Variance::Invariant, rhs, self.origin_span)?)
1020 }
1021
1022 pub(super) fn instantiate_binder_with_infer<T: TypeFoldable<I> + Copy>(
1023 &self,
1024 value: ty::Binder<I, T>,
1025 ) -> T {
1026 self.delegate.instantiate_binder_with_infer(value)
1027 }
1028
1029 pub(super) fn enter_forall<T: TypeFoldable<I>, U>(
1032 &mut self,
1033 value: ty::Binder<I, T>,
1034 f: impl FnOnce(&mut Self, T) -> U,
1035 ) -> U {
1036 self.delegate.enter_forall(value, |value| f(self, value))
1037 }
1038
1039 pub(super) fn resolve_vars_if_possible<T>(&self, value: T) -> T
1040 where
1041 T: TypeFoldable<I>,
1042 {
1043 self.delegate.resolve_vars_if_possible(value)
1044 }
1045
1046 pub(super) fn eager_resolve_region(&self, r: I::Region) -> I::Region {
1047 if let ty::ReVar(vid) = r.kind() {
1048 self.delegate.opportunistic_resolve_lt_var(vid)
1049 } else {
1050 r
1051 }
1052 }
1053
1054 pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
1055 let args = self.delegate.fresh_args_for_item(def_id);
1056 for arg in args.iter() {
1057 self.inspect.add_var_value(arg);
1058 }
1059 args
1060 }
1061
1062 pub(super) fn register_ty_outlives(&self, ty: I::Ty, lt: I::Region) {
1063 self.delegate.register_ty_outlives(ty, lt, self.origin_span);
1064 }
1065
1066 pub(super) fn register_region_outlives(&self, a: I::Region, b: I::Region) {
1067 self.delegate.sub_regions(b, a, self.origin_span);
1069 }
1070
1071 pub(super) fn well_formed_goals(
1073 &self,
1074 param_env: I::ParamEnv,
1075 term: I::Term,
1076 ) -> Option<Vec<Goal<I, I::Predicate>>> {
1077 self.delegate.well_formed_goals(param_env, term)
1078 }
1079
1080 pub(super) fn trait_ref_is_knowable(
1081 &mut self,
1082 param_env: I::ParamEnv,
1083 trait_ref: ty::TraitRef<I>,
1084 ) -> Result<bool, NoSolution> {
1085 let delegate = self.delegate;
1086 let lazily_normalize_ty = |ty| self.structurally_normalize_ty(param_env, ty);
1087 coherence::trait_ref_is_knowable(&**delegate, trait_ref, lazily_normalize_ty)
1088 .map(|is_knowable| is_knowable.is_ok())
1089 }
1090
1091 pub(super) fn fetch_eligible_assoc_item(
1092 &self,
1093 goal_trait_ref: ty::TraitRef<I>,
1094 trait_assoc_def_id: I::DefId,
1095 impl_def_id: I::DefId,
1096 ) -> Result<Option<I::DefId>, I::ErrorGuaranteed> {
1097 self.delegate.fetch_eligible_assoc_item(goal_trait_ref, trait_assoc_def_id, impl_def_id)
1098 }
1099
1100 #[instrument(level = "debug", skip(self), ret)]
1101 pub(super) fn register_hidden_type_in_storage(
1102 &mut self,
1103 opaque_type_key: ty::OpaqueTypeKey<I>,
1104 hidden_ty: I::Ty,
1105 ) -> Option<I::Ty> {
1106 self.delegate.register_hidden_type_in_storage(opaque_type_key, hidden_ty, self.origin_span)
1107 }
1108
1109 pub(super) fn add_item_bounds_for_hidden_type(
1110 &mut self,
1111 opaque_def_id: I::DefId,
1112 opaque_args: I::GenericArgs,
1113 param_env: I::ParamEnv,
1114 hidden_ty: I::Ty,
1115 ) {
1116 let mut goals = Vec::new();
1117 self.delegate.add_item_bounds_for_hidden_type(
1118 opaque_def_id,
1119 opaque_args,
1120 param_env,
1121 hidden_ty,
1122 &mut goals,
1123 );
1124 self.add_goals(GoalSource::AliasWellFormed, goals);
1125 }
1126
1127 pub(super) fn evaluate_const(
1131 &self,
1132 param_env: I::ParamEnv,
1133 uv: ty::UnevaluatedConst<I>,
1134 ) -> Option<I::Const> {
1135 self.delegate.evaluate_const(param_env, uv)
1136 }
1137
1138 pub(super) fn is_transmutable(
1139 &mut self,
1140 dst: I::Ty,
1141 src: I::Ty,
1142 assume: I::Const,
1143 ) -> Result<Certainty, NoSolution> {
1144 self.delegate.is_transmutable(dst, src, assume)
1145 }
1146
1147 pub(super) fn replace_bound_vars<T: TypeFoldable<I>>(
1148 &self,
1149 t: T,
1150 universes: &mut Vec<Option<ty::UniverseIndex>>,
1151 ) -> T {
1152 BoundVarReplacer::replace_bound_vars(&**self.delegate, universes, t).0
1153 }
1154
1155 pub(super) fn may_use_unstable_feature(
1156 &self,
1157 param_env: I::ParamEnv,
1158 symbol: I::Symbol,
1159 ) -> bool {
1160 may_use_unstable_feature(&**self.delegate, param_env, symbol)
1161 }
1162}
1163
1164struct ReplaceAliasWithInfer<'me, 'a, D, I>
1179where
1180 D: SolverDelegate<Interner = I>,
1181 I: Interner,
1182{
1183 ecx: &'me mut EvalCtxt<'a, D>,
1184 param_env: I::ParamEnv,
1185 normalization_goal_source: GoalSource,
1186 cache: HashMap<I::Ty, I::Ty>,
1187}
1188
1189impl<'me, 'a, D, I> ReplaceAliasWithInfer<'me, 'a, D, I>
1190where
1191 D: SolverDelegate<Interner = I>,
1192 I: Interner,
1193{
1194 fn new(
1195 ecx: &'me mut EvalCtxt<'a, D>,
1196 for_goal_source: GoalSource,
1197 param_env: I::ParamEnv,
1198 ) -> Self {
1199 let step_kind = ecx.step_kind_for_source(for_goal_source);
1200 ReplaceAliasWithInfer {
1201 ecx,
1202 param_env,
1203 normalization_goal_source: GoalSource::NormalizeGoal(step_kind),
1204 cache: Default::default(),
1205 }
1206 }
1207}
1208
1209impl<D, I> TypeFolder<I> for ReplaceAliasWithInfer<'_, '_, D, I>
1210where
1211 D: SolverDelegate<Interner = I>,
1212 I: Interner,
1213{
1214 fn cx(&self) -> I {
1215 self.ecx.cx()
1216 }
1217
1218 fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1219 match ty.kind() {
1220 ty::Alias(..) if !ty.has_escaping_bound_vars() => {
1221 let infer_ty = self.ecx.next_ty_infer();
1222 let normalizes_to = ty::PredicateKind::AliasRelate(
1223 ty.into(),
1224 infer_ty.into(),
1225 ty::AliasRelationDirection::Equate,
1226 );
1227 self.ecx.add_goal(
1228 self.normalization_goal_source,
1229 Goal::new(self.cx(), self.param_env, normalizes_to),
1230 );
1231 infer_ty
1232 }
1233 _ => {
1234 if !ty.has_aliases() {
1235 ty
1236 } else if let Some(&entry) = self.cache.get(&ty) {
1237 return entry;
1238 } else {
1239 let res = ty.super_fold_with(self);
1240 assert!(self.cache.insert(ty, res).is_none());
1241 res
1242 }
1243 }
1244 }
1245 }
1246
1247 fn fold_const(&mut self, ct: I::Const) -> I::Const {
1248 match ct.kind() {
1249 ty::ConstKind::Unevaluated(..) if !ct.has_escaping_bound_vars() => {
1250 let infer_ct = self.ecx.next_const_infer();
1251 let normalizes_to = ty::PredicateKind::AliasRelate(
1252 ct.into(),
1253 infer_ct.into(),
1254 ty::AliasRelationDirection::Equate,
1255 );
1256 self.ecx.add_goal(
1257 self.normalization_goal_source,
1258 Goal::new(self.cx(), self.param_env, normalizes_to),
1259 );
1260 infer_ct
1261 }
1262 _ => ct.super_fold_with(self),
1263 }
1264 }
1265
1266 fn fold_predicate(&mut self, predicate: I::Predicate) -> I::Predicate {
1267 if predicate.allow_normalization() { predicate.super_fold_with(self) } else { predicate }
1268 }
1269}
1270
1271pub fn evaluate_root_goal_for_proof_tree_raw_provider<
1273 D: SolverDelegate<Interner = I>,
1274 I: Interner,
1275>(
1276 cx: I,
1277 canonical_goal: CanonicalInput<I>,
1278) -> (QueryResult<I>, I::Probe) {
1279 let mut inspect = inspect::ProofTreeBuilder::new();
1280 let canonical_result = SearchGraph::<D>::evaluate_root_goal_for_proof_tree(
1281 cx,
1282 cx.recursion_limit(),
1283 canonical_goal,
1284 &mut inspect,
1285 );
1286 let final_revision = inspect.unwrap();
1287 (canonical_result, cx.mk_probe(final_revision))
1288}
1289
1290pub(super) fn evaluate_root_goal_for_proof_tree<D: SolverDelegate<Interner = I>, I: Interner>(
1295 delegate: &D,
1296 goal: Goal<I, I::Predicate>,
1297 origin_span: I::Span,
1298) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
1299 let opaque_types = delegate.clone_opaque_types_lookup_table();
1300 let (goal, opaque_types) = eager_resolve_vars(delegate, (goal, opaque_types));
1301
1302 let (orig_values, canonical_goal) = EvalCtxt::canonicalize_goal(delegate, goal, opaque_types);
1303
1304 let (canonical_result, final_revision) =
1305 delegate.cx().evaluate_root_goal_for_proof_tree_raw(canonical_goal);
1306
1307 let proof_tree = inspect::GoalEvaluation {
1308 uncanonicalized_goal: goal,
1309 orig_values,
1310 final_revision,
1311 result: canonical_result,
1312 };
1313
1314 let response = match canonical_result {
1315 Err(e) => return (Err(e), proof_tree),
1316 Ok(response) => response,
1317 };
1318
1319 let (normalization_nested_goals, _certainty) = EvalCtxt::instantiate_and_apply_query_response(
1320 delegate,
1321 goal.param_env,
1322 &proof_tree.orig_values,
1323 response,
1324 origin_span,
1325 );
1326
1327 (Ok(normalization_nested_goals), proof_tree)
1328}