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