]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/index.rs
Rollup merge of #89941 - hermitcore:kernel, r=joshtriplett
[rust.git] / compiler / rustc_ast_lowering / src / index.rs
1 use rustc_data_structures::fx::FxHashMap;
2 use rustc_hir as hir;
3 use rustc_hir::def_id::LocalDefId;
4 use rustc_hir::definitions;
5 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
6 use rustc_hir::*;
7 use rustc_index::vec::{Idx, IndexVec};
8 use rustc_session::Session;
9 use rustc_span::source_map::SourceMap;
10 use rustc_span::{Span, DUMMY_SP};
11
12 use std::iter::repeat;
13 use tracing::debug;
14
15 /// A visitor that walks over the HIR and collects `Node`s into a HIR map.
16 pub(super) struct NodeCollector<'a, 'hir> {
17     /// Source map
18     source_map: &'a SourceMap,
19     bodies: &'a IndexVec<ItemLocalId, Option<&'hir Body<'hir>>>,
20
21     /// Outputs
22     nodes: IndexVec<ItemLocalId, Option<ParentedNode<'hir>>>,
23     parenting: FxHashMap<LocalDefId, ItemLocalId>,
24
25     /// The parent of this node
26     parent_node: hir::ItemLocalId,
27
28     owner: LocalDefId,
29
30     definitions: &'a definitions::Definitions,
31 }
32
33 fn insert_vec_map<K: Idx, V: Clone>(map: &mut IndexVec<K, Option<V>>, k: K, v: V) {
34     let i = k.index();
35     let len = map.len();
36     if i >= len {
37         map.extend(repeat(None).take(i - len + 1));
38     }
39     debug_assert!(map[k].is_none());
40     map[k] = Some(v);
41 }
42
43 pub(super) fn index_hir<'hir>(
44     sess: &Session,
45     definitions: &definitions::Definitions,
46     item: hir::OwnerNode<'hir>,
47     bodies: &IndexVec<ItemLocalId, Option<&'hir Body<'hir>>>,
48 ) -> (IndexVec<ItemLocalId, Option<ParentedNode<'hir>>>, FxHashMap<LocalDefId, ItemLocalId>) {
49     let mut nodes = IndexVec::new();
50     // This node's parent should never be accessed: the owner's parent is computed by the
51     // hir_owner_parent query.  Make it invalid (= ItemLocalId::MAX) to force an ICE whenever it is
52     // used.
53     nodes.push(Some(ParentedNode { parent: ItemLocalId::INVALID, node: item.into() }));
54     let mut collector = NodeCollector {
55         source_map: sess.source_map(),
56         definitions,
57         owner: item.def_id(),
58         parent_node: ItemLocalId::new(0),
59         nodes,
60         bodies,
61         parenting: FxHashMap::default(),
62     };
63
64     match item {
65         OwnerNode::Crate(citem) => collector.visit_mod(&citem, citem.inner, hir::CRATE_HIR_ID),
66         OwnerNode::Item(item) => collector.visit_item(item),
67         OwnerNode::TraitItem(item) => collector.visit_trait_item(item),
68         OwnerNode::ImplItem(item) => collector.visit_impl_item(item),
69         OwnerNode::ForeignItem(item) => collector.visit_foreign_item(item),
70     };
71
72     (collector.nodes, collector.parenting)
73 }
74
75 impl<'a, 'hir> NodeCollector<'a, 'hir> {
76     fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'hir>) {
77         debug_assert_eq!(self.owner, hir_id.owner);
78         debug_assert_ne!(hir_id.local_id.as_u32(), 0);
79
80         // Make sure that the DepNode of some node coincides with the HirId
81         // owner of that node.
82         if cfg!(debug_assertions) {
83             if hir_id.owner != self.owner {
84                 panic!(
85                     "inconsistent DepNode at `{:?}` for `{:?}`: \
86                      current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
87                     self.source_map.span_to_diagnostic_string(span),
88                     node,
89                     self.definitions.def_path(self.owner).to_string_no_crate_verbose(),
90                     self.owner,
91                     self.definitions.def_path(hir_id.owner).to_string_no_crate_verbose(),
92                     hir_id.owner,
93                 )
94             }
95         }
96
97         insert_vec_map(
98             &mut self.nodes,
99             hir_id.local_id,
100             ParentedNode { parent: self.parent_node, node: node },
101         );
102     }
103
104     fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_node_id: HirId, f: F) {
105         debug_assert_eq!(parent_node_id.owner, self.owner);
106         let parent_node = self.parent_node;
107         self.parent_node = parent_node_id.local_id;
108         f(self);
109         self.parent_node = parent_node;
110     }
111
112     fn insert_nested(&mut self, item: LocalDefId) {
113         self.parenting.insert(item, self.parent_node);
114     }
115 }
116
117 impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
118     type Map = !;
119
120     /// Because we want to track parent items and so forth, enable
121     /// deep walking so that we walk nested items in the context of
122     /// their outer items.
123
124     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
125         panic!("`visit_nested_xxx` must be manually implemented in this visitor");
126     }
127
128     fn visit_nested_item(&mut self, item: ItemId) {
129         debug!("visit_nested_item: {:?}", item);
130         self.insert_nested(item.def_id);
131     }
132
133     fn visit_nested_trait_item(&mut self, item_id: TraitItemId) {
134         self.insert_nested(item_id.def_id);
135     }
136
137     fn visit_nested_impl_item(&mut self, item_id: ImplItemId) {
138         self.insert_nested(item_id.def_id);
139     }
140
141     fn visit_nested_foreign_item(&mut self, foreign_id: ForeignItemId) {
142         self.insert_nested(foreign_id.def_id);
143     }
144
145     fn visit_nested_body(&mut self, id: BodyId) {
146         debug_assert_eq!(id.hir_id.owner, self.owner);
147         let body = self.bodies[id.hir_id.local_id].unwrap();
148         self.visit_body(body);
149     }
150
151     fn visit_param(&mut self, param: &'hir Param<'hir>) {
152         let node = Node::Param(param);
153         self.insert(param.pat.span, param.hir_id, node);
154         self.with_parent(param.hir_id, |this| {
155             intravisit::walk_param(this, param);
156         });
157     }
158
159     fn visit_item(&mut self, i: &'hir Item<'hir>) {
160         debug!("visit_item: {:?}", i);
161         debug_assert_eq!(i.def_id, self.owner);
162         self.with_parent(i.hir_id(), |this| {
163             if let ItemKind::Struct(ref struct_def, _) = i.kind {
164                 // If this is a tuple or unit-like struct, register the constructor.
165                 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
166                     this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def));
167                 }
168             }
169             intravisit::walk_item(this, i);
170         });
171     }
172
173     fn visit_foreign_item(&mut self, fi: &'hir ForeignItem<'hir>) {
174         debug_assert_eq!(fi.def_id, self.owner);
175         self.with_parent(fi.hir_id(), |this| {
176             intravisit::walk_foreign_item(this, fi);
177         });
178     }
179
180     fn visit_generic_param(&mut self, param: &'hir GenericParam<'hir>) {
181         self.insert(param.span, param.hir_id, Node::GenericParam(param));
182         intravisit::walk_generic_param(self, param);
183     }
184
185     fn visit_const_param_default(&mut self, param: HirId, ct: &'hir AnonConst) {
186         self.with_parent(param, |this| {
187             intravisit::walk_const_param_default(this, ct);
188         })
189     }
190
191     fn visit_trait_item(&mut self, ti: &'hir TraitItem<'hir>) {
192         debug_assert_eq!(ti.def_id, self.owner);
193         self.with_parent(ti.hir_id(), |this| {
194             intravisit::walk_trait_item(this, ti);
195         });
196     }
197
198     fn visit_impl_item(&mut self, ii: &'hir ImplItem<'hir>) {
199         debug_assert_eq!(ii.def_id, self.owner);
200         self.with_parent(ii.hir_id(), |this| {
201             intravisit::walk_impl_item(this, ii);
202         });
203     }
204
205     fn visit_pat(&mut self, pat: &'hir Pat<'hir>) {
206         let node =
207             if let PatKind::Binding(..) = pat.kind { Node::Binding(pat) } else { Node::Pat(pat) };
208         self.insert(pat.span, pat.hir_id, node);
209
210         self.with_parent(pat.hir_id, |this| {
211             intravisit::walk_pat(this, pat);
212         });
213     }
214
215     fn visit_arm(&mut self, arm: &'hir Arm<'hir>) {
216         let node = Node::Arm(arm);
217
218         self.insert(arm.span, arm.hir_id, node);
219
220         self.with_parent(arm.hir_id, |this| {
221             intravisit::walk_arm(this, arm);
222         });
223     }
224
225     fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
226         self.insert(DUMMY_SP, constant.hir_id, Node::AnonConst(constant));
227
228         self.with_parent(constant.hir_id, |this| {
229             intravisit::walk_anon_const(this, constant);
230         });
231     }
232
233     fn visit_expr(&mut self, expr: &'hir Expr<'hir>) {
234         self.insert(expr.span, expr.hir_id, Node::Expr(expr));
235
236         self.with_parent(expr.hir_id, |this| {
237             intravisit::walk_expr(this, expr);
238         });
239     }
240
241     fn visit_stmt(&mut self, stmt: &'hir Stmt<'hir>) {
242         self.insert(stmt.span, stmt.hir_id, Node::Stmt(stmt));
243
244         self.with_parent(stmt.hir_id, |this| {
245             intravisit::walk_stmt(this, stmt);
246         });
247     }
248
249     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'hir PathSegment<'hir>) {
250         if let Some(hir_id) = path_segment.hir_id {
251             self.insert(path_span, hir_id, Node::PathSegment(path_segment));
252         }
253         intravisit::walk_path_segment(self, path_span, path_segment);
254     }
255
256     fn visit_ty(&mut self, ty: &'hir Ty<'hir>) {
257         self.insert(ty.span, ty.hir_id, Node::Ty(ty));
258
259         self.with_parent(ty.hir_id, |this| {
260             intravisit::walk_ty(this, ty);
261         });
262     }
263
264     fn visit_infer(&mut self, inf: &'hir InferArg) {
265         self.insert(inf.span, inf.hir_id, Node::Infer(inf));
266
267         self.with_parent(inf.hir_id, |this| {
268             intravisit::walk_inf(this, inf);
269         });
270     }
271
272     fn visit_trait_ref(&mut self, tr: &'hir TraitRef<'hir>) {
273         self.insert(tr.path.span, tr.hir_ref_id, Node::TraitRef(tr));
274
275         self.with_parent(tr.hir_ref_id, |this| {
276             intravisit::walk_trait_ref(this, tr);
277         });
278     }
279
280     fn visit_fn(
281         &mut self,
282         fk: intravisit::FnKind<'hir>,
283         fd: &'hir FnDecl<'hir>,
284         b: BodyId,
285         s: Span,
286         id: HirId,
287     ) {
288         assert_eq!(self.owner, id.owner);
289         assert_eq!(self.parent_node, id.local_id);
290         intravisit::walk_fn(self, fk, fd, b, s, id);
291     }
292
293     fn visit_block(&mut self, block: &'hir Block<'hir>) {
294         self.insert(block.span, block.hir_id, Node::Block(block));
295         self.with_parent(block.hir_id, |this| {
296             intravisit::walk_block(this, block);
297         });
298     }
299
300     fn visit_local(&mut self, l: &'hir Local<'hir>) {
301         self.insert(l.span, l.hir_id, Node::Local(l));
302         self.with_parent(l.hir_id, |this| {
303             intravisit::walk_local(this, l);
304         })
305     }
306
307     fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
308         self.insert(lifetime.span, lifetime.hir_id, Node::Lifetime(lifetime));
309     }
310
311     fn visit_vis(&mut self, visibility: &'hir Visibility<'hir>) {
312         match visibility.node {
313             VisibilityKind::Public | VisibilityKind::Crate(_) | VisibilityKind::Inherited => {}
314             VisibilityKind::Restricted { hir_id, .. } => {
315                 self.insert(visibility.span, hir_id, Node::Visibility(visibility));
316                 self.with_parent(hir_id, |this| {
317                     intravisit::walk_vis(this, visibility);
318                 });
319             }
320         }
321     }
322
323     fn visit_variant(&mut self, v: &'hir Variant<'hir>, g: &'hir Generics<'hir>, item_id: HirId) {
324         self.insert(v.span, v.id, Node::Variant(v));
325         self.with_parent(v.id, |this| {
326             // Register the constructor of this variant.
327             if let Some(ctor_hir_id) = v.data.ctor_hir_id() {
328                 this.insert(v.span, ctor_hir_id, Node::Ctor(&v.data));
329             }
330             intravisit::walk_variant(this, v, g, item_id);
331         });
332     }
333
334     fn visit_field_def(&mut self, field: &'hir FieldDef<'hir>) {
335         self.insert(field.span, field.hir_id, Node::Field(field));
336         self.with_parent(field.hir_id, |this| {
337             intravisit::walk_field_def(this, field);
338         });
339     }
340
341     fn visit_trait_item_ref(&mut self, ii: &'hir TraitItemRef) {
342         // Do not visit the duplicate information in TraitItemRef. We want to
343         // map the actual nodes, not the duplicate ones in the *Ref.
344         let TraitItemRef { id, ident: _, kind: _, span: _, defaultness: _ } = *ii;
345
346         self.visit_nested_trait_item(id);
347     }
348
349     fn visit_impl_item_ref(&mut self, ii: &'hir ImplItemRef) {
350         // Do not visit the duplicate information in ImplItemRef. We want to
351         // map the actual nodes, not the duplicate ones in the *Ref.
352         let ImplItemRef { id, ident: _, kind: _, span: _, defaultness: _ } = *ii;
353
354         self.visit_nested_impl_item(id);
355     }
356
357     fn visit_foreign_item_ref(&mut self, fi: &'hir ForeignItemRef) {
358         // Do not visit the duplicate information in ForeignItemRef. We want to
359         // map the actual nodes, not the duplicate ones in the *Ref.
360         let ForeignItemRef { id, ident: _, span: _ } = *fi;
361
362         self.visit_nested_foreign_item(id);
363     }
364 }