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