]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/auto_trait.rs
Rollup merge of #104158 - Ayush1325:executable, r=Mark-Simulacrum
[rust.git] / compiler / rustc_trait_selection / src / traits / auto_trait.rs
1 //! Support code for rustdoc and external tools.
2 //! You really don't want to be using this unless you need to.
3
4 use super::*;
5
6 use crate::errors::UnableToConstructConstantValue;
7 use crate::infer::region_constraints::{Constraint, RegionConstraintData};
8 use crate::infer::InferCtxt;
9 use crate::traits::project::ProjectAndUnifyResult;
10 use rustc_middle::mir::interpret::ErrorHandled;
11 use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable};
12 use rustc_middle::ty::visit::TypeVisitable;
13 use rustc_middle::ty::{PolyTraitRef, Region, RegionVid};
14
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
16
17 use std::collections::hash_map::Entry;
18 use std::collections::VecDeque;
19 use std::iter;
20
21 // FIXME(twk): this is obviously not nice to duplicate like that
22 #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
23 pub enum RegionTarget<'tcx> {
24     Region(Region<'tcx>),
25     RegionVid(RegionVid),
26 }
27
28 #[derive(Default, Debug, Clone)]
29 pub struct RegionDeps<'tcx> {
30     larger: FxIndexSet<RegionTarget<'tcx>>,
31     smaller: FxIndexSet<RegionTarget<'tcx>>,
32 }
33
34 pub enum AutoTraitResult<A> {
35     ExplicitImpl,
36     PositiveImpl(A),
37     NegativeImpl,
38 }
39
40 #[allow(dead_code)]
41 impl<A> AutoTraitResult<A> {
42     fn is_auto(&self) -> bool {
43         matches!(self, AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl)
44     }
45 }
46
47 pub struct AutoTraitInfo<'cx> {
48     pub full_user_env: ty::ParamEnv<'cx>,
49     pub region_data: RegionConstraintData<'cx>,
50     pub vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
51 }
52
53 pub struct AutoTraitFinder<'tcx> {
54     tcx: TyCtxt<'tcx>,
55 }
56
57 impl<'tcx> AutoTraitFinder<'tcx> {
58     pub fn new(tcx: TyCtxt<'tcx>) -> Self {
59         AutoTraitFinder { tcx }
60     }
61
62     /// Makes a best effort to determine whether and under which conditions an auto trait is
63     /// implemented for a type. For example, if you have
64     ///
65     /// ```
66     /// struct Foo<T> { data: Box<T> }
67     /// ```
68     ///
69     /// then this might return that `Foo<T>: Send` if `T: Send` (encoded in the AutoTraitResult
70     /// type). The analysis attempts to account for custom impls as well as other complex cases.
71     /// This result is intended for use by rustdoc and other such consumers.
72     ///
73     /// (Note that due to the coinductive nature of Send, the full and correct result is actually
74     /// quite simple to generate. That is, when a type has no custom impl, it is Send iff its field
75     /// types are all Send. So, in our example, we might have that `Foo<T>: Send` if `Box<T>: Send`.
76     /// But this is often not the best way to present to the user.)
77     ///
78     /// Warning: The API should be considered highly unstable, and it may be refactored or removed
79     /// in the future.
80     pub fn find_auto_trait_generics<A>(
81         &self,
82         ty: Ty<'tcx>,
83         orig_env: ty::ParamEnv<'tcx>,
84         trait_did: DefId,
85         mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
86     ) -> AutoTraitResult<A> {
87         let tcx = self.tcx;
88
89         let trait_ref = ty::TraitRef { def_id: trait_did, substs: tcx.mk_substs_trait(ty, &[]) };
90
91         let trait_pred = ty::Binder::dummy(trait_ref);
92
93         let infcx = tcx.infer_ctxt().build();
94         let mut selcx = SelectionContext::new(&infcx);
95         for f in [
96             PolyTraitRef::to_poly_trait_predicate,
97             PolyTraitRef::to_poly_trait_predicate_negative_polarity,
98         ] {
99             let result =
100                 selcx.select(&Obligation::new(ObligationCause::dummy(), orig_env, f(&trait_pred)));
101             if let Ok(Some(ImplSource::UserDefined(_))) = result {
102                 debug!(
103                     "find_auto_trait_generics({:?}): \
104                  manual impl found, bailing out",
105                     trait_ref
106                 );
107                 // If an explicit impl exists, it always takes priority over an auto impl
108                 return AutoTraitResult::ExplicitImpl;
109             }
110         }
111
112         let infcx = tcx.infer_ctxt().build();
113         let mut fresh_preds = FxHashSet::default();
114
115         // Due to the way projections are handled by SelectionContext, we need to run
116         // evaluate_predicates twice: once on the original param env, and once on the result of
117         // the first evaluate_predicates call.
118         //
119         // The problem is this: most of rustc, including SelectionContext and traits::project,
120         // are designed to work with a concrete usage of a type (e.g., Vec<u8>
121         // fn<T>() { Vec<T> }. This information will generally never change - given
122         // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
123         // If we're unable to prove that 'T' implements a particular trait, we're done -
124         // there's nothing left to do but error out.
125         //
126         // However, synthesizing an auto trait impl works differently. Here, we start out with
127         // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing
128         // with - and progressively discover the conditions we need to fulfill for it to
129         // implement a certain auto trait. This ends up breaking two assumptions made by trait
130         // selection and projection:
131         //
132         // * We can always cache the result of a particular trait selection for the lifetime of
133         // an InfCtxt
134         // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T:
135         // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K'
136         //
137         // We fix the first assumption by manually clearing out all of the InferCtxt's caches
138         // in between calls to SelectionContext.select. This allows us to keep all of the
139         // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift
140         // them between calls.
141         //
142         // We fix the second assumption by reprocessing the result of our first call to
143         // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first
144         // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass,
145         // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing
146         // SelectionContext to return it back to us.
147
148         let Some((new_env, user_env)) = self.evaluate_predicates(
149             &infcx,
150             trait_did,
151             ty,
152             orig_env,
153             orig_env,
154             &mut fresh_preds,
155             false,
156         ) else {
157             return AutoTraitResult::NegativeImpl;
158         };
159
160         let (full_env, full_user_env) = self
161             .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds, true)
162             .unwrap_or_else(|| {
163                 panic!("Failed to fully process: {:?} {:?} {:?}", ty, trait_did, orig_env)
164             });
165
166         debug!(
167             "find_auto_trait_generics({:?}): fulfilling \
168              with {:?}",
169             trait_ref, full_env
170         );
171         infcx.clear_caches();
172
173         // At this point, we already have all of the bounds we need. FulfillmentContext is used
174         // to store all of the necessary region/lifetime bounds in the InferContext, as well as
175         // an additional sanity check.
176         let errors =
177             super::fully_solve_bound(&infcx, ObligationCause::dummy(), full_env, ty, trait_did);
178         if !errors.is_empty() {
179             panic!("Unable to fulfill trait {:?} for '{:?}': {:?}", trait_did, ty, errors);
180         }
181
182         infcx.process_registered_region_obligations(&Default::default(), full_env);
183
184         let region_data =
185             infcx.inner.borrow_mut().unwrap_region_constraints().region_constraint_data().clone();
186
187         let vid_to_region = self.map_vid_to_region(&region_data);
188
189         let info = AutoTraitInfo { full_user_env, region_data, vid_to_region };
190
191         AutoTraitResult::PositiveImpl(auto_trait_callback(info))
192     }
193 }
194
195 impl<'tcx> AutoTraitFinder<'tcx> {
196     /// The core logic responsible for computing the bounds for our synthesized impl.
197     ///
198     /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like
199     /// `FulfillmentContext`, we recursively select the nested obligations of predicates we
200     /// encounter. However, whenever we encounter an `UnimplementedError` involving a type
201     /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular
202     /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met.
203     ///
204     /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key
205     /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete
206     /// user code. According, it considers all possible ways that a `Predicate` could be met, which
207     /// isn't always what we want for a synthesized impl. For example, given the predicate `T:
208     /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T:
209     /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`,
210     /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up.
211     /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl
212     /// like this:
213     /// ```ignore (illustrative)
214     /// impl<T> Send for Foo<T> where T: IntoIterator
215     /// ```
216     /// While it might be technically true that Foo implements Send where `T: IntoIterator`,
217     /// the bound is overly restrictive - it's really only necessary that `T: Iterator`.
218     ///
219     /// For this reason, `evaluate_predicates` handles predicates with type variables specially.
220     /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately
221     /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later
222     /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator`
223     /// needs to hold.
224     ///
225     /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever
226     /// constructed once for a given type. As part of the construction process, the `ParamEnv` will
227     /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo<T: Copy>`, the
228     /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our
229     /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate_predicates`, or
230     /// else `SelectionContext` will choke on the missing predicates. However, this should never
231     /// show up in the final synthesized generics: we don't want our generated docs page to contain
232     /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a
233     /// separate `user_env`, which only holds the predicates that will actually be displayed to the
234     /// user.
235     fn evaluate_predicates(
236         &self,
237         infcx: &InferCtxt<'tcx>,
238         trait_did: DefId,
239         ty: Ty<'tcx>,
240         param_env: ty::ParamEnv<'tcx>,
241         user_env: ty::ParamEnv<'tcx>,
242         fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
243         only_projections: bool,
244     ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> {
245         let tcx = infcx.tcx;
246
247         // Don't try to process any nested obligations involving predicates
248         // that are already in the `ParamEnv` (modulo regions): we already
249         // know that they must hold.
250         for predicate in param_env.caller_bounds() {
251             fresh_preds.insert(self.clean_pred(infcx, predicate));
252         }
253
254         let mut select = SelectionContext::new(&infcx);
255
256         let mut already_visited = FxHashSet::default();
257         let mut predicates = VecDeque::new();
258         predicates.push_back(ty::Binder::dummy(ty::TraitPredicate {
259             trait_ref: ty::TraitRef {
260                 def_id: trait_did,
261                 substs: infcx.tcx.mk_substs_trait(ty, &[]),
262             },
263             constness: ty::BoundConstness::NotConst,
264             // Auto traits are positive
265             polarity: ty::ImplPolarity::Positive,
266         }));
267
268         let computed_preds = param_env.caller_bounds().iter();
269         let mut user_computed_preds: FxIndexSet<_> = user_env.caller_bounds().iter().collect();
270
271         let mut new_env = param_env;
272         let dummy_cause = ObligationCause::dummy();
273
274         while let Some(pred) = predicates.pop_front() {
275             infcx.clear_caches();
276
277             if !already_visited.insert(pred) {
278                 continue;
279             }
280
281             // Call `infcx.resolve_vars_if_possible` to see if we can
282             // get rid of any inference variables.
283             let obligation =
284                 infcx.resolve_vars_if_possible(Obligation::new(dummy_cause.clone(), new_env, pred));
285             let result = select.select(&obligation);
286
287             match result {
288                 Ok(Some(ref impl_source)) => {
289                     // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`),
290                     // we immediately bail out, since it's impossible for us to continue.
291
292                     if let ImplSource::UserDefined(ImplSourceUserDefinedData {
293                         impl_def_id, ..
294                     }) = impl_source
295                     {
296                         // Blame 'tidy' for the weird bracket placement.
297                         if infcx.tcx.impl_polarity(*impl_def_id) == ty::ImplPolarity::Negative {
298                             debug!(
299                                 "evaluate_nested_obligations: found explicit negative impl\
300                                         {:?}, bailing out",
301                                 impl_def_id
302                             );
303                             return None;
304                         }
305                     }
306
307                     let obligations = impl_source.borrow_nested_obligations().iter().cloned();
308
309                     if !self.evaluate_nested_obligations(
310                         ty,
311                         obligations,
312                         &mut user_computed_preds,
313                         fresh_preds,
314                         &mut predicates,
315                         &mut select,
316                         only_projections,
317                     ) {
318                         return None;
319                     }
320                 }
321                 Ok(None) => {}
322                 Err(SelectionError::Unimplemented) => {
323                     if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) {
324                         already_visited.remove(&pred);
325                         self.add_user_pred(&mut user_computed_preds, pred.to_predicate(self.tcx));
326                         predicates.push_back(pred);
327                     } else {
328                         debug!(
329                             "evaluate_nested_obligations: `Unimplemented` found, bailing: \
330                              {:?} {:?} {:?}",
331                             ty,
332                             pred,
333                             pred.skip_binder().trait_ref.substs
334                         );
335                         return None;
336                     }
337                 }
338                 _ => panic!("Unexpected error for '{:?}': {:?}", ty, result),
339             };
340
341             let normalized_preds = elaborate_predicates(
342                 tcx,
343                 computed_preds.clone().chain(user_computed_preds.iter().cloned()),
344             )
345             .map(|o| o.predicate);
346             new_env = ty::ParamEnv::new(
347                 tcx.mk_predicates(normalized_preds),
348                 param_env.reveal(),
349                 param_env.constness(),
350             );
351         }
352
353         let final_user_env = ty::ParamEnv::new(
354             tcx.mk_predicates(user_computed_preds.into_iter()),
355             user_env.reveal(),
356             user_env.constness(),
357         );
358         debug!(
359             "evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \
360              '{:?}'",
361             ty, trait_did, new_env, final_user_env
362         );
363
364         Some((new_env, final_user_env))
365     }
366
367     /// This method is designed to work around the following issue:
368     /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`,
369     /// progressively building a `ParamEnv` based on the results we get.
370     /// However, our usage of `SelectionContext` differs from its normal use within the compiler,
371     /// in that we capture and re-reprocess predicates from `Unimplemented` errors.
372     ///
373     /// This can lead to a corner case when dealing with region parameters.
374     /// During our selection loop in `evaluate_predicates`, we might end up with
375     /// two trait predicates that differ only in their region parameters:
376     /// one containing a HRTB lifetime parameter, and one containing a 'normal'
377     /// lifetime parameter. For example:
378     /// ```ignore (illustrative)
379     /// T as MyTrait<'a>
380     /// T as MyTrait<'static>
381     /// ```
382     /// If we put both of these predicates in our computed `ParamEnv`, we'll
383     /// confuse `SelectionContext`, since it will (correctly) view both as being applicable.
384     ///
385     /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB
386     /// Our end goal is to generate a user-visible description of the conditions
387     /// under which a type implements an auto trait. A trait predicate involving
388     /// a HRTB means that the type needs to work with any choice of lifetime,
389     /// not just one specific lifetime (e.g., `'static`).
390     fn add_user_pred(
391         &self,
392         user_computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
393         new_pred: ty::Predicate<'tcx>,
394     ) {
395         let mut should_add_new = true;
396         user_computed_preds.retain(|&old_pred| {
397             if let (ty::PredicateKind::Trait(new_trait), ty::PredicateKind::Trait(old_trait)) =
398                 (new_pred.kind().skip_binder(), old_pred.kind().skip_binder())
399             {
400                 if new_trait.def_id() == old_trait.def_id() {
401                     let new_substs = new_trait.trait_ref.substs;
402                     let old_substs = old_trait.trait_ref.substs;
403
404                     if !new_substs.types().eq(old_substs.types()) {
405                         // We can't compare lifetimes if the types are different,
406                         // so skip checking `old_pred`.
407                         return true;
408                     }
409
410                     for (new_region, old_region) in
411                         iter::zip(new_substs.regions(), old_substs.regions())
412                     {
413                         match (*new_region, *old_region) {
414                             // If both predicates have an `ReLateBound` (a HRTB) in the
415                             // same spot, we do nothing.
416                             (ty::ReLateBound(_, _), ty::ReLateBound(_, _)) => {}
417
418                             (ty::ReLateBound(_, _), _) | (_, ty::ReVar(_)) => {
419                                 // One of these is true:
420                                 // The new predicate has a HRTB in a spot where the old
421                                 // predicate does not (if they both had a HRTB, the previous
422                                 // match arm would have executed). A HRBT is a 'stricter'
423                                 // bound than anything else, so we want to keep the newer
424                                 // predicate (with the HRBT) in place of the old predicate.
425                                 //
426                                 // OR
427                                 //
428                                 // The old predicate has a region variable where the new
429                                 // predicate has some other kind of region. An region
430                                 // variable isn't something we can actually display to a user,
431                                 // so we choose their new predicate (which doesn't have a region
432                                 // variable).
433                                 //
434                                 // In both cases, we want to remove the old predicate,
435                                 // from `user_computed_preds`, and replace it with the new
436                                 // one. Having both the old and the new
437                                 // predicate in a `ParamEnv` would confuse `SelectionContext`.
438                                 //
439                                 // We're currently in the predicate passed to 'retain',
440                                 // so we return `false` to remove the old predicate from
441                                 // `user_computed_preds`.
442                                 return false;
443                             }
444                             (_, ty::ReLateBound(_, _)) | (ty::ReVar(_), _) => {
445                                 // This is the opposite situation as the previous arm.
446                                 // One of these is true:
447                                 //
448                                 // The old predicate has a HRTB lifetime in a place where the
449                                 // new predicate does not.
450                                 //
451                                 // OR
452                                 //
453                                 // The new predicate has a region variable where the old
454                                 // predicate has some other type of region.
455                                 //
456                                 // We want to leave the old
457                                 // predicate in `user_computed_preds`, and skip adding
458                                 // new_pred to `user_computed_params`.
459                                 should_add_new = false
460                             }
461                             _ => {}
462                         }
463                     }
464                 }
465             }
466             true
467         });
468
469         if should_add_new {
470             user_computed_preds.insert(new_pred);
471         }
472     }
473
474     /// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s
475     /// to each other, we match `ty::RegionVid`s to `ty::Region`s.
476     fn map_vid_to_region<'cx>(
477         &self,
478         regions: &RegionConstraintData<'cx>,
479     ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> {
480         let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap::default();
481         let mut finished_map = FxHashMap::default();
482
483         for constraint in regions.constraints.keys() {
484             match constraint {
485                 &Constraint::VarSubVar(r1, r2) => {
486                     {
487                         let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default();
488                         deps1.larger.insert(RegionTarget::RegionVid(r2));
489                     }
490
491                     let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default();
492                     deps2.smaller.insert(RegionTarget::RegionVid(r1));
493                 }
494                 &Constraint::RegSubVar(region, vid) => {
495                     {
496                         let deps1 = vid_map.entry(RegionTarget::Region(region)).or_default();
497                         deps1.larger.insert(RegionTarget::RegionVid(vid));
498                     }
499
500                     let deps2 = vid_map.entry(RegionTarget::RegionVid(vid)).or_default();
501                     deps2.smaller.insert(RegionTarget::Region(region));
502                 }
503                 &Constraint::VarSubReg(vid, region) => {
504                     finished_map.insert(vid, region);
505                 }
506                 &Constraint::RegSubReg(r1, r2) => {
507                     {
508                         let deps1 = vid_map.entry(RegionTarget::Region(r1)).or_default();
509                         deps1.larger.insert(RegionTarget::Region(r2));
510                     }
511
512                     let deps2 = vid_map.entry(RegionTarget::Region(r2)).or_default();
513                     deps2.smaller.insert(RegionTarget::Region(r1));
514                 }
515             }
516         }
517
518         while !vid_map.is_empty() {
519             let target = *vid_map.keys().next().expect("Keys somehow empty");
520             let deps = vid_map.remove(&target).expect("Entry somehow missing");
521
522             for smaller in deps.smaller.iter() {
523                 for larger in deps.larger.iter() {
524                     match (smaller, larger) {
525                         (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
526                             if let Entry::Occupied(v) = vid_map.entry(*smaller) {
527                                 let smaller_deps = v.into_mut();
528                                 smaller_deps.larger.insert(*larger);
529                                 smaller_deps.larger.remove(&target);
530                             }
531
532                             if let Entry::Occupied(v) = vid_map.entry(*larger) {
533                                 let larger_deps = v.into_mut();
534                                 larger_deps.smaller.insert(*smaller);
535                                 larger_deps.smaller.remove(&target);
536                             }
537                         }
538                         (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
539                             finished_map.insert(v1, r1);
540                         }
541                         (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
542                             // Do nothing; we don't care about regions that are smaller than vids.
543                         }
544                         (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
545                             if let Entry::Occupied(v) = vid_map.entry(*smaller) {
546                                 let smaller_deps = v.into_mut();
547                                 smaller_deps.larger.insert(*larger);
548                                 smaller_deps.larger.remove(&target);
549                             }
550
551                             if let Entry::Occupied(v) = vid_map.entry(*larger) {
552                                 let larger_deps = v.into_mut();
553                                 larger_deps.smaller.insert(*smaller);
554                                 larger_deps.smaller.remove(&target);
555                             }
556                         }
557                     }
558                 }
559             }
560         }
561         finished_map
562     }
563
564     fn is_param_no_infer(&self, substs: SubstsRef<'_>) -> bool {
565         self.is_of_param(substs.type_at(0)) && !substs.types().any(|t| t.has_infer_types())
566     }
567
568     pub fn is_of_param(&self, ty: Ty<'_>) -> bool {
569         match ty.kind() {
570             ty::Param(_) => true,
571             ty::Projection(p) => self.is_of_param(p.self_ty()),
572             _ => false,
573         }
574     }
575
576     fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'_>) -> bool {
577         if let Some(ty) = p.term().skip_binder().ty() {
578             matches!(ty.kind(), ty::Projection(proj) if proj == &p.skip_binder().projection_ty)
579         } else {
580             false
581         }
582     }
583
584     fn evaluate_nested_obligations(
585         &self,
586         ty: Ty<'_>,
587         nested: impl Iterator<Item = Obligation<'tcx, ty::Predicate<'tcx>>>,
588         computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
589         fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>,
590         predicates: &mut VecDeque<ty::PolyTraitPredicate<'tcx>>,
591         select: &mut SelectionContext<'_, 'tcx>,
592         only_projections: bool,
593     ) -> bool {
594         let dummy_cause = ObligationCause::dummy();
595
596         for obligation in nested {
597             let is_new_pred =
598                 fresh_preds.insert(self.clean_pred(select.infcx(), obligation.predicate));
599
600             // Resolve any inference variables that we can, to help selection succeed
601             let predicate = select.infcx().resolve_vars_if_possible(obligation.predicate);
602
603             // We only add a predicate as a user-displayable bound if
604             // it involves a generic parameter, and doesn't contain
605             // any inference variables.
606             //
607             // Displaying a bound involving a concrete type (instead of a generic
608             // parameter) would be pointless, since it's always true
609             // (e.g. u8: Copy)
610             // Displaying an inference variable is impossible, since they're
611             // an internal compiler detail without a defined visual representation
612             //
613             // We check this by calling is_of_param on the relevant types
614             // from the various possible predicates
615
616             let bound_predicate = predicate.kind();
617             match bound_predicate.skip_binder() {
618                 ty::PredicateKind::Trait(p) => {
619                     // Add this to `predicates` so that we end up calling `select`
620                     // with it. If this predicate ends up being unimplemented,
621                     // then `evaluate_predicates` will handle adding it the `ParamEnv`
622                     // if possible.
623                     predicates.push_back(bound_predicate.rebind(p));
624                 }
625                 ty::PredicateKind::Projection(p) => {
626                     let p = bound_predicate.rebind(p);
627                     debug!(
628                         "evaluate_nested_obligations: examining projection predicate {:?}",
629                         predicate
630                     );
631
632                     // As described above, we only want to display
633                     // bounds which include a generic parameter but don't include
634                     // an inference variable.
635                     // Additionally, we check if we've seen this predicate before,
636                     // to avoid rendering duplicate bounds to the user.
637                     if self.is_param_no_infer(p.skip_binder().projection_ty.substs)
638                         && !p.term().skip_binder().has_infer_types()
639                         && is_new_pred
640                     {
641                         debug!(
642                             "evaluate_nested_obligations: adding projection predicate \
643                             to computed_preds: {:?}",
644                             predicate
645                         );
646
647                         // Under unusual circumstances, we can end up with a self-referential
648                         // projection predicate. For example:
649                         // <T as MyType>::Value == <T as MyType>::Value
650                         // Not only is displaying this to the user pointless,
651                         // having it in the ParamEnv will cause an issue if we try to call
652                         // poly_project_and_unify_type on the predicate, since this kind of
653                         // predicate will normally never end up in a ParamEnv.
654                         //
655                         // For these reasons, we ignore these weird predicates,
656                         // ensuring that we're able to properly synthesize an auto trait impl
657                         if self.is_self_referential_projection(p) {
658                             debug!(
659                                 "evaluate_nested_obligations: encountered a projection
660                                  predicate equating a type with itself! Skipping"
661                             );
662                         } else {
663                             self.add_user_pred(computed_preds, predicate);
664                         }
665                     }
666
667                     // There are three possible cases when we project a predicate:
668                     //
669                     // 1. We encounter an error. This means that it's impossible for
670                     // our current type to implement the auto trait - there's bound
671                     // that we could add to our ParamEnv that would 'fix' this kind
672                     // of error, as it's not caused by an unimplemented type.
673                     //
674                     // 2. We successfully project the predicate (Ok(Some(_))), generating
675                     //  some subobligations. We then process these subobligations
676                     //  like any other generated sub-obligations.
677                     //
678                     // 3. We receive an 'ambiguous' result (Ok(None))
679                     // If we were actually trying to compile a crate,
680                     // we would need to re-process this obligation later.
681                     // However, all we care about is finding out what bounds
682                     // are needed for our type to implement a particular auto trait.
683                     // We've already added this obligation to our computed ParamEnv
684                     // above (if it was necessary). Therefore, we don't need
685                     // to do any further processing of the obligation.
686                     //
687                     // Note that we *must* try to project *all* projection predicates
688                     // we encounter, even ones without inference variable.
689                     // This ensures that we detect any projection errors,
690                     // which indicate that our type can *never* implement the given
691                     // auto trait. In that case, we will generate an explicit negative
692                     // impl (e.g. 'impl !Send for MyType'). However, we don't
693                     // try to process any of the generated subobligations -
694                     // they contain no new information, since we already know
695                     // that our type implements the projected-through trait,
696                     // and can lead to weird region issues.
697                     //
698                     // Normally, we'll generate a negative impl as a result of encountering
699                     // a type with an explicit negative impl of an auto trait
700                     // (for example, raw pointers have !Send and !Sync impls)
701                     // However, through some **interesting** manipulations of the type
702                     // system, it's actually possible to write a type that never
703                     // implements an auto trait due to a projection error, not a normal
704                     // negative impl error. To properly handle this case, we need
705                     // to ensure that we catch any potential projection errors,
706                     // and turn them into an explicit negative impl for our type.
707                     debug!("Projecting and unifying projection predicate {:?}", predicate);
708
709                     match project::poly_project_and_unify_type(select, &obligation.with(p)) {
710                         ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
711                             debug!(
712                                 "evaluate_nested_obligations: Unable to unify predicate \
713                                  '{:?}' '{:?}', bailing out",
714                                 ty, e
715                             );
716                             return false;
717                         }
718                         ProjectAndUnifyResult::Recursive => {
719                             debug!("evaluate_nested_obligations: recursive projection predicate");
720                             return false;
721                         }
722                         ProjectAndUnifyResult::Holds(v) => {
723                             // We only care about sub-obligations
724                             // when we started out trying to unify
725                             // some inference variables. See the comment above
726                             // for more information
727                             if p.term().skip_binder().has_infer_types() {
728                                 if !self.evaluate_nested_obligations(
729                                     ty,
730                                     v.into_iter(),
731                                     computed_preds,
732                                     fresh_preds,
733                                     predicates,
734                                     select,
735                                     only_projections,
736                                 ) {
737                                     return false;
738                                 }
739                             }
740                         }
741                         ProjectAndUnifyResult::FailedNormalization => {
742                             // It's ok not to make progress when have no inference variables -
743                             // in that case, we were only performing unification to check if an
744                             // error occurred (which would indicate that it's impossible for our
745                             // type to implement the auto trait).
746                             // However, we should always make progress (either by generating
747                             // subobligations or getting an error) when we started off with
748                             // inference variables
749                             if p.term().skip_binder().has_infer_types() {
750                                 panic!("Unexpected result when selecting {:?} {:?}", ty, obligation)
751                             }
752                         }
753                     }
754                 }
755                 ty::PredicateKind::RegionOutlives(binder) => {
756                     let binder = bound_predicate.rebind(binder);
757                     select.infcx().region_outlives_predicate(&dummy_cause, binder)
758                 }
759                 ty::PredicateKind::TypeOutlives(binder) => {
760                     let binder = bound_predicate.rebind(binder);
761                     match (
762                         binder.no_bound_vars(),
763                         binder.map_bound_ref(|pred| pred.0).no_bound_vars(),
764                     ) {
765                         (None, Some(t_a)) => {
766                             select.infcx().register_region_obligation_with_cause(
767                                 t_a,
768                                 select.infcx().tcx.lifetimes.re_static,
769                                 &dummy_cause,
770                             );
771                         }
772                         (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
773                             select.infcx().register_region_obligation_with_cause(
774                                 t_a,
775                                 r_b,
776                                 &dummy_cause,
777                             );
778                         }
779                         _ => {}
780                     };
781                 }
782                 ty::PredicateKind::ConstEquate(c1, c2) => {
783                     let evaluate = |c: ty::Const<'tcx>| {
784                         if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
785                             match select.infcx().const_eval_resolve(
786                                 obligation.param_env,
787                                 unevaluated,
788                                 Some(obligation.cause.span),
789                             ) {
790                                 Ok(Some(valtree)) => {
791                                     Ok(ty::Const::from_value(select.tcx(), valtree, c.ty()))
792                                 }
793                                 Ok(None) => {
794                                     let tcx = self.tcx;
795                                     let def_id = unevaluated.def.did;
796                                     let reported =
797                                         tcx.sess.emit_err(UnableToConstructConstantValue {
798                                             span: tcx.def_span(def_id),
799                                             unevaluated: unevaluated,
800                                         });
801                                     Err(ErrorHandled::Reported(reported))
802                                 }
803                                 Err(err) => Err(err),
804                             }
805                         } else {
806                             Ok(c)
807                         }
808                     };
809
810                     match (evaluate(c1), evaluate(c2)) {
811                         (Ok(c1), Ok(c2)) => {
812                             match select
813                                 .infcx()
814                                 .at(&obligation.cause, obligation.param_env)
815                                 .eq(c1, c2)
816                             {
817                                 Ok(_) => (),
818                                 Err(_) => return false,
819                             }
820                         }
821                         _ => return false,
822                     }
823                 }
824                 // There's not really much we can do with these predicates -
825                 // we start out with a `ParamEnv` with no inference variables,
826                 // and these don't correspond to adding any new bounds to
827                 // the `ParamEnv`.
828                 ty::PredicateKind::WellFormed(..)
829                 | ty::PredicateKind::ObjectSafe(..)
830                 | ty::PredicateKind::ClosureKind(..)
831                 | ty::PredicateKind::Subtype(..)
832                 | ty::PredicateKind::ConstEvaluatable(..)
833                 | ty::PredicateKind::Coerce(..)
834                 | ty::PredicateKind::TypeWellFormedFromEnv(..) => {}
835             };
836         }
837         true
838     }
839
840     pub fn clean_pred(
841         &self,
842         infcx: &InferCtxt<'tcx>,
843         p: ty::Predicate<'tcx>,
844     ) -> ty::Predicate<'tcx> {
845         infcx.freshen(p)
846     }
847 }
848
849 // Replaces all ReVars in a type with ty::Region's, using the provided map
850 pub struct RegionReplacer<'a, 'tcx> {
851     vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
852     tcx: TyCtxt<'tcx>,
853 }
854
855 impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> {
856     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
857         self.tcx
858     }
859
860     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
861         (match *r {
862             ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
863             _ => None,
864         })
865         .unwrap_or_else(|| r.super_fold_with(self))
866     }
867 }