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