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