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