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