]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/auto_trait.rs
Combine all builtin late lints
[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 rustc_data_structures::fx::{FxHashMap, FxHashSet};
20
21 use infer::region_constraints::{Constraint, RegionConstraintData};
22 use infer::{InferCtxt, RegionObligation};
23
24 use ty::fold::TypeFolder;
25 use ty::{Region, RegionVid};
26
27 // FIXME(twk): this is obviously not nice to duplicate like that
28 #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
29 pub enum RegionTarget<'tcx> {
30     Region(Region<'tcx>),
31     RegionVid(RegionVid),
32 }
33
34 #[derive(Default, Debug, Clone)]
35 pub struct RegionDeps<'tcx> {
36     larger: FxHashSet<RegionTarget<'tcx>>,
37     smaller: FxHashSet<RegionTarget<'tcx>>,
38 }
39
40 pub enum AutoTraitResult<A> {
41     ExplicitImpl,
42     PositiveImpl(A),
43     NegativeImpl,
44 }
45
46 impl<A> AutoTraitResult<A> {
47     fn is_auto(&self) -> bool {
48         match *self {
49             AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl => true,
50             _ => false,
51         }
52     }
53 }
54
55 pub struct AutoTraitInfo<'cx> {
56     pub full_user_env: ty::ParamEnv<'cx>,
57     pub region_data: RegionConstraintData<'cx>,
58     pub names_map: FxHashSet<String>,
59     pub vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>,
60 }
61
62 pub struct AutoTraitFinder<'a, 'tcx: 'a> {
63     tcx: &'a TyCtxt<'a, 'tcx, 'tcx>,
64 }
65
66 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
67     pub fn new(tcx: &'a TyCtxt<'a, 'tcx, 'tcx>) -> Self {
68         AutoTraitFinder { tcx }
69     }
70
71     /// Make a best effort to determine whether and under which conditions an auto trait is
72     /// implemented for a type. For example, if you have
73     ///
74     /// ```
75     /// struct Foo<T> { data: Box<T> }
76     /// ```
77
78     /// then this might return that Foo<T>: Send if T: Send (encoded in the AutoTraitResult type).
79     /// The analysis attempts to account for custom impls as well as other complex cases. This
80     /// result is intended for use by rustdoc and other such consumers.
81
82     /// (Note that due to the coinductive nature of Send, the full and correct result is actually
83     /// quite simple to generate. That is, when a type has no custom impl, it is Send iff its field
84     /// types are all Send. So, in our example, we might have that Foo<T>: Send if Box<T>: Send.
85     /// But this is often not the best way to present to the user.)
86
87     /// Warning: The API should be considered highly unstable, and it may be refactored or removed
88     /// in the future.
89     pub fn find_auto_trait_generics<A>(
90         &self,
91         did: DefId,
92         trait_did: DefId,
93         generics: &ty::Generics,
94         auto_trait_callback: impl for<'i> Fn(&InferCtxt<'_, 'tcx, 'i>, AutoTraitInfo<'i>) -> A,
95     ) -> AutoTraitResult<A> {
96         let tcx = self.tcx;
97         let ty = self.tcx.type_of(did);
98
99         let orig_params = tcx.param_env(did);
100
101         let trait_ref = ty::TraitRef {
102             def_id: trait_did,
103             substs: tcx.mk_substs_trait(ty, &[]),
104         };
105
106         let trait_pred = ty::Binder::bind(trait_ref);
107
108         let bail_out = tcx.infer_ctxt().enter(|infcx| {
109             let mut selcx = SelectionContext::with_negative(&infcx, true);
110             let result = selcx.select(&Obligation::new(
111                 ObligationCause::dummy(),
112                 orig_params,
113                 trait_pred.to_poly_trait_predicate(),
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                     return true;
123                 }
124                 _ => return 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();
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| {
228                     match param.kind {
229                         ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()),
230                         _ => None
231                     }
232                 })
233                 .collect();
234
235             let body_ids: FxHashSet<_> = infcx
236                 .region_obligations
237                 .borrow()
238                 .iter()
239                 .map(|&(id, _)| id)
240                 .collect();
241
242             for id in body_ids {
243                 infcx.process_registered_region_obligations(&[], None, full_env.clone(), id);
244             }
245
246             let region_data = infcx
247                 .borrow_region_constraints()
248                 .region_constraint_data()
249                 .clone();
250
251             let vid_to_region = self.map_vid_to_region(&region_data);
252
253             let info = AutoTraitInfo {
254                 full_user_env,
255                 region_data,
256                 names_map,
257                 vid_to_region,
258             };
259
260             return AutoTraitResult::PositiveImpl(auto_trait_callback(&infcx, info));
261         });
262     }
263 }
264
265 impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
266     // The core logic responsible for computing the bounds for our synthesized impl.
267     //
268     // To calculate the bounds, we call SelectionContext.select in a loop. Like FulfillmentContext,
269     // we recursively select the nested obligations of predicates we encounter. However, whenver we
270     // encounter an UnimplementedError involving a type parameter, we add it to our ParamEnv. Since
271     // our goal is to determine when a particular type implements an auto trait, Unimplemented
272     // errors tell us what conditions need to be met.
273     //
274     // This method ends up working somewhat similary to FulfillmentContext, but with a few key
275     // differences. FulfillmentContext works under the assumption that it's dealing with concrete
276     // user code. According, it considers all possible ways that a Predicate could be met - which
277     // isn't always what we want for a synthesized impl. For example, given the predicate 'T:
278     // Iterator', FulfillmentContext can end up reporting an Unimplemented error for T:
279     // IntoIterator - since there's an implementation of Iteratpr where T: IntoIterator,
280     // FulfillmentContext will drive SelectionContext to consider that impl before giving up. If we
281     // were to rely on FulfillmentContext's decision, we might end up synthesizing an impl like
282     // this:
283     // 'impl<T> Send for Foo<T> where T: IntoIterator'
284     //
285     // While it might be technically true that Foo implements Send where T: IntoIterator,
286     // the bound is overly restrictive - it's really only necessary that T: Iterator.
287     //
288     // For this reason, evaluate_predicates handles predicates with type variables specially. When
289     // we encounter an Unimplemented error for a bound such as 'T: Iterator', we immediately add it
290     // to our ParamEnv, and add it to our stack for recursive evaluation. When we later select it,
291     // we'll pick up any nested bounds, without ever inferring that 'T: IntoIterator' needs to
292     // hold.
293     //
294     // One additonal consideration is supertrait bounds. Normally, a ParamEnv is only ever
295     // consutrcted once for a given type. As part of the construction process, the ParamEnv will
296     // have any supertrait bounds normalized - e.g. if we have a type 'struct Foo<T: Copy>', the
297     // ParamEnv will contain 'T: Copy' and 'T: Clone', since 'Copy: Clone'. When we construct our
298     // own ParamEnv, we need to do this outselves, through traits::elaborate_predicates, or else
299     // SelectionContext will choke on the missing predicates. However, this should never show up in
300     // the final synthesized generics: we don't want our generated docs page to contain something
301     // like 'T: Copy + Clone', as that's redundant. Therefore, we keep track of a separate
302     // 'user_env', which only holds the predicates that will actually be displayed to the user.
303     pub fn evaluate_predicates<'b, 'gcx, 'c>(
304         &self,
305         infcx: &InferCtxt<'b, 'tcx, 'c>,
306         ty_did: DefId,
307         trait_did: DefId,
308         ty: ty::Ty<'c>,
309         param_env: ty::ParamEnv<'c>,
310         user_env: ty::ParamEnv<'c>,
311         fresh_preds: &mut FxHashSet<ty::Predicate<'c>>,
312         only_projections: bool,
313     ) -> Option<(ty::ParamEnv<'c>, ty::ParamEnv<'c>)> {
314         let tcx = infcx.tcx;
315
316         let mut select = SelectionContext::new(&infcx);
317
318         let mut already_visited = FxHashSet();
319         let mut predicates = VecDeque::new();
320         predicates.push_back(ty::Binder::bind(ty::TraitPredicate {
321             trait_ref: ty::TraitRef {
322                 def_id: trait_did,
323                 substs: infcx.tcx.mk_substs_trait(ty, &[]),
324             },
325         }));
326
327         let mut computed_preds: FxHashSet<_> = param_env.caller_bounds.iter().cloned().collect();
328         let mut user_computed_preds: FxHashSet<_> =
329             user_env.caller_bounds.iter().cloned().collect();
330
331         let mut new_env = param_env.clone();
332         let dummy_cause = ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID);
333
334         while let Some(pred) = predicates.pop_front() {
335             infcx.clear_caches();
336
337             if !already_visited.insert(pred.clone()) {
338                 continue;
339             }
340
341             let result = select.select(&Obligation::new(dummy_cause.clone(), new_env, pred));
342
343             match &result {
344                 &Ok(Some(ref vtable)) => {
345                     let obligations = vtable.clone().nested_obligations().into_iter();
346
347                     if !self.evaluate_nested_obligations(
348                         ty,
349                         obligations,
350                         &mut user_computed_preds,
351                         fresh_preds,
352                         &mut predicates,
353                         &mut select,
354                         only_projections,
355                     ) {
356                         return None;
357                     }
358                 }
359                 &Ok(None) => {}
360                 &Err(SelectionError::Unimplemented) => {
361                     if self.is_of_param(pred.skip_binder().trait_ref.substs) {
362                         already_visited.remove(&pred);
363                         user_computed_preds.insert(ty::Predicate::Trait(pred.clone()));
364                         predicates.push_back(pred);
365                     } else {
366                         debug!(
367                             "evaluate_nested_obligations: Unimplemented found, bailing: \
368                              {:?} {:?} {:?}",
369                             ty,
370                             pred,
371                             pred.skip_binder().trait_ref.substs
372                         );
373                         return None;
374                     }
375                 }
376                 _ => panic!("Unexpected error for '{:?}': {:?}", ty, result),
377             };
378
379             computed_preds.extend(user_computed_preds.iter().cloned());
380             let normalized_preds =
381                 elaborate_predicates(tcx, computed_preds.clone().into_iter().collect());
382             new_env = ty::ParamEnv::new(tcx.mk_predicates(normalized_preds), param_env.reveal);
383         }
384
385         let final_user_env = ty::ParamEnv::new(
386             tcx.mk_predicates(user_computed_preds.into_iter()),
387             user_env.reveal,
388         );
389         debug!(
390             "evaluate_nested_obligations(ty_did={:?}, trait_did={:?}): succeeded with '{:?}' \
391              '{:?}'",
392             ty_did, trait_did, new_env, final_user_env
393         );
394
395         return Some((new_env, final_user_env));
396     }
397
398     pub fn region_name(&self, region: Region) -> Option<String> {
399         match region {
400             &ty::ReEarlyBound(r) => Some(r.name.to_string()),
401             _ => None,
402         }
403     }
404
405     pub fn get_lifetime(&self, region: Region, names_map: &FxHashMap<String, String>) -> String {
406         self.region_name(region)
407             .map(|name| {
408                 names_map.get(&name).unwrap_or_else(|| {
409                     panic!("Missing lifetime with name {:?} for {:?}", name, region)
410                 })
411             })
412             .unwrap_or(&"'static".to_string())
413             .clone()
414     }
415
416     // This is very similar to handle_lifetimes. However, instead of matching ty::Region's
417     // to each other, we match ty::RegionVid's to ty::Region's
418     pub fn map_vid_to_region<'cx>(
419         &self,
420         regions: &RegionConstraintData<'cx>,
421     ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> {
422         let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap();
423         let mut finished_map = FxHashMap();
424
425         for constraint in regions.constraints.keys() {
426             match constraint {
427                 &Constraint::VarSubVar(r1, r2) => {
428                     {
429                         let deps1 = vid_map
430                             .entry(RegionTarget::RegionVid(r1))
431                             .or_insert_with(|| Default::default());
432                         deps1.larger.insert(RegionTarget::RegionVid(r2));
433                     }
434
435                     let deps2 = vid_map
436                         .entry(RegionTarget::RegionVid(r2))
437                         .or_insert_with(|| Default::default());
438                     deps2.smaller.insert(RegionTarget::RegionVid(r1));
439                 }
440                 &Constraint::RegSubVar(region, vid) => {
441                     {
442                         let deps1 = vid_map
443                             .entry(RegionTarget::Region(region))
444                             .or_insert_with(|| Default::default());
445                         deps1.larger.insert(RegionTarget::RegionVid(vid));
446                     }
447
448                     let deps2 = vid_map
449                         .entry(RegionTarget::RegionVid(vid))
450                         .or_insert_with(|| Default::default());
451                     deps2.smaller.insert(RegionTarget::Region(region));
452                 }
453                 &Constraint::VarSubReg(vid, region) => {
454                     finished_map.insert(vid, region);
455                 }
456                 &Constraint::RegSubReg(r1, r2) => {
457                     {
458                         let deps1 = vid_map
459                             .entry(RegionTarget::Region(r1))
460                             .or_insert_with(|| Default::default());
461                         deps1.larger.insert(RegionTarget::Region(r2));
462                     }
463
464                     let deps2 = vid_map
465                         .entry(RegionTarget::Region(r2))
466                         .or_insert_with(|| Default::default());
467                     deps2.smaller.insert(RegionTarget::Region(r1));
468                 }
469             }
470         }
471
472         while !vid_map.is_empty() {
473             let target = vid_map.keys().next().expect("Keys somehow empty").clone();
474             let deps = vid_map.remove(&target).expect("Entry somehow missing");
475
476             for smaller in deps.smaller.iter() {
477                 for larger in deps.larger.iter() {
478                     match (smaller, larger) {
479                         (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
480                             if let Entry::Occupied(v) = vid_map.entry(*smaller) {
481                                 let smaller_deps = v.into_mut();
482                                 smaller_deps.larger.insert(*larger);
483                                 smaller_deps.larger.remove(&target);
484                             }
485
486                             if let Entry::Occupied(v) = vid_map.entry(*larger) {
487                                 let larger_deps = v.into_mut();
488                                 larger_deps.smaller.insert(*smaller);
489                                 larger_deps.smaller.remove(&target);
490                             }
491                         }
492                         (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
493                             finished_map.insert(v1, r1);
494                         }
495                         (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
496                             // Do nothing - we don't care about regions that are smaller than vids
497                         }
498                         (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
499                             if let Entry::Occupied(v) = vid_map.entry(*smaller) {
500                                 let smaller_deps = v.into_mut();
501                                 smaller_deps.larger.insert(*larger);
502                                 smaller_deps.larger.remove(&target);
503                             }
504
505                             if let Entry::Occupied(v) = vid_map.entry(*larger) {
506                                 let larger_deps = v.into_mut();
507                                 larger_deps.smaller.insert(*smaller);
508                                 larger_deps.smaller.remove(&target);
509                             }
510                         }
511                     }
512                 }
513             }
514         }
515         finished_map
516     }
517
518     pub fn is_of_param(&self, substs: &Substs) -> bool {
519         if substs.is_noop() {
520             return false;
521         }
522
523         return match substs.type_at(0).sty {
524             ty::TyParam(_) => true,
525             ty::TyProjection(p) => self.is_of_param(p.substs),
526             _ => false,
527         };
528     }
529
530     pub fn evaluate_nested_obligations<
531         'b,
532         'c,
533         'd,
534         'cx,
535         T: Iterator<Item = Obligation<'cx, ty::Predicate<'cx>>>,
536     >(
537         &self,
538         ty: ty::Ty,
539         nested: T,
540         computed_preds: &'b mut FxHashSet<ty::Predicate<'cx>>,
541         fresh_preds: &'b mut FxHashSet<ty::Predicate<'cx>>,
542         predicates: &'b mut VecDeque<ty::PolyTraitPredicate<'cx>>,
543         select: &mut SelectionContext<'c, 'd, 'cx>,
544         only_projections: bool,
545     ) -> bool {
546         let dummy_cause = ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID);
547
548         for (obligation, predicate) in nested
549             .filter(|o| o.recursion_depth == 1)
550             .map(|o| (o.clone(), o.predicate.clone()))
551         {
552             let is_new_pred =
553                 fresh_preds.insert(self.clean_pred(select.infcx(), predicate.clone()));
554
555             match &predicate {
556                 &ty::Predicate::Trait(ref p) => {
557                     let substs = &p.skip_binder().trait_ref.substs;
558
559                     if self.is_of_param(substs) && !only_projections && is_new_pred {
560                         computed_preds.insert(predicate);
561                     }
562                     predicates.push_back(p.clone());
563                 }
564                 &ty::Predicate::Projection(p) => {
565                     // If the projection isn't all type vars, then
566                     // we don't want to add it as a bound
567                     if self.is_of_param(p.skip_binder().projection_ty.substs) && is_new_pred {
568                         computed_preds.insert(predicate);
569                     } else {
570                         match poly_project_and_unify_type(select, &obligation.with(p.clone())) {
571                             Err(e) => {
572                                 debug!(
573                                     "evaluate_nested_obligations: Unable to unify predicate \
574                                      '{:?}' '{:?}', bailing out",
575                                     ty, e
576                                 );
577                                 return false;
578                             }
579                             Ok(Some(v)) => {
580                                 if !self.evaluate_nested_obligations(
581                                     ty,
582                                     v.clone().iter().cloned(),
583                                     computed_preds,
584                                     fresh_preds,
585                                     predicates,
586                                     select,
587                                     only_projections,
588                                 ) {
589                                     return false;
590                                 }
591                             }
592                             Ok(None) => {
593                                 panic!("Unexpected result when selecting {:?} {:?}", ty, obligation)
594                             }
595                         }
596                     }
597                 }
598                 &ty::Predicate::RegionOutlives(ref binder) => {
599                     if let Err(_) = select
600                         .infcx()
601                         .region_outlives_predicate(&dummy_cause, binder)
602                     {
603                         return false;
604                     }
605                 }
606                 &ty::Predicate::TypeOutlives(ref binder) => {
607                     match (
608                         binder.no_late_bound_regions(),
609                         binder.map_bound_ref(|pred| pred.0).no_late_bound_regions(),
610                     ) {
611                         (None, Some(t_a)) => {
612                             select.infcx().register_region_obligation(
613                                 ast::DUMMY_NODE_ID,
614                                 RegionObligation {
615                                     sup_type: t_a,
616                                     sub_region: select.infcx().tcx.types.re_static,
617                                     cause: dummy_cause.clone(),
618                                 },
619                             );
620                         }
621                         (Some(ty::OutlivesPredicate(t_a, r_b)), _) => {
622                             select.infcx().register_region_obligation(
623                                 ast::DUMMY_NODE_ID,
624                                 RegionObligation {
625                                     sup_type: t_a,
626                                     sub_region: r_b,
627                                     cause: dummy_cause.clone(),
628                                 },
629                             );
630                         }
631                         _ => {}
632                     };
633                 }
634                 _ => panic!("Unexpected predicate {:?} {:?}", ty, predicate),
635             };
636         }
637         return true;
638     }
639
640     pub fn clean_pred<'c, 'd, 'cx>(
641         &self,
642         infcx: &InferCtxt<'c, 'd, 'cx>,
643         p: ty::Predicate<'cx>,
644     ) -> ty::Predicate<'cx> {
645         infcx.freshen(p)
646     }
647 }
648
649 // Replaces all ReVars in a type with ty::Region's, using the provided map
650 pub struct RegionReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
651     vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>,
652     tcx: TyCtxt<'a, 'gcx, 'tcx>,
653 }
654
655 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
656     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> {
657         self.tcx
658     }
659
660     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
661         (match r {
662             &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(),
663             _ => None,
664         }).unwrap_or_else(|| r.super_fold_with(self))
665     }
666 }