]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/util.rs
Rollup merge of #55764 - murarth:fix-rc-alloc, r=RalfJung
[rust.git] / src / librustc / traits / util.rs
1 // Copyright 2014 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 use hir::def_id::DefId;
12 use ty::subst::{Kind, Subst, Substs};
13 use ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef};
14 use ty::outlives::Component;
15 use util::nodemap::FxHashSet;
16 use hir::{self};
17 use traits::specialize::specialization_graph::NodeItem;
18
19 use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
20
21 fn anonymize_predicate<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
22                                        pred: &ty::Predicate<'tcx>)
23                                        -> ty::Predicate<'tcx> {
24     match *pred {
25         ty::Predicate::Trait(ref data) =>
26             ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data)),
27
28         ty::Predicate::RegionOutlives(ref data) =>
29             ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
30
31         ty::Predicate::TypeOutlives(ref data) =>
32             ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
33
34         ty::Predicate::Projection(ref data) =>
35             ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
36
37         ty::Predicate::WellFormed(data) =>
38             ty::Predicate::WellFormed(data),
39
40         ty::Predicate::ObjectSafe(data) =>
41             ty::Predicate::ObjectSafe(data),
42
43         ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
44             ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind),
45
46         ty::Predicate::Subtype(ref data) =>
47             ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
48
49         ty::Predicate::ConstEvaluatable(def_id, substs) =>
50             ty::Predicate::ConstEvaluatable(def_id, substs),
51     }
52 }
53
54
55 struct PredicateSet<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
56     tcx: TyCtxt<'a, 'gcx, 'tcx>,
57     set: FxHashSet<ty::Predicate<'tcx>>,
58 }
59
60 impl<'a, 'gcx, 'tcx> PredicateSet<'a, 'gcx, 'tcx> {
61     fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PredicateSet<'a, 'gcx, 'tcx> {
62         PredicateSet { tcx: tcx, set: Default::default() }
63     }
64
65     fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
66         // We have to be careful here because we want
67         //
68         //    for<'a> Foo<&'a int>
69         //
70         // and
71         //
72         //    for<'b> Foo<&'b int>
73         //
74         // to be considered equivalent. So normalize all late-bound
75         // regions before we throw things into the underlying set.
76         self.set.insert(anonymize_predicate(self.tcx, pred))
77     }
78 }
79
80 ///////////////////////////////////////////////////////////////////////////
81 // `Elaboration` iterator
82 ///////////////////////////////////////////////////////////////////////////
83
84 /// "Elaboration" is the process of identifying all the predicates that
85 /// are implied by a source predicate. Currently this basically means
86 /// walking the "supertraits" and other similar assumptions. For
87 /// example, if we know that `T : Ord`, the elaborator would deduce
88 /// that `T : PartialOrd` holds as well. Similarly, if we have `trait
89 /// Foo : 'static`, and we know that `T : Foo`, then we know that `T :
90 /// 'static`.
91 pub struct Elaborator<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
92     stack: Vec<ty::Predicate<'tcx>>,
93     visited: PredicateSet<'a, 'gcx, 'tcx>,
94 }
95
96 pub fn elaborate_trait_ref<'cx, 'gcx, 'tcx>(
97     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
98     trait_ref: ty::PolyTraitRef<'tcx>)
99     -> Elaborator<'cx, 'gcx, 'tcx>
100 {
101     elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
102 }
103
104 pub fn elaborate_trait_refs<'cx, 'gcx, 'tcx>(
105     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
106     trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>)
107     -> Elaborator<'cx, 'gcx, 'tcx>
108 {
109     let predicates = trait_refs.map(|trait_ref| trait_ref.to_predicate())
110                                .collect();
111     elaborate_predicates(tcx, predicates)
112 }
113
114 pub fn elaborate_predicates<'cx, 'gcx, 'tcx>(
115     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
116     mut predicates: Vec<ty::Predicate<'tcx>>)
117     -> Elaborator<'cx, 'gcx, 'tcx>
118 {
119     let mut visited = PredicateSet::new(tcx);
120     predicates.retain(|pred| visited.insert(pred));
121     Elaborator { stack: predicates, visited: visited }
122 }
123
124 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
125     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
126         FilterToTraits::new(self)
127     }
128
129     fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
130         let tcx = self.visited.tcx;
131         match *predicate {
132             ty::Predicate::Trait(ref data) => {
133                 // Predicates declared on the trait.
134                 let predicates = tcx.super_predicates_of(data.def_id());
135
136                 let mut predicates: Vec<_> =
137                     predicates.predicates
138                               .iter()
139                               .map(|(p, _)| p.subst_supertrait(tcx, &data.to_poly_trait_ref()))
140                               .collect();
141
142                 debug!("super_predicates: data={:?} predicates={:?}",
143                        data, predicates);
144
145                 // Only keep those bounds that we haven't already
146                 // seen.  This is necessary to prevent infinite
147                 // recursion in some cases.  One common case is when
148                 // people define `trait Sized: Sized { }` rather than `trait
149                 // Sized { }`.
150                 predicates.retain(|r| self.visited.insert(r));
151
152                 self.stack.extend(predicates);
153             }
154             ty::Predicate::WellFormed(..) => {
155                 // Currently, we do not elaborate WF predicates,
156                 // although we easily could.
157             }
158             ty::Predicate::ObjectSafe(..) => {
159                 // Currently, we do not elaborate object-safe
160                 // predicates.
161             }
162             ty::Predicate::Subtype(..) => {
163                 // Currently, we do not "elaborate" predicates like `X
164                 // <: Y`, though conceivably we might.
165             }
166             ty::Predicate::Projection(..) => {
167                 // Nothing to elaborate in a projection predicate.
168             }
169             ty::Predicate::ClosureKind(..) => {
170                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
171             }
172             ty::Predicate::ConstEvaluatable(..) => {
173                 // Currently, we do not elaborate const-evaluatable
174                 // predicates.
175             }
176
177             ty::Predicate::RegionOutlives(..) => {
178                 // Nothing to elaborate from `'a: 'b`.
179             }
180
181             ty::Predicate::TypeOutlives(ref data) => {
182                 // We know that `T: 'a` for some type `T`. We can
183                 // often elaborate this. For example, if we know that
184                 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
185                 // we know `&'a U: 'b`, then we know that `'a: 'b` and
186                 // `U: 'b`.
187                 //
188                 // We can basically ignore bound regions here. So for
189                 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
190                 // `'a: 'b`.
191
192                 // Ignore `for<'a> T: 'a` -- we might in the future
193                 // consider this as evidence that `T: 'static`, but
194                 // I'm a bit wary of such constructions and so for now
195                 // I want to be conservative. --nmatsakis
196                 let ty_max = data.skip_binder().0;
197                 let r_min = data.skip_binder().1;
198                 if r_min.is_late_bound() {
199                     return;
200                 }
201
202                 let visited = &mut self.visited;
203                 let mut components = smallvec![];
204                 tcx.push_outlives_components(ty_max, &mut components);
205                 self.stack.extend(
206                     components
207                        .into_iter()
208                        .filter_map(|component| match component {
209                            Component::Region(r) => if r.is_late_bound() {
210                                None
211                            } else {
212                                Some(ty::Predicate::RegionOutlives(
213                                    ty::Binder::dummy(ty::OutlivesPredicate(r, r_min))))
214                            },
215
216                            Component::Param(p) => {
217                                let ty = tcx.mk_ty_param(p.idx, p.name);
218                                Some(ty::Predicate::TypeOutlives(
219                                    ty::Binder::dummy(ty::OutlivesPredicate(ty, r_min))))
220                            },
221
222                            Component::UnresolvedInferenceVariable(_) => {
223                                None
224                            },
225
226                            Component::Projection(_) |
227                            Component::EscapingProjection(_) => {
228                                // We can probably do more here. This
229                                // corresponds to a case like `<T as
230                                // Foo<'a>>::U: 'b`.
231                                None
232                            },
233                        })
234                        .filter(|p| visited.insert(p)));
235             }
236         }
237     }
238 }
239
240 impl<'cx, 'gcx, 'tcx> Iterator for Elaborator<'cx, 'gcx, 'tcx> {
241     type Item = ty::Predicate<'tcx>;
242
243     fn size_hint(&self) -> (usize, Option<usize>) {
244         (self.stack.len(), None)
245     }
246
247     fn next(&mut self) -> Option<ty::Predicate<'tcx>> {
248         // Extract next item from top-most stack frame, if any.
249         let next_predicate = match self.stack.pop() {
250             Some(predicate) => predicate,
251             None => {
252                 // No more stack frames. Done.
253                 return None;
254             }
255         };
256         self.push(&next_predicate);
257         return Some(next_predicate);
258     }
259 }
260
261 ///////////////////////////////////////////////////////////////////////////
262 // Supertrait iterator
263 ///////////////////////////////////////////////////////////////////////////
264
265 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
266
267 pub fn supertraits<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
268                                     trait_ref: ty::PolyTraitRef<'tcx>)
269                                     -> Supertraits<'cx, 'gcx, 'tcx>
270 {
271     elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
272 }
273
274 pub fn transitive_bounds<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
275                                           bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>)
276                                           -> Supertraits<'cx, 'gcx, 'tcx>
277 {
278     elaborate_trait_refs(tcx, bounds).filter_to_traits()
279 }
280
281 ///////////////////////////////////////////////////////////////////////////
282 // Iterator over def-ids of supertraits
283
284 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
285     tcx: TyCtxt<'a, 'gcx, 'tcx>,
286     stack: Vec<DefId>,
287     visited: FxHashSet<DefId>,
288 }
289
290 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
291                                            trait_def_id: DefId)
292                                            -> SupertraitDefIds<'cx, 'gcx, 'tcx>
293 {
294     SupertraitDefIds {
295         tcx,
296         stack: vec![trait_def_id],
297         visited: Some(trait_def_id).into_iter().collect(),
298     }
299 }
300
301 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
302     type Item = DefId;
303
304     fn next(&mut self) -> Option<DefId> {
305         let def_id = match self.stack.pop() {
306             Some(def_id) => def_id,
307             None => { return None; }
308         };
309
310         let predicates = self.tcx.super_predicates_of(def_id);
311         let visited = &mut self.visited;
312         self.stack.extend(
313             predicates.predicates
314                       .iter()
315                       .filter_map(|(p, _)| p.to_opt_poly_trait_ref())
316                       .map(|t| t.def_id())
317                       .filter(|&super_def_id| visited.insert(super_def_id)));
318         Some(def_id)
319     }
320 }
321
322 ///////////////////////////////////////////////////////////////////////////
323 // Other
324 ///////////////////////////////////////////////////////////////////////////
325
326 /// A filter around an iterator of predicates that makes it yield up
327 /// just trait references.
328 pub struct FilterToTraits<I> {
329     base_iterator: I
330 }
331
332 impl<I> FilterToTraits<I> {
333     fn new(base: I) -> FilterToTraits<I> {
334         FilterToTraits { base_iterator: base }
335     }
336 }
337
338 impl<'tcx, I: Iterator<Item = ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
339     type Item = ty::PolyTraitRef<'tcx>;
340
341     fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
342         loop {
343             match self.base_iterator.next() {
344                 None => {
345                     return None;
346                 }
347                 Some(ty::Predicate::Trait(data)) => {
348                     return Some(data.to_poly_trait_ref());
349                 }
350                 Some(_) => {}
351             }
352         }
353     }
354
355     fn size_hint(&self) -> (usize, Option<usize>) {
356         let (_, upper) = self.base_iterator.size_hint();
357         (0, upper)
358     }
359 }
360
361 ///////////////////////////////////////////////////////////////////////////
362 // Other
363 ///////////////////////////////////////////////////////////////////////////
364
365 /// Instantiate all bound parameters of the impl with the given substs,
366 /// returning the resulting trait ref and all obligations that arise.
367 /// The obligations are closed under normalization.
368 pub fn impl_trait_ref_and_oblig<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
369                                                 param_env: ty::ParamEnv<'tcx>,
370                                                 impl_def_id: DefId,
371                                                 impl_substs: &Substs<'tcx>)
372                                                 -> (ty::TraitRef<'tcx>,
373                                                     Vec<PredicateObligation<'tcx>>)
374 {
375     let impl_trait_ref =
376         selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
377     let impl_trait_ref =
378         impl_trait_ref.subst(selcx.tcx(), impl_substs);
379     let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
380         super::normalize(selcx, param_env, ObligationCause::dummy(), &impl_trait_ref);
381
382     let predicates = selcx.tcx().predicates_of(impl_def_id);
383     let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
384     let Normalized { value: predicates, obligations: normalization_obligations2 } =
385         super::normalize(selcx, param_env, ObligationCause::dummy(), &predicates);
386     let impl_obligations =
387         predicates_for_generics(ObligationCause::dummy(), 0, param_env, &predicates);
388
389     let impl_obligations: Vec<_> =
390         impl_obligations.into_iter()
391         .chain(normalization_obligations1)
392         .chain(normalization_obligations2)
393         .collect();
394
395     (impl_trait_ref, impl_obligations)
396 }
397
398 /// See `super::obligations_for_generics`
399 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
400                                      recursion_depth: usize,
401                                      param_env: ty::ParamEnv<'tcx>,
402                                      generic_bounds: &ty::InstantiatedPredicates<'tcx>)
403                                      -> Vec<PredicateObligation<'tcx>>
404 {
405     debug!("predicates_for_generics(generic_bounds={:?})",
406            generic_bounds);
407
408     generic_bounds.predicates.iter().map(|predicate| {
409         Obligation { cause: cause.clone(),
410                      recursion_depth,
411                      param_env,
412                      predicate: predicate.clone() }
413     }).collect()
414 }
415
416 pub fn predicate_for_trait_ref<'tcx>(
417     cause: ObligationCause<'tcx>,
418     param_env: ty::ParamEnv<'tcx>,
419     trait_ref: ty::TraitRef<'tcx>,
420     recursion_depth: usize)
421     -> PredicateObligation<'tcx>
422 {
423     Obligation {
424         cause,
425         param_env,
426         recursion_depth,
427         predicate: trait_ref.to_predicate(),
428     }
429 }
430
431 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
432     pub fn predicate_for_trait_def(self,
433                                    param_env: ty::ParamEnv<'tcx>,
434                                    cause: ObligationCause<'tcx>,
435                                    trait_def_id: DefId,
436                                    recursion_depth: usize,
437                                    self_ty: Ty<'tcx>,
438                                    params: &[Kind<'tcx>])
439         -> PredicateObligation<'tcx>
440     {
441         let trait_ref = ty::TraitRef {
442             def_id: trait_def_id,
443             substs: self.mk_substs_trait(self_ty, params)
444         };
445         predicate_for_trait_ref(cause, param_env, trait_ref, recursion_depth)
446     }
447
448     /// Cast a trait reference into a reference to one of its super
449     /// traits; returns `None` if `target_trait_def_id` is not a
450     /// supertrait.
451     pub fn upcast_choices(self,
452                           source_trait_ref: ty::PolyTraitRef<'tcx>,
453                           target_trait_def_id: DefId)
454                           -> Vec<ty::PolyTraitRef<'tcx>>
455     {
456         if source_trait_ref.def_id() == target_trait_def_id {
457             return vec![source_trait_ref]; // shorcut the most common case
458         }
459
460         supertraits(self, source_trait_ref)
461             .filter(|r| r.def_id() == target_trait_def_id)
462             .collect()
463     }
464
465     /// Given a trait `trait_ref`, returns the number of vtable entries
466     /// that come from `trait_ref`, excluding its supertraits. Used in
467     /// computing the vtable base for an upcast trait of a trait object.
468     pub fn count_own_vtable_entries(self, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
469         let mut entries = 0;
470         // Count number of methods and add them to the total offset.
471         // Skip over associated types and constants.
472         for trait_item in self.associated_items(trait_ref.def_id()) {
473             if trait_item.kind == ty::AssociatedKind::Method {
474                 entries += 1;
475             }
476         }
477         entries
478     }
479
480     /// Given an upcast trait object described by `object`, returns the
481     /// index of the method `method_def_id` (which should be part of
482     /// `object.upcast_trait_ref`) within the vtable for `object`.
483     pub fn get_vtable_index_of_object_method<N>(self,
484                                                 object: &super::VtableObjectData<'tcx, N>,
485                                                 method_def_id: DefId) -> usize {
486         // Count number of methods preceding the one we are selecting and
487         // add them to the total offset.
488         // Skip over associated types and constants.
489         let mut entries = object.vtable_base;
490         for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) {
491             if trait_item.def_id == method_def_id {
492                 // The item with the ID we were given really ought to be a method.
493                 assert_eq!(trait_item.kind, ty::AssociatedKind::Method);
494                 return entries;
495             }
496             if trait_item.kind == ty::AssociatedKind::Method {
497                 entries += 1;
498             }
499         }
500
501         bug!("get_vtable_index_of_object_method: {:?} was not found",
502              method_def_id);
503     }
504
505     pub fn closure_trait_ref_and_return_type(self,
506         fn_trait_def_id: DefId,
507         self_ty: Ty<'tcx>,
508         sig: ty::PolyFnSig<'tcx>,
509         tuple_arguments: TupleArgumentsFlag)
510         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
511     {
512         let arguments_tuple = match tuple_arguments {
513             TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
514             TupleArgumentsFlag::Yes =>
515                 self.intern_tup(sig.skip_binder().inputs()),
516         };
517         let trait_ref = ty::TraitRef {
518             def_id: fn_trait_def_id,
519             substs: self.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
520         };
521         ty::Binder::bind((trait_ref, sig.skip_binder().output()))
522     }
523
524     pub fn generator_trait_ref_and_outputs(self,
525         fn_trait_def_id: DefId,
526         self_ty: Ty<'tcx>,
527         sig: ty::PolyGenSig<'tcx>)
528         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)>
529     {
530         let trait_ref = ty::TraitRef {
531             def_id: fn_trait_def_id,
532             substs: self.mk_substs_trait(self_ty, &[]),
533         };
534         ty::Binder::bind((trait_ref, sig.skip_binder().yield_ty, sig.skip_binder().return_ty))
535     }
536
537     pub fn impl_is_default(self, node_item_def_id: DefId) -> bool {
538         match self.hir.as_local_node_id(node_item_def_id) {
539             Some(node_id) => {
540                 let item = self.hir.expect_item(node_id);
541                 if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.node {
542                     defaultness.is_default()
543                 } else {
544                     false
545                 }
546             }
547             None => {
548                 self.global_tcx()
549                     .impl_defaultness(node_item_def_id)
550                     .is_default()
551             }
552         }
553     }
554
555     pub fn impl_item_is_final(self, node_item: &NodeItem<hir::Defaultness>) -> bool {
556         node_item.item.is_final() && !self.impl_is_default(node_item.node.def_id())
557     }
558 }
559
560 pub enum TupleArgumentsFlag { Yes, No }