]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/fulfill.rs
Add an unused field of type `Option<DefId>` to `ParamEnv` struct.
[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::{DoCompleted, Error, ForestObligation};
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<'_>, 64);
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         debug!("select(obligation-forest-size={})", self.predicates.len());
124
125         let mut errors = Vec::new();
126
127         loop {
128             debug!("select: starting another iteration");
129
130             // Process pending obligations.
131             let outcome = self.predicates.process_obligations(
132                 &mut FulfillProcessor {
133                     selcx,
134                     register_region_obligations: self.register_region_obligations,
135                 },
136                 DoCompleted::No,
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!("normalize_projection_type(projection_ty={:?})", projection_ty);
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!("normalize_projection_type: result={:?}", 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!("register_predicate_obligation(obligation={:?})", 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),
303                 pending_obligation.stalled_on
304             );
305             return ProcessResult::Unchanged;
306         }
307
308         // This part of the code is much colder.
309
310         pending_obligation.stalled_on.truncate(0);
311
312         let obligation = &mut pending_obligation.obligation;
313
314         if obligation.predicate.has_infer_types_or_consts() {
315             obligation.predicate =
316                 self.selcx.infcx().resolve_vars_if_possible(&obligation.predicate);
317         }
318
319         debug!("process_obligation: obligation = {:?} cause = {:?}", obligation, obligation.cause);
320
321         let infcx = self.selcx.infcx();
322
323         match obligation.predicate.kind() {
324             ty::PredicateKind::ForAll(binder) => match binder.skip_binder() {
325                 // Evaluation will discard candidates using the leak check.
326                 // This means we need to pass it the bound version of our
327                 // predicate.
328                 ty::PredicateAtom::Trait(trait_ref, _constness) => {
329                     let trait_obligation = obligation.with(Binder::bind(trait_ref));
330
331                     self.process_trait_obligation(
332                         obligation,
333                         trait_obligation,
334                         &mut pending_obligation.stalled_on,
335                     )
336                 }
337                 ty::PredicateAtom::Projection(data) => {
338                     let project_obligation = obligation.with(Binder::bind(data));
339
340                     self.process_projection_obligation(
341                         project_obligation,
342                         &mut pending_obligation.stalled_on,
343                     )
344                 }
345                 ty::PredicateAtom::RegionOutlives(_)
346                 | ty::PredicateAtom::TypeOutlives(_)
347                 | ty::PredicateAtom::WellFormed(_)
348                 | ty::PredicateAtom::ObjectSafe(_)
349                 | ty::PredicateAtom::ClosureKind(..)
350                 | ty::PredicateAtom::Subtype(_)
351                 | ty::PredicateAtom::ConstEvaluatable(..)
352                 | ty::PredicateAtom::ConstEquate(..) => {
353                     let (pred, _) = infcx.replace_bound_vars_with_placeholders(binder);
354                     ProcessResult::Changed(mk_pending(vec![
355                         obligation.with(pred.to_predicate(self.selcx.tcx())),
356                     ]))
357                 }
358                 ty::PredicateAtom::TypeWellFormedFromEnv(..) => {
359                     bug!("TypeWellFormedFromEnv is only used for Chalk")
360                 }
361             },
362             &ty::PredicateKind::Atom(atom) => match atom {
363                 ty::PredicateAtom::Trait(ref data, _) => {
364                     let trait_obligation = obligation.with(Binder::dummy(*data));
365
366                     self.process_trait_obligation(
367                         obligation,
368                         trait_obligation,
369                         &mut pending_obligation.stalled_on,
370                     )
371                 }
372
373                 ty::PredicateAtom::RegionOutlives(data) => {
374                     match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) {
375                         Ok(()) => ProcessResult::Changed(vec![]),
376                         Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
377                     }
378                 }
379
380                 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
381                     if self.register_region_obligations {
382                         self.selcx.infcx().register_region_obligation_with_cause(
383                             t_a,
384                             r_b,
385                             &obligation.cause,
386                         );
387                     }
388                     ProcessResult::Changed(vec![])
389                 }
390
391                 ty::PredicateAtom::Projection(ref data) => {
392                     let project_obligation = obligation.with(Binder::dummy(*data));
393
394                     self.process_projection_obligation(
395                         project_obligation,
396                         &mut pending_obligation.stalled_on,
397                     )
398                 }
399
400                 ty::PredicateAtom::ObjectSafe(trait_def_id) => {
401                     if !self.selcx.tcx().is_object_safe(trait_def_id) {
402                         ProcessResult::Error(CodeSelectionError(Unimplemented))
403                     } else {
404                         ProcessResult::Changed(vec![])
405                     }
406                 }
407
408                 ty::PredicateAtom::ClosureKind(_, closure_substs, kind) => {
409                     match self.selcx.infcx().closure_kind(closure_substs) {
410                         Some(closure_kind) => {
411                             if closure_kind.extends(kind) {
412                                 ProcessResult::Changed(vec![])
413                             } else {
414                                 ProcessResult::Error(CodeSelectionError(Unimplemented))
415                             }
416                         }
417                         None => ProcessResult::Unchanged,
418                     }
419                 }
420
421                 ty::PredicateAtom::WellFormed(arg) => {
422                     match wf::obligations(
423                         self.selcx.infcx(),
424                         obligation.param_env,
425                         obligation.cause.body_id,
426                         arg,
427                         obligation.cause.span,
428                     ) {
429                         None => {
430                             pending_obligation.stalled_on =
431                                 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
432                             ProcessResult::Unchanged
433                         }
434                         Some(os) => ProcessResult::Changed(mk_pending(os)),
435                     }
436                 }
437
438                 ty::PredicateAtom::Subtype(subtype) => {
439                     match self.selcx.infcx().subtype_predicate(
440                         &obligation.cause,
441                         obligation.param_env,
442                         Binder::dummy(subtype),
443                     ) {
444                         None => {
445                             // None means that both are unresolved.
446                             pending_obligation.stalled_on = vec![
447                                 TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(),
448                                 TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(),
449                             ];
450                             ProcessResult::Unchanged
451                         }
452                         Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
453                         Some(Err(err)) => {
454                             let expected_found =
455                                 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
456                             ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
457                                 expected_found,
458                                 err,
459                             ))
460                         }
461                     }
462                 }
463
464                 ty::PredicateAtom::ConstEvaluatable(def_id, substs) => {
465                     match const_evaluatable::is_const_evaluatable(
466                         self.selcx.infcx(),
467                         def_id,
468                         substs,
469                         obligation.param_env,
470                         obligation.cause.span,
471                     ) {
472                         Ok(()) => ProcessResult::Changed(vec![]),
473                         Err(e) => ProcessResult::Error(CodeSelectionError(ConstEvalFailure(e))),
474                     }
475                 }
476
477                 ty::PredicateAtom::ConstEquate(c1, c2) => {
478                     debug!("equating consts: c1={:?} c2={:?}", c1, c2);
479                     if self.selcx.tcx().features().const_evaluatable_checked {
480                         // FIXME: we probably should only try to unify abstract constants
481                         // if the constants depend on generic parameters.
482                         //
483                         // Let's just see where this breaks :shrug:
484                         if let (
485                             ty::ConstKind::Unevaluated(a_def, a_substs, None),
486                             ty::ConstKind::Unevaluated(b_def, b_substs, None),
487                         ) = (c1.val, c2.val)
488                         {
489                             if self
490                                 .selcx
491                                 .tcx()
492                                 .try_unify_abstract_consts(((a_def, a_substs), (b_def, b_substs)))
493                             {
494                                 return ProcessResult::Changed(vec![]);
495                             }
496                         }
497                     }
498
499                     let stalled_on = &mut pending_obligation.stalled_on;
500
501                     let mut evaluate = |c: &'tcx Const<'tcx>| {
502                         if let ty::ConstKind::Unevaluated(def, substs, promoted) = c.val {
503                             match self.selcx.infcx().const_eval_resolve(
504                                 obligation.param_env,
505                                 def,
506                                 substs,
507                                 promoted,
508                                 Some(obligation.cause.span),
509                             ) {
510                                 Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty)),
511                                 Err(ErrorHandled::TooGeneric) => {
512                                     stalled_on.append(
513                                         &mut substs
514                                             .types()
515                                             .filter_map(|ty| TyOrConstInferVar::maybe_from_ty(ty))
516                                             .collect(),
517                                     );
518                                     Err(ErrorHandled::TooGeneric)
519                                 }
520                                 Err(err) => Err(err),
521                             }
522                         } else {
523                             Ok(c)
524                         }
525                     };
526
527                     match (evaluate(c1), evaluate(c2)) {
528                         (Ok(c1), Ok(c2)) => {
529                             match self
530                                 .selcx
531                                 .infcx()
532                                 .at(&obligation.cause, obligation.param_env)
533                                 .eq(c1, c2)
534                             {
535                                 Ok(_) => ProcessResult::Changed(vec![]),
536                                 Err(err) => ProcessResult::Error(
537                                     FulfillmentErrorCode::CodeConstEquateError(
538                                         ExpectedFound::new(true, c1, c2),
539                                         err,
540                                     ),
541                                 ),
542                             }
543                         }
544                         (Err(ErrorHandled::Reported(ErrorReported)), _)
545                         | (_, Err(ErrorHandled::Reported(ErrorReported))) => {
546                             ProcessResult::Error(CodeSelectionError(ConstEvalFailure(
547                                 ErrorHandled::Reported(ErrorReported),
548                             )))
549                         }
550                         (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
551                             span_bug!(
552                                 obligation.cause.span(self.selcx.tcx()),
553                                 "ConstEquate: const_eval_resolve returned an unexpected error"
554                             )
555                         }
556                         (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
557                             ProcessResult::Unchanged
558                         }
559                     }
560                 }
561                 ty::PredicateAtom::TypeWellFormedFromEnv(..) => {
562                     bug!("TypeWellFormedFromEnv is only used for Chalk")
563                 }
564             },
565         }
566     }
567
568     fn process_backedge<'c, I>(
569         &mut self,
570         cycle: I,
571         _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
572     ) where
573         I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
574     {
575         if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
576             debug!("process_child_obligations: coinductive match");
577         } else {
578             let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
579             self.selcx.infcx().report_overflow_error_cycle(&cycle);
580         }
581     }
582 }
583
584 impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> {
585     fn process_trait_obligation(
586         &mut self,
587         obligation: &PredicateObligation<'tcx>,
588         trait_obligation: TraitObligation<'tcx>,
589         stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
590     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
591         let infcx = self.selcx.infcx();
592         if obligation.predicate.is_global() {
593             // no type variables present, can use evaluation for better caching.
594             // FIXME: consider caching errors too.
595             if infcx.predicate_must_hold_considering_regions(obligation) {
596                 debug!(
597                     "selecting trait `{:?}` at depth {} evaluated to holds",
598                     obligation.predicate, obligation.recursion_depth
599                 );
600                 return ProcessResult::Changed(vec![]);
601             }
602         }
603
604         match self.selcx.select(&trait_obligation) {
605             Ok(Some(impl_source)) => {
606                 debug!(
607                     "selecting trait `{:?}` at depth {} yielded Ok(Some)",
608                     trait_obligation.predicate, obligation.recursion_depth
609                 );
610                 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
611             }
612             Ok(None) => {
613                 debug!(
614                     "selecting trait `{:?}` at depth {} yielded Ok(None)",
615                     trait_obligation.predicate, obligation.recursion_depth
616                 );
617
618                 // This is a bit subtle: for the most part, the
619                 // only reason we can fail to make progress on
620                 // trait selection is because we don't have enough
621                 // information about the types in the trait.
622                 *stalled_on = trait_ref_infer_vars(
623                     self.selcx,
624                     trait_obligation.predicate.map_bound(|pred| pred.trait_ref),
625                 );
626
627                 debug!(
628                     "process_predicate: pending obligation {:?} now stalled on {:?}",
629                     infcx.resolve_vars_if_possible(obligation),
630                     stalled_on
631                 );
632
633                 ProcessResult::Unchanged
634             }
635             Err(selection_err) => {
636                 info!(
637                     "selecting trait `{:?}` at depth {} yielded Err",
638                     trait_obligation.predicate, obligation.recursion_depth
639                 );
640
641                 ProcessResult::Error(CodeSelectionError(selection_err))
642             }
643         }
644     }
645
646     fn process_projection_obligation(
647         &mut self,
648         project_obligation: PolyProjectionObligation<'tcx>,
649         stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
650     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
651         let tcx = self.selcx.tcx();
652         match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
653             Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)),
654             Ok(Ok(None)) => {
655                 *stalled_on = trait_ref_infer_vars(
656                     self.selcx,
657                     project_obligation.predicate.to_poly_trait_ref(self.selcx.tcx()),
658                 );
659                 ProcessResult::Unchanged
660             }
661             // Let the caller handle the recursion
662             Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![
663                 project_obligation.with(project_obligation.predicate.to_predicate(tcx)),
664             ])),
665             Err(e) => ProcessResult::Error(CodeProjectionError(e)),
666         }
667     }
668 }
669
670 /// Returns the set of inference variables contained in a trait ref.
671 fn trait_ref_infer_vars<'a, 'tcx>(
672     selcx: &mut SelectionContext<'a, 'tcx>,
673     trait_ref: ty::PolyTraitRef<'tcx>,
674 ) -> Vec<TyOrConstInferVar<'tcx>> {
675     selcx
676         .infcx()
677         .resolve_vars_if_possible(&trait_ref)
678         .skip_binder()
679         .substs
680         .iter()
681         // FIXME(eddyb) try using `skip_current_subtree` to skip everything that
682         // doesn't contain inference variables, not just the outermost level.
683         .filter(|arg| arg.has_infer_types_or_consts())
684         .flat_map(|arg| arg.walk())
685         .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
686         .collect()
687 }
688
689 fn to_fulfillment_error<'tcx>(
690     error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
691 ) -> FulfillmentError<'tcx> {
692     let obligation = error.backtrace.into_iter().next().unwrap().obligation;
693     FulfillmentError::new(obligation, error.error)
694 }