]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/variance/terms.rs
7af7c79bb3c0d7f300f0403ab4b28b980a39fc2c
[rust.git] / src / librustc_typeck / variance / terms.rs
1 // Representing terms
2 //
3 // Terms are structured as a straightforward tree. Rather than rely on
4 // GC, we allocate terms out of a bounded arena (the lifetime of this
5 // arena is the lifetime 'a that is threaded around).
6 //
7 // We assign a unique index to each type/region parameter whose variance
8 // is to be inferred. We refer to such variables as "inferreds". An
9 // `InferredIndex` is a newtype'd int representing the index of such
10 // a variable.
11
12 use arena::TypedArena;
13 use rustc::ty::{self, TyCtxt};
14 use std::fmt;
15 use rustc::hir;
16 use rustc::hir::itemlikevisit::ItemLikeVisitor;
17 use crate::util::nodemap::HirIdMap;
18
19 use self::VarianceTerm::*;
20
21 pub type VarianceTermPtr<'a> = &'a VarianceTerm<'a>;
22
23 #[derive(Copy, Clone, Debug)]
24 pub struct InferredIndex(pub usize);
25
26 #[derive(Copy, Clone)]
27 pub enum VarianceTerm<'a> {
28     ConstantTerm(ty::Variance),
29     TransformTerm(VarianceTermPtr<'a>, VarianceTermPtr<'a>),
30     InferredTerm(InferredIndex),
31 }
32
33 impl<'a> fmt::Debug for VarianceTerm<'a> {
34     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35         match *self {
36             ConstantTerm(c1) => write!(f, "{:?}", c1),
37             TransformTerm(v1, v2) => write!(f, "({:?} \u{00D7} {:?})", v1, v2),
38             InferredTerm(id) => {
39                 write!(f, "[{}]", {
40                     let InferredIndex(i) = id;
41                     i
42                 })
43             }
44         }
45     }
46 }
47
48 // The first pass over the crate simply builds up the set of inferreds.
49
50 pub struct TermsContext<'a, 'tcx> {
51     pub tcx: TyCtxt<'tcx>,
52     pub arena: &'a TypedArena<VarianceTerm<'a>>,
53
54     // For marker types, UnsafeCell, and other lang items where
55     // variance is hardcoded, records the item-id and the hardcoded
56     // variance.
57     pub lang_items: Vec<(hir::HirId, Vec<ty::Variance>)>,
58
59     // Maps from the node id of an item to the first inferred index
60     // used for its type & region parameters.
61     pub inferred_starts: HirIdMap<InferredIndex>,
62
63     // Maps from an InferredIndex to the term for that variable.
64     pub inferred_terms: Vec<VarianceTermPtr<'a>>,
65 }
66
67 pub fn determine_parameters_to_be_inferred<'a, 'tcx>(
68     tcx: TyCtxt<'tcx>,
69     arena: &'a mut TypedArena<VarianceTerm<'a>>,
70 ) -> TermsContext<'a, 'tcx> {
71     let mut terms_cx = TermsContext {
72         tcx,
73         arena,
74         inferred_starts: Default::default(),
75         inferred_terms: vec![],
76
77         lang_items: lang_items(tcx),
78     };
79
80     // See the following for a discussion on dep-graph management.
81     //
82     // - https://rust-lang.github.io/rustc-guide/query.html
83     // - https://rust-lang.github.io/rustc-guide/variance.html
84     tcx.hir().krate().visit_all_item_likes(&mut terms_cx);
85
86     terms_cx
87 }
88
89 fn lang_items(tcx: TyCtxt<'_>) -> Vec<(hir::HirId, Vec<ty::Variance>)> {
90     let lang_items = tcx.lang_items();
91     let all = vec![
92         (lang_items.phantom_data(), vec![ty::Covariant]),
93         (lang_items.unsafe_cell_type(), vec![ty::Invariant]),
94         ];
95
96     all.into_iter() // iterating over (Option<DefId>, Variance)
97        .filter(|&(ref d,_)| d.is_some())
98        .map(|(d, v)| (d.unwrap(), v)) // (DefId, Variance)
99        .filter_map(|(d, v)| tcx.hir().as_local_hir_id(d).map(|n| (n, v))) // (HirId, Variance)
100        .collect()
101 }
102
103 impl<'a, 'tcx> TermsContext<'a, 'tcx> {
104     fn add_inferreds_for_item(&mut self, id: hir::HirId) {
105         let tcx = self.tcx;
106         let def_id = tcx.hir().local_def_id(id);
107         let count = tcx.generics_of(def_id).count();
108
109         if count == 0 {
110             return;
111         }
112
113         // Record the start of this item's inferreds.
114         let start = self.inferred_terms.len();
115         let newly_added = self.inferred_starts.insert(id, InferredIndex(start)).is_none();
116         assert!(newly_added);
117
118         // N.B., in the code below for writing the results back into the
119         // `CrateVariancesMap`, we rely on the fact that all inferreds
120         // for a particular item are assigned continuous indices.
121
122         let arena = self.arena;
123         self.inferred_terms.extend((start..(start + count)).map(|i| {
124             &*arena.alloc(InferredTerm(InferredIndex(i)))
125         }));
126     }
127 }
128
129 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for TermsContext<'a, 'tcx> {
130     fn visit_item(&mut self, item: &hir::Item) {
131         debug!("add_inferreds for item {}",
132                self.tcx.hir().node_to_string(item.hir_id));
133
134         match item.node {
135             hir::ItemKind::Struct(ref struct_def, _) |
136             hir::ItemKind::Union(ref struct_def, _) => {
137                 self.add_inferreds_for_item(item.hir_id);
138
139                 if let hir::VariantData::Tuple(..) = *struct_def {
140                     self.add_inferreds_for_item(struct_def.ctor_hir_id().unwrap());
141                 }
142             }
143
144             hir::ItemKind::Enum(ref enum_def, _) => {
145                 self.add_inferreds_for_item(item.hir_id);
146
147                 for variant in &enum_def.variants {
148                     if let hir::VariantData::Tuple(..) = variant.node.data {
149                         self.add_inferreds_for_item(variant.node.data.ctor_hir_id().unwrap());
150                     }
151                 }
152             }
153
154             hir::ItemKind::Fn(..) => {
155                 self.add_inferreds_for_item(item.hir_id);
156             }
157
158             hir::ItemKind::ForeignMod(ref foreign_mod) => {
159                 for foreign_item in &foreign_mod.items {
160                     if let hir::ForeignItemKind::Fn(..) = foreign_item.node {
161                         self.add_inferreds_for_item(foreign_item.hir_id);
162                     }
163                 }
164             }
165
166             _ => {}
167         }
168     }
169
170     fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
171         if let hir::TraitItemKind::Method(..) = trait_item.node {
172             self.add_inferreds_for_item(trait_item.hir_id);
173         }
174     }
175
176     fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
177         if let hir::ImplItemKind::Method(..) = impl_item.node {
178             self.add_inferreds_for_item(impl_item.hir_id);
179         }
180     }
181 }