]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/fulfill.rs
move `considering_regions` to the infcx
[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::error_reporting::InferCtxtExt as _;
29 use crate::traits::project::PolyProjectionObligation;
30 use crate::traits::project::ProjectionCacheKeyExt as _;
31 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
32
33 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
34     /// Note that we include both the `ParamEnv` and the `Predicate`,
35     /// as the `ParamEnv` can influence whether fulfillment succeeds
36     /// or fails.
37     type CacheKey = ty::ParamEnvAnd<'tcx, ty::Predicate<'tcx>>;
38
39     fn as_cache_key(&self) -> Self::CacheKey {
40         self.obligation.param_env.and(self.obligation.predicate)
41     }
42 }
43
44 /// The fulfillment context is used to drive trait resolution. It
45 /// consists of a list of obligations that must be (eventually)
46 /// satisfied. The job is to track which are satisfied, which yielded
47 /// errors, and which are still pending. At any point, users can call
48 /// `select_where_possible`, and the fulfillment context will try to do
49 /// selection, retaining only those obligations that remain
50 /// ambiguous. This may be helpful in pushing type inference
51 /// along. Once all type inference constraints have been generated, the
52 /// method `select_all_or_error` can be used to report any remaining
53 /// ambiguous cases as errors.
54 pub struct FulfillmentContext<'tcx> {
55     // A list of all obligations that have been registered with this
56     // fulfillment context.
57     predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
58
59     relationships: FxHashMap<ty::TyVid, ty::FoundRelationships>,
60
61     // Is it OK to register obligations into this infcx inside
62     // an infcx snapshot?
63     //
64     // The "primary fulfillment" in many cases in typeck lives
65     // outside of any snapshot, so any use of it inside a snapshot
66     // will lead to trouble and therefore is checked against, but
67     // other fulfillment contexts sometimes do live inside of
68     // a snapshot (they don't *straddle* a snapshot, so there
69     // is no trouble there).
70     usable_in_snapshot: bool,
71 }
72
73 #[derive(Clone, Debug)]
74 pub struct PendingPredicateObligation<'tcx> {
75     pub obligation: PredicateObligation<'tcx>,
76     // This is far more often read than modified, meaning that we
77     // should mostly optimize for reading speed, while modifying is not as relevant.
78     //
79     // For whatever reason using a boxed slice is slower than using a `Vec` here.
80     pub stalled_on: Vec<TyOrConstInferVar<'tcx>>,
81 }
82
83 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
84 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
85 static_assert_size!(PendingPredicateObligation<'_>, 72);
86
87 impl<'a, 'tcx> FulfillmentContext<'tcx> {
88     /// Creates a new fulfillment context.
89     pub fn new() -> FulfillmentContext<'tcx> {
90         FulfillmentContext {
91             predicates: ObligationForest::new(),
92             relationships: FxHashMap::default(),
93             usable_in_snapshot: false,
94         }
95     }
96
97     pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
98         FulfillmentContext {
99             predicates: ObligationForest::new(),
100             relationships: FxHashMap::default(),
101             usable_in_snapshot: true,
102         }
103     }
104
105     /// Attempts to select obligations using `selcx`.
106     fn select(&mut self, selcx: &mut SelectionContext<'a, 'tcx>) -> Vec<FulfillmentError<'tcx>> {
107         let span = debug_span!("select", obligation_forest_size = ?self.predicates.len());
108         let _enter = span.enter();
109
110         // Process pending obligations.
111         let outcome: Outcome<_, _> =
112             self.predicates.process_obligations(&mut FulfillProcessor { selcx });
113
114         // FIXME: if we kept the original cache key, we could mark projection
115         // obligations as complete for the projection cache here.
116
117         let errors: Vec<FulfillmentError<'tcx>> =
118             outcome.errors.into_iter().map(to_fulfillment_error).collect();
119
120         debug!(
121             "select({} predicates remaining, {} errors) done",
122             self.predicates.len(),
123             errors.len()
124         );
125
126         errors
127     }
128 }
129
130 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
131     /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
132     /// creating a fresh type variable `$0` as well as a projection
133     /// predicate `<SomeType as SomeTrait>::X == $0`. When the
134     /// inference engine runs, it will attempt to find an impl of
135     /// `SomeTrait` or a where-clause that lets us unify `$0` with
136     /// something concrete. If this fails, we'll unify `$0` with
137     /// `projection_ty` again.
138     #[tracing::instrument(level = "debug", skip(self, infcx, param_env, cause))]
139     fn normalize_projection_type(
140         &mut self,
141         infcx: &InferCtxt<'_, 'tcx>,
142         param_env: ty::ParamEnv<'tcx>,
143         projection_ty: ty::ProjectionTy<'tcx>,
144         cause: ObligationCause<'tcx>,
145     ) -> Ty<'tcx> {
146         debug_assert!(!projection_ty.has_escaping_bound_vars());
147
148         // FIXME(#20304) -- cache
149
150         let mut selcx = SelectionContext::new(infcx);
151         let mut obligations = vec![];
152         let normalized_ty = project::normalize_projection_type(
153             &mut selcx,
154             param_env,
155             projection_ty,
156             cause,
157             0,
158             &mut obligations,
159         );
160         self.register_predicate_obligations(infcx, obligations);
161
162         debug!(?normalized_ty);
163
164         normalized_ty.ty().unwrap()
165     }
166
167     fn register_predicate_obligation(
168         &mut self,
169         infcx: &InferCtxt<'_, 'tcx>,
170         obligation: PredicateObligation<'tcx>,
171     ) {
172         // this helps to reduce duplicate errors, as well as making
173         // debug output much nicer to read and so on.
174         let obligation = infcx.resolve_vars_if_possible(obligation);
175
176         debug!(?obligation, "register_predicate_obligation");
177
178         assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
179
180         super::relationships::update(self, infcx, &obligation);
181
182         self.predicates
183             .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
184     }
185
186     fn select_all_or_error(&mut self, infcx: &InferCtxt<'_, 'tcx>) -> Vec<FulfillmentError<'tcx>> {
187         {
188             let errors = self.select_where_possible(infcx);
189             if !errors.is_empty() {
190                 return errors;
191             }
192         }
193
194         self.predicates.to_errors(CodeAmbiguity).into_iter().map(to_fulfillment_error).collect()
195     }
196
197     fn select_where_possible(
198         &mut self,
199         infcx: &InferCtxt<'_, 'tcx>,
200     ) -> Vec<FulfillmentError<'tcx>> {
201         let mut selcx = SelectionContext::new(infcx);
202         self.select(&mut selcx)
203     }
204
205     fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
206         self.predicates.map_pending_obligations(|o| o.obligation.clone())
207     }
208
209     fn relationships(&mut self) -> &mut FxHashMap<ty::TyVid, ty::FoundRelationships> {
210         &mut self.relationships
211     }
212 }
213
214 struct FulfillProcessor<'a, 'b, 'tcx> {
215     selcx: &'a mut SelectionContext<'b, 'tcx>,
216 }
217
218 fn mk_pending(os: Vec<PredicateObligation<'_>>) -> Vec<PendingPredicateObligation<'_>> {
219     os.into_iter()
220         .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
221         .collect()
222 }
223
224 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
225     type Obligation = PendingPredicateObligation<'tcx>;
226     type Error = FulfillmentErrorCode<'tcx>;
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                         match infcx
363                             .region_outlives_predicate(&obligation.cause, Binder::dummy(data))
364                         {
365                             Ok(()) => ProcessResult::Changed(vec![]),
366                             Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
367                         }
368                     } else {
369                         ProcessResult::Changed(vec![])
370                     }
371                 }
372
373                 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
374                     if infcx.considering_regions {
375                         infcx.register_region_obligation_with_cause(t_a, r_b, &obligation.cause);
376                     }
377                     ProcessResult::Changed(vec![])
378                 }
379
380                 ty::PredicateKind::Projection(ref data) => {
381                     let project_obligation = obligation.with(Binder::dummy(*data));
382
383                     self.process_projection_obligation(
384                         obligation,
385                         project_obligation,
386                         &mut pending_obligation.stalled_on,
387                     )
388                 }
389
390                 ty::PredicateKind::ObjectSafe(trait_def_id) => {
391                     if !self.selcx.tcx().is_object_safe(trait_def_id) {
392                         ProcessResult::Error(CodeSelectionError(Unimplemented))
393                     } else {
394                         ProcessResult::Changed(vec![])
395                     }
396                 }
397
398                 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
399                     match self.selcx.infcx().closure_kind(closure_substs) {
400                         Some(closure_kind) => {
401                             if closure_kind.extends(kind) {
402                                 ProcessResult::Changed(vec![])
403                             } else {
404                                 ProcessResult::Error(CodeSelectionError(Unimplemented))
405                             }
406                         }
407                         None => ProcessResult::Unchanged,
408                     }
409                 }
410
411                 ty::PredicateKind::WellFormed(arg) => {
412                     match wf::obligations(
413                         self.selcx.infcx(),
414                         obligation.param_env,
415                         obligation.cause.body_id,
416                         obligation.recursion_depth + 1,
417                         arg,
418                         obligation.cause.span,
419                     ) {
420                         None => {
421                             pending_obligation.stalled_on =
422                                 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
423                             ProcessResult::Unchanged
424                         }
425                         Some(os) => ProcessResult::Changed(mk_pending(os)),
426                     }
427                 }
428
429                 ty::PredicateKind::Subtype(subtype) => {
430                     match self.selcx.infcx().subtype_predicate(
431                         &obligation.cause,
432                         obligation.param_env,
433                         Binder::dummy(subtype),
434                     ) {
435                         None => {
436                             // None means that both are unresolved.
437                             pending_obligation.stalled_on = vec![
438                                 TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(),
439                                 TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(),
440                             ];
441                             ProcessResult::Unchanged
442                         }
443                         Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
444                         Some(Err(err)) => {
445                             let expected_found =
446                                 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
447                             ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
448                                 expected_found,
449                                 err,
450                             ))
451                         }
452                     }
453                 }
454
455                 ty::PredicateKind::Coerce(coerce) => {
456                     match self.selcx.infcx().coerce_predicate(
457                         &obligation.cause,
458                         obligation.param_env,
459                         Binder::dummy(coerce),
460                     ) {
461                         None => {
462                             // None means that both are unresolved.
463                             pending_obligation.stalled_on = vec![
464                                 TyOrConstInferVar::maybe_from_ty(coerce.a).unwrap(),
465                                 TyOrConstInferVar::maybe_from_ty(coerce.b).unwrap(),
466                             ];
467                             ProcessResult::Unchanged
468                         }
469                         Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
470                         Some(Err(err)) => {
471                             let expected_found = ExpectedFound::new(false, coerce.a, coerce.b);
472                             ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
473                                 expected_found,
474                                 err,
475                             ))
476                         }
477                     }
478                 }
479
480                 ty::PredicateKind::ConstEvaluatable(uv) => {
481                     match const_evaluatable::is_const_evaluatable(
482                         self.selcx.infcx(),
483                         uv,
484                         obligation.param_env,
485                         obligation.cause.span,
486                     ) {
487                         Ok(()) => ProcessResult::Changed(vec![]),
488                         Err(NotConstEvaluatable::MentionsInfer) => {
489                             pending_obligation.stalled_on.clear();
490                             pending_obligation.stalled_on.extend(
491                                 uv.substs
492                                     .iter()
493                                     .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
494                             );
495                             ProcessResult::Unchanged
496                         }
497                         Err(
498                             e @ NotConstEvaluatable::MentionsParam
499                             | e @ NotConstEvaluatable::Error(_),
500                         ) => ProcessResult::Error(CodeSelectionError(
501                             SelectionError::NotConstEvaluatable(e),
502                         )),
503                     }
504                 }
505
506                 ty::PredicateKind::ConstEquate(c1, c2) => {
507                     debug!(?c1, ?c2, "equating consts");
508                     let tcx = self.selcx.tcx();
509                     if tcx.features().generic_const_exprs {
510                         // FIXME: we probably should only try to unify abstract constants
511                         // if the constants depend on generic parameters.
512                         //
513                         // Let's just see where this breaks :shrug:
514                         if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
515                             (c1.kind(), c2.kind())
516                         {
517                             if infcx.try_unify_abstract_consts(
518                                 a.shrink(),
519                                 b.shrink(),
520                                 obligation.param_env,
521                             ) {
522                                 return ProcessResult::Changed(vec![]);
523                             }
524                         }
525                     }
526
527                     let stalled_on = &mut pending_obligation.stalled_on;
528
529                     let mut evaluate = |c: Const<'tcx>| {
530                         if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
531                             match self.selcx.infcx().try_const_eval_resolve(
532                                 obligation.param_env,
533                                 unevaluated,
534                                 c.ty(),
535                                 Some(obligation.cause.span),
536                             ) {
537                                 Ok(val) => Ok(val),
538                                 Err(e) => match e {
539                                     ErrorHandled::TooGeneric => {
540                                         stalled_on.extend(
541                                             unevaluated.substs.iter().filter_map(
542                                                 TyOrConstInferVar::maybe_from_generic_arg,
543                                             ),
544                                         );
545                                         Err(ErrorHandled::TooGeneric)
546                                     }
547                                     _ => Err(e),
548                                 },
549                             }
550                         } else {
551                             Ok(c)
552                         }
553                     };
554
555                     match (evaluate(c1), evaluate(c2)) {
556                         (Ok(c1), Ok(c2)) => {
557                             match self
558                                 .selcx
559                                 .infcx()
560                                 .at(&obligation.cause, obligation.param_env)
561                                 .eq(c1, c2)
562                             {
563                                 Ok(_) => ProcessResult::Changed(vec![]),
564                                 Err(err) => ProcessResult::Error(
565                                     FulfillmentErrorCode::CodeConstEquateError(
566                                         ExpectedFound::new(true, c1, c2),
567                                         err,
568                                     ),
569                                 ),
570                             }
571                         }
572                         (Err(ErrorHandled::Reported(reported)), _)
573                         | (_, Err(ErrorHandled::Reported(reported))) => ProcessResult::Error(
574                             CodeSelectionError(SelectionError::NotConstEvaluatable(
575                                 NotConstEvaluatable::Error(reported),
576                             )),
577                         ),
578                         (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
579                             span_bug!(
580                                 obligation.cause.span(),
581                                 "ConstEquate: const_eval_resolve returned an unexpected error"
582                             )
583                         }
584                         (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
585                             if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
586                                 ProcessResult::Unchanged
587                             } else {
588                                 // Two different constants using generic parameters ~> error.
589                                 let expected_found = ExpectedFound::new(true, c1, c2);
590                                 ProcessResult::Error(FulfillmentErrorCode::CodeConstEquateError(
591                                     expected_found,
592                                     TypeError::ConstMismatch(expected_found),
593                                 ))
594                             }
595                         }
596                     }
597                 }
598                 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
599                     bug!("TypeWellFormedFromEnv is only used for Chalk")
600                 }
601             },
602         }
603     }
604
605     fn process_backedge<'c, I>(
606         &mut self,
607         cycle: I,
608         _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
609     ) where
610         I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
611     {
612         if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
613             debug!("process_child_obligations: coinductive match");
614         } else {
615             let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
616             self.selcx.infcx().report_overflow_error_cycle(&cycle);
617         }
618     }
619 }
620
621 impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> {
622     #[instrument(level = "debug", skip(self, obligation, stalled_on))]
623     fn process_trait_obligation(
624         &mut self,
625         obligation: &PredicateObligation<'tcx>,
626         trait_obligation: TraitObligation<'tcx>,
627         stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
628     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
629         let infcx = self.selcx.infcx();
630         if obligation.predicate.is_global() {
631             // no type variables present, can use evaluation for better caching.
632             // FIXME: consider caching errors too.
633             if infcx.predicate_must_hold_considering_regions(obligation) {
634                 debug!(
635                     "selecting trait at depth {} evaluated to holds",
636                     obligation.recursion_depth
637                 );
638                 return ProcessResult::Changed(vec![]);
639             }
640         }
641
642         match self.selcx.select(&trait_obligation) {
643             Ok(Some(impl_source)) => {
644                 debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth);
645                 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
646             }
647             Ok(None) => {
648                 debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth);
649
650                 // This is a bit subtle: for the most part, the
651                 // only reason we can fail to make progress on
652                 // trait selection is because we don't have enough
653                 // information about the types in the trait.
654                 stalled_on.clear();
655                 stalled_on.extend(substs_infer_vars(
656                     self.selcx,
657                     trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs),
658                 ));
659
660                 debug!(
661                     "process_predicate: pending obligation {:?} now stalled on {:?}",
662                     infcx.resolve_vars_if_possible(obligation.clone()),
663                     stalled_on
664                 );
665
666                 ProcessResult::Unchanged
667             }
668             Err(selection_err) => {
669                 debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth);
670
671                 ProcessResult::Error(CodeSelectionError(selection_err))
672             }
673         }
674     }
675
676     fn process_projection_obligation(
677         &mut self,
678         obligation: &PredicateObligation<'tcx>,
679         project_obligation: PolyProjectionObligation<'tcx>,
680         stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
681     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
682         let tcx = self.selcx.tcx();
683
684         if obligation.predicate.is_global() {
685             // no type variables present, can use evaluation for better caching.
686             // FIXME: consider caching errors too.
687             if self.selcx.infcx().predicate_must_hold_considering_regions(obligation) {
688                 if let Some(key) = ProjectionCacheKey::from_poly_projection_predicate(
689                     &mut self.selcx,
690                     project_obligation.predicate,
691                 ) {
692                     // If `predicate_must_hold_considering_regions` succeeds, then we've
693                     // evaluated all sub-obligations. We can therefore mark the 'root'
694                     // obligation as complete, and skip evaluating sub-obligations.
695                     self.selcx
696                         .infcx()
697                         .inner
698                         .borrow_mut()
699                         .projection_cache()
700                         .complete(key, EvaluationResult::EvaluatedToOk);
701                 }
702                 return ProcessResult::Changed(vec![]);
703             } else {
704                 debug!("Does NOT hold: {:?}", obligation);
705             }
706         }
707
708         match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
709             ProjectAndUnifyResult::Holds(os) => ProcessResult::Changed(mk_pending(os)),
710             ProjectAndUnifyResult::FailedNormalization => {
711                 stalled_on.clear();
712                 stalled_on.extend(substs_infer_vars(
713                     self.selcx,
714                     project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs),
715                 ));
716                 ProcessResult::Unchanged
717             }
718             // Let the caller handle the recursion
719             ProjectAndUnifyResult::Recursive => ProcessResult::Changed(mk_pending(vec![
720                 project_obligation.with(project_obligation.predicate.to_predicate(tcx)),
721             ])),
722             ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
723                 ProcessResult::Error(CodeProjectionError(e))
724             }
725         }
726     }
727 }
728
729 /// Returns the set of inference variables contained in `substs`.
730 fn substs_infer_vars<'a, 'tcx>(
731     selcx: &mut SelectionContext<'a, 'tcx>,
732     substs: ty::Binder<'tcx, SubstsRef<'tcx>>,
733 ) -> impl Iterator<Item = TyOrConstInferVar<'tcx>> {
734     selcx
735         .infcx()
736         .resolve_vars_if_possible(substs)
737         .skip_binder() // ok because this check doesn't care about regions
738         .iter()
739         .filter(|arg| arg.has_infer_types_or_consts())
740         .flat_map(|arg| {
741             let mut walker = arg.walk();
742             while let Some(c) = walker.next() {
743                 if !c.has_infer_types_or_consts() {
744                     walker.visited.remove(&c);
745                     walker.skip_current_subtree();
746                 }
747             }
748             walker.visited.into_iter()
749         })
750         .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
751 }
752
753 fn to_fulfillment_error<'tcx>(
754     error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
755 ) -> FulfillmentError<'tcx> {
756     let mut iter = error.backtrace.into_iter();
757     let obligation = iter.next().unwrap().obligation;
758     // The root obligation is the last item in the backtrace - if there's only
759     // one item, then it's the same as the main obligation
760     let root_obligation = iter.next_back().map_or_else(|| obligation.clone(), |e| e.obligation);
761     FulfillmentError::new(obligation, error.error, root_obligation)
762 }