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