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