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