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