]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/hir/map/mod.rs
Merge commit '9809f5d21990d9e24b3e9876ea7da756fd4e9def' into libgccjit-codegen
[rust.git] / compiler / rustc_middle / src / hir / map / mod.rs
1 use self::collector::NodeCollector;
2
3 use crate::hir::{AttributeMap, IndexedHir, Owner};
4 use crate::ty::TyCtxt;
5 use rustc_ast as ast;
6 use rustc_data_structures::fingerprint::Fingerprint;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_data_structures::svh::Svh;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
12 use rustc_hir::intravisit;
13 use rustc_hir::intravisit::Visitor;
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::*;
16 use rustc_index::vec::Idx;
17 use rustc_span::def_id::StableCrateId;
18 use rustc_span::hygiene::MacroKind;
19 use rustc_span::source_map::Spanned;
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use rustc_span::Span;
22 use rustc_target::spec::abi::Abi;
23
24 pub mod blocks;
25 mod collector;
26
27 fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
28     match node {
29         Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
30         | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
31         | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl),
32         Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. })
33         | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, ..), .. }) => {
34             Some(fn_decl)
35         }
36         _ => None,
37     }
38 }
39
40 pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
41     match &node {
42         Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
43         | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
44         | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig),
45         _ => None,
46     }
47 }
48
49 pub fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
50     match node {
51         Node::Item(Item {
52             kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body),
53             ..
54         })
55         | Node::TraitItem(TraitItem {
56             kind:
57                 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
58             ..
59         })
60         | Node::ImplItem(ImplItem {
61             kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
62             ..
63         })
64         | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body),
65
66         Node::AnonConst(constant) => Some(constant.body),
67
68         _ => None,
69     }
70 }
71
72 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
73     match associated_body(node) {
74         Some(b) => b.hir_id == hir_id,
75         None => false,
76     }
77 }
78
79 #[derive(Copy, Clone)]
80 pub struct Map<'hir> {
81     pub(super) tcx: TyCtxt<'hir>,
82 }
83
84 /// An iterator that walks up the ancestor tree of a given `HirId`.
85 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
86 pub struct ParentHirIterator<'map, 'hir> {
87     current_id: HirId,
88     map: &'map Map<'hir>,
89 }
90
91 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
92     type Item = (HirId, Node<'hir>);
93
94     fn next(&mut self) -> Option<Self::Item> {
95         if self.current_id == CRATE_HIR_ID {
96             return None;
97         }
98         loop {
99             // There are nodes that do not have entries, so we need to skip them.
100             let parent_id = self.map.get_parent_node(self.current_id);
101
102             if parent_id == self.current_id {
103                 self.current_id = CRATE_HIR_ID;
104                 return None;
105             }
106
107             self.current_id = parent_id;
108             if let Some(node) = self.map.find(parent_id) {
109                 return Some((parent_id, node));
110             }
111             // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
112         }
113     }
114 }
115
116 /// An iterator that walks up the ancestor tree of a given `HirId`.
117 /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`.
118 pub struct ParentOwnerIterator<'map, 'hir> {
119     current_id: HirId,
120     map: &'map Map<'hir>,
121 }
122
123 impl<'hir> Iterator for ParentOwnerIterator<'_, 'hir> {
124     type Item = (HirId, OwnerNode<'hir>);
125
126     fn next(&mut self) -> Option<Self::Item> {
127         if self.current_id.local_id.index() != 0 {
128             self.current_id.local_id = ItemLocalId::new(0);
129             if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
130                 return Some((self.current_id, node.node));
131             }
132         }
133         if self.current_id == CRATE_HIR_ID {
134             return None;
135         }
136         loop {
137             // There are nodes that do not have entries, so we need to skip them.
138             let parent_id = self.map.def_key(self.current_id.owner).parent;
139
140             let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| {
141                 let def_id = LocalDefId { local_def_index };
142                 self.map.local_def_id_to_hir_id(def_id).owner
143             });
144             self.current_id = HirId::make_owner(parent_id);
145
146             // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
147             if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
148                 return Some((self.current_id, node.node));
149             }
150         }
151     }
152 }
153
154 impl<'hir> Map<'hir> {
155     pub fn krate(&self) -> &'hir Crate<'hir> {
156         self.tcx.hir_crate(())
157     }
158
159     pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
160         // Accessing the DefKey is ok, since it is part of DefPathHash.
161         self.tcx.untracked_resolutions.definitions.def_key(def_id)
162     }
163
164     pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
165         self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
166     }
167
168     pub fn def_path(&self, def_id: LocalDefId) -> DefPath {
169         // Accessing the DefPath is ok, since it is part of DefPathHash.
170         self.tcx.untracked_resolutions.definitions.def_path(def_id)
171     }
172
173     #[inline]
174     pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
175         // Accessing the DefPathHash is ok, it is incr. comp. stable.
176         self.tcx.untracked_resolutions.definitions.def_path_hash(def_id)
177     }
178
179     #[inline]
180     pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId {
181         self.opt_local_def_id(hir_id).unwrap_or_else(|| {
182             bug!(
183                 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
184                 hir_id,
185                 self.find(hir_id)
186             )
187         })
188     }
189
190     #[inline]
191     pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<LocalDefId> {
192         // FIXME(#85914) is this access safe for incr. comp.?
193         self.tcx.untracked_resolutions.definitions.opt_hir_id_to_local_def_id(hir_id)
194     }
195
196     #[inline]
197     pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
198         // FIXME(#85914) is this access safe for incr. comp.?
199         self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id)
200     }
201
202     pub fn iter_local_def_id(&self) -> impl Iterator<Item = LocalDefId> + '_ {
203         // Create a dependency to the crate to be sure we reexcute this when the amount of
204         // definitions change.
205         self.tcx.ensure().hir_crate(());
206         self.tcx.untracked_resolutions.definitions.iter_local_def_id()
207     }
208
209     pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option<DefKind> {
210         // FIXME(eddyb) support `find` on the crate root.
211         if local_def_id.to_def_id().index == CRATE_DEF_INDEX {
212             return Some(DefKind::Mod);
213         }
214
215         let hir_id = self.local_def_id_to_hir_id(local_def_id);
216         let def_kind = match self.find(hir_id)? {
217             Node::Item(item) => match item.kind {
218                 ItemKind::Static(..) => DefKind::Static,
219                 ItemKind::Const(..) => DefKind::Const,
220                 ItemKind::Fn(..) => DefKind::Fn,
221                 ItemKind::Mod(..) => DefKind::Mod,
222                 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
223                 ItemKind::TyAlias(..) => DefKind::TyAlias,
224                 ItemKind::Enum(..) => DefKind::Enum,
225                 ItemKind::Struct(..) => DefKind::Struct,
226                 ItemKind::Union(..) => DefKind::Union,
227                 ItemKind::Trait(..) => DefKind::Trait,
228                 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
229                 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
230                 ItemKind::Use(..) => DefKind::Use,
231                 ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
232                 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
233                 ItemKind::Impl { .. } => DefKind::Impl,
234             },
235             Node::ForeignItem(item) => match item.kind {
236                 ForeignItemKind::Fn(..) => DefKind::Fn,
237                 ForeignItemKind::Static(..) => DefKind::Static,
238                 ForeignItemKind::Type => DefKind::ForeignTy,
239             },
240             Node::TraitItem(item) => match item.kind {
241                 TraitItemKind::Const(..) => DefKind::AssocConst,
242                 TraitItemKind::Fn(..) => DefKind::AssocFn,
243                 TraitItemKind::Type(..) => DefKind::AssocTy,
244             },
245             Node::ImplItem(item) => match item.kind {
246                 ImplItemKind::Const(..) => DefKind::AssocConst,
247                 ImplItemKind::Fn(..) => DefKind::AssocFn,
248                 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
249             },
250             Node::Variant(_) => DefKind::Variant,
251             Node::Ctor(variant_data) => {
252                 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
253                 assert_ne!(variant_data.ctor_hir_id(), None);
254
255                 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
256                     Some(Node::Item(..)) => def::CtorOf::Struct,
257                     Some(Node::Variant(..)) => def::CtorOf::Variant,
258                     _ => unreachable!(),
259                 };
260                 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
261             }
262             Node::AnonConst(_) => DefKind::AnonConst,
263             Node::Field(_) => DefKind::Field,
264             Node::Expr(expr) => match expr.kind {
265                 ExprKind::Closure(.., None) => DefKind::Closure,
266                 ExprKind::Closure(.., Some(_)) => DefKind::Generator,
267                 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
268             },
269             Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
270             Node::GenericParam(param) => match param.kind {
271                 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
272                 GenericParamKind::Type { .. } => DefKind::TyParam,
273                 GenericParamKind::Const { .. } => DefKind::ConstParam,
274             },
275             Node::Crate(_) => DefKind::Mod,
276             Node::Stmt(_)
277             | Node::PathSegment(_)
278             | Node::Ty(_)
279             | Node::Infer(_)
280             | Node::TraitRef(_)
281             | Node::Pat(_)
282             | Node::Binding(_)
283             | Node::Local(_)
284             | Node::Param(_)
285             | Node::Arm(_)
286             | Node::Lifetime(_)
287             | Node::Visibility(_)
288             | Node::Block(_) => return None,
289         };
290         Some(def_kind)
291     }
292
293     pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind {
294         self.opt_def_kind(local_def_id)
295             .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id))
296     }
297
298     pub fn find_parent_node(&self, id: HirId) -> Option<HirId> {
299         if id.local_id == ItemLocalId::from_u32(0) {
300             Some(self.tcx.hir_owner_parent(id.owner))
301         } else {
302             let owner = self.tcx.hir_owner_nodes(id.owner)?;
303             let node = owner.nodes[id.local_id].as_ref()?;
304             let hir_id = HirId { owner: id.owner, local_id: node.parent };
305             Some(hir_id)
306         }
307     }
308
309     pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
310         self.find_parent_node(hir_id).unwrap_or(CRATE_HIR_ID)
311     }
312
313     /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
314     pub fn find(&self, id: HirId) -> Option<Node<'hir>> {
315         if id.local_id == ItemLocalId::from_u32(0) {
316             let owner = self.tcx.hir_owner(id.owner)?;
317             Some(owner.node.into())
318         } else {
319             let owner = self.tcx.hir_owner_nodes(id.owner)?;
320             let node = owner.nodes[id.local_id].as_ref()?;
321             Some(node.node)
322         }
323     }
324
325     /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
326     pub fn get(&self, id: HirId) -> Node<'hir> {
327         self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
328     }
329
330     pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
331         id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
332     }
333
334     pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
335         let id = id.as_local()?;
336         let node = self.tcx.hir_owner(id)?;
337         match node.node {
338             OwnerNode::ImplItem(impl_item) => Some(&impl_item.generics),
339             OwnerNode::TraitItem(trait_item) => Some(&trait_item.generics),
340             OwnerNode::Item(Item {
341                 kind:
342                     ItemKind::Fn(_, generics, _)
343                     | ItemKind::TyAlias(_, generics)
344                     | ItemKind::Enum(_, generics)
345                     | ItemKind::Struct(_, generics)
346                     | ItemKind::Union(_, generics)
347                     | ItemKind::Trait(_, _, generics, ..)
348                     | ItemKind::TraitAlias(generics, _)
349                     | ItemKind::Impl(Impl { generics, .. }),
350                 ..
351             }) => Some(generics),
352             _ => None,
353         }
354     }
355
356     pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
357         self.tcx.hir_owner(id.def_id).unwrap().node.expect_item()
358     }
359
360     pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
361         self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item()
362     }
363
364     pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
365         self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item()
366     }
367
368     pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
369         self.tcx.hir_owner(id.def_id).unwrap().node.expect_foreign_item()
370     }
371
372     pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
373         self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies.get(&id.hir_id.local_id).unwrap()
374     }
375
376     pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
377         if let Some(node) = self.find(hir_id) {
378             fn_decl(node)
379         } else {
380             bug!("no node for hir_id `{}`", hir_id)
381         }
382     }
383
384     pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
385         if let Some(node) = self.find(hir_id) {
386             fn_sig(node)
387         } else {
388             bug!("no node for hir_id `{}`", hir_id)
389         }
390     }
391
392     pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId {
393         for (parent, _) in self.parent_iter(hir_id) {
394             if let Some(body) = self.maybe_body_owned_by(parent) {
395                 return self.body_owner(body);
396             }
397         }
398
399         bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
400     }
401
402     /// Returns the `HirId` that corresponds to the definition of
403     /// which this is the body of, i.e., a `fn`, `const` or `static`
404     /// item (possibly associated), a closure, or a `hir::AnonConst`.
405     pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
406         let parent = self.get_parent_node(hir_id);
407         assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
408         parent
409     }
410
411     pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId {
412         self.local_def_id(self.body_owner(id))
413     }
414
415     /// Given a `HirId`, returns the `BodyId` associated with it,
416     /// if the node is a body owner, otherwise returns `None`.
417     pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
418         self.find(hir_id).map(associated_body).flatten()
419     }
420
421     /// Given a body owner's id, returns the `BodyId` associated with it.
422     pub fn body_owned_by(&self, id: HirId) -> BodyId {
423         self.maybe_body_owned_by(id).unwrap_or_else(|| {
424             span_bug!(
425                 self.span(id),
426                 "body_owned_by: {} has no associated body",
427                 self.node_to_string(id)
428             );
429         })
430     }
431
432     pub fn body_param_names(&self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
433         self.body(id).params.iter().map(|arg| match arg.pat.kind {
434             PatKind::Binding(_, _, ident, _) => ident,
435             _ => Ident::new(kw::Empty, rustc_span::DUMMY_SP),
436         })
437     }
438
439     /// Returns the `BodyOwnerKind` of this `LocalDefId`.
440     ///
441     /// Panics if `LocalDefId` does not have an associated body.
442     pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
443         match self.get(id) {
444             Node::Item(&Item { kind: ItemKind::Const(..), .. })
445             | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
446             | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
447             | Node::AnonConst(_) => BodyOwnerKind::Const,
448             Node::Ctor(..)
449             | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
450             | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
451             | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
452             Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
453             Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
454             node => bug!("{:#?} is not a body node", node),
455         }
456     }
457
458     /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
459     ///
460     /// Panics if `LocalDefId` does not have an associated body.
461     ///
462     /// This should only be used for determining the context of a body, a return
463     /// value of `Some` does not always suggest that the owner of the body is `const`.
464     pub fn body_const_context(&self, did: LocalDefId) -> Option<ConstContext> {
465         let hir_id = self.local_def_id_to_hir_id(did);
466         let ccx = match self.body_owner_kind(hir_id) {
467             BodyOwnerKind::Const => ConstContext::Const,
468             BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
469
470             BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None,
471             BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn,
472             BodyOwnerKind::Fn
473                 if self.tcx.has_attr(did.to_def_id(), sym::default_method_body_is_const) =>
474             {
475                 ConstContext::ConstFn
476             }
477             BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
478         };
479
480         Some(ccx)
481     }
482
483     pub fn ty_param_owner(&self, id: HirId) -> HirId {
484         match self.get(id) {
485             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => id,
486             Node::GenericParam(_) => self.get_parent_node(id),
487             _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
488         }
489     }
490
491     pub fn ty_param_name(&self, id: HirId) -> Symbol {
492         match self.get(id) {
493             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
494                 kw::SelfUpper
495             }
496             Node::GenericParam(param) => param.name.ident().name,
497             _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
498         }
499     }
500
501     pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] {
502         self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
503     }
504
505     /// Gets the attributes on the crate. This is preferable to
506     /// invoking `krate.attrs` because it registers a tighter
507     /// dep-graph access.
508     pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
509         self.attrs(CRATE_HIR_ID)
510     }
511
512     pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
513         let hir_id = HirId::make_owner(module);
514         match self.tcx.hir_owner(module).map(|o| o.node) {
515             Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => {
516                 (m, span, hir_id)
517             }
518             Some(OwnerNode::Crate(item)) => (item, item.inner, hir_id),
519             node => panic!("not a module: {:?}", node),
520         }
521     }
522
523     pub fn visit_item_likes_in_module<V>(&self, module: LocalDefId, visitor: &mut V)
524     where
525         V: ItemLikeVisitor<'hir>,
526     {
527         let module = self.tcx.hir_module_items(module);
528
529         for id in &module.items {
530             visitor.visit_item(self.item(*id));
531         }
532
533         for id in &module.trait_items {
534             visitor.visit_trait_item(self.trait_item(*id));
535         }
536
537         for id in &module.impl_items {
538             visitor.visit_impl_item(self.impl_item(*id));
539         }
540
541         for id in &module.foreign_items {
542             visitor.visit_foreign_item(self.foreign_item(*id));
543         }
544     }
545
546     pub fn visit_exported_macros_in_krate<V>(&self, visitor: &mut V)
547     where
548         V: Visitor<'hir>,
549     {
550         for macro_def in self.krate().exported_macros() {
551             visitor.visit_macro_def(macro_def);
552         }
553     }
554
555     /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
556     /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
557     pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
558         ParentHirIterator { current_id, map: self }
559     }
560
561     /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
562     /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
563     pub fn parent_owner_iter(&self, current_id: HirId) -> ParentOwnerIterator<'_, 'hir> {
564         ParentOwnerIterator { current_id, map: self }
565     }
566
567     /// Checks if the node is left-hand side of an assignment.
568     pub fn is_lhs(&self, id: HirId) -> bool {
569         match self.find(self.get_parent_node(id)) {
570             Some(Node::Expr(expr)) => match expr.kind {
571                 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
572                 _ => false,
573             },
574             _ => false,
575         }
576     }
577
578     /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
579     /// Used exclusively for diagnostics, to avoid suggestion function calls.
580     pub fn is_inside_const_context(&self, hir_id: HirId) -> bool {
581         self.body_const_context(self.local_def_id(self.enclosing_body_owner(hir_id))).is_some()
582     }
583
584     /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
585     /// `while` or `loop` before reaching it, as block tail returns are not
586     /// available in them.
587     ///
588     /// ```
589     /// fn foo(x: usize) -> bool {
590     ///     if x == 1 {
591     ///         true  // If `get_return_block` gets passed the `id` corresponding
592     ///     } else {  // to this, it will return `foo`'s `HirId`.
593     ///         false
594     ///     }
595     /// }
596     /// ```
597     ///
598     /// ```
599     /// fn foo(x: usize) -> bool {
600     ///     loop {
601     ///         true  // If `get_return_block` gets passed the `id` corresponding
602     ///     }         // to this, it will return `None`.
603     ///     false
604     /// }
605     /// ```
606     pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
607         let mut iter = self.parent_iter(id).peekable();
608         let mut ignore_tail = false;
609         if let Some(node) = self.find(id) {
610             if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node {
611                 // When dealing with `return` statements, we don't care about climbing only tail
612                 // expressions.
613                 ignore_tail = true;
614             }
615         }
616         while let Some((hir_id, node)) = iter.next() {
617             if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
618                 match next_node {
619                     Node::Block(Block { expr: None, .. }) => return None,
620                     // The current node is not the tail expression of its parent.
621                     Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
622                     _ => {}
623                 }
624             }
625             match node {
626                 Node::Item(_)
627                 | Node::ForeignItem(_)
628                 | Node::TraitItem(_)
629                 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
630                 | Node::ImplItem(_) => return Some(hir_id),
631                 // Ignore `return`s on the first iteration
632                 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
633                 | Node::Local(_) => {
634                     return None;
635                 }
636                 _ => {}
637             }
638         }
639         None
640     }
641
642     /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
643     /// parent item is in this map. The "parent item" is the closest parent node
644     /// in the HIR which is recorded by the map and is an item, either an item
645     /// in a module, trait, or impl.
646     pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
647         if let Some((hir_id, _node)) = self.parent_owner_iter(hir_id).next() {
648             // A MacroDef does not have children.
649             debug_assert!(!matches!(_node, OwnerNode::MacroDef(_)));
650             hir_id
651         } else {
652             CRATE_HIR_ID
653         }
654     }
655
656     /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
657     /// module parent is in this map.
658     pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
659         for (hir_id, node) in self.parent_owner_iter(hir_id) {
660             if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
661                 return hir_id;
662             }
663         }
664         CRATE_HIR_ID
665     }
666
667     /// When on an if expression, a match arm tail expression or a match arm, give back
668     /// the enclosing `if` or `match` expression.
669     ///
670     /// Used by error reporting when there's a type error in an if or match arm caused by the
671     /// expression needing to be unit.
672     pub fn get_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
673         for (_, node) in self.parent_iter(hir_id) {
674             match node {
675                 Node::Item(_)
676                 | Node::ForeignItem(_)
677                 | Node::TraitItem(_)
678                 | Node::ImplItem(_)
679                 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
680                 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
681                     return Some(expr);
682                 }
683                 _ => {}
684             }
685         }
686         None
687     }
688
689     /// Returns the nearest enclosing scope. A scope is roughly an item or block.
690     pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
691         for (hir_id, node) in self.parent_iter(hir_id) {
692             if let Node::Item(Item {
693                 kind:
694                     ItemKind::Fn(..)
695                     | ItemKind::Const(..)
696                     | ItemKind::Static(..)
697                     | ItemKind::Mod(..)
698                     | ItemKind::Enum(..)
699                     | ItemKind::Struct(..)
700                     | ItemKind::Union(..)
701                     | ItemKind::Trait(..)
702                     | ItemKind::Impl { .. },
703                 ..
704             })
705             | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
706             | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
707             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
708             | Node::Block(_) = node
709             {
710                 return Some(hir_id);
711             }
712         }
713         None
714     }
715
716     /// Returns the defining scope for an opaque type definition.
717     pub fn get_defining_scope(&self, id: HirId) -> HirId {
718         let mut scope = id;
719         loop {
720             scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
721             if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
722                 return scope;
723             }
724         }
725     }
726
727     pub fn get_parent_did(&self, id: HirId) -> LocalDefId {
728         self.local_def_id(self.get_parent_item(id))
729     }
730
731     pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
732         let parent = self.get_parent_item(hir_id);
733         if let Some(node) = self.tcx.hir_owner(self.local_def_id(parent)) {
734             if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node.node
735             {
736                 return *abi;
737             }
738         }
739         bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
740     }
741
742     pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
743         match self.tcx.hir_owner(id.expect_owner()) {
744             Some(Owner { node: OwnerNode::Item(item) }) => item,
745             _ => bug!("expected item, found {}", self.node_to_string(id)),
746         }
747     }
748
749     pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
750         match self.tcx.hir_owner(id.expect_owner()) {
751             Some(Owner { node: OwnerNode::ImplItem(item) }) => item,
752             _ => bug!("expected impl item, found {}", self.node_to_string(id)),
753         }
754     }
755
756     pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
757         match self.tcx.hir_owner(id.expect_owner()) {
758             Some(Owner { node: OwnerNode::TraitItem(item) }) => item,
759             _ => bug!("expected trait item, found {}", self.node_to_string(id)),
760         }
761     }
762
763     pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
764         match self.find(id) {
765             Some(Node::Variant(variant)) => variant,
766             _ => bug!("expected variant, found {}", self.node_to_string(id)),
767         }
768     }
769
770     pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
771         match self.tcx.hir_owner(id.expect_owner()) {
772             Some(Owner { node: OwnerNode::ForeignItem(item) }) => item,
773             _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
774         }
775     }
776
777     pub fn expect_macro_def(&self, id: HirId) -> &'hir MacroDef<'hir> {
778         match self.tcx.hir_owner(id.expect_owner()) {
779             Some(Owner { node: OwnerNode::MacroDef(macro_def) }) => macro_def,
780             _ => bug!("expected macro def, found {}", self.node_to_string(id)),
781         }
782     }
783
784     pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
785         match self.find(id) {
786             Some(Node::Expr(expr)) => expr,
787             _ => bug!("expected expr, found {}", self.node_to_string(id)),
788         }
789     }
790
791     pub fn opt_name(&self, id: HirId) -> Option<Symbol> {
792         Some(match self.get(id) {
793             Node::Item(i) => i.ident.name,
794             Node::ForeignItem(fi) => fi.ident.name,
795             Node::ImplItem(ii) => ii.ident.name,
796             Node::TraitItem(ti) => ti.ident.name,
797             Node::Variant(v) => v.ident.name,
798             Node::Field(f) => f.ident.name,
799             Node::Lifetime(lt) => lt.name.ident().name,
800             Node::GenericParam(param) => param.name.ident().name,
801             Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
802             Node::Ctor(..) => self.name(self.get_parent_item(id)),
803             Node::MacroDef(md) => md.ident.name,
804             _ => return None,
805         })
806     }
807
808     pub fn name(&self, id: HirId) -> Symbol {
809         match self.opt_name(id) {
810             Some(name) => name,
811             None => bug!("no name for {}", self.node_to_string(id)),
812         }
813     }
814
815     /// Given a node ID, gets a list of attributes associated with the AST
816     /// corresponding to the node-ID.
817     pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
818         self.tcx.hir_attrs(id.owner).get(id.local_id)
819     }
820
821     /// Gets the span of the definition of the specified HIR node.
822     /// This is used by `tcx.get_span`
823     pub fn span(&self, hir_id: HirId) -> Span {
824         self.opt_span(hir_id)
825             .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
826     }
827
828     pub fn opt_span(&self, hir_id: HirId) -> Option<Span> {
829         let span = match self.find(hir_id)? {
830             Node::Param(param) => param.span,
831             Node::Item(item) => match &item.kind {
832                 ItemKind::Fn(sig, _, _) => sig.span,
833                 _ => item.span,
834             },
835             Node::ForeignItem(foreign_item) => foreign_item.span,
836             Node::TraitItem(trait_item) => match &trait_item.kind {
837                 TraitItemKind::Fn(sig, _) => sig.span,
838                 _ => trait_item.span,
839             },
840             Node::ImplItem(impl_item) => match &impl_item.kind {
841                 ImplItemKind::Fn(sig, _) => sig.span,
842                 _ => impl_item.span,
843             },
844             Node::Variant(variant) => variant.span,
845             Node::Field(field) => field.span,
846             Node::AnonConst(constant) => self.body(constant.body).value.span,
847             Node::Expr(expr) => expr.span,
848             Node::Stmt(stmt) => stmt.span,
849             Node::PathSegment(seg) => seg.ident.span,
850             Node::Ty(ty) => ty.span,
851             Node::TraitRef(tr) => tr.path.span,
852             Node::Binding(pat) => pat.span,
853             Node::Pat(pat) => pat.span,
854             Node::Arm(arm) => arm.span,
855             Node::Block(block) => block.span,
856             Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? {
857                 Node::Item(item) => item.span,
858                 Node::Variant(variant) => variant.span,
859                 _ => unreachable!(),
860             },
861             Node::Lifetime(lifetime) => lifetime.span,
862             Node::GenericParam(param) => param.span,
863             Node::Visibility(&Spanned {
864                 node: VisibilityKind::Restricted { ref path, .. },
865                 ..
866             }) => path.span,
867             Node::Infer(i) => i.span,
868             Node::Visibility(v) => bug!("unexpected Visibility {:?}", v),
869             Node::Local(local) => local.span,
870             Node::MacroDef(macro_def) => macro_def.span,
871             Node::Crate(item) => item.inner,
872         };
873         Some(span)
874     }
875
876     /// Like `hir.span()`, but includes the body of function items
877     /// (instead of just the function header)
878     pub fn span_with_body(&self, hir_id: HirId) -> Span {
879         match self.find(hir_id) {
880             Some(Node::TraitItem(item)) => item.span,
881             Some(Node::ImplItem(impl_item)) => impl_item.span,
882             Some(Node::Item(item)) => item.span,
883             Some(_) => self.span(hir_id),
884             _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id),
885         }
886     }
887
888     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
889         id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id)))
890     }
891
892     pub fn res_span(&self, res: Res) -> Option<Span> {
893         match res {
894             Res::Err => None,
895             Res::Local(id) => Some(self.span(id)),
896             res => self.span_if_local(res.opt_def_id()?),
897         }
898     }
899
900     /// Get a representation of this `id` for debugging purposes.
901     /// NOTE: Do NOT use this in diagnostics!
902     pub fn node_to_string(&self, id: HirId) -> String {
903         hir_id_to_string(self, id)
904     }
905
906     /// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when
907     /// called with the HirId for the `{ ... }` anon const
908     pub fn opt_const_param_default_param_hir_id(&self, anon_const: HirId) -> Option<HirId> {
909         match self.get(self.get_parent_node(anon_const)) {
910             Node::GenericParam(GenericParam {
911                 hir_id: param_id,
912                 kind: GenericParamKind::Const { .. },
913                 ..
914             }) => Some(*param_id),
915             _ => None,
916         }
917     }
918 }
919
920 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
921     fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
922         self.find(hir_id)
923     }
924
925     fn body(&self, id: BodyId) -> &'hir Body<'hir> {
926         self.body(id)
927     }
928
929     fn item(&self, id: ItemId) -> &'hir Item<'hir> {
930         self.item(id)
931     }
932
933     fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
934         self.trait_item(id)
935     }
936
937     fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
938         self.impl_item(id)
939     }
940
941     fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
942         self.foreign_item(id)
943     }
944 }
945
946 pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> &'tcx IndexedHir<'tcx> {
947     let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
948
949     // We can access untracked state since we are an eval_always query.
950     let hcx = tcx.create_stable_hashing_context();
951     let mut collector = NodeCollector::root(
952         tcx.sess,
953         &**tcx.arena,
954         tcx.untracked_crate,
955         &tcx.untracked_resolutions.definitions,
956         hcx,
957     );
958     intravisit::walk_crate(&mut collector, tcx.untracked_crate);
959
960     let map = collector.finalize_and_compute_crate_hash();
961     tcx.arena.alloc(map)
962 }
963
964 pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
965     assert_eq!(crate_num, LOCAL_CRATE);
966
967     // We can access untracked state since we are an eval_always query.
968     let mut hcx = tcx.create_stable_hashing_context();
969
970     let mut hir_body_nodes: Vec<_> = tcx
971         .index_hir(())
972         .map
973         .iter_enumerated()
974         .filter_map(|(def_id, hod)| {
975             let def_path_hash = tcx.untracked_resolutions.definitions.def_path_hash(def_id);
976             let mut hasher = StableHasher::new();
977             hod.as_ref()?.hash_stable(&mut hcx, &mut hasher);
978             AttributeMap { map: &tcx.untracked_crate.attrs, prefix: def_id }
979                 .hash_stable(&mut hcx, &mut hasher);
980             Some((def_path_hash, hasher.finish()))
981         })
982         .collect();
983     hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
984
985     let node_hashes = hir_body_nodes.iter().fold(
986         Fingerprint::ZERO,
987         |combined_fingerprint, &(def_path_hash, fingerprint)| {
988             combined_fingerprint.combine(def_path_hash.0.combine(fingerprint))
989         },
990     );
991
992     let upstream_crates = upstream_crates(tcx);
993
994     // We hash the final, remapped names of all local source files so we
995     // don't have to include the path prefix remapping commandline args.
996     // If we included the full mapping in the SVH, we could only have
997     // reproducible builds by compiling from the same directory. So we just
998     // hash the result of the mapping instead of the mapping itself.
999     let mut source_file_names: Vec<_> = tcx
1000         .sess
1001         .source_map()
1002         .files()
1003         .iter()
1004         .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1005         .map(|source_file| source_file.name_hash)
1006         .collect();
1007
1008     source_file_names.sort_unstable();
1009
1010     let mut stable_hasher = StableHasher::new();
1011     node_hashes.hash_stable(&mut hcx, &mut stable_hasher);
1012     upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1013     source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1014     tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1015     tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher);
1016     tcx.untracked_crate.non_exported_macro_attrs.hash_stable(&mut hcx, &mut stable_hasher);
1017
1018     let crate_hash: Fingerprint = stable_hasher.finish();
1019     Svh::new(crate_hash.to_smaller_hash())
1020 }
1021
1022 fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1023     let mut upstream_crates: Vec<_> = tcx
1024         .crates(())
1025         .iter()
1026         .map(|&cnum| {
1027             let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum);
1028             let hash = tcx.crate_hash(cnum);
1029             (stable_crate_id, hash)
1030         })
1031         .collect();
1032     upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1033     upstream_crates
1034 }
1035
1036 fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String {
1037     let id_str = format!(" (hir_id={})", id);
1038
1039     let path_str = || {
1040         // This functionality is used for debugging, try to use `TyCtxt` to get
1041         // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1042         crate::ty::tls::with_opt(|tcx| {
1043             if let Some(tcx) = tcx {
1044                 let def_id = map.local_def_id(id);
1045                 tcx.def_path_str(def_id.to_def_id())
1046             } else if let Some(path) = map.def_path_from_hir_id(id) {
1047                 path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
1048             } else {
1049                 String::from("<missing path>")
1050             }
1051         })
1052     };
1053
1054     let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1055     let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1056
1057     match map.find(id) {
1058         Some(Node::Item(item)) => {
1059             let item_str = match item.kind {
1060                 ItemKind::ExternCrate(..) => "extern crate",
1061                 ItemKind::Use(..) => "use",
1062                 ItemKind::Static(..) => "static",
1063                 ItemKind::Const(..) => "const",
1064                 ItemKind::Fn(..) => "fn",
1065                 ItemKind::Mod(..) => "mod",
1066                 ItemKind::ForeignMod { .. } => "foreign mod",
1067                 ItemKind::GlobalAsm(..) => "global asm",
1068                 ItemKind::TyAlias(..) => "ty",
1069                 ItemKind::OpaqueTy(..) => "opaque type",
1070                 ItemKind::Enum(..) => "enum",
1071                 ItemKind::Struct(..) => "struct",
1072                 ItemKind::Union(..) => "union",
1073                 ItemKind::Trait(..) => "trait",
1074                 ItemKind::TraitAlias(..) => "trait alias",
1075                 ItemKind::Impl { .. } => "impl",
1076             };
1077             format!("{} {}{}", item_str, path_str(), id_str)
1078         }
1079         Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1080         Some(Node::ImplItem(ii)) => match ii.kind {
1081             ImplItemKind::Const(..) => {
1082                 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1083             }
1084             ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1085             ImplItemKind::TyAlias(_) => {
1086                 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1087             }
1088         },
1089         Some(Node::TraitItem(ti)) => {
1090             let kind = match ti.kind {
1091                 TraitItemKind::Const(..) => "assoc constant",
1092                 TraitItemKind::Fn(..) => "trait method",
1093                 TraitItemKind::Type(..) => "assoc type",
1094             };
1095
1096             format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1097         }
1098         Some(Node::Variant(ref variant)) => {
1099             format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1100         }
1101         Some(Node::Field(ref field)) => {
1102             format!("field {} in {}{}", field.ident, path_str(), id_str)
1103         }
1104         Some(Node::AnonConst(_)) => node_str("const"),
1105         Some(Node::Expr(_)) => node_str("expr"),
1106         Some(Node::Stmt(_)) => node_str("stmt"),
1107         Some(Node::PathSegment(_)) => node_str("path segment"),
1108         Some(Node::Ty(_)) => node_str("type"),
1109         Some(Node::TraitRef(_)) => node_str("trait ref"),
1110         Some(Node::Binding(_)) => node_str("local"),
1111         Some(Node::Pat(_)) => node_str("pat"),
1112         Some(Node::Param(_)) => node_str("param"),
1113         Some(Node::Arm(_)) => node_str("arm"),
1114         Some(Node::Block(_)) => node_str("block"),
1115         Some(Node::Infer(_)) => node_str("infer"),
1116         Some(Node::Local(_)) => node_str("local"),
1117         Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1118         Some(Node::Lifetime(_)) => node_str("lifetime"),
1119         Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1120         Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1121         Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1122         Some(Node::Crate(..)) => String::from("root_crate"),
1123         None => format!("unknown node{}", id_str),
1124     }
1125 }