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