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::ErrorReported;
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::Unimplemented;
25 use super::{FulfillmentError, FulfillmentErrorCode};
26 use super::{ObligationCause, PredicateObligation};
28 use crate::traits::error_reporting::InferCtxtExt as _;
29 use crate::traits::project::PolyProjectionObligation;
30 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
32 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
33 /// Note that we include both the `ParamEnv` and the `Predicate`,
34 /// as the `ParamEnv` can influence whether fulfillment succeeds
36 type CacheKey = ty::ParamEnvAnd<'tcx, ty::Predicate<'tcx>>;
38 fn as_cache_key(&self) -> Self::CacheKey {
39 self.obligation.param_env.and(self.obligation.predicate)
43 /// The fulfillment context is used to drive trait resolution. It
44 /// consists of a list of obligations that must be (eventually)
45 /// satisfied. The job is to track which are satisfied, which yielded
46 /// errors, and which are still pending. At any point, users can call
47 /// `select_where_possible`, and the fulfillment context will try to do
48 /// selection, retaining only those obligations that remain
49 /// ambiguous. This may be helpful in pushing type inference
50 /// along. Once all type inference constraints have been generated, the
51 /// method `select_all_or_error` can be used to report any remaining
52 /// ambiguous cases as errors.
53 pub struct FulfillmentContext<'tcx> {
54 // A list of all obligations that have been registered with this
55 // fulfillment context.
56 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
58 relationships: FxHashMap<ty::TyVid, ty::FoundRelationships>,
60 // Should this fulfillment context register type-lives-for-region
61 // obligations on its parent infcx? In some cases, region
62 // obligations are either already known to hold (normalization) or
63 // hopefully verifed elsewhere (type-impls-bound), and therefore
64 // should not be checked.
66 // Note that if we are normalizing a type that we already
67 // know is well-formed, there should be no harm setting this
68 // to true - all the region variables should be determinable
69 // using the RFC 447 rules, which don't depend on
70 // type-lives-for-region constraints, and because the type
71 // is well-formed, the constraints should hold.
72 register_region_obligations: bool,
73 // Is it OK to register obligations into this infcx inside
76 // The "primary fulfillment" in many cases in typeck lives
77 // outside of any snapshot, so any use of it inside a snapshot
78 // will lead to trouble and therefore is checked against, but
79 // other fulfillment contexts sometimes do live inside of
80 // a snapshot (they don't *straddle* a snapshot, so there
81 // is no trouble there).
82 usable_in_snapshot: bool,
85 #[derive(Clone, Debug)]
86 pub struct PendingPredicateObligation<'tcx> {
87 pub obligation: PredicateObligation<'tcx>,
88 // This is far more often read than modified, meaning that we
89 // should mostly optimize for reading speed, while modifying is not as relevant.
91 // For whatever reason using a boxed slice is slower than using a `Vec` here.
92 pub stalled_on: Vec<TyOrConstInferVar<'tcx>>,
95 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
96 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
97 static_assert_size!(PendingPredicateObligation<'_>, 56);
99 impl<'a, 'tcx> FulfillmentContext<'tcx> {
100 /// Creates a new fulfillment context.
101 pub fn new() -> FulfillmentContext<'tcx> {
103 predicates: ObligationForest::new(),
104 relationships: FxHashMap::default(),
105 register_region_obligations: true,
106 usable_in_snapshot: false,
110 pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
112 predicates: ObligationForest::new(),
113 relationships: FxHashMap::default(),
114 register_region_obligations: true,
115 usable_in_snapshot: true,
119 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
121 predicates: ObligationForest::new(),
122 relationships: FxHashMap::default(),
123 register_region_obligations: false,
124 usable_in_snapshot: false,
128 /// Attempts to select obligations using `selcx`.
131 selcx: &mut SelectionContext<'a, 'tcx>,
132 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
133 let span = debug_span!("select", obligation_forest_size = ?self.predicates.len());
134 let _enter = span.enter();
136 let mut errors = Vec::new();
139 debug!("select: starting another iteration");
141 // Process pending obligations.
142 let outcome: Outcome<_, _> =
143 self.predicates.process_obligations(&mut FulfillProcessor {
145 register_region_obligations: self.register_region_obligations,
147 debug!("select: outcome={:#?}", outcome);
149 // FIXME: if we kept the original cache key, we could mark projection
150 // obligations as complete for the projection cache here.
152 errors.extend(outcome.errors.into_iter().map(to_fulfillment_error));
154 // If nothing new was added, no need to keep looping.
161 "select({} predicates remaining, {} errors) done",
162 self.predicates.len(),
166 if errors.is_empty() { Ok(()) } else { Err(errors) }
170 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
171 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
172 /// creating a fresh type variable `$0` as well as a projection
173 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
174 /// inference engine runs, it will attempt to find an impl of
175 /// `SomeTrait` or a where-clause that lets us unify `$0` with
176 /// something concrete. If this fails, we'll unify `$0` with
177 /// `projection_ty` again.
178 #[tracing::instrument(level = "debug", skip(self, infcx, param_env, cause))]
179 fn normalize_projection_type(
181 infcx: &InferCtxt<'_, 'tcx>,
182 param_env: ty::ParamEnv<'tcx>,
183 projection_ty: ty::ProjectionTy<'tcx>,
184 cause: ObligationCause<'tcx>,
186 debug_assert!(!projection_ty.has_escaping_bound_vars());
188 // FIXME(#20304) -- cache
190 let mut selcx = SelectionContext::new(infcx);
191 let mut obligations = vec![];
192 let normalized_ty = project::normalize_projection_type(
200 self.register_predicate_obligations(infcx, obligations);
202 debug!(?normalized_ty);
207 fn register_predicate_obligation(
209 infcx: &InferCtxt<'_, 'tcx>,
210 obligation: PredicateObligation<'tcx>,
212 // this helps to reduce duplicate errors, as well as making
213 // debug output much nicer to read and so on.
214 let obligation = infcx.resolve_vars_if_possible(obligation);
216 debug!(?obligation, "register_predicate_obligation");
218 assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
220 super::relationships::update(self, infcx, &obligation);
223 .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
226 fn select_all_or_error(
228 infcx: &InferCtxt<'_, 'tcx>,
229 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
230 self.select_where_possible(infcx)?;
232 let errors: Vec<_> = self
234 .to_errors(CodeAmbiguity)
236 .map(to_fulfillment_error)
238 if errors.is_empty() { Ok(()) } else { Err(errors) }
241 fn select_all_with_constness_or_error(
243 infcx: &InferCtxt<'_, 'tcx>,
244 constness: rustc_hir::Constness,
245 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
246 self.select_with_constness_where_possible(infcx, constness)?;
248 let errors: Vec<_> = self
250 .to_errors(CodeAmbiguity)
252 .map(to_fulfillment_error)
254 if errors.is_empty() { Ok(()) } else { Err(errors) }
257 fn select_where_possible(
259 infcx: &InferCtxt<'_, 'tcx>,
260 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
261 let mut selcx = SelectionContext::new(infcx);
262 self.select(&mut selcx)
265 fn select_with_constness_where_possible(
267 infcx: &InferCtxt<'_, 'tcx>,
268 constness: hir::Constness,
269 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
270 let mut selcx = SelectionContext::with_constness(infcx, constness);
271 self.select(&mut selcx)
274 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
275 self.predicates.map_pending_obligations(|o| o.obligation.clone())
278 fn relationships(&mut self) -> &mut FxHashMap<ty::TyVid, ty::FoundRelationships> {
279 &mut self.relationships
283 struct FulfillProcessor<'a, 'b, 'tcx> {
284 selcx: &'a mut SelectionContext<'b, 'tcx>,
285 register_region_obligations: bool,
288 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
290 .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
294 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
295 type Obligation = PendingPredicateObligation<'tcx>;
296 type Error = FulfillmentErrorCode<'tcx>;
298 /// Processes a predicate obligation and returns either:
299 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
300 /// - `Unchanged` if we don't have enough info to be sure
301 /// - `Error(e)` if the predicate does not hold
303 /// This is always inlined, despite its size, because it has a single
304 /// callsite and it is called *very* frequently.
306 fn process_obligation(
308 pending_obligation: &mut Self::Obligation,
309 ) -> ProcessResult<Self::Obligation, Self::Error> {
310 // If we were stalled on some unresolved variables, first check whether
311 // any of them have been resolved; if not, don't bother doing more work
313 let change = match pending_obligation.stalled_on.len() {
314 // Match arms are in order of frequency, which matters because this
315 // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
317 let infer_var = pending_obligation.stalled_on[0];
318 self.selcx.infcx().ty_or_const_infer_var_changed(infer_var)
321 // In this case we haven't changed, but wish to make a change.
325 // This `for` loop was once a call to `all()`, but this lower-level
326 // form was a perf win. See #64545 for details.
328 for &infer_var in &pending_obligation.stalled_on {
329 if self.selcx.infcx().ty_or_const_infer_var_changed(infer_var) {
340 "process_predicate: pending obligation {:?} still stalled on {:?}",
341 self.selcx.infcx().resolve_vars_if_possible(pending_obligation.obligation.clone()),
342 pending_obligation.stalled_on
344 return ProcessResult::Unchanged;
347 self.progress_changed_obligations(pending_obligation)
350 fn process_backedge<'c, I>(
353 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
355 I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
357 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
358 debug!("process_child_obligations: coinductive match");
360 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
361 self.selcx.infcx().report_overflow_error_cycle(&cycle);
366 impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> {
367 // The code calling this method is extremely hot and only rarely
368 // actually uses this, so move this part of the code
371 fn progress_changed_obligations(
373 pending_obligation: &mut PendingPredicateObligation<'tcx>,
374 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
375 pending_obligation.stalled_on.truncate(0);
377 let obligation = &mut pending_obligation.obligation;
379 if obligation.predicate.has_infer_types_or_consts() {
380 obligation.predicate =
381 self.selcx.infcx().resolve_vars_if_possible(obligation.predicate);
384 debug!(?obligation, ?obligation.cause, "process_obligation");
386 let infcx = self.selcx.infcx();
388 let binder = obligation.predicate.kind();
389 match binder.no_bound_vars() {
390 None => match binder.skip_binder() {
391 // Evaluation will discard candidates using the leak check.
392 // This means we need to pass it the bound version of our
394 ty::PredicateKind::Trait(trait_ref) => {
395 let trait_obligation = obligation.with(binder.rebind(trait_ref));
397 self.process_trait_obligation(
400 &mut pending_obligation.stalled_on,
403 ty::PredicateKind::Projection(data) => {
404 let project_obligation = obligation.with(binder.rebind(data));
406 self.process_projection_obligation(
409 &mut pending_obligation.stalled_on,
412 ty::PredicateKind::RegionOutlives(_)
413 | ty::PredicateKind::TypeOutlives(_)
414 | ty::PredicateKind::WellFormed(_)
415 | ty::PredicateKind::ObjectSafe(_)
416 | ty::PredicateKind::ClosureKind(..)
417 | ty::PredicateKind::Subtype(_)
418 | ty::PredicateKind::Coerce(_)
419 | ty::PredicateKind::ConstEvaluatable(..)
420 | ty::PredicateKind::ConstEquate(..) => {
422 ty::Binder::dummy(infcx.replace_bound_vars_with_placeholders(binder));
423 ProcessResult::Changed(mk_pending(vec![
424 obligation.with(pred.to_predicate(self.selcx.tcx())),
427 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
428 bug!("TypeWellFormedFromEnv is only used for Chalk")
431 Some(pred) => match pred {
432 ty::PredicateKind::Trait(data) => {
433 let trait_obligation = obligation.with(Binder::dummy(data));
435 self.process_trait_obligation(
438 &mut pending_obligation.stalled_on,
442 ty::PredicateKind::RegionOutlives(data) => {
443 match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) {
444 Ok(()) => ProcessResult::Changed(vec![]),
445 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
449 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
450 if self.register_region_obligations {
451 self.selcx.infcx().register_region_obligation_with_cause(
457 ProcessResult::Changed(vec![])
460 ty::PredicateKind::Projection(ref data) => {
461 let project_obligation = obligation.with(Binder::dummy(*data));
463 self.process_projection_obligation(
466 &mut pending_obligation.stalled_on,
470 ty::PredicateKind::ObjectSafe(trait_def_id) => {
471 if !self.selcx.tcx().is_object_safe(trait_def_id) {
472 ProcessResult::Error(CodeSelectionError(Unimplemented))
474 ProcessResult::Changed(vec![])
478 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
479 match self.selcx.infcx().closure_kind(closure_substs) {
480 Some(closure_kind) => {
481 if closure_kind.extends(kind) {
482 ProcessResult::Changed(vec![])
484 ProcessResult::Error(CodeSelectionError(Unimplemented))
487 None => ProcessResult::Unchanged,
491 ty::PredicateKind::WellFormed(arg) => {
492 match wf::obligations(
494 obligation.param_env,
495 obligation.cause.body_id,
496 obligation.recursion_depth + 1,
498 obligation.cause.span,
501 pending_obligation.stalled_on =
502 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
503 ProcessResult::Unchanged
505 Some(os) => ProcessResult::Changed(mk_pending(os)),
509 ty::PredicateKind::Subtype(subtype) => {
510 match self.selcx.infcx().subtype_predicate(
512 obligation.param_env,
513 Binder::dummy(subtype),
516 // None means that both are unresolved.
517 pending_obligation.stalled_on = vec![
518 TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(),
519 TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(),
521 ProcessResult::Unchanged
523 Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
526 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
527 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
535 ty::PredicateKind::Coerce(coerce) => {
536 match self.selcx.infcx().coerce_predicate(
538 obligation.param_env,
539 Binder::dummy(coerce),
542 // None means that both are unresolved.
543 pending_obligation.stalled_on = vec![
544 TyOrConstInferVar::maybe_from_ty(coerce.a).unwrap(),
545 TyOrConstInferVar::maybe_from_ty(coerce.b).unwrap(),
547 ProcessResult::Unchanged
549 Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
551 let expected_found = ExpectedFound::new(false, coerce.a, coerce.b);
552 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
560 ty::PredicateKind::ConstEvaluatable(uv) => {
561 match const_evaluatable::is_const_evaluatable(
564 obligation.param_env,
565 obligation.cause.span,
567 Ok(()) => ProcessResult::Changed(vec![]),
568 Err(NotConstEvaluatable::MentionsInfer) => {
569 pending_obligation.stalled_on.clear();
570 pending_obligation.stalled_on.extend(
573 .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
575 ProcessResult::Unchanged
578 e @ NotConstEvaluatable::MentionsParam
579 | e @ NotConstEvaluatable::Error(_),
580 ) => ProcessResult::Error(CodeSelectionError(
581 SelectionError::NotConstEvaluatable(e),
586 ty::PredicateKind::ConstEquate(c1, c2) => {
587 debug!(?c1, ?c2, "equating consts");
588 let tcx = self.selcx.tcx();
589 if tcx.features().generic_const_exprs {
590 // FIXME: we probably should only try to unify abstract constants
591 // if the constants depend on generic parameters.
593 // Let's just see where this breaks :shrug:
594 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
597 if infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
598 return ProcessResult::Changed(vec![]);
603 let stalled_on = &mut pending_obligation.stalled_on;
605 let mut evaluate = |c: &'tcx Const<'tcx>| {
606 if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
607 match self.selcx.infcx().const_eval_resolve(
608 obligation.param_env,
610 Some(obligation.cause.span),
612 Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty)),
613 Err(ErrorHandled::TooGeneric) => {
618 .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
620 Err(ErrorHandled::TooGeneric)
622 Err(err) => Err(err),
629 match (evaluate(c1), evaluate(c2)) {
630 (Ok(c1), Ok(c2)) => {
634 .at(&obligation.cause, obligation.param_env)
637 Ok(_) => ProcessResult::Changed(vec![]),
638 Err(err) => ProcessResult::Error(
639 FulfillmentErrorCode::CodeConstEquateError(
640 ExpectedFound::new(true, c1, c2),
646 (Err(ErrorHandled::Reported(ErrorReported)), _)
647 | (_, Err(ErrorHandled::Reported(ErrorReported))) => ProcessResult::Error(
648 CodeSelectionError(SelectionError::NotConstEvaluatable(
649 NotConstEvaluatable::Error(ErrorReported),
652 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
654 obligation.cause.span(self.selcx.tcx()),
655 "ConstEquate: const_eval_resolve returned an unexpected error"
658 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
659 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
660 ProcessResult::Unchanged
662 // Two different constants using generic parameters ~> error.
663 let expected_found = ExpectedFound::new(true, c1, c2);
664 ProcessResult::Error(FulfillmentErrorCode::CodeConstEquateError(
666 TypeError::ConstMismatch(expected_found),
672 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
673 bug!("TypeWellFormedFromEnv is only used for Chalk")
679 #[instrument(level = "debug", skip(self, obligation, stalled_on))]
680 fn process_trait_obligation(
682 obligation: &PredicateObligation<'tcx>,
683 trait_obligation: TraitObligation<'tcx>,
684 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
685 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
686 let infcx = self.selcx.infcx();
687 if obligation.predicate.is_known_global() {
688 // no type variables present, can use evaluation for better caching.
689 // FIXME: consider caching errors too.
691 // If the predicate is considered const, then we cannot use this because
692 // it will cause false negatives in the ui tests.
693 if !self.selcx.is_predicate_const(obligation.predicate)
694 && infcx.predicate_must_hold_considering_regions(obligation)
697 "selecting trait at depth {} evaluated to holds",
698 obligation.recursion_depth
700 return ProcessResult::Changed(vec![]);
704 match self.selcx.select(&trait_obligation) {
705 Ok(Some(impl_source)) => {
706 debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth);
707 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
710 debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth);
712 // This is a bit subtle: for the most part, the
713 // only reason we can fail to make progress on
714 // trait selection is because we don't have enough
715 // information about the types in the trait.
717 stalled_on.extend(substs_infer_vars(
719 trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs),
723 "process_predicate: pending obligation {:?} now stalled on {:?}",
724 infcx.resolve_vars_if_possible(obligation.clone()),
728 ProcessResult::Unchanged
730 Err(selection_err) => {
731 debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth);
733 ProcessResult::Error(CodeSelectionError(selection_err))
738 fn process_projection_obligation(
740 obligation: &PredicateObligation<'tcx>,
741 project_obligation: PolyProjectionObligation<'tcx>,
742 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
743 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
744 let tcx = self.selcx.tcx();
746 if obligation.predicate.is_global(tcx) {
747 // no type variables present, can use evaluation for better caching.
748 // FIXME: consider caching errors too.
750 // If the predicate is considered const, then we cannot use this because
751 // it will cause false negatives in the ui tests.
752 if !self.selcx.is_predicate_const(obligation.predicate)
753 && self.selcx.infcx().predicate_must_hold_considering_regions(obligation)
755 return ProcessResult::Changed(vec![]);
757 tracing::debug!("Does NOT hold: {:?}", obligation);
761 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
762 Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)),
765 stalled_on.extend(substs_infer_vars(
767 project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs),
769 ProcessResult::Unchanged
771 // Let the caller handle the recursion
772 Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![
773 project_obligation.with(project_obligation.predicate.to_predicate(tcx)),
775 Err(e) => ProcessResult::Error(CodeProjectionError(e)),
780 /// Returns the set of inference variables contained in `substs`.
781 fn substs_infer_vars<'a, 'tcx>(
782 selcx: &mut SelectionContext<'a, 'tcx>,
783 substs: ty::Binder<'tcx, SubstsRef<'tcx>>,
784 ) -> impl Iterator<Item = TyOrConstInferVar<'tcx>> {
785 let tcx = selcx.tcx();
788 .resolve_vars_if_possible(substs)
789 .skip_binder() // ok because this check doesn't care about regions
791 .filter(|arg| arg.has_infer_types_or_consts())
792 .flat_map(move |arg| {
793 let mut walker = arg.walk(tcx);
794 while let Some(c) = walker.next() {
795 if !c.has_infer_types_or_consts() {
796 walker.visited.remove(&c);
797 walker.skip_current_subtree();
800 walker.visited.into_iter()
802 .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
805 fn to_fulfillment_error<'tcx>(
806 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
807 ) -> FulfillmentError<'tcx> {
808 let mut iter = error.backtrace.into_iter();
809 let obligation = iter.next().unwrap().obligation;
810 // The root obligation is the last item in the backtrace - if there's only
811 // one item, then it's the same as the main obligation
812 let root_obligation = iter.next_back().map_or_else(|| obligation.clone(), |e| e.obligation);
813 FulfillmentError::new(obligation, error.error, root_obligation)