1use intravisit::InferKind;
2use rustc_data_structures::sorted_map::SortedMap;
3use rustc_hir as hir;
4use rustc_hir::def_id::{LocalDefId, LocalDefIdMap};
5use rustc_hir::intravisit::Visitor;
6use rustc_hir::*;
7use rustc_index::IndexVec;
8use rustc_middle::span_bug;
9use rustc_middle::ty::TyCtxt;
10use rustc_span::{DUMMY_SP, Span};
11use tracing::{debug, instrument};
12
13struct NodeCollector<'a, 'hir> {
15 tcx: TyCtxt<'hir>,
16
17 bodies: &'a SortedMap<ItemLocalId, &'hir Body<'hir>>,
18
19 nodes: IndexVec<ItemLocalId, ParentedNode<'hir>>,
21 parenting: LocalDefIdMap<ItemLocalId>,
22
23 parent_node: ItemLocalId,
25
26 owner: OwnerId,
27}
28
29#[instrument(level = "debug", skip(tcx, bodies))]
30pub(super) fn index_hir<'hir>(
31 tcx: TyCtxt<'hir>,
32 item: hir::OwnerNode<'hir>,
33 bodies: &SortedMap<ItemLocalId, &'hir Body<'hir>>,
34 num_nodes: usize,
35) -> (IndexVec<ItemLocalId, ParentedNode<'hir>>, LocalDefIdMap<ItemLocalId>) {
36 let err_node = ParentedNode { parent: ItemLocalId::ZERO, node: Node::Err(item.span()) };
37 let mut nodes = IndexVec::from_elem_n(err_node, num_nodes);
38 nodes[ItemLocalId::ZERO] = ParentedNode { parent: ItemLocalId::INVALID, node: item.into() };
42 let mut collector = NodeCollector {
43 tcx,
44 owner: item.def_id(),
45 parent_node: ItemLocalId::ZERO,
46 nodes,
47 bodies,
48 parenting: Default::default(),
49 };
50
51 match item {
52 OwnerNode::Crate(citem) => {
53 collector.visit_mod(citem, citem.spans.inner_span, hir::CRATE_HIR_ID)
54 }
55 OwnerNode::Item(item) => collector.visit_item(item),
56 OwnerNode::TraitItem(item) => collector.visit_trait_item(item),
57 OwnerNode::ImplItem(item) => collector.visit_impl_item(item),
58 OwnerNode::ForeignItem(item) => collector.visit_foreign_item(item),
59 OwnerNode::Synthetic => unreachable!(),
60 };
61
62 for (local_id, node) in collector.nodes.iter_enumerated() {
63 if let Node::Err(span) = node.node {
64 let hir_id = HirId { owner: item.def_id(), local_id };
65 let msg = format!("ID {hir_id} not encountered when visiting item HIR");
66 tcx.dcx().span_delayed_bug(span, msg);
67 }
68 }
69
70 (collector.nodes, collector.parenting)
71}
72
73impl<'a, 'hir> NodeCollector<'a, 'hir> {
74 #[instrument(level = "debug", skip(self))]
75 fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'hir>) {
76 debug_assert_eq!(self.owner, hir_id.owner);
77 debug_assert_ne!(hir_id.local_id.as_u32(), 0);
78 debug_assert_ne!(hir_id.local_id, self.parent_node);
79
80 if cfg!(debug_assertions) {
83 if hir_id.owner != self.owner {
84 span_bug!(
85 span,
86 "inconsistent HirId at `{:?}` for `{node:?}`: \
87 current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
88 self.tcx.sess.source_map().span_to_diagnostic_string(span),
89 self.tcx
90 .definitions_untracked()
91 .def_path(self.owner.def_id)
92 .to_string_no_crate_verbose(),
93 self.owner,
94 self.tcx
95 .definitions_untracked()
96 .def_path(hir_id.owner.def_id)
97 .to_string_no_crate_verbose(),
98 hir_id.owner,
99 )
100 }
101 if self.tcx.sess.opts.incremental.is_some()
102 && span.parent().is_none()
103 && !span.is_dummy()
104 {
105 span_bug!(span, "span without a parent: {:#?}, {node:?}", span.data())
106 }
107 }
108
109 self.nodes[hir_id.local_id] = ParentedNode { parent: self.parent_node, node };
110 }
111
112 fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_node_id: HirId, f: F) {
113 debug_assert_eq!(parent_node_id.owner, self.owner);
114 let parent_node = self.parent_node;
115 self.parent_node = parent_node_id.local_id;
116 f(self);
117 self.parent_node = parent_node;
118 }
119
120 fn insert_nested(&mut self, item: LocalDefId) {
121 if self.parent_node != ItemLocalId::ZERO {
122 self.parenting.insert(item, self.parent_node);
123 }
124 }
125}
126
127impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
128 fn visit_nested_item(&mut self, item: ItemId) {
133 debug!("visit_nested_item: {:?}", item);
134 self.insert_nested(item.owner_id.def_id);
135 }
136
137 fn visit_nested_trait_item(&mut self, item_id: TraitItemId) {
138 self.insert_nested(item_id.owner_id.def_id);
139 }
140
141 fn visit_nested_impl_item(&mut self, item_id: ImplItemId) {
142 self.insert_nested(item_id.owner_id.def_id);
143 }
144
145 fn visit_nested_foreign_item(&mut self, foreign_id: ForeignItemId) {
146 self.insert_nested(foreign_id.owner_id.def_id);
147 }
148
149 fn visit_nested_body(&mut self, id: BodyId) {
150 debug_assert_eq!(id.hir_id.owner, self.owner);
151 let body = self.bodies[&id.hir_id.local_id];
152 self.visit_body(body);
153 }
154
155 fn visit_param(&mut self, param: &'hir Param<'hir>) {
156 let node = Node::Param(param);
157 self.insert(param.pat.span, param.hir_id, node);
158 self.with_parent(param.hir_id, |this| {
159 intravisit::walk_param(this, param);
160 });
161 }
162
163 #[instrument(level = "debug", skip(self))]
164 fn visit_item(&mut self, i: &'hir Item<'hir>) {
165 debug_assert_eq!(i.owner_id, self.owner);
166 self.with_parent(i.hir_id(), |this| {
167 if let ItemKind::Struct(struct_def, _) = &i.kind {
168 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
170 this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def));
171 }
172 }
173 intravisit::walk_item(this, i);
174 });
175 }
176
177 #[instrument(level = "debug", skip(self))]
178 fn visit_foreign_item(&mut self, fi: &'hir ForeignItem<'hir>) {
179 debug_assert_eq!(fi.owner_id, self.owner);
180 self.with_parent(fi.hir_id(), |this| {
181 intravisit::walk_foreign_item(this, fi);
182 });
183 }
184
185 fn visit_generic_param(&mut self, param: &'hir GenericParam<'hir>) {
186 self.insert(param.span, param.hir_id, Node::GenericParam(param));
187 intravisit::walk_generic_param(self, param);
188 }
189
190 fn visit_const_param_default(&mut self, param: HirId, ct: &'hir ConstArg<'hir>) {
191 self.with_parent(param, |this| {
192 intravisit::walk_const_param_default(this, ct);
193 })
194 }
195
196 #[instrument(level = "debug", skip(self))]
197 fn visit_trait_item(&mut self, ti: &'hir TraitItem<'hir>) {
198 debug_assert_eq!(ti.owner_id, self.owner);
199 self.with_parent(ti.hir_id(), |this| {
200 intravisit::walk_trait_item(this, ti);
201 });
202 }
203
204 #[instrument(level = "debug", skip(self))]
205 fn visit_impl_item(&mut self, ii: &'hir ImplItem<'hir>) {
206 debug_assert_eq!(ii.owner_id, self.owner);
207 self.with_parent(ii.hir_id(), |this| {
208 intravisit::walk_impl_item(this, ii);
209 });
210 }
211
212 fn visit_pat(&mut self, pat: &'hir Pat<'hir>) {
213 self.insert(pat.span, pat.hir_id, Node::Pat(pat));
214
215 self.with_parent(pat.hir_id, |this| {
216 intravisit::walk_pat(this, pat);
217 });
218 }
219
220 fn visit_pat_expr(&mut self, expr: &'hir PatExpr<'hir>) {
221 self.insert(expr.span, expr.hir_id, Node::PatExpr(expr));
222
223 self.with_parent(expr.hir_id, |this| {
224 intravisit::walk_pat_expr(this, expr);
225 });
226 }
227
228 fn visit_pat_field(&mut self, field: &'hir PatField<'hir>) {
229 self.insert(field.span, field.hir_id, Node::PatField(field));
230 self.with_parent(field.hir_id, |this| {
231 intravisit::walk_pat_field(this, field);
232 });
233 }
234
235 fn visit_arm(&mut self, arm: &'hir Arm<'hir>) {
236 let node = Node::Arm(arm);
237
238 self.insert(arm.span, arm.hir_id, node);
239
240 self.with_parent(arm.hir_id, |this| {
241 intravisit::walk_arm(this, arm);
242 });
243 }
244
245 fn visit_opaque_ty(&mut self, opaq: &'hir OpaqueTy<'hir>) {
246 self.insert(opaq.span, opaq.hir_id, Node::OpaqueTy(opaq));
247
248 self.with_parent(opaq.hir_id, |this| {
249 intravisit::walk_opaque_ty(this, opaq);
250 });
251 }
252
253 fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
254 self.insert(constant.span, constant.hir_id, Node::AnonConst(constant));
255
256 self.with_parent(constant.hir_id, |this| {
257 intravisit::walk_anon_const(this, constant);
258 });
259 }
260
261 fn visit_inline_const(&mut self, constant: &'hir ConstBlock) {
262 self.insert(DUMMY_SP, constant.hir_id, Node::ConstBlock(constant));
263
264 self.with_parent(constant.hir_id, |this| {
265 intravisit::walk_inline_const(this, constant);
266 });
267 }
268
269 fn visit_expr(&mut self, expr: &'hir Expr<'hir>) {
270 self.insert(expr.span, expr.hir_id, Node::Expr(expr));
271
272 self.with_parent(expr.hir_id, |this| {
273 intravisit::walk_expr(this, expr);
274 });
275 }
276
277 fn visit_expr_field(&mut self, field: &'hir ExprField<'hir>) {
278 self.insert(field.span, field.hir_id, Node::ExprField(field));
279 self.with_parent(field.hir_id, |this| {
280 intravisit::walk_expr_field(this, field);
281 });
282 }
283
284 fn visit_stmt(&mut self, stmt: &'hir Stmt<'hir>) {
285 self.insert(stmt.span, stmt.hir_id, Node::Stmt(stmt));
286
287 self.with_parent(stmt.hir_id, |this| {
288 intravisit::walk_stmt(this, stmt);
289 });
290 }
291
292 fn visit_path_segment(&mut self, path_segment: &'hir PathSegment<'hir>) {
293 self.insert(path_segment.ident.span, path_segment.hir_id, Node::PathSegment(path_segment));
295 intravisit::walk_path_segment(self, path_segment);
296 }
297
298 fn visit_ty(&mut self, ty: &'hir Ty<'hir, AmbigArg>) {
299 self.insert(ty.span, ty.hir_id, Node::Ty(ty.as_unambig_ty()));
300
301 self.with_parent(ty.hir_id, |this| {
302 intravisit::walk_ty(this, ty);
303 });
304 }
305
306 fn visit_const_arg(&mut self, const_arg: &'hir ConstArg<'hir, AmbigArg>) {
307 self.insert(
308 const_arg.as_unambig_ct().span(),
309 const_arg.hir_id,
310 Node::ConstArg(const_arg.as_unambig_ct()),
311 );
312
313 self.with_parent(const_arg.hir_id, |this| {
314 intravisit::walk_ambig_const_arg(this, const_arg);
315 });
316 }
317
318 fn visit_infer(
319 &mut self,
320 inf_id: HirId,
321 inf_span: Span,
322 kind: InferKind<'hir>,
323 ) -> Self::Result {
324 match kind {
325 InferKind::Ty(ty) => self.insert(inf_span, inf_id, Node::Ty(ty)),
326 InferKind::Const(ct) => self.insert(inf_span, inf_id, Node::ConstArg(ct)),
327 InferKind::Ambig(inf) => self.insert(inf_span, inf_id, Node::Infer(inf)),
328 }
329
330 self.visit_id(inf_id);
331 }
332
333 fn visit_trait_ref(&mut self, tr: &'hir TraitRef<'hir>) {
334 self.insert(tr.path.span, tr.hir_ref_id, Node::TraitRef(tr));
335
336 self.with_parent(tr.hir_ref_id, |this| {
337 intravisit::walk_trait_ref(this, tr);
338 });
339 }
340
341 fn visit_block(&mut self, block: &'hir Block<'hir>) {
342 self.insert(block.span, block.hir_id, Node::Block(block));
343 self.with_parent(block.hir_id, |this| {
344 intravisit::walk_block(this, block);
345 });
346 }
347
348 fn visit_local(&mut self, l: &'hir LetStmt<'hir>) {
349 self.insert(l.span, l.hir_id, Node::LetStmt(l));
350 self.with_parent(l.hir_id, |this| {
351 intravisit::walk_local(this, l);
352 })
353 }
354
355 fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
356 self.insert(lifetime.ident.span, lifetime.hir_id, Node::Lifetime(lifetime));
357 }
358
359 fn visit_variant(&mut self, v: &'hir Variant<'hir>) {
360 self.insert(v.span, v.hir_id, Node::Variant(v));
361 self.with_parent(v.hir_id, |this| {
362 if let Some(ctor_hir_id) = v.data.ctor_hir_id() {
364 this.insert(v.span, ctor_hir_id, Node::Ctor(&v.data));
365 }
366 intravisit::walk_variant(this, v);
367 });
368 }
369
370 fn visit_field_def(&mut self, field: &'hir FieldDef<'hir>) {
371 self.insert(field.span, field.hir_id, Node::Field(field));
372 self.with_parent(field.hir_id, |this| {
373 intravisit::walk_field_def(this, field);
374 });
375 }
376
377 fn visit_assoc_item_constraint(&mut self, constraint: &'hir AssocItemConstraint<'hir>) {
378 self.insert(constraint.span, constraint.hir_id, Node::AssocItemConstraint(constraint));
379 self.with_parent(constraint.hir_id, |this| {
380 intravisit::walk_assoc_item_constraint(this, constraint)
381 })
382 }
383
384 fn visit_trait_item_ref(&mut self, ii: &'hir TraitItemRef) {
385 let TraitItemRef { id, ident: _, kind: _, span: _ } = *ii;
388
389 self.visit_nested_trait_item(id);
390 }
391
392 fn visit_impl_item_ref(&mut self, ii: &'hir ImplItemRef) {
393 let ImplItemRef { id, ident: _, kind: _, span: _, trait_item_def_id: _ } = *ii;
396
397 self.visit_nested_impl_item(id);
398 }
399
400 fn visit_foreign_item_ref(&mut self, fi: &'hir ForeignItemRef) {
401 let ForeignItemRef { id, ident: _, span: _ } = *fi;
404
405 self.visit_nested_foreign_item(id);
406 }
407
408 fn visit_where_predicate(&mut self, predicate: &'hir WherePredicate<'hir>) {
409 self.insert(predicate.span, predicate.hir_id, Node::WherePredicate(predicate));
410 self.with_parent(predicate.hir_id, |this| {
411 intravisit::walk_where_predicate(this, predicate)
412 });
413 }
414
415 fn visit_pattern_type_pattern(&mut self, pat: &'hir hir::TyPat<'hir>) {
416 self.insert(pat.span, pat.hir_id, Node::TyPat(pat));
417
418 self.with_parent(pat.hir_id, |this| {
419 intravisit::walk_ty_pat(this, pat);
420 });
421 }
422
423 fn visit_precise_capturing_arg(
424 &mut self,
425 arg: &'hir PreciseCapturingArg<'hir>,
426 ) -> Self::Result {
427 match arg {
428 PreciseCapturingArg::Lifetime(_) => {
429 }
431 PreciseCapturingArg::Param(param) => self.insert(
432 param.ident.span,
433 param.hir_id,
434 Node::PreciseCapturingNonLifetimeArg(param),
435 ),
436 }
437 intravisit::walk_precise_capturing_arg(self, arg);
438 }
439}