1 use crate::infer::{InferCtxt, TyOrConstInferVar};
2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_data_structures::obligation_forest::ProcessResult;
4 use rustc_data_structures::obligation_forest::{Error, ForestObligation, Outcome};
5 use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};
6 use rustc_errors::ErrorGuaranteed;
7 use rustc_infer::traits::ProjectionCacheKey;
8 use rustc_infer::traits::{SelectionError, TraitEngine, TraitEngineExt as _, TraitObligation};
9 use rustc_middle::mir::interpret::ErrorHandled;
10 use rustc_middle::thir::abstract_const::NotConstEvaluatable;
11 use rustc_middle::ty::error::{ExpectedFound, TypeError};
12 use rustc_middle::ty::subst::SubstsRef;
13 use rustc_middle::ty::ToPredicate;
14 use rustc_middle::ty::{self, Binder, Const, Ty, TypeFoldable};
15 use std::marker::PhantomData;
17 use super::const_evaluatable;
19 use super::select::SelectionContext;
21 use super::CodeAmbiguity;
22 use super::CodeProjectionError;
23 use super::CodeSelectionError;
24 use super::EvaluationResult;
25 use super::Unimplemented;
26 use super::{FulfillmentError, FulfillmentErrorCode};
27 use super::{ObligationCause, PredicateObligation};
29 use crate::traits::error_reporting::InferCtxtExt as _;
30 use crate::traits::project::PolyProjectionObligation;
31 use crate::traits::project::ProjectionCacheKeyExt as _;
32 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
34 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
35 /// Note that we include both the `ParamEnv` and the `Predicate`,
36 /// as the `ParamEnv` can influence whether fulfillment succeeds
38 type CacheKey = ty::ParamEnvAnd<'tcx, ty::Predicate<'tcx>>;
40 fn as_cache_key(&self) -> Self::CacheKey {
41 self.obligation.param_env.and(self.obligation.predicate)
45 /// The fulfillment context is used to drive trait resolution. It
46 /// consists of a list of obligations that must be (eventually)
47 /// satisfied. The job is to track which are satisfied, which yielded
48 /// errors, and which are still pending. At any point, users can call
49 /// `select_where_possible`, and the fulfillment context will try to do
50 /// selection, retaining only those obligations that remain
51 /// ambiguous. This may be helpful in pushing type inference
52 /// along. Once all type inference constraints have been generated, the
53 /// method `select_all_or_error` can be used to report any remaining
54 /// ambiguous cases as errors.
55 pub struct FulfillmentContext<'tcx> {
56 // A list of all obligations that have been registered with this
57 // fulfillment context.
58 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
60 relationships: FxHashMap<ty::TyVid, ty::FoundRelationships>,
62 // Should this fulfillment context register type-lives-for-region
63 // obligations on its parent infcx? In some cases, region
64 // obligations are either already known to hold (normalization) or
65 // hopefully verifed elsewhere (type-impls-bound), and therefore
66 // should not be checked.
68 // Note that if we are normalizing a type that we already
69 // know is well-formed, there should be no harm setting this
70 // to true - all the region variables should be determinable
71 // using the RFC 447 rules, which don't depend on
72 // type-lives-for-region constraints, and because the type
73 // is well-formed, the constraints should hold.
74 register_region_obligations: bool,
75 // Is it OK to register obligations into this infcx inside
78 // The "primary fulfillment" in many cases in typeck lives
79 // outside of any snapshot, so any use of it inside a snapshot
80 // will lead to trouble and therefore is checked against, but
81 // other fulfillment contexts sometimes do live inside of
82 // a snapshot (they don't *straddle* a snapshot, so there
83 // is no trouble there).
84 usable_in_snapshot: bool,
87 #[derive(Clone, Debug)]
88 pub struct PendingPredicateObligation<'tcx> {
89 pub obligation: PredicateObligation<'tcx>,
90 // This is far more often read than modified, meaning that we
91 // should mostly optimize for reading speed, while modifying is not as relevant.
93 // For whatever reason using a boxed slice is slower than using a `Vec` here.
94 pub stalled_on: Vec<TyOrConstInferVar<'tcx>>,
97 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
98 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
99 static_assert_size!(PendingPredicateObligation<'_>, 72);
101 impl<'a, 'tcx> FulfillmentContext<'tcx> {
102 /// Creates a new fulfillment context.
103 pub fn new() -> FulfillmentContext<'tcx> {
105 predicates: ObligationForest::new(),
106 relationships: FxHashMap::default(),
107 register_region_obligations: true,
108 usable_in_snapshot: false,
112 pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
114 predicates: ObligationForest::new(),
115 relationships: FxHashMap::default(),
116 register_region_obligations: true,
117 usable_in_snapshot: true,
121 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
123 predicates: ObligationForest::new(),
124 relationships: FxHashMap::default(),
125 register_region_obligations: false,
126 usable_in_snapshot: false,
130 /// Attempts to select obligations using `selcx`.
131 fn select(&mut self, selcx: &mut SelectionContext<'a, 'tcx>) -> Vec<FulfillmentError<'tcx>> {
132 let span = debug_span!("select", obligation_forest_size = ?self.predicates.len());
133 let _enter = span.enter();
135 let mut errors = Vec::new();
138 debug!("select: starting another iteration");
140 // Process pending obligations.
141 let outcome: Outcome<_, _> =
142 self.predicates.process_obligations(&mut FulfillProcessor {
144 register_region_obligations: self.register_region_obligations,
146 debug!("select: outcome={:#?}", outcome);
148 // FIXME: if we kept the original cache key, we could mark projection
149 // obligations as complete for the projection cache here.
151 errors.extend(outcome.errors.into_iter().map(to_fulfillment_error));
153 // If nothing new was added, no need to keep looping.
160 "select({} predicates remaining, {} errors) done",
161 self.predicates.len(),
169 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
170 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
171 /// creating a fresh type variable `$0` as well as a projection
172 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
173 /// inference engine runs, it will attempt to find an impl of
174 /// `SomeTrait` or a where-clause that lets us unify `$0` with
175 /// something concrete. If this fails, we'll unify `$0` with
176 /// `projection_ty` again.
177 #[tracing::instrument(level = "debug", skip(self, infcx, param_env, cause))]
178 fn normalize_projection_type(
180 infcx: &InferCtxt<'_, 'tcx>,
181 param_env: ty::ParamEnv<'tcx>,
182 projection_ty: ty::ProjectionTy<'tcx>,
183 cause: ObligationCause<'tcx>,
185 debug_assert!(!projection_ty.has_escaping_bound_vars());
187 // FIXME(#20304) -- cache
189 let mut selcx = SelectionContext::new(infcx);
190 let mut obligations = vec![];
191 let normalized_ty = project::normalize_projection_type(
199 self.register_predicate_obligations(infcx, obligations);
201 debug!(?normalized_ty);
203 normalized_ty.ty().unwrap()
206 fn register_predicate_obligation(
208 infcx: &InferCtxt<'_, 'tcx>,
209 obligation: PredicateObligation<'tcx>,
211 // this helps to reduce duplicate errors, as well as making
212 // debug output much nicer to read and so on.
213 let obligation = infcx.resolve_vars_if_possible(obligation);
215 debug!(?obligation, "register_predicate_obligation");
217 assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
219 super::relationships::update(self, infcx, &obligation);
222 .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
225 fn select_all_or_error(&mut self, infcx: &InferCtxt<'_, 'tcx>) -> Vec<FulfillmentError<'tcx>> {
227 let errors = self.select_where_possible(infcx);
228 if !errors.is_empty() {
233 self.predicates.to_errors(CodeAmbiguity).into_iter().map(to_fulfillment_error).collect()
236 fn select_where_possible(
238 infcx: &InferCtxt<'_, 'tcx>,
239 ) -> Vec<FulfillmentError<'tcx>> {
240 let mut selcx = SelectionContext::new(infcx);
241 self.select(&mut selcx)
244 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
245 self.predicates.map_pending_obligations(|o| o.obligation.clone())
248 fn relationships(&mut self) -> &mut FxHashMap<ty::TyVid, ty::FoundRelationships> {
249 &mut self.relationships
253 struct FulfillProcessor<'a, 'b, 'tcx> {
254 selcx: &'a mut SelectionContext<'b, 'tcx>,
255 register_region_obligations: bool,
258 fn mk_pending(os: Vec<PredicateObligation<'_>>) -> Vec<PendingPredicateObligation<'_>> {
260 .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
264 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
265 type Obligation = PendingPredicateObligation<'tcx>;
266 type Error = FulfillmentErrorCode<'tcx>;
268 /// Processes a predicate obligation and returns either:
269 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
270 /// - `Unchanged` if we don't have enough info to be sure
271 /// - `Error(e)` if the predicate does not hold
273 /// This is always inlined, despite its size, because it has a single
274 /// callsite and it is called *very* frequently.
276 fn process_obligation(
278 pending_obligation: &mut Self::Obligation,
279 ) -> ProcessResult<Self::Obligation, Self::Error> {
280 // If we were stalled on some unresolved variables, first check whether
281 // any of them have been resolved; if not, don't bother doing more work
283 let change = match pending_obligation.stalled_on.len() {
284 // Match arms are in order of frequency, which matters because this
285 // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
287 let infer_var = pending_obligation.stalled_on[0];
288 self.selcx.infcx().ty_or_const_infer_var_changed(infer_var)
291 // In this case we haven't changed, but wish to make a change.
295 // This `for` loop was once a call to `all()`, but this lower-level
296 // form was a perf win. See #64545 for details.
298 for &infer_var in &pending_obligation.stalled_on {
299 if self.selcx.infcx().ty_or_const_infer_var_changed(infer_var) {
310 "process_predicate: pending obligation {:?} still stalled on {:?}",
311 self.selcx.infcx().resolve_vars_if_possible(pending_obligation.obligation.clone()),
312 pending_obligation.stalled_on
314 return ProcessResult::Unchanged;
317 self.process_changed_obligations(pending_obligation)
320 fn process_backedge<'c, I>(
323 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
325 I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
327 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
328 debug!("process_child_obligations: coinductive match");
330 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
331 self.selcx.infcx().report_overflow_error_cycle(&cycle);
336 impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> {
337 // The code calling this method is extremely hot and only rarely
338 // actually uses this, so move this part of the code
341 fn process_changed_obligations(
343 pending_obligation: &mut PendingPredicateObligation<'tcx>,
344 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
345 pending_obligation.stalled_on.truncate(0);
347 let obligation = &mut pending_obligation.obligation;
349 debug!(?obligation, "process_obligation pre-resolve");
351 if obligation.predicate.has_infer_types_or_consts() {
352 obligation.predicate =
353 self.selcx.infcx().resolve_vars_if_possible(obligation.predicate);
356 debug!(?obligation, ?obligation.cause, "process_obligation");
358 let infcx = self.selcx.infcx();
360 if obligation.predicate.has_projections() {
361 let mut obligations = Vec::new();
362 let predicate = crate::traits::project::try_normalize_with_depth_to(
364 obligation.param_env,
365 obligation.cause.clone(),
366 obligation.recursion_depth + 1,
367 obligation.predicate,
370 if predicate != obligation.predicate {
371 obligations.push(obligation.with(predicate));
372 return ProcessResult::Changed(mk_pending(obligations));
375 let binder = obligation.predicate.kind();
376 match binder.no_bound_vars() {
377 None => match binder.skip_binder() {
378 // Evaluation will discard candidates using the leak check.
379 // This means we need to pass it the bound version of our
381 ty::PredicateKind::Trait(trait_ref) => {
382 let trait_obligation = obligation.with(binder.rebind(trait_ref));
384 self.process_trait_obligation(
387 &mut pending_obligation.stalled_on,
390 ty::PredicateKind::Projection(data) => {
391 let project_obligation = obligation.with(binder.rebind(data));
393 self.process_projection_obligation(
396 &mut pending_obligation.stalled_on,
399 ty::PredicateKind::RegionOutlives(_)
400 | ty::PredicateKind::TypeOutlives(_)
401 | ty::PredicateKind::WellFormed(_)
402 | ty::PredicateKind::ObjectSafe(_)
403 | ty::PredicateKind::ClosureKind(..)
404 | ty::PredicateKind::Subtype(_)
405 | ty::PredicateKind::Coerce(_)
406 | ty::PredicateKind::ConstEvaluatable(..)
407 | ty::PredicateKind::ConstEquate(..) => {
409 ty::Binder::dummy(infcx.replace_bound_vars_with_placeholders(binder));
410 ProcessResult::Changed(mk_pending(vec![
411 obligation.with(pred.to_predicate(self.selcx.tcx())),
414 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
415 bug!("TypeWellFormedFromEnv is only used for Chalk")
418 Some(pred) => match pred {
419 ty::PredicateKind::Trait(data) => {
420 let trait_obligation = obligation.with(Binder::dummy(data));
422 self.process_trait_obligation(
425 &mut pending_obligation.stalled_on,
429 ty::PredicateKind::RegionOutlives(data) => {
430 match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) {
431 Ok(()) => ProcessResult::Changed(vec![]),
432 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
436 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
437 if self.register_region_obligations {
438 self.selcx.infcx().register_region_obligation_with_cause(
444 ProcessResult::Changed(vec![])
447 ty::PredicateKind::Projection(ref data) => {
448 let project_obligation = obligation.with(Binder::dummy(*data));
450 self.process_projection_obligation(
453 &mut pending_obligation.stalled_on,
457 ty::PredicateKind::ObjectSafe(trait_def_id) => {
458 if !self.selcx.tcx().is_object_safe(trait_def_id) {
459 ProcessResult::Error(CodeSelectionError(Unimplemented))
461 ProcessResult::Changed(vec![])
465 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
466 match self.selcx.infcx().closure_kind(closure_substs) {
467 Some(closure_kind) => {
468 if closure_kind.extends(kind) {
469 ProcessResult::Changed(vec![])
471 ProcessResult::Error(CodeSelectionError(Unimplemented))
474 None => ProcessResult::Unchanged,
478 ty::PredicateKind::WellFormed(arg) => {
479 match wf::obligations(
481 obligation.param_env,
482 obligation.cause.body_id,
483 obligation.recursion_depth + 1,
485 obligation.cause.span,
488 pending_obligation.stalled_on =
489 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
490 ProcessResult::Unchanged
492 Some(os) => ProcessResult::Changed(mk_pending(os)),
496 ty::PredicateKind::Subtype(subtype) => {
497 match self.selcx.infcx().subtype_predicate(
499 obligation.param_env,
500 Binder::dummy(subtype),
503 // None means that both are unresolved.
504 pending_obligation.stalled_on = vec![
505 TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(),
506 TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(),
508 ProcessResult::Unchanged
510 Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
513 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
514 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
522 ty::PredicateKind::Coerce(coerce) => {
523 match self.selcx.infcx().coerce_predicate(
525 obligation.param_env,
526 Binder::dummy(coerce),
529 // None means that both are unresolved.
530 pending_obligation.stalled_on = vec![
531 TyOrConstInferVar::maybe_from_ty(coerce.a).unwrap(),
532 TyOrConstInferVar::maybe_from_ty(coerce.b).unwrap(),
534 ProcessResult::Unchanged
536 Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
538 let expected_found = ExpectedFound::new(false, coerce.a, coerce.b);
539 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
547 ty::PredicateKind::ConstEvaluatable(uv) => {
548 match const_evaluatable::is_const_evaluatable(
551 obligation.param_env,
552 obligation.cause.span,
554 Ok(()) => ProcessResult::Changed(vec![]),
555 Err(NotConstEvaluatable::MentionsInfer) => {
556 pending_obligation.stalled_on.clear();
557 pending_obligation.stalled_on.extend(
560 .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
562 ProcessResult::Unchanged
565 e @ NotConstEvaluatable::MentionsParam
566 | e @ NotConstEvaluatable::Error(_),
567 ) => ProcessResult::Error(CodeSelectionError(
568 SelectionError::NotConstEvaluatable(e),
573 ty::PredicateKind::ConstEquate(c1, c2) => {
574 debug!(?c1, ?c2, "equating consts");
575 let tcx = self.selcx.tcx();
576 if tcx.features().generic_const_exprs {
577 // FIXME: we probably should only try to unify abstract constants
578 // if the constants depend on generic parameters.
580 // Let's just see where this breaks :shrug:
581 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
584 if infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
585 return ProcessResult::Changed(vec![]);
590 let stalled_on = &mut pending_obligation.stalled_on;
592 let mut evaluate = |c: Const<'tcx>| {
593 if let ty::ConstKind::Unevaluated(unevaluated) = c.val() {
594 match self.selcx.infcx().const_eval_resolve(
595 obligation.param_env,
597 Some(obligation.cause.span),
599 Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty())),
600 Err(ErrorHandled::TooGeneric) => {
605 .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
607 Err(ErrorHandled::TooGeneric)
609 Err(err) => Err(err),
616 match (evaluate(c1), evaluate(c2)) {
617 (Ok(c1), Ok(c2)) => {
621 .at(&obligation.cause, obligation.param_env)
624 Ok(_) => ProcessResult::Changed(vec![]),
625 Err(err) => ProcessResult::Error(
626 FulfillmentErrorCode::CodeConstEquateError(
627 ExpectedFound::new(true, c1, c2),
633 (Err(ErrorHandled::Reported(ErrorGuaranteed)), _)
634 | (_, Err(ErrorHandled::Reported(ErrorGuaranteed))) => {
635 ProcessResult::Error(CodeSelectionError(
636 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(
641 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
643 obligation.cause.span(self.selcx.tcx()),
644 "ConstEquate: const_eval_resolve returned an unexpected error"
647 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
648 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
649 ProcessResult::Unchanged
651 // Two different constants using generic parameters ~> error.
652 let expected_found = ExpectedFound::new(true, c1, c2);
653 ProcessResult::Error(FulfillmentErrorCode::CodeConstEquateError(
655 TypeError::ConstMismatch(expected_found),
661 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
662 bug!("TypeWellFormedFromEnv is only used for Chalk")
668 #[instrument(level = "debug", skip(self, obligation, stalled_on))]
669 fn process_trait_obligation(
671 obligation: &PredicateObligation<'tcx>,
672 trait_obligation: TraitObligation<'tcx>,
673 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
674 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
675 let infcx = self.selcx.infcx();
676 if obligation.predicate.is_global() {
677 // no type variables present, can use evaluation for better caching.
678 // FIXME: consider caching errors too.
679 if infcx.predicate_must_hold_considering_regions(obligation) {
681 "selecting trait at depth {} evaluated to holds",
682 obligation.recursion_depth
684 return ProcessResult::Changed(vec![]);
688 match self.selcx.select(&trait_obligation) {
689 Ok(Some(impl_source)) => {
690 debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth);
691 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
694 debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth);
696 // This is a bit subtle: for the most part, the
697 // only reason we can fail to make progress on
698 // trait selection is because we don't have enough
699 // information about the types in the trait.
701 stalled_on.extend(substs_infer_vars(
703 trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs),
707 "process_predicate: pending obligation {:?} now stalled on {:?}",
708 infcx.resolve_vars_if_possible(obligation.clone()),
712 ProcessResult::Unchanged
714 Err(selection_err) => {
715 debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth);
717 ProcessResult::Error(CodeSelectionError(selection_err))
722 fn process_projection_obligation(
724 obligation: &PredicateObligation<'tcx>,
725 project_obligation: PolyProjectionObligation<'tcx>,
726 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
727 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
728 let tcx = self.selcx.tcx();
730 if obligation.predicate.is_global() {
731 // no type variables present, can use evaluation for better caching.
732 // FIXME: consider caching errors too.
733 if self.selcx.infcx().predicate_must_hold_considering_regions(obligation) {
734 if let Some(key) = ProjectionCacheKey::from_poly_projection_predicate(
736 project_obligation.predicate,
738 // If `predicate_must_hold_considering_regions` succeeds, then we've
739 // evaluated all sub-obligations. We can therefore mark the 'root'
740 // obligation as complete, and skip evaluating sub-obligations.
746 .complete(key, EvaluationResult::EvaluatedToOk);
748 return ProcessResult::Changed(vec![]);
750 tracing::debug!("Does NOT hold: {:?}", obligation);
754 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
755 Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)),
758 stalled_on.extend(substs_infer_vars(
760 project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs),
762 ProcessResult::Unchanged
764 // Let the caller handle the recursion
765 Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![
766 project_obligation.with(project_obligation.predicate.to_predicate(tcx)),
768 Err(e) => ProcessResult::Error(CodeProjectionError(e)),
773 /// Returns the set of inference variables contained in `substs`.
774 fn substs_infer_vars<'a, 'tcx>(
775 selcx: &mut SelectionContext<'a, 'tcx>,
776 substs: ty::Binder<'tcx, SubstsRef<'tcx>>,
777 ) -> impl Iterator<Item = TyOrConstInferVar<'tcx>> {
780 .resolve_vars_if_possible(substs)
781 .skip_binder() // ok because this check doesn't care about regions
783 .filter(|arg| arg.has_infer_types_or_consts())
785 let mut walker = arg.walk();
786 while let Some(c) = walker.next() {
787 if !c.has_infer_types_or_consts() {
788 walker.visited.remove(&c);
789 walker.skip_current_subtree();
792 walker.visited.into_iter()
794 .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
797 fn to_fulfillment_error<'tcx>(
798 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
799 ) -> FulfillmentError<'tcx> {
800 let mut iter = error.backtrace.into_iter();
801 let obligation = iter.next().unwrap().obligation;
802 // The root obligation is the last item in the backtrace - if there's only
803 // one item, then it's the same as the main obligation
804 let root_obligation = iter.next_back().map_or_else(|| obligation.clone(), |e| e.obligation);
805 FulfillmentError::new(obligation, error.error, root_obligation)