]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/hir/map/collector.rs
Rollup merge of #85174 - GuillaumeGomez:doc-code-block-border-radius, r=jsha
[rust.git] / compiler / rustc_middle / src / hir / map / collector.rs
1 use crate::arena::Arena;
2 use crate::hir::map::{HirOwnerData, Map};
3 use crate::hir::{IndexedHir, Owner, OwnerNodes, ParentedNode};
4 use crate::ich::StableHashingContext;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_hir as hir;
9 use rustc_hir::def_id::LocalDefId;
10 use rustc_hir::def_id::CRATE_DEF_INDEX;
11 use rustc_hir::definitions;
12 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
13 use rustc_hir::*;
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_session::Session;
16 use rustc_span::source_map::SourceMap;
17 use rustc_span::{Span, DUMMY_SP};
18
19 use std::iter::repeat;
20
21 /// A visitor that walks over the HIR and collects `Node`s into a HIR map.
22 pub(super) struct NodeCollector<'a, 'hir> {
23     arena: &'hir Arena<'hir>,
24
25     /// The crate
26     krate: &'hir Crate<'hir>,
27
28     /// Source map
29     source_map: &'a SourceMap,
30
31     map: IndexVec<LocalDefId, HirOwnerData<'hir>>,
32     parenting: FxHashMap<LocalDefId, HirId>,
33
34     /// The parent of this node
35     parent_node: hir::HirId,
36
37     current_dep_node_owner: LocalDefId,
38
39     definitions: &'a definitions::Definitions,
40
41     hcx: StableHashingContext<'a>,
42 }
43
44 fn insert_vec_map<K: Idx, V: Clone>(map: &mut IndexVec<K, Option<V>>, k: K, v: V) {
45     let i = k.index();
46     let len = map.len();
47     if i >= len {
48         map.extend(repeat(None).take(i - len + 1));
49     }
50     debug_assert!(map[k].is_none());
51     map[k] = Some(v);
52 }
53
54 fn hash_body(
55     hcx: &mut StableHashingContext<'_>,
56     item_like: impl for<'a> HashStable<StableHashingContext<'a>>,
57 ) -> Fingerprint {
58     let mut stable_hasher = StableHasher::new();
59     hcx.while_hashing_hir_bodies(true, |hcx| {
60         item_like.hash_stable(hcx, &mut stable_hasher);
61     });
62     stable_hasher.finish()
63 }
64
65 /// Represents an entry and its parent `HirId`.
66 #[derive(Copy, Clone, Debug)]
67 pub struct Entry<'hir> {
68     parent: HirId,
69     node: Node<'hir>,
70 }
71
72 impl<'a, 'hir> NodeCollector<'a, 'hir> {
73     pub(super) fn root(
74         sess: &'a Session,
75         arena: &'hir Arena<'hir>,
76         krate: &'hir Crate<'hir>,
77         definitions: &'a definitions::Definitions,
78         mut hcx: StableHashingContext<'a>,
79     ) -> NodeCollector<'a, 'hir> {
80         let hash = {
81             let Crate {
82                 ref item,
83                 // These fields are handled separately:
84                 exported_macros: _,
85                 non_exported_macro_attrs: _,
86                 items: _,
87                 trait_items: _,
88                 impl_items: _,
89                 foreign_items: _,
90                 bodies: _,
91                 trait_impls: _,
92                 body_ids: _,
93                 modules: _,
94                 proc_macros: _,
95                 trait_map: _,
96                 attrs: _,
97             } = *krate;
98
99             hash_body(&mut hcx, item)
100         };
101
102         let mut collector = NodeCollector {
103             arena,
104             krate,
105             source_map: sess.source_map(),
106             parent_node: hir::CRATE_HIR_ID,
107             current_dep_node_owner: LocalDefId { local_def_index: CRATE_DEF_INDEX },
108             definitions,
109             hcx,
110             map: (0..definitions.def_index_count())
111                 .map(|_| HirOwnerData { signature: None, with_bodies: None })
112                 .collect(),
113             parenting: FxHashMap::default(),
114         };
115         collector.insert_entry(
116             hir::CRATE_HIR_ID,
117             Entry { parent: hir::CRATE_HIR_ID, node: Node::Crate(&krate.item) },
118             hash,
119         );
120
121         collector
122     }
123
124     pub(super) fn finalize_and_compute_crate_hash(mut self) -> IndexedHir<'hir> {
125         // Insert bodies into the map
126         for (id, body) in self.krate.bodies.iter() {
127             let bodies = &mut self.map[id.hir_id.owner].with_bodies.as_mut().unwrap().bodies;
128             assert!(bodies.insert(id.hir_id.local_id, body).is_none());
129         }
130         IndexedHir { map: self.map, parenting: self.parenting }
131     }
132
133     fn insert_entry(&mut self, id: HirId, entry: Entry<'hir>, hash: Fingerprint) {
134         let i = id.local_id.as_u32() as usize;
135
136         let arena = self.arena;
137
138         let data = &mut self.map[id.owner];
139
140         if data.with_bodies.is_none() {
141             data.with_bodies = Some(arena.alloc(OwnerNodes {
142                 hash,
143                 nodes: IndexVec::new(),
144                 bodies: FxHashMap::default(),
145             }));
146         }
147
148         let nodes = data.with_bodies.as_mut().unwrap();
149
150         if i == 0 {
151             // Overwrite the dummy hash with the real HIR owner hash.
152             nodes.hash = hash;
153
154             debug_assert!(data.signature.is_none());
155             data.signature = Some(self.arena.alloc(Owner { node: entry.node }));
156
157             let dk_parent = self.definitions.def_key(id.owner).parent;
158             if let Some(dk_parent) = dk_parent {
159                 let dk_parent = LocalDefId { local_def_index: dk_parent };
160                 let dk_parent = self.definitions.local_def_id_to_hir_id(dk_parent);
161                 if dk_parent.owner != entry.parent.owner {
162                     panic!(
163                         "Different parents for {:?} => dk_parent={:?} actual={:?}",
164                         id.owner, dk_parent, entry.parent,
165                     )
166                 }
167
168                 debug_assert_eq!(self.parenting.get(&id.owner), Some(&entry.parent));
169             }
170         } else {
171             assert_eq!(entry.parent.owner, id.owner);
172             insert_vec_map(
173                 &mut nodes.nodes,
174                 id.local_id,
175                 ParentedNode { parent: entry.parent.local_id, node: entry.node },
176             );
177         }
178     }
179
180     fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'hir>) {
181         self.insert_with_hash(span, hir_id, node, Fingerprint::ZERO)
182     }
183
184     fn insert_with_hash(&mut self, span: Span, hir_id: HirId, node: Node<'hir>, hash: Fingerprint) {
185         let entry = Entry { parent: self.parent_node, node };
186
187         // Make sure that the DepNode of some node coincides with the HirId
188         // owner of that node.
189         if cfg!(debug_assertions) {
190             if hir_id.owner != self.current_dep_node_owner {
191                 let node_str = match self.definitions.opt_hir_id_to_local_def_id(hir_id) {
192                     Some(def_id) => self.definitions.def_path(def_id).to_string_no_crate_verbose(),
193                     None => format!("{:?}", node),
194                 };
195
196                 span_bug!(
197                     span,
198                     "inconsistent DepNode at `{:?}` for `{}`: \
199                      current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
200                     self.source_map.span_to_diagnostic_string(span),
201                     node_str,
202                     self.definitions
203                         .def_path(self.current_dep_node_owner)
204                         .to_string_no_crate_verbose(),
205                     self.current_dep_node_owner,
206                     self.definitions.def_path(hir_id.owner).to_string_no_crate_verbose(),
207                     hir_id.owner,
208                 )
209             }
210         }
211
212         self.insert_entry(hir_id, entry, hash);
213     }
214
215     fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_node_id: HirId, f: F) {
216         let parent_node = self.parent_node;
217         self.parent_node = parent_node_id;
218         f(self);
219         self.parent_node = parent_node;
220     }
221
222     fn with_dep_node_owner<
223         T: for<'b> HashStable<StableHashingContext<'b>>,
224         F: FnOnce(&mut Self, Fingerprint),
225     >(
226         &mut self,
227         dep_node_owner: LocalDefId,
228         item_like: &T,
229         f: F,
230     ) {
231         let prev_owner = self.current_dep_node_owner;
232         let hash = hash_body(&mut self.hcx, item_like);
233
234         self.current_dep_node_owner = dep_node_owner;
235         f(self, hash);
236         self.current_dep_node_owner = prev_owner;
237     }
238
239     fn insert_nested(&mut self, item: LocalDefId) {
240         #[cfg(debug_assertions)]
241         {
242             let dk_parent = self.definitions.def_key(item).parent.unwrap();
243             let dk_parent = LocalDefId { local_def_index: dk_parent };
244             let dk_parent = self.definitions.local_def_id_to_hir_id(dk_parent);
245             debug_assert_eq!(
246                 dk_parent.owner, self.parent_node.owner,
247                 "Different parents for {:?}",
248                 item
249             )
250         }
251
252         assert_eq!(self.parenting.insert(item, self.parent_node), None);
253     }
254 }
255
256 impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
257     type Map = Map<'hir>;
258
259     /// Because we want to track parent items and so forth, enable
260     /// deep walking so that we walk nested items in the context of
261     /// their outer items.
262
263     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
264         panic!("`visit_nested_xxx` must be manually implemented in this visitor");
265     }
266
267     fn visit_nested_item(&mut self, item: ItemId) {
268         debug!("visit_nested_item: {:?}", item);
269         self.insert_nested(item.def_id);
270         self.visit_item(self.krate.item(item));
271     }
272
273     fn visit_nested_trait_item(&mut self, item_id: TraitItemId) {
274         self.insert_nested(item_id.def_id);
275         self.visit_trait_item(self.krate.trait_item(item_id));
276     }
277
278     fn visit_nested_impl_item(&mut self, item_id: ImplItemId) {
279         self.insert_nested(item_id.def_id);
280         self.visit_impl_item(self.krate.impl_item(item_id));
281     }
282
283     fn visit_nested_foreign_item(&mut self, foreign_id: ForeignItemId) {
284         self.insert_nested(foreign_id.def_id);
285         self.visit_foreign_item(self.krate.foreign_item(foreign_id));
286     }
287
288     fn visit_nested_body(&mut self, id: BodyId) {
289         self.visit_body(self.krate.body(id));
290     }
291
292     fn visit_param(&mut self, param: &'hir Param<'hir>) {
293         let node = Node::Param(param);
294         self.insert(param.pat.span, param.hir_id, node);
295         self.with_parent(param.hir_id, |this| {
296             intravisit::walk_param(this, param);
297         });
298     }
299
300     fn visit_item(&mut self, i: &'hir Item<'hir>) {
301         debug!("visit_item: {:?}", i);
302         self.with_dep_node_owner(i.def_id, i, |this, hash| {
303             let hir_id = i.hir_id();
304             this.insert_with_hash(i.span, hir_id, Node::Item(i), hash);
305             this.with_parent(hir_id, |this| {
306                 if let ItemKind::Struct(ref struct_def, _) = i.kind {
307                     // If this is a tuple or unit-like struct, register the constructor.
308                     if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
309                         this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def));
310                     }
311                 }
312                 intravisit::walk_item(this, i);
313             });
314         });
315     }
316
317     fn visit_foreign_item(&mut self, fi: &'hir ForeignItem<'hir>) {
318         self.with_dep_node_owner(fi.def_id, fi, |this, hash| {
319             this.insert_with_hash(fi.span, fi.hir_id(), Node::ForeignItem(fi), hash);
320
321             this.with_parent(fi.hir_id(), |this| {
322                 intravisit::walk_foreign_item(this, fi);
323             });
324         });
325     }
326
327     fn visit_generic_param(&mut self, param: &'hir GenericParam<'hir>) {
328         self.insert(param.span, param.hir_id, Node::GenericParam(param));
329         intravisit::walk_generic_param(self, param);
330     }
331
332     fn visit_const_param_default(&mut self, param: HirId, ct: &'hir AnonConst) {
333         self.with_parent(param, |this| intravisit::walk_const_param_default(this, ct))
334     }
335
336     fn visit_trait_item(&mut self, ti: &'hir TraitItem<'hir>) {
337         self.with_dep_node_owner(ti.def_id, ti, |this, hash| {
338             this.insert_with_hash(ti.span, ti.hir_id(), Node::TraitItem(ti), hash);
339
340             this.with_parent(ti.hir_id(), |this| {
341                 intravisit::walk_trait_item(this, ti);
342             });
343         });
344     }
345
346     fn visit_impl_item(&mut self, ii: &'hir ImplItem<'hir>) {
347         self.with_dep_node_owner(ii.def_id, ii, |this, hash| {
348             this.insert_with_hash(ii.span, ii.hir_id(), Node::ImplItem(ii), hash);
349
350             this.with_parent(ii.hir_id(), |this| {
351                 intravisit::walk_impl_item(this, ii);
352             });
353         });
354     }
355
356     fn visit_pat(&mut self, pat: &'hir Pat<'hir>) {
357         let node =
358             if let PatKind::Binding(..) = pat.kind { Node::Binding(pat) } else { Node::Pat(pat) };
359         self.insert(pat.span, pat.hir_id, node);
360
361         self.with_parent(pat.hir_id, |this| {
362             intravisit::walk_pat(this, pat);
363         });
364     }
365
366     fn visit_arm(&mut self, arm: &'hir Arm<'hir>) {
367         let node = Node::Arm(arm);
368
369         self.insert(arm.span, arm.hir_id, node);
370
371         self.with_parent(arm.hir_id, |this| {
372             intravisit::walk_arm(this, arm);
373         });
374     }
375
376     fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
377         self.insert(DUMMY_SP, constant.hir_id, Node::AnonConst(constant));
378
379         self.with_parent(constant.hir_id, |this| {
380             intravisit::walk_anon_const(this, constant);
381         });
382     }
383
384     fn visit_expr(&mut self, expr: &'hir Expr<'hir>) {
385         self.insert(expr.span, expr.hir_id, Node::Expr(expr));
386
387         self.with_parent(expr.hir_id, |this| {
388             intravisit::walk_expr(this, expr);
389         });
390     }
391
392     fn visit_stmt(&mut self, stmt: &'hir Stmt<'hir>) {
393         self.insert(stmt.span, stmt.hir_id, Node::Stmt(stmt));
394
395         self.with_parent(stmt.hir_id, |this| {
396             intravisit::walk_stmt(this, stmt);
397         });
398     }
399
400     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'hir PathSegment<'hir>) {
401         if let Some(hir_id) = path_segment.hir_id {
402             self.insert(path_span, hir_id, Node::PathSegment(path_segment));
403         }
404         intravisit::walk_path_segment(self, path_span, path_segment);
405     }
406
407     fn visit_ty(&mut self, ty: &'hir Ty<'hir>) {
408         self.insert(ty.span, ty.hir_id, Node::Ty(ty));
409
410         self.with_parent(ty.hir_id, |this| {
411             intravisit::walk_ty(this, ty);
412         });
413     }
414
415     fn visit_trait_ref(&mut self, tr: &'hir TraitRef<'hir>) {
416         self.insert(tr.path.span, tr.hir_ref_id, Node::TraitRef(tr));
417
418         self.with_parent(tr.hir_ref_id, |this| {
419             intravisit::walk_trait_ref(this, tr);
420         });
421     }
422
423     fn visit_fn(
424         &mut self,
425         fk: intravisit::FnKind<'hir>,
426         fd: &'hir FnDecl<'hir>,
427         b: BodyId,
428         s: Span,
429         id: HirId,
430     ) {
431         assert_eq!(self.parent_node, id);
432         intravisit::walk_fn(self, fk, fd, b, s, id);
433     }
434
435     fn visit_block(&mut self, block: &'hir Block<'hir>) {
436         self.insert(block.span, block.hir_id, Node::Block(block));
437         self.with_parent(block.hir_id, |this| {
438             intravisit::walk_block(this, block);
439         });
440     }
441
442     fn visit_local(&mut self, l: &'hir Local<'hir>) {
443         self.insert(l.span, l.hir_id, Node::Local(l));
444         self.with_parent(l.hir_id, |this| intravisit::walk_local(this, l))
445     }
446
447     fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
448         self.insert(lifetime.span, lifetime.hir_id, Node::Lifetime(lifetime));
449     }
450
451     fn visit_vis(&mut self, visibility: &'hir Visibility<'hir>) {
452         match visibility.node {
453             VisibilityKind::Public | VisibilityKind::Crate(_) | VisibilityKind::Inherited => {}
454             VisibilityKind::Restricted { hir_id, .. } => {
455                 self.insert(visibility.span, hir_id, Node::Visibility(visibility));
456                 self.with_parent(hir_id, |this| {
457                     intravisit::walk_vis(this, visibility);
458                 });
459             }
460         }
461     }
462
463     fn visit_macro_def(&mut self, macro_def: &'hir MacroDef<'hir>) {
464         // Exported macros are visited directly from the crate root,
465         // so they do not have `parent_node` set.
466         // Find the correct enclosing module from their DefKey.
467         let def_key = self.definitions.def_key(macro_def.def_id);
468         let parent = def_key.parent.map_or(hir::CRATE_HIR_ID, |local_def_index| {
469             self.definitions.local_def_id_to_hir_id(LocalDefId { local_def_index })
470         });
471         self.with_parent(parent, |this| {
472             this.insert_nested(macro_def.def_id);
473             this.with_dep_node_owner(macro_def.def_id, macro_def, |this, hash| {
474                 this.insert_with_hash(
475                     macro_def.span,
476                     macro_def.hir_id(),
477                     Node::MacroDef(macro_def),
478                     hash,
479                 );
480             })
481         });
482     }
483
484     fn visit_variant(&mut self, v: &'hir Variant<'hir>, g: &'hir Generics<'hir>, item_id: HirId) {
485         self.insert(v.span, v.id, Node::Variant(v));
486         self.with_parent(v.id, |this| {
487             // Register the constructor of this variant.
488             if let Some(ctor_hir_id) = v.data.ctor_hir_id() {
489                 this.insert(v.span, ctor_hir_id, Node::Ctor(&v.data));
490             }
491             intravisit::walk_variant(this, v, g, item_id);
492         });
493     }
494
495     fn visit_field_def(&mut self, field: &'hir FieldDef<'hir>) {
496         self.insert(field.span, field.hir_id, Node::Field(field));
497         self.with_parent(field.hir_id, |this| {
498             intravisit::walk_field_def(this, field);
499         });
500     }
501
502     fn visit_trait_item_ref(&mut self, ii: &'hir TraitItemRef) {
503         // Do not visit the duplicate information in TraitItemRef. We want to
504         // map the actual nodes, not the duplicate ones in the *Ref.
505         let TraitItemRef { id, ident: _, kind: _, span: _, defaultness: _ } = *ii;
506
507         self.visit_nested_trait_item(id);
508     }
509
510     fn visit_impl_item_ref(&mut self, ii: &'hir ImplItemRef<'hir>) {
511         // Do not visit the duplicate information in ImplItemRef. We want to
512         // map the actual nodes, not the duplicate ones in the *Ref.
513         let ImplItemRef { id, ident: _, kind: _, span: _, vis: _, defaultness: _ } = *ii;
514
515         self.visit_nested_impl_item(id);
516     }
517
518     fn visit_foreign_item_ref(&mut self, fi: &'hir ForeignItemRef<'hir>) {
519         // Do not visit the duplicate information in ForeignItemRef. We want to
520         // map the actual nodes, not the duplicate ones in the *Ref.
521         let ForeignItemRef { id, ident: _, span: _, vis: _ } = *fi;
522
523         self.visit_nested_foreign_item(id);
524     }
525 }