]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/util.rs
Rollup merge of #41957 - llogiq:clippy-libsyntax, r=petrochenkov
[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::{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::Equate(ref data) =>
29             ty::Predicate::Equate(tcx.anonymize_late_bound_regions(data)),
30
31         ty::Predicate::RegionOutlives(ref data) =>
32             ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
33
34         ty::Predicate::TypeOutlives(ref data) =>
35             ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
36
37         ty::Predicate::Projection(ref data) =>
38             ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
39
40         ty::Predicate::WellFormed(data) =>
41             ty::Predicate::WellFormed(data),
42
43         ty::Predicate::ObjectSafe(data) =>
44             ty::Predicate::ObjectSafe(data),
45
46         ty::Predicate::ClosureKind(closure_def_id, kind) =>
47             ty::Predicate::ClosureKind(closure_def_id, kind),
48
49         ty::Predicate::Subtype(ref data) =>
50             ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
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: FxHashSet() }
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: &[ty::PolyTraitRef<'tcx>])
107     -> Elaborator<'cx, 'gcx, 'tcx>
108 {
109     let predicates = trait_refs.iter()
110                                .map(|trait_ref| trait_ref.to_predicate())
111                                .collect();
112     elaborate_predicates(tcx, predicates)
113 }
114
115 pub fn elaborate_predicates<'cx, 'gcx, 'tcx>(
116     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
117     mut predicates: Vec<ty::Predicate<'tcx>>)
118     -> Elaborator<'cx, 'gcx, 'tcx>
119 {
120     let mut visited = PredicateSet::new(tcx);
121     predicates.retain(|pred| visited.insert(pred));
122     Elaborator { stack: predicates, visited: visited }
123 }
124
125 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
126     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
127         FilterToTraits::new(self)
128     }
129
130     fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
131         let tcx = self.visited.tcx;
132         match *predicate {
133             ty::Predicate::Trait(ref data) => {
134                 // Predicates declared on the trait.
135                 let predicates = tcx.super_predicates_of(data.def_id());
136
137                 let mut predicates: Vec<_> =
138                     predicates.predicates
139                               .iter()
140                               .map(|p| p.subst_supertrait(tcx, &data.to_poly_trait_ref()))
141                               .collect();
142
143                 debug!("super_predicates: data={:?} predicates={:?}",
144                        data, predicates);
145
146                 // Only keep those bounds that we haven't already
147                 // seen.  This is necessary to prevent infinite
148                 // recursion in some cases.  One common case is when
149                 // people define `trait Sized: Sized { }` rather than `trait
150                 // Sized { }`.
151                 predicates.retain(|r| self.visited.insert(r));
152
153                 self.stack.extend(predicates);
154             }
155             ty::Predicate::WellFormed(..) => {
156                 // Currently, we do not elaborate WF predicates,
157                 // although we easily could.
158             }
159             ty::Predicate::ObjectSafe(..) => {
160                 // Currently, we do not elaborate object-safe
161                 // predicates.
162             }
163             ty::Predicate::Equate(..) => {
164                 // Currently, we do not "elaborate" predicates like
165                 // `X == Y`, though conceivably we might. For example,
166                 // `&X == &Y` implies that `X == Y`.
167             }
168             ty::Predicate::Subtype(..) => {
169                 // Currently, we do not "elaborate" predicates like `X
170                 // <: Y`, though conceivably we might.
171             }
172             ty::Predicate::Projection(..) => {
173                 // Nothing to elaborate in a projection predicate.
174             }
175             ty::Predicate::ClosureKind(..) => {
176                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
177             }
178
179             ty::Predicate::RegionOutlives(..) => {
180                 // Nothing to elaborate from `'a: 'b`.
181             }
182
183             ty::Predicate::TypeOutlives(ref data) => {
184                 // We know that `T: 'a` for some type `T`. We can
185                 // often elaborate this. For example, if we know that
186                 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
187                 // we know `&'a U: 'b`, then we know that `'a: 'b` and
188                 // `U: 'b`.
189                 //
190                 // We can basically ignore bound regions here. So for
191                 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
192                 // `'a: 'b`.
193
194                 // Ignore `for<'a> T: 'a` -- we might in the future
195                 // consider this as evidence that `T: 'static`, but
196                 // I'm a bit wary of such constructions and so for now
197                 // I want to be conservative. --nmatsakis
198                 let ty_max = data.skip_binder().0;
199                 let r_min = data.skip_binder().1;
200                 if r_min.is_late_bound() {
201                     return;
202                 }
203
204                 let visited = &mut self.visited;
205                 self.stack.extend(
206                     tcx.outlives_components(ty_max)
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(ty::OutlivesPredicate(r, r_min))))
214                            },
215
216                            Component::Param(p) => {
217                                let ty = tcx.mk_param(p.idx, p.name);
218                                Some(ty::Predicate::TypeOutlives(
219                                    ty::Binder(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 next(&mut self) -> Option<ty::Predicate<'tcx>> {
244         // Extract next item from top-most stack frame, if any.
245         let next_predicate = match self.stack.pop() {
246             Some(predicate) => predicate,
247             None => {
248                 // No more stack frames. Done.
249                 return None;
250             }
251         };
252         self.push(&next_predicate);
253         return Some(next_predicate);
254     }
255 }
256
257 ///////////////////////////////////////////////////////////////////////////
258 // Supertrait iterator
259 ///////////////////////////////////////////////////////////////////////////
260
261 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
262
263 pub fn supertraits<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
264                                     trait_ref: ty::PolyTraitRef<'tcx>)
265                                     -> Supertraits<'cx, 'gcx, 'tcx>
266 {
267     elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
268 }
269
270 pub fn transitive_bounds<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
271                                           bounds: &[ty::PolyTraitRef<'tcx>])
272                                           -> Supertraits<'cx, 'gcx, 'tcx>
273 {
274     elaborate_trait_refs(tcx, bounds).filter_to_traits()
275 }
276
277 ///////////////////////////////////////////////////////////////////////////
278 // Iterator over def-ids of supertraits
279
280 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
281     tcx: TyCtxt<'a, 'gcx, 'tcx>,
282     stack: Vec<DefId>,
283     visited: FxHashSet<DefId>,
284 }
285
286 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
287                                            trait_def_id: DefId)
288                                            -> SupertraitDefIds<'cx, 'gcx, 'tcx>
289 {
290     SupertraitDefIds {
291         tcx: tcx,
292         stack: vec![trait_def_id],
293         visited: Some(trait_def_id).into_iter().collect(),
294     }
295 }
296
297 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
298     type Item = DefId;
299
300     fn next(&mut self) -> Option<DefId> {
301         let def_id = match self.stack.pop() {
302             Some(def_id) => def_id,
303             None => { return None; }
304         };
305
306         let predicates = self.tcx.super_predicates_of(def_id);
307         let visited = &mut self.visited;
308         self.stack.extend(
309             predicates.predicates
310                       .iter()
311                       .filter_map(|p| p.to_opt_poly_trait_ref())
312                       .map(|t| t.def_id())
313                       .filter(|&super_def_id| visited.insert(super_def_id)));
314         Some(def_id)
315     }
316 }
317
318 ///////////////////////////////////////////////////////////////////////////
319 // Other
320 ///////////////////////////////////////////////////////////////////////////
321
322 /// A filter around an iterator of predicates that makes it yield up
323 /// just trait references.
324 pub struct FilterToTraits<I> {
325     base_iterator: I
326 }
327
328 impl<I> FilterToTraits<I> {
329     fn new(base: I) -> FilterToTraits<I> {
330         FilterToTraits { base_iterator: base }
331     }
332 }
333
334 impl<'tcx,I:Iterator<Item=ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
335     type Item = ty::PolyTraitRef<'tcx>;
336
337     fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
338         loop {
339             match self.base_iterator.next() {
340                 None => {
341                     return None;
342                 }
343                 Some(ty::Predicate::Trait(data)) => {
344                     return Some(data.to_poly_trait_ref());
345                 }
346                 Some(_) => {
347                 }
348             }
349         }
350     }
351 }
352
353 ///////////////////////////////////////////////////////////////////////////
354 // Other
355 ///////////////////////////////////////////////////////////////////////////
356
357 /// Instantiate all bound parameters of the impl with the given substs,
358 /// returning the resulting trait ref and all obligations that arise.
359 /// The obligations are closed under normalization.
360 pub fn impl_trait_ref_and_oblig<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
361                                                 impl_def_id: DefId,
362                                                 impl_substs: &Substs<'tcx>)
363                                                 -> (ty::TraitRef<'tcx>,
364                                                     Vec<PredicateObligation<'tcx>>)
365 {
366     let impl_trait_ref =
367         selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
368     let impl_trait_ref =
369         impl_trait_ref.subst(selcx.tcx(), impl_substs);
370     let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
371         super::normalize(selcx, ObligationCause::dummy(), &impl_trait_ref);
372
373     let predicates = selcx.tcx().predicates_of(impl_def_id);
374     let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
375     let Normalized { value: predicates, obligations: normalization_obligations2 } =
376         super::normalize(selcx, ObligationCause::dummy(), &predicates);
377     let impl_obligations =
378         predicates_for_generics(ObligationCause::dummy(), 0, &predicates);
379
380     let impl_obligations: Vec<_> =
381         impl_obligations.into_iter()
382         .chain(normalization_obligations1)
383         .chain(normalization_obligations2)
384         .collect();
385
386     (impl_trait_ref, impl_obligations)
387 }
388
389 /// See `super::obligations_for_generics`
390 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
391                                      recursion_depth: usize,
392                                      generic_bounds: &ty::InstantiatedPredicates<'tcx>)
393                                      -> Vec<PredicateObligation<'tcx>>
394 {
395     debug!("predicates_for_generics(generic_bounds={:?})",
396            generic_bounds);
397
398     generic_bounds.predicates.iter().map(|predicate| {
399         Obligation { cause: cause.clone(),
400                      recursion_depth: recursion_depth,
401                      predicate: predicate.clone() }
402     }).collect()
403 }
404
405 pub fn predicate_for_trait_ref<'tcx>(
406     cause: ObligationCause<'tcx>,
407     trait_ref: ty::TraitRef<'tcx>,
408     recursion_depth: usize)
409     -> PredicateObligation<'tcx>
410 {
411     Obligation {
412         cause: cause,
413         recursion_depth: recursion_depth,
414         predicate: trait_ref.to_predicate(),
415     }
416 }
417
418 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
419     pub fn predicate_for_trait_def(self,
420         cause: ObligationCause<'tcx>,
421         trait_def_id: DefId,
422         recursion_depth: usize,
423         param_ty: Ty<'tcx>,
424         ty_params: &[Ty<'tcx>])
425         -> PredicateObligation<'tcx>
426     {
427         let trait_ref = ty::TraitRef {
428             def_id: trait_def_id,
429             substs: self.mk_substs_trait(param_ty, ty_params)
430         };
431         predicate_for_trait_ref(cause, trait_ref, recursion_depth)
432     }
433
434     /// Cast a trait reference into a reference to one of its super
435     /// traits; returns `None` if `target_trait_def_id` is not a
436     /// supertrait.
437     pub fn upcast_choices(self,
438                           source_trait_ref: ty::PolyTraitRef<'tcx>,
439                           target_trait_def_id: DefId)
440                           -> Vec<ty::PolyTraitRef<'tcx>>
441     {
442         if source_trait_ref.def_id() == target_trait_def_id {
443             return vec![source_trait_ref]; // shorcut the most common case
444         }
445
446         supertraits(self, source_trait_ref)
447             .filter(|r| r.def_id() == target_trait_def_id)
448             .collect()
449     }
450
451     /// Given a trait `trait_ref`, returns the number of vtable entries
452     /// that come from `trait_ref`, excluding its supertraits. Used in
453     /// computing the vtable base for an upcast trait of a trait object.
454     pub fn count_own_vtable_entries(self, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
455         let mut entries = 0;
456         // Count number of methods and add them to the total offset.
457         // Skip over associated types and constants.
458         for trait_item in self.associated_items(trait_ref.def_id()) {
459             if trait_item.kind == ty::AssociatedKind::Method {
460                 entries += 1;
461             }
462         }
463         entries
464     }
465
466     /// Given an upcast trait object described by `object`, returns the
467     /// index of the method `method_def_id` (which should be part of
468     /// `object.upcast_trait_ref`) within the vtable for `object`.
469     pub fn get_vtable_index_of_object_method<N>(self,
470                                                 object: &super::VtableObjectData<'tcx, N>,
471                                                 method_def_id: DefId) -> usize {
472         // Count number of methods preceding the one we are selecting and
473         // add them to the total offset.
474         // Skip over associated types and constants.
475         let mut entries = object.vtable_base;
476         for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) {
477             if trait_item.def_id == method_def_id {
478                 // The item with the ID we were given really ought to be a method.
479                 assert_eq!(trait_item.kind, ty::AssociatedKind::Method);
480                 return entries;
481             }
482             if trait_item.kind == ty::AssociatedKind::Method {
483                 entries += 1;
484             }
485         }
486
487         bug!("get_vtable_index_of_object_method: {:?} was not found",
488              method_def_id);
489     }
490
491     pub fn closure_trait_ref_and_return_type(self,
492         fn_trait_def_id: DefId,
493         self_ty: Ty<'tcx>,
494         sig: ty::PolyFnSig<'tcx>,
495         tuple_arguments: TupleArgumentsFlag)
496         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
497     {
498         let arguments_tuple = match tuple_arguments {
499             TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
500             TupleArgumentsFlag::Yes =>
501                 self.intern_tup(sig.skip_binder().inputs(), false),
502         };
503         let trait_ref = ty::TraitRef {
504             def_id: fn_trait_def_id,
505             substs: self.mk_substs_trait(self_ty, &[arguments_tuple]),
506         };
507         ty::Binder((trait_ref, sig.skip_binder().output()))
508     }
509
510     pub fn impl_is_default(self, node_item_def_id: DefId) -> bool {
511         match self.hir.as_local_node_id(node_item_def_id) {
512             Some(node_id) => {
513                 let item = self.hir.expect_item(node_id);
514                 if let hir::ItemImpl(_, _, defaultness, ..) = item.node {
515                     defaultness.is_default()
516                 } else {
517                     false
518                 }
519             }
520             None => {
521                 self.global_tcx()
522                     .sess
523                     .cstore
524                     .impl_defaultness(node_item_def_id)
525                     .is_default()
526             }
527         }
528     }
529
530     pub fn impl_item_is_final(self, node_item: &NodeItem<hir::Defaultness>) -> bool {
531         node_item.item.is_final() && !self.impl_is_default(node_item.node.def_id())
532     }
533 }
534
535 pub enum TupleArgumentsFlag { Yes, No }