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