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;
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);
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.progress_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 progress_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 if obligation.predicate.has_infer_types_or_consts() {
350 obligation.predicate =
351 self.selcx.infcx().resolve_vars_if_possible(obligation.predicate);
354 debug!(?obligation, ?obligation.cause, "process_obligation");
356 let infcx = self.selcx.infcx();
358 let binder = obligation.predicate.kind();
359 match binder.no_bound_vars() {
360 None => match binder.skip_binder() {
361 // Evaluation will discard candidates using the leak check.
362 // This means we need to pass it the bound version of our
364 ty::PredicateKind::Trait(trait_ref) => {
365 let trait_obligation = obligation.with(binder.rebind(trait_ref));
367 self.process_trait_obligation(
370 &mut pending_obligation.stalled_on,
373 ty::PredicateKind::Projection(data) => {
374 let project_obligation = obligation.with(binder.rebind(data));
376 self.process_projection_obligation(
379 &mut pending_obligation.stalled_on,
382 ty::PredicateKind::RegionOutlives(_)
383 | ty::PredicateKind::TypeOutlives(_)
384 | ty::PredicateKind::WellFormed(_)
385 | ty::PredicateKind::ObjectSafe(_)
386 | ty::PredicateKind::ClosureKind(..)
387 | ty::PredicateKind::Subtype(_)
388 | ty::PredicateKind::Coerce(_)
389 | ty::PredicateKind::ConstEvaluatable(..)
390 | ty::PredicateKind::ConstEquate(..) => {
392 ty::Binder::dummy(infcx.replace_bound_vars_with_placeholders(binder));
393 ProcessResult::Changed(mk_pending(vec![
394 obligation.with(pred.to_predicate(self.selcx.tcx())),
397 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
398 bug!("TypeWellFormedFromEnv is only used for Chalk")
401 Some(pred) => match pred {
402 ty::PredicateKind::Trait(data) => {
403 let trait_obligation = obligation.with(Binder::dummy(data));
405 self.process_trait_obligation(
408 &mut pending_obligation.stalled_on,
412 ty::PredicateKind::RegionOutlives(data) => {
413 match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) {
414 Ok(()) => ProcessResult::Changed(vec![]),
415 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
419 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
420 if self.register_region_obligations {
421 self.selcx.infcx().register_region_obligation_with_cause(
427 ProcessResult::Changed(vec![])
430 ty::PredicateKind::Projection(ref data) => {
431 let project_obligation = obligation.with(Binder::dummy(*data));
433 self.process_projection_obligation(
436 &mut pending_obligation.stalled_on,
440 ty::PredicateKind::ObjectSafe(trait_def_id) => {
441 if !self.selcx.tcx().is_object_safe(trait_def_id) {
442 ProcessResult::Error(CodeSelectionError(Unimplemented))
444 ProcessResult::Changed(vec![])
448 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
449 match self.selcx.infcx().closure_kind(closure_substs) {
450 Some(closure_kind) => {
451 if closure_kind.extends(kind) {
452 ProcessResult::Changed(vec![])
454 ProcessResult::Error(CodeSelectionError(Unimplemented))
457 None => ProcessResult::Unchanged,
461 ty::PredicateKind::WellFormed(arg) => {
462 match wf::obligations(
464 obligation.param_env,
465 obligation.cause.body_id,
466 obligation.recursion_depth + 1,
468 obligation.cause.span,
471 pending_obligation.stalled_on =
472 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
473 ProcessResult::Unchanged
475 Some(os) => ProcessResult::Changed(mk_pending(os)),
479 ty::PredicateKind::Subtype(subtype) => {
480 match self.selcx.infcx().subtype_predicate(
482 obligation.param_env,
483 Binder::dummy(subtype),
486 // None means that both are unresolved.
487 pending_obligation.stalled_on = vec![
488 TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(),
489 TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(),
491 ProcessResult::Unchanged
493 Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
496 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
497 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
505 ty::PredicateKind::Coerce(coerce) => {
506 match self.selcx.infcx().coerce_predicate(
508 obligation.param_env,
509 Binder::dummy(coerce),
512 // None means that both are unresolved.
513 pending_obligation.stalled_on = vec![
514 TyOrConstInferVar::maybe_from_ty(coerce.a).unwrap(),
515 TyOrConstInferVar::maybe_from_ty(coerce.b).unwrap(),
517 ProcessResult::Unchanged
519 Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
521 let expected_found = ExpectedFound::new(false, coerce.a, coerce.b);
522 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
530 ty::PredicateKind::ConstEvaluatable(uv) => {
531 match const_evaluatable::is_const_evaluatable(
534 obligation.param_env,
535 obligation.cause.span,
537 Ok(()) => ProcessResult::Changed(vec![]),
538 Err(NotConstEvaluatable::MentionsInfer) => {
539 pending_obligation.stalled_on.clear();
540 pending_obligation.stalled_on.extend(
543 .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
545 ProcessResult::Unchanged
548 e @ NotConstEvaluatable::MentionsParam
549 | e @ NotConstEvaluatable::Error(_),
550 ) => ProcessResult::Error(CodeSelectionError(
551 SelectionError::NotConstEvaluatable(e),
556 ty::PredicateKind::ConstEquate(c1, c2) => {
557 debug!(?c1, ?c2, "equating consts");
558 let tcx = self.selcx.tcx();
559 if tcx.features().generic_const_exprs {
560 // FIXME: we probably should only try to unify abstract constants
561 // if the constants depend on generic parameters.
563 // Let's just see where this breaks :shrug:
564 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
567 if infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
568 return ProcessResult::Changed(vec![]);
573 let stalled_on = &mut pending_obligation.stalled_on;
575 let mut evaluate = |c: &'tcx Const<'tcx>| {
576 if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
577 match self.selcx.infcx().const_eval_resolve(
578 obligation.param_env,
580 Some(obligation.cause.span),
582 Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty)),
583 Err(ErrorHandled::TooGeneric) => {
588 .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
590 Err(ErrorHandled::TooGeneric)
592 Err(err) => Err(err),
599 match (evaluate(c1), evaluate(c2)) {
600 (Ok(c1), Ok(c2)) => {
604 .at(&obligation.cause, obligation.param_env)
607 Ok(_) => ProcessResult::Changed(vec![]),
608 Err(err) => ProcessResult::Error(
609 FulfillmentErrorCode::CodeConstEquateError(
610 ExpectedFound::new(true, c1, c2),
616 (Err(ErrorHandled::Reported(ErrorReported)), _)
617 | (_, Err(ErrorHandled::Reported(ErrorReported))) => ProcessResult::Error(
618 CodeSelectionError(SelectionError::NotConstEvaluatable(
619 NotConstEvaluatable::Error(ErrorReported),
622 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
624 obligation.cause.span(self.selcx.tcx()),
625 "ConstEquate: const_eval_resolve returned an unexpected error"
628 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
629 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
630 ProcessResult::Unchanged
632 // Two different constants using generic parameters ~> error.
633 let expected_found = ExpectedFound::new(true, c1, c2);
634 ProcessResult::Error(FulfillmentErrorCode::CodeConstEquateError(
636 TypeError::ConstMismatch(expected_found),
642 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
643 bug!("TypeWellFormedFromEnv is only used for Chalk")
649 #[instrument(level = "debug", skip(self, obligation, stalled_on))]
650 fn process_trait_obligation(
652 obligation: &PredicateObligation<'tcx>,
653 trait_obligation: TraitObligation<'tcx>,
654 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
655 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
656 let infcx = self.selcx.infcx();
657 if obligation.predicate.is_global() {
658 // no type variables present, can use evaluation for better caching.
659 // FIXME: consider caching errors too.
660 if infcx.predicate_must_hold_considering_regions(obligation) {
662 "selecting trait at depth {} evaluated to holds",
663 obligation.recursion_depth
665 return ProcessResult::Changed(vec![]);
669 match self.selcx.select(&trait_obligation) {
670 Ok(Some(impl_source)) => {
671 debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth);
672 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
675 debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth);
677 // This is a bit subtle: for the most part, the
678 // only reason we can fail to make progress on
679 // trait selection is because we don't have enough
680 // information about the types in the trait.
682 stalled_on.extend(substs_infer_vars(
684 trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs),
688 "process_predicate: pending obligation {:?} now stalled on {:?}",
689 infcx.resolve_vars_if_possible(obligation.clone()),
693 ProcessResult::Unchanged
695 Err(selection_err) => {
696 debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth);
698 ProcessResult::Error(CodeSelectionError(selection_err))
703 fn process_projection_obligation(
705 obligation: &PredicateObligation<'tcx>,
706 project_obligation: PolyProjectionObligation<'tcx>,
707 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
708 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
709 let tcx = self.selcx.tcx();
711 if obligation.predicate.is_global() {
712 // no type variables present, can use evaluation for better caching.
713 // FIXME: consider caching errors too.
714 if self.selcx.infcx().predicate_must_hold_considering_regions(obligation) {
715 if let Some(key) = ProjectionCacheKey::from_poly_projection_predicate(
717 project_obligation.predicate,
719 // If `predicate_must_hold_considering_regions` succeeds, then we've
720 // evaluated all sub-obligations. We can therefore mark the 'root'
721 // obligation as complete, and skip evaluating sub-obligations.
727 .complete(key, EvaluationResult::EvaluatedToOk);
729 return ProcessResult::Changed(vec![]);
731 tracing::debug!("Does NOT hold: {:?}", obligation);
735 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
736 Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)),
739 stalled_on.extend(substs_infer_vars(
741 project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs),
743 ProcessResult::Unchanged
745 // Let the caller handle the recursion
746 Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![
747 project_obligation.with(project_obligation.predicate.to_predicate(tcx)),
749 Err(e) => ProcessResult::Error(CodeProjectionError(e)),
754 /// Returns the set of inference variables contained in `substs`.
755 fn substs_infer_vars<'a, 'tcx>(
756 selcx: &mut SelectionContext<'a, 'tcx>,
757 substs: ty::Binder<'tcx, SubstsRef<'tcx>>,
758 ) -> impl Iterator<Item = TyOrConstInferVar<'tcx>> {
761 .resolve_vars_if_possible(substs)
762 .skip_binder() // ok because this check doesn't care about regions
764 .filter(|arg| arg.has_infer_types_or_consts())
766 let mut walker = arg.walk();
767 while let Some(c) = walker.next() {
768 if !c.has_infer_types_or_consts() {
769 walker.visited.remove(&c);
770 walker.skip_current_subtree();
773 walker.visited.into_iter()
775 .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
778 fn to_fulfillment_error<'tcx>(
779 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
780 ) -> FulfillmentError<'tcx> {
781 let mut iter = error.backtrace.into_iter();
782 let obligation = iter.next().unwrap().obligation;
783 // The root obligation is the last item in the backtrace - if there's only
784 // one item, then it's the same as the main obligation
785 let root_obligation = iter.next_back().map_or_else(|| obligation.clone(), |e| e.obligation);
786 FulfillmentError::new(obligation, error.error, root_obligation)