]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/fulfill.rs
update `const_eval_resolve`
[rust.git] / compiler / rustc_trait_selection / src / traits / fulfill.rs
1 use crate::infer::{InferCtxt, TyOrConstInferVar};
2 use rustc_data_structures::obligation_forest::ProcessResult;
3 use rustc_data_structures::obligation_forest::{Error, ForestObligation, Outcome};
4 use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};
5 use rustc_errors::ErrorReported;
6 use rustc_infer::traits::{TraitEngine, TraitEngineExt as _, TraitObligation};
7 use rustc_middle::mir::interpret::ErrorHandled;
8 use rustc_middle::ty::error::ExpectedFound;
9 use rustc_middle::ty::subst::SubstsRef;
10 use rustc_middle::ty::ToPredicate;
11 use rustc_middle::ty::{self, Binder, Const, Ty, TypeFoldable};
12 use std::marker::PhantomData;
13
14 use super::const_evaluatable;
15 use super::project;
16 use super::select::SelectionContext;
17 use super::wf;
18 use super::CodeAmbiguity;
19 use super::CodeProjectionError;
20 use super::CodeSelectionError;
21 use super::{ConstEvalFailure, Unimplemented};
22 use super::{FulfillmentError, FulfillmentErrorCode};
23 use super::{ObligationCause, PredicateObligation};
24
25 use crate::traits::error_reporting::InferCtxtExt as _;
26 use crate::traits::project::PolyProjectionObligation;
27 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
28
29 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
30     /// Note that we include both the `ParamEnv` and the `Predicate`,
31     /// as the `ParamEnv` can influence whether fulfillment succeeds
32     /// or fails.
33     type CacheKey = ty::ParamEnvAnd<'tcx, ty::Predicate<'tcx>>;
34
35     fn as_cache_key(&self) -> Self::CacheKey {
36         self.obligation.param_env.and(self.obligation.predicate)
37     }
38 }
39
40 /// The fulfillment context is used to drive trait resolution. It
41 /// consists of a list of obligations that must be (eventually)
42 /// satisfied. The job is to track which are satisfied, which yielded
43 /// errors, and which are still pending. At any point, users can call
44 /// `select_where_possible`, and the fulfillment context will try to do
45 /// selection, retaining only those obligations that remain
46 /// ambiguous. This may be helpful in pushing type inference
47 /// along. Once all type inference constraints have been generated, the
48 /// method `select_all_or_error` can be used to report any remaining
49 /// ambiguous cases as errors.
50 pub struct FulfillmentContext<'tcx> {
51     // A list of all obligations that have been registered with this
52     // fulfillment context.
53     predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
54     // Should this fulfillment context register type-lives-for-region
55     // obligations on its parent infcx? In some cases, region
56     // obligations are either already known to hold (normalization) or
57     // hopefully verifed elsewhere (type-impls-bound), and therefore
58     // should not be checked.
59     //
60     // Note that if we are normalizing a type that we already
61     // know is well-formed, there should be no harm setting this
62     // to true - all the region variables should be determinable
63     // using the RFC 447 rules, which don't depend on
64     // type-lives-for-region constraints, and because the type
65     // is well-formed, the constraints should hold.
66     register_region_obligations: bool,
67     // Is it OK to register obligations into this infcx inside
68     // an infcx snapshot?
69     //
70     // The "primary fulfillment" in many cases in typeck lives
71     // outside of any snapshot, so any use of it inside a snapshot
72     // will lead to trouble and therefore is checked against, but
73     // other fulfillment contexts sometimes do live inside of
74     // a snapshot (they don't *straddle* a snapshot, so there
75     // is no trouble there).
76     usable_in_snapshot: bool,
77 }
78
79 #[derive(Clone, Debug)]
80 pub struct PendingPredicateObligation<'tcx> {
81     pub obligation: PredicateObligation<'tcx>,
82     // This is far more often read than modified, meaning that we
83     // should mostly optimize for reading speed, while modifying is not as relevant.
84     //
85     // For whatever reason using a boxed slice is slower than using a `Vec` here.
86     pub stalled_on: Vec<TyOrConstInferVar<'tcx>>,
87 }
88
89 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
90 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
91 static_assert_size!(PendingPredicateObligation<'_>, 56);
92
93 impl<'a, 'tcx> FulfillmentContext<'tcx> {
94     /// Creates a new fulfillment context.
95     pub fn new() -> FulfillmentContext<'tcx> {
96         FulfillmentContext {
97             predicates: ObligationForest::new(),
98             register_region_obligations: true,
99             usable_in_snapshot: false,
100         }
101     }
102
103     pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
104         FulfillmentContext {
105             predicates: ObligationForest::new(),
106             register_region_obligations: true,
107             usable_in_snapshot: true,
108         }
109     }
110
111     pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
112         FulfillmentContext {
113             predicates: ObligationForest::new(),
114             register_region_obligations: false,
115             usable_in_snapshot: false,
116         }
117     }
118
119     /// Attempts to select obligations using `selcx`.
120     fn select(
121         &mut self,
122         selcx: &mut SelectionContext<'a, 'tcx>,
123     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
124         let span = debug_span!("select", obligation_forest_size = ?self.predicates.len());
125         let _enter = span.enter();
126
127         let mut errors = Vec::new();
128
129         loop {
130             debug!("select: starting another iteration");
131
132             // Process pending obligations.
133             let outcome: Outcome<_, _> =
134                 self.predicates.process_obligations(&mut FulfillProcessor {
135                     selcx,
136                     register_region_obligations: self.register_region_obligations,
137                 });
138             debug!("select: outcome={:#?}", outcome);
139
140             // FIXME: if we kept the original cache key, we could mark projection
141             // obligations as complete for the projection cache here.
142
143             errors.extend(outcome.errors.into_iter().map(to_fulfillment_error));
144
145             // If nothing new was added, no need to keep looping.
146             if outcome.stalled {
147                 break;
148             }
149         }
150
151         debug!(
152             "select({} predicates remaining, {} errors) done",
153             self.predicates.len(),
154             errors.len()
155         );
156
157         if errors.is_empty() { Ok(()) } else { Err(errors) }
158     }
159 }
160
161 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
162     /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
163     /// creating a fresh type variable `$0` as well as a projection
164     /// predicate `<SomeType as SomeTrait>::X == $0`. When the
165     /// inference engine runs, it will attempt to find an impl of
166     /// `SomeTrait` or a where-clause that lets us unify `$0` with
167     /// something concrete. If this fails, we'll unify `$0` with
168     /// `projection_ty` again.
169     fn normalize_projection_type(
170         &mut self,
171         infcx: &InferCtxt<'_, 'tcx>,
172         param_env: ty::ParamEnv<'tcx>,
173         projection_ty: ty::ProjectionTy<'tcx>,
174         cause: ObligationCause<'tcx>,
175     ) -> Ty<'tcx> {
176         debug!(?projection_ty, "normalize_projection_type");
177
178         debug_assert!(!projection_ty.has_escaping_bound_vars());
179
180         // FIXME(#20304) -- cache
181
182         let mut selcx = SelectionContext::new(infcx);
183         let mut obligations = vec![];
184         let normalized_ty = project::normalize_projection_type(
185             &mut selcx,
186             param_env,
187             projection_ty,
188             cause,
189             0,
190             &mut obligations,
191         );
192         self.register_predicate_obligations(infcx, obligations);
193
194         debug!(?normalized_ty);
195
196         normalized_ty
197     }
198
199     fn register_predicate_obligation(
200         &mut self,
201         infcx: &InferCtxt<'_, 'tcx>,
202         obligation: PredicateObligation<'tcx>,
203     ) {
204         // this helps to reduce duplicate errors, as well as making
205         // debug output much nicer to read and so on.
206         let obligation = infcx.resolve_vars_if_possible(obligation);
207
208         debug!(?obligation, "register_predicate_obligation");
209
210         assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
211
212         self.predicates
213             .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
214     }
215
216     fn select_all_or_error(
217         &mut self,
218         infcx: &InferCtxt<'_, 'tcx>,
219     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
220         self.select_where_possible(infcx)?;
221
222         let errors: Vec<_> = self
223             .predicates
224             .to_errors(CodeAmbiguity)
225             .into_iter()
226             .map(to_fulfillment_error)
227             .collect();
228         if errors.is_empty() { Ok(()) } else { Err(errors) }
229     }
230
231     fn select_where_possible(
232         &mut self,
233         infcx: &InferCtxt<'_, 'tcx>,
234     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
235         let mut selcx = SelectionContext::new(infcx);
236         self.select(&mut selcx)
237     }
238
239     fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
240         self.predicates.map_pending_obligations(|o| o.obligation.clone())
241     }
242 }
243
244 struct FulfillProcessor<'a, 'b, 'tcx> {
245     selcx: &'a mut SelectionContext<'b, 'tcx>,
246     register_region_obligations: bool,
247 }
248
249 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
250     os.into_iter()
251         .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
252         .collect()
253 }
254
255 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
256     type Obligation = PendingPredicateObligation<'tcx>;
257     type Error = FulfillmentErrorCode<'tcx>;
258
259     /// Processes a predicate obligation and returns either:
260     /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
261     /// - `Unchanged` if we don't have enough info to be sure
262     /// - `Error(e)` if the predicate does not hold
263     ///
264     /// This is always inlined, despite its size, because it has a single
265     /// callsite and it is called *very* frequently.
266     #[inline(always)]
267     fn process_obligation(
268         &mut self,
269         pending_obligation: &mut Self::Obligation,
270     ) -> ProcessResult<Self::Obligation, Self::Error> {
271         // If we were stalled on some unresolved variables, first check whether
272         // any of them have been resolved; if not, don't bother doing more work
273         // yet.
274         let change = match pending_obligation.stalled_on.len() {
275             // Match arms are in order of frequency, which matters because this
276             // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
277             1 => {
278                 let infer_var = pending_obligation.stalled_on[0];
279                 self.selcx.infcx().ty_or_const_infer_var_changed(infer_var)
280             }
281             0 => {
282                 // In this case we haven't changed, but wish to make a change.
283                 true
284             }
285             _ => {
286                 // This `for` loop was once a call to `all()`, but this lower-level
287                 // form was a perf win. See #64545 for details.
288                 (|| {
289                     for &infer_var in &pending_obligation.stalled_on {
290                         if self.selcx.infcx().ty_or_const_infer_var_changed(infer_var) {
291                             return true;
292                         }
293                     }
294                     false
295                 })()
296             }
297         };
298
299         if !change {
300             debug!(
301                 "process_predicate: pending obligation {:?} still stalled on {:?}",
302                 self.selcx.infcx().resolve_vars_if_possible(pending_obligation.obligation.clone()),
303                 pending_obligation.stalled_on
304             );
305             return ProcessResult::Unchanged;
306         }
307
308         self.progress_changed_obligations(pending_obligation)
309     }
310
311     fn process_backedge<'c, I>(
312         &mut self,
313         cycle: I,
314         _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
315     ) where
316         I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
317     {
318         if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
319             debug!("process_child_obligations: coinductive match");
320         } else {
321             let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
322             self.selcx.infcx().report_overflow_error_cycle(&cycle);
323         }
324     }
325 }
326
327 impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> {
328     // The code calling this method is extremely hot and only rarely
329     // actually uses this, so move this part of the code
330     // out of that loop.
331     #[inline(never)]
332     fn progress_changed_obligations(
333         &mut self,
334         pending_obligation: &mut PendingPredicateObligation<'tcx>,
335     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
336         pending_obligation.stalled_on.truncate(0);
337
338         let obligation = &mut pending_obligation.obligation;
339
340         if obligation.predicate.has_infer_types_or_consts() {
341             obligation.predicate =
342                 self.selcx.infcx().resolve_vars_if_possible(obligation.predicate);
343         }
344
345         debug!(?obligation, ?obligation.cause, "process_obligation");
346
347         let infcx = self.selcx.infcx();
348
349         let binder = obligation.predicate.kind();
350         match binder.no_bound_vars() {
351             None => match binder.skip_binder() {
352                 // Evaluation will discard candidates using the leak check.
353                 // This means we need to pass it the bound version of our
354                 // predicate.
355                 ty::PredicateKind::Trait(trait_ref, _constness) => {
356                     let trait_obligation = obligation.with(binder.rebind(trait_ref));
357
358                     self.process_trait_obligation(
359                         obligation,
360                         trait_obligation,
361                         &mut pending_obligation.stalled_on,
362                     )
363                 }
364                 ty::PredicateKind::Projection(data) => {
365                     let project_obligation = obligation.with(binder.rebind(data));
366
367                     self.process_projection_obligation(
368                         project_obligation,
369                         &mut pending_obligation.stalled_on,
370                     )
371                 }
372                 ty::PredicateKind::RegionOutlives(_)
373                 | ty::PredicateKind::TypeOutlives(_)
374                 | ty::PredicateKind::WellFormed(_)
375                 | ty::PredicateKind::ObjectSafe(_)
376                 | ty::PredicateKind::ClosureKind(..)
377                 | ty::PredicateKind::Subtype(_)
378                 | ty::PredicateKind::ConstEvaluatable(..)
379                 | ty::PredicateKind::ConstEquate(..) => {
380                     let pred = infcx.replace_bound_vars_with_placeholders(binder);
381                     ProcessResult::Changed(mk_pending(vec![
382                         obligation.with(pred.to_predicate(self.selcx.tcx())),
383                     ]))
384                 }
385                 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
386                     bug!("TypeWellFormedFromEnv is only used for Chalk")
387                 }
388             },
389             Some(pred) => match pred {
390                 ty::PredicateKind::Trait(data, _) => {
391                     let trait_obligation = obligation.with(Binder::dummy(data));
392
393                     self.process_trait_obligation(
394                         obligation,
395                         trait_obligation,
396                         &mut pending_obligation.stalled_on,
397                     )
398                 }
399
400                 ty::PredicateKind::RegionOutlives(data) => {
401                     match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) {
402                         Ok(()) => ProcessResult::Changed(vec![]),
403                         Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
404                     }
405                 }
406
407                 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
408                     if self.register_region_obligations {
409                         self.selcx.infcx().register_region_obligation_with_cause(
410                             t_a,
411                             r_b,
412                             &obligation.cause,
413                         );
414                     }
415                     ProcessResult::Changed(vec![])
416                 }
417
418                 ty::PredicateKind::Projection(ref data) => {
419                     let project_obligation = obligation.with(Binder::dummy(*data));
420
421                     self.process_projection_obligation(
422                         project_obligation,
423                         &mut pending_obligation.stalled_on,
424                     )
425                 }
426
427                 ty::PredicateKind::ObjectSafe(trait_def_id) => {
428                     if !self.selcx.tcx().is_object_safe(trait_def_id) {
429                         ProcessResult::Error(CodeSelectionError(Unimplemented))
430                     } else {
431                         ProcessResult::Changed(vec![])
432                     }
433                 }
434
435                 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
436                     match self.selcx.infcx().closure_kind(closure_substs) {
437                         Some(closure_kind) => {
438                             if closure_kind.extends(kind) {
439                                 ProcessResult::Changed(vec![])
440                             } else {
441                                 ProcessResult::Error(CodeSelectionError(Unimplemented))
442                             }
443                         }
444                         None => ProcessResult::Unchanged,
445                     }
446                 }
447
448                 ty::PredicateKind::WellFormed(arg) => {
449                     match wf::obligations(
450                         self.selcx.infcx(),
451                         obligation.param_env,
452                         obligation.cause.body_id,
453                         obligation.recursion_depth + 1,
454                         arg,
455                         obligation.cause.span,
456                     ) {
457                         None => {
458                             pending_obligation.stalled_on =
459                                 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
460                             ProcessResult::Unchanged
461                         }
462                         Some(os) => ProcessResult::Changed(mk_pending(os)),
463                     }
464                 }
465
466                 ty::PredicateKind::Subtype(subtype) => {
467                     match self.selcx.infcx().subtype_predicate(
468                         &obligation.cause,
469                         obligation.param_env,
470                         Binder::dummy(subtype),
471                     ) {
472                         None => {
473                             // None means that both are unresolved.
474                             pending_obligation.stalled_on = vec![
475                                 TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(),
476                                 TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(),
477                             ];
478                             ProcessResult::Unchanged
479                         }
480                         Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
481                         Some(Err(err)) => {
482                             let expected_found =
483                                 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
484                             ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
485                                 expected_found,
486                                 err,
487                             ))
488                         }
489                     }
490                 }
491
492                 ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
493                     match const_evaluatable::is_const_evaluatable(
494                         self.selcx.infcx(),
495                         def_id,
496                         substs,
497                         obligation.param_env,
498                         obligation.cause.span,
499                     ) {
500                         Ok(()) => ProcessResult::Changed(vec![]),
501                         Err(ErrorHandled::TooGeneric) => {
502                             pending_obligation.stalled_on.clear();
503                             pending_obligation.stalled_on.extend(
504                                 substs.iter().filter_map(TyOrConstInferVar::maybe_from_generic_arg),
505                             );
506                             ProcessResult::Unchanged
507                         }
508                         Err(e) => ProcessResult::Error(CodeSelectionError(ConstEvalFailure(e))),
509                     }
510                 }
511
512                 ty::PredicateKind::ConstEquate(c1, c2) => {
513                     debug!(?c1, ?c2, "equating consts");
514                     if self.selcx.tcx().features().const_evaluatable_checked {
515                         // FIXME: we probably should only try to unify abstract constants
516                         // if the constants depend on generic parameters.
517                         //
518                         // Let's just see where this breaks :shrug:
519                         if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
520                             (c1.val, c2.val)
521                         {
522                             if self
523                                 .selcx
524                                 .tcx()
525                                 .try_unify_abstract_consts(((a.def, a.substs), (b.def, b.substs)))
526                             {
527                                 return ProcessResult::Changed(vec![]);
528                             }
529                         }
530                     }
531
532                     let stalled_on = &mut pending_obligation.stalled_on;
533
534                     let mut evaluate = |c: &'tcx Const<'tcx>| {
535                         if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
536                             match self.selcx.infcx().const_eval_resolve(
537                                 obligation.param_env,
538                                 unevaluated,
539                                 Some(obligation.cause.span),
540                             ) {
541                                 Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty)),
542                                 Err(ErrorHandled::TooGeneric) => {
543                                     stalled_on.extend(
544                                         unevaluated
545                                             .substs
546                                             .iter()
547                                             .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
548                                     );
549                                     Err(ErrorHandled::TooGeneric)
550                                 }
551                                 Err(err) => Err(err),
552                             }
553                         } else {
554                             Ok(c)
555                         }
556                     };
557
558                     match (evaluate(c1), evaluate(c2)) {
559                         (Ok(c1), Ok(c2)) => {
560                             match self
561                                 .selcx
562                                 .infcx()
563                                 .at(&obligation.cause, obligation.param_env)
564                                 .eq(c1, c2)
565                             {
566                                 Ok(_) => ProcessResult::Changed(vec![]),
567                                 Err(err) => ProcessResult::Error(
568                                     FulfillmentErrorCode::CodeConstEquateError(
569                                         ExpectedFound::new(true, c1, c2),
570                                         err,
571                                     ),
572                                 ),
573                             }
574                         }
575                         (Err(ErrorHandled::Reported(ErrorReported)), _)
576                         | (_, Err(ErrorHandled::Reported(ErrorReported))) => {
577                             ProcessResult::Error(CodeSelectionError(ConstEvalFailure(
578                                 ErrorHandled::Reported(ErrorReported),
579                             )))
580                         }
581                         (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
582                             span_bug!(
583                                 obligation.cause.span(self.selcx.tcx()),
584                                 "ConstEquate: const_eval_resolve returned an unexpected error"
585                             )
586                         }
587                         (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
588                             ProcessResult::Unchanged
589                         }
590                     }
591                 }
592                 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
593                     bug!("TypeWellFormedFromEnv is only used for Chalk")
594                 }
595             },
596         }
597     }
598
599     #[instrument(level = "debug", skip(self, obligation, stalled_on))]
600     fn process_trait_obligation(
601         &mut self,
602         obligation: &PredicateObligation<'tcx>,
603         trait_obligation: TraitObligation<'tcx>,
604         stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
605     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
606         let infcx = self.selcx.infcx();
607         if obligation.predicate.is_global() {
608             // no type variables present, can use evaluation for better caching.
609             // FIXME: consider caching errors too.
610             if infcx.predicate_must_hold_considering_regions(obligation) {
611                 debug!(
612                     "selecting trait at depth {} evaluated to holds",
613                     obligation.recursion_depth
614                 );
615                 return ProcessResult::Changed(vec![]);
616             }
617         }
618
619         match self.selcx.select(&trait_obligation) {
620             Ok(Some(impl_source)) => {
621                 debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth);
622                 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
623             }
624             Ok(None) => {
625                 debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth);
626
627                 // This is a bit subtle: for the most part, the
628                 // only reason we can fail to make progress on
629                 // trait selection is because we don't have enough
630                 // information about the types in the trait.
631                 stalled_on.clear();
632                 stalled_on.extend(substs_infer_vars(
633                     self.selcx,
634                     trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs),
635                 ));
636
637                 debug!(
638                     "process_predicate: pending obligation {:?} now stalled on {:?}",
639                     infcx.resolve_vars_if_possible(obligation.clone()),
640                     stalled_on
641                 );
642
643                 ProcessResult::Unchanged
644             }
645             Err(selection_err) => {
646                 debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth);
647
648                 ProcessResult::Error(CodeSelectionError(selection_err))
649             }
650         }
651     }
652
653     fn process_projection_obligation(
654         &mut self,
655         project_obligation: PolyProjectionObligation<'tcx>,
656         stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
657     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
658         let tcx = self.selcx.tcx();
659         match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
660             Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)),
661             Ok(Ok(None)) => {
662                 stalled_on.clear();
663                 stalled_on.extend(substs_infer_vars(
664                     self.selcx,
665                     project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs),
666                 ));
667                 ProcessResult::Unchanged
668             }
669             // Let the caller handle the recursion
670             Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![
671                 project_obligation.with(project_obligation.predicate.to_predicate(tcx)),
672             ])),
673             Err(e) => ProcessResult::Error(CodeProjectionError(e)),
674         }
675     }
676 }
677
678 /// Returns the set of inference variables contained in `substs`.
679 fn substs_infer_vars<'a, 'tcx>(
680     selcx: &mut SelectionContext<'a, 'tcx>,
681     substs: ty::Binder<SubstsRef<'tcx>>,
682 ) -> impl Iterator<Item = TyOrConstInferVar<'tcx>> {
683     selcx
684         .infcx()
685         .resolve_vars_if_possible(substs)
686         .skip_binder() // ok because this check doesn't care about regions
687         .iter()
688         .filter(|arg| arg.has_infer_types_or_consts())
689         .flat_map(|arg| {
690             let mut walker = arg.walk();
691             while let Some(c) = walker.next() {
692                 if !c.has_infer_types_or_consts() {
693                     walker.visited.remove(&c);
694                     walker.skip_current_subtree();
695                 }
696             }
697             walker.visited.into_iter()
698         })
699         .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
700 }
701
702 fn to_fulfillment_error<'tcx>(
703     error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
704 ) -> FulfillmentError<'tcx> {
705     let obligation = error.backtrace.into_iter().next().unwrap().obligation;
706     FulfillmentError::new(obligation, error.error)
707 }