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};
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};
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};
19 use std::iter::repeat;
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>,
26 krate: &'hir Crate<'hir>,
29 source_map: &'a SourceMap,
31 map: IndexVec<LocalDefId, HirOwnerData<'hir>>,
32 parenting: FxHashMap<LocalDefId, HirId>,
34 /// The parent of this node
35 parent_node: hir::HirId,
37 current_dep_node_owner: LocalDefId,
39 definitions: &'a definitions::Definitions,
41 hcx: StableHashingContext<'a>,
44 fn insert_vec_map<K: Idx, V: Clone>(map: &mut IndexVec<K, Option<V>>, k: K, v: V) {
48 map.extend(repeat(None).take(i - len + 1));
50 debug_assert!(map[k].is_none());
55 hcx: &mut StableHashingContext<'_>,
56 item_like: impl for<'a> HashStable<StableHashingContext<'a>>,
58 let mut stable_hasher = StableHasher::new();
59 hcx.while_hashing_hir_bodies(true, |hcx| {
60 item_like.hash_stable(hcx, &mut stable_hasher);
62 stable_hasher.finish()
65 /// Represents an entry and its parent `HirId`.
66 #[derive(Copy, Clone, Debug)]
67 pub struct Entry<'hir> {
72 impl<'a, 'hir> NodeCollector<'a, 'hir> {
75 arena: &'hir Arena<'hir>,
76 krate: &'hir Crate<'hir>,
77 definitions: &'a definitions::Definitions,
78 mut hcx: StableHashingContext<'a>,
79 ) -> NodeCollector<'a, 'hir> {
83 // These fields are handled separately:
85 non_exported_macro_attrs: _,
99 hash_body(&mut hcx, item)
102 let mut collector = NodeCollector {
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 },
110 map: (0..definitions.def_index_count())
111 .map(|_| HirOwnerData { signature: None, with_bodies: None })
113 parenting: FxHashMap::default(),
115 collector.insert_entry(
117 Entry { parent: hir::CRATE_HIR_ID, node: Node::Crate(&krate.item) },
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());
130 IndexedHir { map: self.map, parenting: self.parenting }
133 fn insert_entry(&mut self, id: HirId, entry: Entry<'hir>, hash: Fingerprint) {
134 let i = id.local_id.as_u32() as usize;
136 let arena = self.arena;
138 let data = &mut self.map[id.owner];
140 if data.with_bodies.is_none() {
141 data.with_bodies = Some(arena.alloc(OwnerNodes {
143 nodes: IndexVec::new(),
144 bodies: FxHashMap::default(),
148 let nodes = data.with_bodies.as_mut().unwrap();
151 // Overwrite the dummy hash with the real HIR owner hash.
154 debug_assert!(data.signature.is_none());
155 data.signature = Some(self.arena.alloc(Owner { node: entry.node }));
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 {
163 "Different parents for {:?} => dk_parent={:?} actual={:?}",
164 id.owner, dk_parent, entry.parent,
168 debug_assert_eq!(self.parenting.get(&id.owner), Some(&entry.parent));
171 assert_eq!(entry.parent.owner, id.owner);
175 ParentedNode { parent: entry.parent.local_id, node: entry.node },
180 fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'hir>) {
181 self.insert_with_hash(span, hir_id, node, Fingerprint::ZERO)
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 };
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),
198 "inconsistent DepNode at `{:?}` for `{}`: \
199 current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
200 self.source_map.span_to_diagnostic_string(span),
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(),
212 self.insert_entry(hir_id, entry, hash);
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;
219 self.parent_node = parent_node;
222 fn with_dep_node_owner<
223 T: for<'b> HashStable<StableHashingContext<'b>>,
224 F: FnOnce(&mut Self, Fingerprint),
227 dep_node_owner: LocalDefId,
231 let prev_owner = self.current_dep_node_owner;
232 let hash = hash_body(&mut self.hcx, item_like);
234 self.current_dep_node_owner = dep_node_owner;
236 self.current_dep_node_owner = prev_owner;
239 fn insert_nested(&mut self, item: LocalDefId) {
240 #[cfg(debug_assertions)]
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);
246 dk_parent.owner, self.parent_node.owner,
247 "Different parents for {:?}",
252 assert_eq!(self.parenting.insert(item, self.parent_node), None);
256 impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
257 type Map = Map<'hir>;
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.
263 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
264 panic!("`visit_nested_xxx` must be manually implemented in this visitor");
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));
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));
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));
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));
288 fn visit_nested_body(&mut self, id: BodyId) {
289 self.visit_body(self.krate.body(id));
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);
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));
312 intravisit::walk_item(this, i);
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);
321 this.with_parent(fi.hir_id(), |this| {
322 intravisit::walk_foreign_item(this, fi);
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);
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))
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);
340 this.with_parent(ti.hir_id(), |this| {
341 intravisit::walk_trait_item(this, ti);
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);
350 this.with_parent(ii.hir_id(), |this| {
351 intravisit::walk_impl_item(this, ii);
356 fn visit_pat(&mut self, pat: &'hir Pat<'hir>) {
358 if let PatKind::Binding(..) = pat.kind { Node::Binding(pat) } else { Node::Pat(pat) };
359 self.insert(pat.span, pat.hir_id, node);
361 self.with_parent(pat.hir_id, |this| {
362 intravisit::walk_pat(this, pat);
366 fn visit_arm(&mut self, arm: &'hir Arm<'hir>) {
367 let node = Node::Arm(arm);
369 self.insert(arm.span, arm.hir_id, node);
371 self.with_parent(arm.hir_id, |this| {
372 intravisit::walk_arm(this, arm);
376 fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
377 self.insert(DUMMY_SP, constant.hir_id, Node::AnonConst(constant));
379 self.with_parent(constant.hir_id, |this| {
380 intravisit::walk_anon_const(this, constant);
384 fn visit_expr(&mut self, expr: &'hir Expr<'hir>) {
385 self.insert(expr.span, expr.hir_id, Node::Expr(expr));
387 self.with_parent(expr.hir_id, |this| {
388 intravisit::walk_expr(this, expr);
392 fn visit_stmt(&mut self, stmt: &'hir Stmt<'hir>) {
393 self.insert(stmt.span, stmt.hir_id, Node::Stmt(stmt));
395 self.with_parent(stmt.hir_id, |this| {
396 intravisit::walk_stmt(this, stmt);
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));
404 intravisit::walk_path_segment(self, path_span, path_segment);
407 fn visit_ty(&mut self, ty: &'hir Ty<'hir>) {
408 self.insert(ty.span, ty.hir_id, Node::Ty(ty));
410 self.with_parent(ty.hir_id, |this| {
411 intravisit::walk_ty(this, ty);
415 fn visit_trait_ref(&mut self, tr: &'hir TraitRef<'hir>) {
416 self.insert(tr.path.span, tr.hir_ref_id, Node::TraitRef(tr));
418 self.with_parent(tr.hir_ref_id, |this| {
419 intravisit::walk_trait_ref(this, tr);
425 fk: intravisit::FnKind<'hir>,
426 fd: &'hir FnDecl<'hir>,
431 assert_eq!(self.parent_node, id);
432 intravisit::walk_fn(self, fk, fd, b, s, id);
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);
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))
447 fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
448 self.insert(lifetime.span, lifetime.hir_id, Node::Lifetime(lifetime));
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);
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 })
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(
477 Node::MacroDef(macro_def),
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));
491 intravisit::walk_variant(this, v, g, item_id);
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);
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;
507 self.visit_nested_trait_item(id);
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;
515 self.visit_nested_impl_item(id);
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;
523 self.visit_nested_foreign_item(id);