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