]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/fulfill.rs
Auto merge of #94139 - est31:let_else_rustdoc, r=notriddle
[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::ErrorGuaranteed;
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.process_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 process_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         debug!(?obligation, "process_obligation pre-resolve");
350
351         if obligation.predicate.has_infer_types_or_consts() {
352             obligation.predicate =
353                 self.selcx.infcx().resolve_vars_if_possible(obligation.predicate);
354         }
355
356         debug!(?obligation, ?obligation.cause, "process_obligation");
357
358         let infcx = self.selcx.infcx();
359
360         if obligation.predicate.has_projections() {
361             let mut obligations = Vec::new();
362             let predicate = crate::traits::project::try_normalize_with_depth_to(
363                 self.selcx,
364                 obligation.param_env,
365                 obligation.cause.clone(),
366                 obligation.recursion_depth + 1,
367                 obligation.predicate,
368                 &mut obligations,
369             );
370             if predicate != obligation.predicate {
371                 obligations.push(obligation.with(predicate));
372                 return ProcessResult::Changed(mk_pending(obligations));
373             }
374         }
375         let binder = obligation.predicate.kind();
376         match binder.no_bound_vars() {
377             None => match binder.skip_binder() {
378                 // Evaluation will discard candidates using the leak check.
379                 // This means we need to pass it the bound version of our
380                 // predicate.
381                 ty::PredicateKind::Trait(trait_ref) => {
382                     let trait_obligation = obligation.with(binder.rebind(trait_ref));
383
384                     self.process_trait_obligation(
385                         obligation,
386                         trait_obligation,
387                         &mut pending_obligation.stalled_on,
388                     )
389                 }
390                 ty::PredicateKind::Projection(data) => {
391                     let project_obligation = obligation.with(binder.rebind(data));
392
393                     self.process_projection_obligation(
394                         obligation,
395                         project_obligation,
396                         &mut pending_obligation.stalled_on,
397                     )
398                 }
399                 ty::PredicateKind::RegionOutlives(_)
400                 | ty::PredicateKind::TypeOutlives(_)
401                 | ty::PredicateKind::WellFormed(_)
402                 | ty::PredicateKind::ObjectSafe(_)
403                 | ty::PredicateKind::ClosureKind(..)
404                 | ty::PredicateKind::Subtype(_)
405                 | ty::PredicateKind::Coerce(_)
406                 | ty::PredicateKind::ConstEvaluatable(..)
407                 | ty::PredicateKind::ConstEquate(..) => {
408                     let pred =
409                         ty::Binder::dummy(infcx.replace_bound_vars_with_placeholders(binder));
410                     ProcessResult::Changed(mk_pending(vec![
411                         obligation.with(pred.to_predicate(self.selcx.tcx())),
412                     ]))
413                 }
414                 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
415                     bug!("TypeWellFormedFromEnv is only used for Chalk")
416                 }
417             },
418             Some(pred) => match pred {
419                 ty::PredicateKind::Trait(data) => {
420                     let trait_obligation = obligation.with(Binder::dummy(data));
421
422                     self.process_trait_obligation(
423                         obligation,
424                         trait_obligation,
425                         &mut pending_obligation.stalled_on,
426                     )
427                 }
428
429                 ty::PredicateKind::RegionOutlives(data) => {
430                     match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) {
431                         Ok(()) => ProcessResult::Changed(vec![]),
432                         Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
433                     }
434                 }
435
436                 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
437                     if self.register_region_obligations {
438                         self.selcx.infcx().register_region_obligation_with_cause(
439                             t_a,
440                             r_b,
441                             &obligation.cause,
442                         );
443                     }
444                     ProcessResult::Changed(vec![])
445                 }
446
447                 ty::PredicateKind::Projection(ref data) => {
448                     let project_obligation = obligation.with(Binder::dummy(*data));
449
450                     self.process_projection_obligation(
451                         obligation,
452                         project_obligation,
453                         &mut pending_obligation.stalled_on,
454                     )
455                 }
456
457                 ty::PredicateKind::ObjectSafe(trait_def_id) => {
458                     if !self.selcx.tcx().is_object_safe(trait_def_id) {
459                         ProcessResult::Error(CodeSelectionError(Unimplemented))
460                     } else {
461                         ProcessResult::Changed(vec![])
462                     }
463                 }
464
465                 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
466                     match self.selcx.infcx().closure_kind(closure_substs) {
467                         Some(closure_kind) => {
468                             if closure_kind.extends(kind) {
469                                 ProcessResult::Changed(vec![])
470                             } else {
471                                 ProcessResult::Error(CodeSelectionError(Unimplemented))
472                             }
473                         }
474                         None => ProcessResult::Unchanged,
475                     }
476                 }
477
478                 ty::PredicateKind::WellFormed(arg) => {
479                     match wf::obligations(
480                         self.selcx.infcx(),
481                         obligation.param_env,
482                         obligation.cause.body_id,
483                         obligation.recursion_depth + 1,
484                         arg,
485                         obligation.cause.span,
486                     ) {
487                         None => {
488                             pending_obligation.stalled_on =
489                                 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
490                             ProcessResult::Unchanged
491                         }
492                         Some(os) => ProcessResult::Changed(mk_pending(os)),
493                     }
494                 }
495
496                 ty::PredicateKind::Subtype(subtype) => {
497                     match self.selcx.infcx().subtype_predicate(
498                         &obligation.cause,
499                         obligation.param_env,
500                         Binder::dummy(subtype),
501                     ) {
502                         None => {
503                             // None means that both are unresolved.
504                             pending_obligation.stalled_on = vec![
505                                 TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(),
506                                 TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(),
507                             ];
508                             ProcessResult::Unchanged
509                         }
510                         Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
511                         Some(Err(err)) => {
512                             let expected_found =
513                                 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
514                             ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
515                                 expected_found,
516                                 err,
517                             ))
518                         }
519                     }
520                 }
521
522                 ty::PredicateKind::Coerce(coerce) => {
523                     match self.selcx.infcx().coerce_predicate(
524                         &obligation.cause,
525                         obligation.param_env,
526                         Binder::dummy(coerce),
527                     ) {
528                         None => {
529                             // None means that both are unresolved.
530                             pending_obligation.stalled_on = vec![
531                                 TyOrConstInferVar::maybe_from_ty(coerce.a).unwrap(),
532                                 TyOrConstInferVar::maybe_from_ty(coerce.b).unwrap(),
533                             ];
534                             ProcessResult::Unchanged
535                         }
536                         Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
537                         Some(Err(err)) => {
538                             let expected_found = ExpectedFound::new(false, coerce.a, coerce.b);
539                             ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
540                                 expected_found,
541                                 err,
542                             ))
543                         }
544                     }
545                 }
546
547                 ty::PredicateKind::ConstEvaluatable(uv) => {
548                     match const_evaluatable::is_const_evaluatable(
549                         self.selcx.infcx(),
550                         uv,
551                         obligation.param_env,
552                         obligation.cause.span,
553                     ) {
554                         Ok(()) => ProcessResult::Changed(vec![]),
555                         Err(NotConstEvaluatable::MentionsInfer) => {
556                             pending_obligation.stalled_on.clear();
557                             pending_obligation.stalled_on.extend(
558                                 uv.substs
559                                     .iter()
560                                     .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
561                             );
562                             ProcessResult::Unchanged
563                         }
564                         Err(
565                             e @ NotConstEvaluatable::MentionsParam
566                             | e @ NotConstEvaluatable::Error(_),
567                         ) => ProcessResult::Error(CodeSelectionError(
568                             SelectionError::NotConstEvaluatable(e),
569                         )),
570                     }
571                 }
572
573                 ty::PredicateKind::ConstEquate(c1, c2) => {
574                     debug!(?c1, ?c2, "equating consts");
575                     let tcx = self.selcx.tcx();
576                     if tcx.features().generic_const_exprs {
577                         // FIXME: we probably should only try to unify abstract constants
578                         // if the constants depend on generic parameters.
579                         //
580                         // Let's just see where this breaks :shrug:
581                         if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
582                             (c1.val(), c2.val())
583                         {
584                             if infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
585                                 return ProcessResult::Changed(vec![]);
586                             }
587                         }
588                     }
589
590                     let stalled_on = &mut pending_obligation.stalled_on;
591
592                     let mut evaluate = |c: Const<'tcx>| {
593                         if let ty::ConstKind::Unevaluated(unevaluated) = c.val() {
594                             match self.selcx.infcx().const_eval_resolve(
595                                 obligation.param_env,
596                                 unevaluated,
597                                 Some(obligation.cause.span),
598                             ) {
599                                 Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty())),
600                                 Err(ErrorHandled::TooGeneric) => {
601                                     stalled_on.extend(
602                                         unevaluated
603                                             .substs
604                                             .iter()
605                                             .filter_map(TyOrConstInferVar::maybe_from_generic_arg),
606                                     );
607                                     Err(ErrorHandled::TooGeneric)
608                                 }
609                                 Err(err) => Err(err),
610                             }
611                         } else {
612                             Ok(c)
613                         }
614                     };
615
616                     match (evaluate(c1), evaluate(c2)) {
617                         (Ok(c1), Ok(c2)) => {
618                             match self
619                                 .selcx
620                                 .infcx()
621                                 .at(&obligation.cause, obligation.param_env)
622                                 .eq(c1, c2)
623                             {
624                                 Ok(_) => ProcessResult::Changed(vec![]),
625                                 Err(err) => ProcessResult::Error(
626                                     FulfillmentErrorCode::CodeConstEquateError(
627                                         ExpectedFound::new(true, c1, c2),
628                                         err,
629                                     ),
630                                 ),
631                             }
632                         }
633                         (Err(ErrorHandled::Reported(ErrorGuaranteed)), _)
634                         | (_, Err(ErrorHandled::Reported(ErrorGuaranteed))) => {
635                             ProcessResult::Error(CodeSelectionError(
636                                 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(
637                                     ErrorGuaranteed,
638                                 )),
639                             ))
640                         }
641                         (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
642                             span_bug!(
643                                 obligation.cause.span(self.selcx.tcx()),
644                                 "ConstEquate: const_eval_resolve returned an unexpected error"
645                             )
646                         }
647                         (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
648                             if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
649                                 ProcessResult::Unchanged
650                             } else {
651                                 // Two different constants using generic parameters ~> error.
652                                 let expected_found = ExpectedFound::new(true, c1, c2);
653                                 ProcessResult::Error(FulfillmentErrorCode::CodeConstEquateError(
654                                     expected_found,
655                                     TypeError::ConstMismatch(expected_found),
656                                 ))
657                             }
658                         }
659                     }
660                 }
661                 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
662                     bug!("TypeWellFormedFromEnv is only used for Chalk")
663                 }
664             },
665         }
666     }
667
668     #[instrument(level = "debug", skip(self, obligation, stalled_on))]
669     fn process_trait_obligation(
670         &mut self,
671         obligation: &PredicateObligation<'tcx>,
672         trait_obligation: TraitObligation<'tcx>,
673         stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
674     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
675         let infcx = self.selcx.infcx();
676         if obligation.predicate.is_global() {
677             // no type variables present, can use evaluation for better caching.
678             // FIXME: consider caching errors too.
679             if infcx.predicate_must_hold_considering_regions(obligation) {
680                 debug!(
681                     "selecting trait at depth {} evaluated to holds",
682                     obligation.recursion_depth
683                 );
684                 return ProcessResult::Changed(vec![]);
685             }
686         }
687
688         match self.selcx.select(&trait_obligation) {
689             Ok(Some(impl_source)) => {
690                 debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth);
691                 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
692             }
693             Ok(None) => {
694                 debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth);
695
696                 // This is a bit subtle: for the most part, the
697                 // only reason we can fail to make progress on
698                 // trait selection is because we don't have enough
699                 // information about the types in the trait.
700                 stalled_on.clear();
701                 stalled_on.extend(substs_infer_vars(
702                     self.selcx,
703                     trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs),
704                 ));
705
706                 debug!(
707                     "process_predicate: pending obligation {:?} now stalled on {:?}",
708                     infcx.resolve_vars_if_possible(obligation.clone()),
709                     stalled_on
710                 );
711
712                 ProcessResult::Unchanged
713             }
714             Err(selection_err) => {
715                 debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth);
716
717                 ProcessResult::Error(CodeSelectionError(selection_err))
718             }
719         }
720     }
721
722     fn process_projection_obligation(
723         &mut self,
724         obligation: &PredicateObligation<'tcx>,
725         project_obligation: PolyProjectionObligation<'tcx>,
726         stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
727     ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
728         let tcx = self.selcx.tcx();
729
730         if obligation.predicate.is_global() {
731             // no type variables present, can use evaluation for better caching.
732             // FIXME: consider caching errors too.
733             if self.selcx.infcx().predicate_must_hold_considering_regions(obligation) {
734                 if let Some(key) = ProjectionCacheKey::from_poly_projection_predicate(
735                     &mut self.selcx,
736                     project_obligation.predicate,
737                 ) {
738                     // If `predicate_must_hold_considering_regions` succeeds, then we've
739                     // evaluated all sub-obligations. We can therefore mark the 'root'
740                     // obligation as complete, and skip evaluating sub-obligations.
741                     self.selcx
742                         .infcx()
743                         .inner
744                         .borrow_mut()
745                         .projection_cache()
746                         .complete(key, EvaluationResult::EvaluatedToOk);
747                 }
748                 return ProcessResult::Changed(vec![]);
749             } else {
750                 tracing::debug!("Does NOT hold: {:?}", obligation);
751             }
752         }
753
754         match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
755             Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)),
756             Ok(Ok(None)) => {
757                 stalled_on.clear();
758                 stalled_on.extend(substs_infer_vars(
759                     self.selcx,
760                     project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs),
761                 ));
762                 ProcessResult::Unchanged
763             }
764             // Let the caller handle the recursion
765             Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![
766                 project_obligation.with(project_obligation.predicate.to_predicate(tcx)),
767             ])),
768             Err(e) => ProcessResult::Error(CodeProjectionError(e)),
769         }
770     }
771 }
772
773 /// Returns the set of inference variables contained in `substs`.
774 fn substs_infer_vars<'a, 'tcx>(
775     selcx: &mut SelectionContext<'a, 'tcx>,
776     substs: ty::Binder<'tcx, SubstsRef<'tcx>>,
777 ) -> impl Iterator<Item = TyOrConstInferVar<'tcx>> {
778     selcx
779         .infcx()
780         .resolve_vars_if_possible(substs)
781         .skip_binder() // ok because this check doesn't care about regions
782         .iter()
783         .filter(|arg| arg.has_infer_types_or_consts())
784         .flat_map(|arg| {
785             let mut walker = arg.walk();
786             while let Some(c) = walker.next() {
787                 if !c.has_infer_types_or_consts() {
788                     walker.visited.remove(&c);
789                     walker.skip_current_subtree();
790                 }
791             }
792             walker.visited.into_iter()
793         })
794         .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
795 }
796
797 fn to_fulfillment_error<'tcx>(
798     error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
799 ) -> FulfillmentError<'tcx> {
800     let mut iter = error.backtrace.into_iter();
801     let obligation = iter.next().unwrap().obligation;
802     // The root obligation is the last item in the backtrace - if there's only
803     // one item, then it's the same as the main obligation
804     let root_obligation = iter.next_back().map_or_else(|| obligation.clone(), |e| e.obligation);
805     FulfillmentError::new(obligation, error.error, root_obligation)
806 }