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