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