Skip to main content

rustc_middle/hir/
map.rs

1//! This module used to contain a type called `Map`. That type has since been
2//! eliminated, and all its methods are now on `TyCtxt`. But the module name
3//! stays as `map` because there isn't an obviously better name for it.
4
5use rustc_abi::ExternAbi;
6use rustc_ast::visit::{VisitorResult, walk_list};
7use rustc_data_structures::fingerprint::Fingerprint;
8use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
9use rustc_data_structures::svh::Svh;
10use rustc_data_structures::sync::{DynSend, DynSync, par_for_each_in, try_par_for_each_in};
11use rustc_hir::def::{DefKind, Res};
12use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId, LocalModDefId};
13use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
14use rustc_hir::intravisit::Visitor;
15use rustc_hir::*;
16use rustc_hir_pretty as pprust_hir;
17use rustc_span::def_id::StableCrateId;
18use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, kw, with_metavar_spans};
19
20use crate::hir::{ModuleItems, nested_filter};
21use crate::middle::debugger_visualizer::DebuggerVisualizerFile;
22use crate::query::LocalCrate;
23use crate::ty::TyCtxt;
24
25/// An iterator that walks up the ancestor tree of a given `HirId`.
26/// Constructed using `tcx.hir_parent_iter(hir_id)`.
27struct ParentHirIterator<'tcx> {
28    current_id: HirId,
29    tcx: TyCtxt<'tcx>,
30    // Cache the current value of `hir_owner_nodes` to avoid repeatedly calling the same query for
31    // the same owner, which will uselessly record many times the same query dependency.
32    current_owner_nodes: Option<&'tcx OwnerNodes<'tcx>>,
33}
34
35impl<'tcx> ParentHirIterator<'tcx> {
36    fn new(tcx: TyCtxt<'tcx>, current_id: HirId) -> ParentHirIterator<'tcx> {
37        ParentHirIterator { current_id, tcx, current_owner_nodes: None }
38    }
39}
40
41impl<'tcx> Iterator for ParentHirIterator<'tcx> {
42    type Item = HirId;
43
44    fn next(&mut self) -> Option<Self::Item> {
45        if self.current_id == CRATE_HIR_ID {
46            return None;
47        }
48
49        let HirId { owner, local_id } = self.current_id;
50
51        let parent_id = if local_id == ItemLocalId::ZERO {
52            // We go from an owner to its parent, so clear the cache.
53            self.current_owner_nodes = None;
54            self.tcx.hir_owner_parent(owner)
55        } else {
56            let owner_nodes =
57                self.current_owner_nodes.get_or_insert_with(|| self.tcx.hir_owner_nodes(owner));
58            let parent_local_id = owner_nodes.nodes[local_id].parent;
59            // HIR indexing should have checked that.
60            if true {
    match (&parent_local_id, &local_id) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_ne!(parent_local_id, local_id);
61            HirId { owner, local_id: parent_local_id }
62        };
63
64        if true {
    match (&parent_id, &self.current_id) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_ne!(parent_id, self.current_id);
65
66        self.current_id = parent_id;
67        Some(parent_id)
68    }
69}
70
71/// An iterator that walks up the ancestor tree of a given `HirId`.
72/// Constructed using `tcx.hir_parent_owner_iter(hir_id)`.
73pub struct ParentOwnerIterator<'tcx> {
74    current_id: HirId,
75    tcx: TyCtxt<'tcx>,
76}
77
78impl<'tcx> Iterator for ParentOwnerIterator<'tcx> {
79    type Item = (OwnerId, OwnerNode<'tcx>);
80
81    fn next(&mut self) -> Option<Self::Item> {
82        if self.current_id.local_id.index() != 0 {
83            self.current_id.local_id = ItemLocalId::ZERO;
84            let node = self.tcx.hir_owner_node(self.current_id.owner);
85            return Some((self.current_id.owner, node));
86        }
87        if self.current_id == CRATE_HIR_ID {
88            return None;
89        }
90
91        let parent_id = self.tcx.hir_def_key(self.current_id.owner.def_id).parent;
92        let parent_id = parent_id.map_or(CRATE_OWNER_ID, |local_def_index| {
93            let def_id = LocalDefId { local_def_index };
94            self.tcx.local_def_id_to_hir_id(def_id).owner
95        });
96        self.current_id = HirId::make_owner(parent_id.def_id);
97
98        let node = self.tcx.hir_owner_node(self.current_id.owner);
99        Some((self.current_id.owner, node))
100    }
101}
102
103impl<'tcx> TyCtxt<'tcx> {
104    #[inline]
105    fn expect_hir_owner_nodes(self, def_id: LocalDefId) -> &'tcx OwnerNodes<'tcx> {
106        self.opt_hir_owner_nodes(def_id)
107            .unwrap_or_else(|| crate::util::bug::span_bug_fmt(self.def_span(def_id),
    format_args!("{0:?} is not an owner", def_id))span_bug!(self.def_span(def_id), "{def_id:?} is not an owner"))
108    }
109
110    #[inline]
111    pub fn hir_owner_nodes(self, owner_id: OwnerId) -> &'tcx OwnerNodes<'tcx> {
112        self.expect_hir_owner_nodes(owner_id.def_id)
113    }
114
115    #[inline]
116    fn opt_hir_owner_node(self, def_id: LocalDefId) -> Option<OwnerNode<'tcx>> {
117        self.opt_hir_owner_nodes(def_id).map(|nodes| nodes.node())
118    }
119
120    #[inline]
121    pub fn expect_hir_owner_node(self, def_id: LocalDefId) -> OwnerNode<'tcx> {
122        self.expect_hir_owner_nodes(def_id).node()
123    }
124
125    #[inline]
126    pub fn hir_owner_node(self, owner_id: OwnerId) -> OwnerNode<'tcx> {
127        self.hir_owner_nodes(owner_id).node()
128    }
129
130    /// Retrieves the `hir::Node` corresponding to `id`.
131    pub fn hir_node(self, id: HirId) -> Node<'tcx> {
132        self.hir_owner_nodes(id.owner).nodes[id.local_id].node
133    }
134
135    /// Retrieves the `hir::Node` corresponding to `id`.
136    #[inline]
137    pub fn hir_node_by_def_id(self, id: LocalDefId) -> Node<'tcx> {
138        self.hir_node(self.local_def_id_to_hir_id(id))
139    }
140
141    /// Returns `HirId` of the parent HIR node of node with this `hir_id`.
142    /// Returns the same `hir_id` if and only if `hir_id == CRATE_HIR_ID`.
143    ///
144    /// If calling repeatedly and iterating over parents, prefer [`TyCtxt::hir_parent_iter`].
145    pub fn parent_hir_id(self, hir_id: HirId) -> HirId {
146        let HirId { owner, local_id } = hir_id;
147        if local_id == ItemLocalId::ZERO {
148            self.hir_owner_parent(owner)
149        } else {
150            let parent_local_id = self.hir_owner_nodes(owner).nodes[local_id].parent;
151            // HIR indexing should have checked that.
152            if true {
    match (&parent_local_id, &local_id) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_ne!(parent_local_id, local_id);
153            HirId { owner, local_id: parent_local_id }
154        }
155    }
156
157    /// Returns parent HIR node of node with this `hir_id`.
158    /// Returns HIR node of the same `hir_id` if and only if `hir_id == CRATE_HIR_ID`.
159    pub fn parent_hir_node(self, hir_id: HirId) -> Node<'tcx> {
160        self.hir_node(self.parent_hir_id(hir_id))
161    }
162
163    #[inline]
164    pub fn hir_root_module(self) -> &'tcx Mod<'tcx> {
165        match self.hir_owner_node(CRATE_OWNER_ID) {
166            OwnerNode::Crate(item) => item,
167            _ => crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
168        }
169    }
170
171    #[inline]
172    pub fn hir_free_items(self) -> impl Iterator<Item = ItemId> {
173        self.hir_crate_items(()).free_items.iter().copied()
174    }
175
176    #[inline]
177    pub fn hir_module_free_items(self, module: LocalModDefId) -> impl Iterator<Item = ItemId> {
178        self.hir_module_items(module).free_items()
179    }
180
181    pub fn hir_def_key(self, def_id: LocalDefId) -> DefKey {
182        // Accessing the DefKey is ok, since it is part of DefPathHash.
183        self.definitions_untracked().def_key(def_id)
184    }
185
186    pub fn hir_def_path(self, def_id: LocalDefId) -> DefPath {
187        // Accessing the DefPath is ok, since it is part of DefPathHash.
188        self.definitions_untracked().def_path(def_id)
189    }
190
191    #[inline]
192    pub fn hir_def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
193        // Accessing the DefPathHash is ok, it is incr. comp. stable.
194        self.definitions_untracked().def_path_hash(def_id)
195    }
196
197    pub fn hir_get_if_local(self, id: DefId) -> Option<Node<'tcx>> {
198        id.as_local().map(|id| self.hir_node_by_def_id(id))
199    }
200
201    pub fn hir_get_generics(self, id: LocalDefId) -> Option<&'tcx Generics<'tcx>> {
202        self.opt_hir_owner_node(id)?.generics()
203    }
204
205    pub fn hir_item(self, id: ItemId) -> &'tcx Item<'tcx> {
206        self.hir_owner_node(id.owner_id).expect_item()
207    }
208
209    pub fn hir_trait_item(self, id: TraitItemId) -> &'tcx TraitItem<'tcx> {
210        self.hir_owner_node(id.owner_id).expect_trait_item()
211    }
212
213    pub fn hir_impl_item(self, id: ImplItemId) -> &'tcx ImplItem<'tcx> {
214        self.hir_owner_node(id.owner_id).expect_impl_item()
215    }
216
217    pub fn hir_foreign_item(self, id: ForeignItemId) -> &'tcx ForeignItem<'tcx> {
218        self.hir_owner_node(id.owner_id).expect_foreign_item()
219    }
220
221    pub fn hir_body(self, id: BodyId) -> &'tcx Body<'tcx> {
222        self.hir_owner_nodes(id.hir_id.owner).bodies[&id.hir_id.local_id]
223    }
224
225    #[track_caller]
226    pub fn hir_fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'tcx FnDecl<'tcx>> {
227        self.hir_node(hir_id).fn_decl()
228    }
229
230    #[track_caller]
231    pub fn hir_fn_sig_by_hir_id(self, hir_id: HirId) -> Option<&'tcx FnSig<'tcx>> {
232        self.hir_node(hir_id).fn_sig()
233    }
234
235    #[track_caller]
236    pub fn hir_enclosing_body_owner(self, hir_id: HirId) -> LocalDefId {
237        for (_, node) in self.hir_parent_iter(hir_id) {
238            if let Some((def_id, _)) = node.associated_body() {
239                return def_id;
240            }
241        }
242
243        crate::util::bug::bug_fmt(format_args!("no `hir_enclosing_body_owner` for hir_id `{0}`",
        hir_id));bug!("no `hir_enclosing_body_owner` for hir_id `{}`", hir_id);
244    }
245
246    /// Returns the `HirId` that corresponds to the definition of
247    /// which this is the body of, i.e., a `fn`, `const` or `static`
248    /// item (possibly associated), a closure, or a `hir::AnonConst`.
249    pub fn hir_body_owner(self, BodyId { hir_id }: BodyId) -> HirId {
250        let parent = self.parent_hir_id(hir_id);
251        match (&self.hir_node(parent).body_id().unwrap().hir_id, &hir_id) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("{0:?}", hir_id)));
        }
    }
};assert_eq!(self.hir_node(parent).body_id().unwrap().hir_id, hir_id, "{hir_id:?}");
252        parent
253    }
254
255    pub fn hir_body_owner_def_id(self, BodyId { hir_id }: BodyId) -> LocalDefId {
256        self.parent_hir_node(hir_id).associated_body().unwrap().0
257    }
258
259    /// Given a `LocalDefId`, returns the `BodyId` associated with it,
260    /// if the node is a body owner, otherwise returns `None`.
261    pub fn hir_maybe_body_owned_by(self, id: LocalDefId) -> Option<&'tcx Body<'tcx>> {
262        Some(self.hir_body(self.hir_node_by_def_id(id).body_id()?))
263    }
264
265    /// Given a body owner's id, returns the `BodyId` associated with it.
266    #[track_caller]
267    pub fn hir_body_owned_by(self, id: LocalDefId) -> &'tcx Body<'tcx> {
268        self.hir_maybe_body_owned_by(id).unwrap_or_else(|| {
269            let hir_id = self.local_def_id_to_hir_id(id);
270            crate::util::bug::span_bug_fmt(self.hir_span(hir_id),
    format_args!("body_owned_by: {0} has no associated body",
        self.hir_id_to_string(hir_id)));span_bug!(
271                self.hir_span(hir_id),
272                "body_owned_by: {} has no associated body",
273                self.hir_id_to_string(hir_id)
274            );
275        })
276    }
277
278    pub fn hir_body_param_idents(self, id: BodyId) -> impl Iterator<Item = Option<Ident>> {
279        self.hir_body(id).params.iter().map(|param| match param.pat.kind {
280            PatKind::Binding(_, _, ident, _) => Some(ident),
281            PatKind::Wild => Some(Ident::new(kw::Underscore, param.pat.span)),
282            _ => None,
283        })
284    }
285
286    /// Returns the `BodyOwnerKind` of this `LocalDefId`.
287    ///
288    /// Panics if `LocalDefId` does not have an associated body.
289    pub fn hir_body_owner_kind(self, def_id: impl Into<DefId>) -> BodyOwnerKind {
290        let def_id = def_id.into();
291        match self.def_kind(def_id) {
292            DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => {
293                BodyOwnerKind::Const { inline: false }
294            }
295            DefKind::InlineConst => BodyOwnerKind::Const { inline: true },
296            DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => BodyOwnerKind::Fn,
297            DefKind::Closure | DefKind::SyntheticCoroutineBody => BodyOwnerKind::Closure,
298            DefKind::Static { safety: _, mutability, nested: false } => {
299                BodyOwnerKind::Static(mutability)
300            }
301            DefKind::GlobalAsm => BodyOwnerKind::GlobalAsm,
302            dk => crate::util::bug::bug_fmt(format_args!("{0:?} is not a body node: {1:?}",
        def_id, dk))bug!("{:?} is not a body node: {:?}", def_id, dk),
303        }
304    }
305
306    /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
307    ///
308    /// Panics if `LocalDefId` does not have an associated body.
309    ///
310    /// This should only be used for determining the context of a body, a return
311    /// value of `Some` does not always suggest that the owner of the body is `const`,
312    /// just that it has to be checked as if it were.
313    pub fn hir_body_const_context(self, def_id: LocalDefId) -> Option<ConstContext> {
314        let def_id = def_id.into();
315        let ccx = match self.hir_body_owner_kind(def_id) {
316            BodyOwnerKind::Const { inline } => ConstContext::Const { inline },
317            BodyOwnerKind::Static(mutability) => ConstContext::Static(mutability),
318
319            BodyOwnerKind::Fn if self.is_constructor(def_id) => return None,
320            BodyOwnerKind::Fn | BodyOwnerKind::Closure if self.is_const_fn(def_id) => {
321                ConstContext::ConstFn
322            }
323            BodyOwnerKind::Fn | BodyOwnerKind::Closure | BodyOwnerKind::GlobalAsm => return None,
324        };
325
326        Some(ccx)
327    }
328
329    /// Returns an iterator of the `DefId`s for all body-owners in this
330    /// crate.
331    #[inline]
332    pub fn hir_body_owners(self) -> impl Iterator<Item = LocalDefId> {
333        self.hir_crate_items(()).body_owners.iter().copied()
334    }
335
336    #[inline]
337    pub fn par_hir_body_owners(self, f: impl Fn(LocalDefId) + DynSend + DynSync) {
338        par_for_each_in(&self.hir_crate_items(()).body_owners[..], |&&def_id| f(def_id));
339    }
340
341    pub fn hir_ty_param_owner(self, def_id: LocalDefId) -> LocalDefId {
342        let def_kind = self.def_kind(def_id);
343        match def_kind {
344            DefKind::Trait | DefKind::TraitAlias => def_id,
345            DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
346                self.local_parent(def_id)
347            }
348            _ => crate::util::bug::bug_fmt(format_args!("ty_param_owner: {0:?} is a {1:?} not a type parameter",
        def_id, def_kind))bug!("ty_param_owner: {:?} is a {:?} not a type parameter", def_id, def_kind),
349        }
350    }
351
352    pub fn hir_ty_param_name(self, def_id: LocalDefId) -> Symbol {
353        let def_kind = self.def_kind(def_id);
354        match def_kind {
355            DefKind::Trait | DefKind::TraitAlias => kw::SelfUpper,
356            DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
357                self.item_name(def_id.to_def_id())
358            }
359            _ => crate::util::bug::bug_fmt(format_args!("ty_param_name: {0:?} is a {1:?} not a type parameter",
        def_id, def_kind))bug!("ty_param_name: {:?} is a {:?} not a type parameter", def_id, def_kind),
360        }
361    }
362
363    /// Gets the attributes on the crate. This is preferable to
364    /// invoking `krate.attrs` because it registers a tighter
365    /// dep-graph access.
366    pub fn hir_krate_attrs(self) -> &'tcx [Attribute] {
367        self.hir_attrs(CRATE_HIR_ID)
368    }
369
370    pub fn hir_rustc_coherence_is_core(self) -> bool {
371        {
    {
            'done:
                {
                for i in self.hir_krate_attrs() {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcCoherenceIsCore(..)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(self.hir_krate_attrs(), RustcCoherenceIsCore(..))
372    }
373
374    pub fn hir_get_module(self, module: LocalModDefId) -> (&'tcx Mod<'tcx>, Span, HirId) {
375        let hir_id = HirId::make_owner(module.to_local_def_id());
376        match self.hir_owner_node(hir_id.owner) {
377            OwnerNode::Item(&Item { span, kind: ItemKind::Mod(_, m), .. }) => (m, span, hir_id),
378            OwnerNode::Crate(item) => (item, item.spans.inner_span, hir_id),
379            node => { ::core::panicking::panic_fmt(format_args!("not a module: {0:?}", node)); }panic!("not a module: {node:?}"),
380        }
381    }
382
383    /// Walks the contents of the local crate. See also `visit_all_item_likes_in_crate`.
384    pub fn hir_walk_toplevel_module<V>(self, visitor: &mut V) -> V::Result
385    where
386        V: Visitor<'tcx>,
387    {
388        let (top_mod, span, hir_id) = self.hir_get_module(LocalModDefId::CRATE_DEF_ID);
389        visitor.visit_mod(top_mod, span, hir_id)
390    }
391
392    /// Walks the attributes in a crate.
393    pub fn hir_walk_attributes<V>(self, visitor: &mut V) -> V::Result
394    where
395        V: Visitor<'tcx>,
396    {
397        let krate = self.hir_crate_items(());
398        for owner in krate.owners() {
399            let attrs = self.hir_attr_map(owner);
400            for attrs in attrs.map.values() {
401                for elem in *attrs {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_attribute(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(visitor, visit_attribute, *attrs);
402            }
403        }
404        V::Result::output()
405    }
406
407    /// Visits all item-likes in the crate in some deterministic (but unspecified) order. If you
408    /// need to process every item-like, and don't care about visiting nested items in a particular
409    /// order then this method is the best choice. If you do care about this nesting, you should
410    /// use the `tcx.hir_walk_toplevel_module`.
411    ///
412    /// Note that this function will access HIR for all the item-likes in the crate. If you only
413    /// need to access some of them, it is usually better to manually loop on the iterators
414    /// provided by `tcx.hir_crate_items(())`.
415    ///
416    /// Please see the notes in `intravisit.rs` for more information.
417    pub fn hir_visit_all_item_likes_in_crate<V>(self, visitor: &mut V) -> V::Result
418    where
419        V: Visitor<'tcx>,
420    {
421        let krate = self.hir_crate_items(());
422        for elem in krate.free_items().map(|id| self.hir_item(id)) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(visitor, visit_item, krate.free_items().map(|id| self.hir_item(id)));
423        for elem in krate.trait_items().map(|id| self.hir_trait_item(id)) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_trait_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(
424            visitor,
425            visit_trait_item,
426            krate.trait_items().map(|id| self.hir_trait_item(id))
427        );
428        for elem in krate.impl_items().map(|id| self.hir_impl_item(id)) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_impl_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(visitor, visit_impl_item, krate.impl_items().map(|id| self.hir_impl_item(id)));
429        for elem in krate.foreign_items().map(|id| self.hir_foreign_item(id)) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_foreign_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(
430            visitor,
431            visit_foreign_item,
432            krate.foreign_items().map(|id| self.hir_foreign_item(id))
433        );
434        V::Result::output()
435    }
436
437    /// This method is the equivalent of `visit_all_item_likes_in_crate` but restricted to
438    /// item-likes in a single module.
439    pub fn hir_visit_item_likes_in_module<V>(
440        self,
441        module: LocalModDefId,
442        visitor: &mut V,
443    ) -> V::Result
444    where
445        V: Visitor<'tcx>,
446    {
447        let module = self.hir_module_items(module);
448        for elem in module.free_items().map(|id| self.hir_item(id)) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(visitor, visit_item, module.free_items().map(|id| self.hir_item(id)));
449        for elem in module.trait_items().map(|id| self.hir_trait_item(id)) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_trait_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(
450            visitor,
451            visit_trait_item,
452            module.trait_items().map(|id| self.hir_trait_item(id))
453        );
454        for elem in module.impl_items().map(|id| self.hir_impl_item(id)) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_impl_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(visitor, visit_impl_item, module.impl_items().map(|id| self.hir_impl_item(id)));
455        for elem in module.foreign_items().map(|id| self.hir_foreign_item(id)) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_foreign_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(
456            visitor,
457            visit_foreign_item,
458            module.foreign_items().map(|id| self.hir_foreign_item(id))
459        );
460        V::Result::output()
461    }
462
463    pub fn hir_for_each_module(self, mut f: impl FnMut(LocalModDefId)) {
464        let crate_items = self.hir_crate_items(());
465        for module in crate_items.submodules.iter() {
466            f(LocalModDefId::new_unchecked(module.def_id))
467        }
468    }
469
470    #[inline]
471    pub fn par_hir_for_each_module(self, f: impl Fn(LocalModDefId) + DynSend + DynSync) {
472        let crate_items = self.hir_crate_items(());
473        par_for_each_in(&crate_items.submodules[..], |module| {
474            f(LocalModDefId::new_unchecked(module.def_id))
475        })
476    }
477
478    #[inline]
479    pub fn try_par_hir_for_each_module(
480        self,
481        f: impl Fn(LocalModDefId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
482    ) -> Result<(), ErrorGuaranteed> {
483        let crate_items = self.hir_crate_items(());
484        try_par_for_each_in(&crate_items.submodules[..], |module| {
485            f(LocalModDefId::new_unchecked(module.def_id))
486        })
487    }
488
489    /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
490    /// until the crate root is reached. Prefer this over your own loop using `parent_id`.
491    #[inline]
492    pub fn hir_parent_id_iter(self, current_id: HirId) -> impl Iterator<Item = HirId> {
493        ParentHirIterator::new(self, current_id)
494    }
495
496    /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
497    /// until the crate root is reached. Prefer this over your own loop using `parent_id`.
498    #[inline]
499    pub fn hir_parent_iter(self, current_id: HirId) -> impl Iterator<Item = (HirId, Node<'tcx>)> {
500        self.hir_parent_id_iter(current_id).map(move |id| (id, self.hir_node(id)))
501    }
502
503    /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
504    /// until the crate root is reached. Prefer this over your own loop using `parent_id`.
505    #[inline]
506    pub fn hir_parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'tcx> {
507        ParentOwnerIterator { current_id, tcx: self }
508    }
509
510    /// Checks if the node is left-hand side of an assignment.
511    pub fn hir_is_lhs(self, id: HirId) -> bool {
512        match self.parent_hir_node(id) {
513            Node::Expr(expr) => match expr.kind {
514                ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
515                _ => false,
516            },
517            _ => false,
518        }
519    }
520
521    /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
522    /// Used exclusively for diagnostics, to avoid suggestion function calls.
523    pub fn hir_is_inside_const_context(self, hir_id: HirId) -> bool {
524        self.hir_body_const_context(self.hir_enclosing_body_owner(hir_id)).is_some()
525    }
526
527    /// Retrieves the `HirId` for `id`'s enclosing function *if* the `id` block or return is
528    /// in the "tail" position of the function, in other words if it's likely to correspond
529    /// to the return type of the function.
530    ///
531    /// ```
532    /// fn foo(x: usize) -> bool {
533    ///     if x == 1 {
534    ///         // If `get_fn_id_for_return_block` gets passed the `id` corresponding to this, it
535    ///         // will return `foo`'s `HirId`.
536    ///         true
537    ///     } else {
538    ///         false
539    ///     }
540    /// }
541    /// ```
542    ///
543    /// ```compile_fail,E0308
544    /// fn foo(x: usize) -> bool {
545    ///     loop {
546    ///         // If `get_fn_id_for_return_block` gets passed the `id` corresponding to this, it
547    ///         // will return `None`.
548    ///         true
549    ///     }
550    ///     false
551    /// }
552    /// ```
553    pub fn hir_get_fn_id_for_return_block(self, id: HirId) -> Option<HirId> {
554        let enclosing_body_owner = self.local_def_id_to_hir_id(self.hir_enclosing_body_owner(id));
555
556        // Return `None` if the `id` expression is not the returned value of the enclosing body
557        let mut iter = [id].into_iter().chain(self.hir_parent_id_iter(id)).peekable();
558        while let Some(cur_id) = iter.next() {
559            if enclosing_body_owner == cur_id {
560                break;
561            }
562
563            // A return statement is always the value returned from the enclosing body regardless of
564            // what the parent expressions are.
565            if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = self.hir_node(cur_id) {
566                break;
567            }
568
569            // If the current expression's value doesnt get used as the parent expressions value
570            // then return `None`
571            if let Some(&parent_id) = iter.peek() {
572                match self.hir_node(parent_id) {
573                    // The current node is not the tail expression of the block expression parent
574                    // expr.
575                    Node::Block(Block { expr: Some(e), .. }) if cur_id != e.hir_id => return None,
576                    Node::Block(Block { expr: Some(e), .. })
577                        if #[allow(non_exhaustive_omitted_patterns)] match e.kind {
    ExprKind::If(_, _, None) => true,
    _ => false,
}matches!(e.kind, ExprKind::If(_, _, None)) =>
578                    {
579                        return None;
580                    }
581
582                    // The current expression's value does not pass up through these parent
583                    // expressions.
584                    Node::Block(Block { expr: None, .. })
585                    | Node::Expr(Expr { kind: ExprKind::Loop(..), .. })
586                    | Node::LetStmt(..) => return None,
587
588                    _ => {}
589                }
590            }
591        }
592
593        Some(enclosing_body_owner)
594    }
595
596    /// Retrieves the `OwnerId` for `id`'s parent item, or `id` itself if no
597    /// parent item is in this map. The "parent item" is the closest parent node
598    /// in the HIR which is recorded by the map and is an item, either an item
599    /// in a module, trait, or impl.
600    pub fn hir_get_parent_item(self, hir_id: HirId) -> OwnerId {
601        if hir_id.local_id != ItemLocalId::ZERO {
602            // If this is a child of a HIR owner, return the owner.
603            hir_id.owner
604        } else if let Some((def_id, _node)) = self.hir_parent_owner_iter(hir_id).next() {
605            def_id
606        } else {
607            CRATE_OWNER_ID
608        }
609    }
610
611    /// When on an if expression, a match arm tail expression or a match arm, give back
612    /// the enclosing `if` or `match` expression.
613    ///
614    /// Used by error reporting when there's a type error in an if or match arm caused by the
615    /// expression needing to be unit.
616    pub fn hir_get_if_cause(self, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
617        for (_, node) in self.hir_parent_iter(hir_id) {
618            match node {
619                Node::Item(_)
620                | Node::ForeignItem(_)
621                | Node::TraitItem(_)
622                | Node::ImplItem(_)
623                | Node::Stmt(Stmt { kind: StmtKind::Let(_), .. }) => break,
624                Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
625                    return Some(expr);
626                }
627                _ => {}
628            }
629        }
630        None
631    }
632
633    /// Returns the nearest enclosing scope. A scope is roughly an item or block.
634    pub fn hir_get_enclosing_scope(self, hir_id: HirId) -> Option<HirId> {
635        for (hir_id, node) in self.hir_parent_iter(hir_id) {
636            if let Node::Item(Item {
637                kind:
638                    ItemKind::Fn { .. }
639                    | ItemKind::Const(..)
640                    | ItemKind::Static(..)
641                    | ItemKind::Mod(..)
642                    | ItemKind::Enum(..)
643                    | ItemKind::Struct(..)
644                    | ItemKind::Union(..)
645                    | ItemKind::Trait(..)
646                    | ItemKind::Impl { .. },
647                ..
648            })
649            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
650            | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
651            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
652            | Node::Block(_) = node
653            {
654                return Some(hir_id);
655            }
656        }
657        None
658    }
659
660    /// Returns the defining scope for an opaque type definition.
661    pub fn hir_get_defining_scope(self, id: HirId) -> HirId {
662        let mut scope = id;
663        loop {
664            scope = self.hir_get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
665            if scope == CRATE_HIR_ID || !#[allow(non_exhaustive_omitted_patterns)] match self.hir_node(scope) {
    Node::Block(_) => true,
    _ => false,
}matches!(self.hir_node(scope), Node::Block(_)) {
666                return scope;
667            }
668        }
669    }
670
671    /// Get a representation of this `id` for debugging purposes.
672    /// NOTE: Do NOT use this in diagnostics!
673    pub fn hir_id_to_string(self, id: HirId) -> String {
674        let path_str = |def_id: LocalDefId| self.def_path_str(def_id);
675
676        let span_str =
677            || self.sess.source_map().span_to_snippet(self.hir_span(id)).unwrap_or_default();
678        let node_str = |prefix| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} ({2} `{0}`)", span_str(), id,
                prefix))
    })format!("{id} ({prefix} `{}`)", span_str());
679
680        match self.hir_node(id) {
681            Node::Item(item) => {
682                let item_str = match item.kind {
683                    ItemKind::ExternCrate(..) => "extern crate",
684                    ItemKind::Use(..) => "use",
685                    ItemKind::Static(..) => "static",
686                    ItemKind::Const(..) => "const",
687                    ItemKind::Fn { .. } => "fn",
688                    ItemKind::Macro(..) => "macro",
689                    ItemKind::Mod(..) => "mod",
690                    ItemKind::ForeignMod { .. } => "foreign mod",
691                    ItemKind::GlobalAsm { .. } => "global asm",
692                    ItemKind::TyAlias(..) => "ty",
693                    ItemKind::Enum(..) => "enum",
694                    ItemKind::Struct(..) => "struct",
695                    ItemKind::Union(..) => "union",
696                    ItemKind::Trait(..) => "trait",
697                    ItemKind::TraitAlias(..) => "trait alias",
698                    ItemKind::Impl { .. } => "impl",
699                };
700                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} ({2} {0})",
                path_str(item.owner_id.def_id), id, item_str))
    })format!("{id} ({item_str} {})", path_str(item.owner_id.def_id))
701            }
702            Node::ForeignItem(item) => {
703                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} (foreign item {0})",
                path_str(item.owner_id.def_id), id))
    })format!("{id} (foreign item {})", path_str(item.owner_id.def_id))
704            }
705            Node::ImplItem(ii) => {
706                let kind = match ii.kind {
707                    ImplItemKind::Const(..) => "associated constant",
708                    ImplItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self {
709                        ImplicitSelfKind::None => "associated function",
710                        _ => "method",
711                    },
712                    ImplItemKind::Type(_) => "associated type",
713                };
714                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2} ({3} `{0}` in {1})", ii.ident,
                path_str(ii.owner_id.def_id), id, kind))
    })format!("{id} ({kind} `{}` in {})", ii.ident, path_str(ii.owner_id.def_id))
715            }
716            Node::TraitItem(ti) => {
717                let kind = match ti.kind {
718                    TraitItemKind::Const(..) => "associated constant",
719                    TraitItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self {
720                        ImplicitSelfKind::None => "associated function",
721                        _ => "trait method",
722                    },
723                    TraitItemKind::Type(..) => "associated type",
724                };
725
726                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2} ({3} `{0}` in {1})", ti.ident,
                path_str(ti.owner_id.def_id), id, kind))
    })format!("{id} ({kind} `{}` in {})", ti.ident, path_str(ti.owner_id.def_id))
727            }
728            Node::Variant(variant) => {
729                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2} (variant `{0}` in {1})",
                variant.ident, path_str(variant.def_id), id))
    })format!("{id} (variant `{}` in {})", variant.ident, path_str(variant.def_id))
730            }
731            Node::Field(field) => {
732                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2} (field `{0}` in {1})",
                field.ident, path_str(field.def_id), id))
    })format!("{id} (field `{}` in {})", field.ident, path_str(field.def_id))
733            }
734            Node::AnonConst(_) => node_str("const"),
735            Node::ConstBlock(_) => node_str("const"),
736            Node::ConstArg(_) => node_str("const"),
737            Node::Expr(_) => node_str("expr"),
738            Node::ExprField(_) => node_str("expr field"),
739            Node::ConstArgExprField(_) => node_str("const arg expr field"),
740            Node::Stmt(_) => node_str("stmt"),
741            Node::PathSegment(_) => node_str("path segment"),
742            Node::Ty(_) => node_str("type"),
743            Node::AssocItemConstraint(_) => node_str("assoc item constraint"),
744            Node::TraitRef(_) => node_str("trait ref"),
745            Node::OpaqueTy(_) => node_str("opaque type"),
746            Node::Pat(_) => node_str("pat"),
747            Node::TyPat(_) => node_str("pat ty"),
748            Node::PatField(_) => node_str("pattern field"),
749            Node::PatExpr(_) => node_str("pattern literal"),
750            Node::Param(_) => node_str("param"),
751            Node::Arm(_) => node_str("arm"),
752            Node::Block(_) => node_str("block"),
753            Node::Infer(_) => node_str("infer"),
754            Node::LetStmt(_) => node_str("local"),
755            Node::Ctor(ctor) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} (ctor {0})",
                ctor.ctor_def_id().map_or("<missing path>".into(),
                    |def_id| path_str(def_id)), id))
    })format!(
756                "{id} (ctor {})",
757                ctor.ctor_def_id().map_or("<missing path>".into(), |def_id| path_str(def_id)),
758            ),
759            Node::Lifetime(_) => node_str("lifetime"),
760            Node::GenericParam(param) => {
761                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} (generic_param {0})",
                path_str(param.def_id), id))
    })format!("{id} (generic_param {})", path_str(param.def_id))
762            }
763            Node::Crate(..) => String::from("(root_crate)"),
764            Node::WherePredicate(_) => node_str("where predicate"),
765            Node::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
766            Node::Err(_) => node_str("error"),
767            Node::PreciseCapturingNonLifetimeArg(_param) => node_str("parameter"),
768        }
769    }
770
771    pub fn hir_get_foreign_abi(self, hir_id: HirId) -> ExternAbi {
772        let parent = self.hir_get_parent_item(hir_id);
773        if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) =
774            self.hir_owner_node(parent)
775        {
776            return *abi;
777        }
778        crate::util::bug::bug_fmt(format_args!("expected foreign mod or inlined parent, found {0}",
        self.hir_id_to_string(HirId::make_owner(parent.def_id))))bug!(
779            "expected foreign mod or inlined parent, found {}",
780            self.hir_id_to_string(HirId::make_owner(parent.def_id))
781        )
782    }
783
784    pub fn hir_expect_item(self, id: LocalDefId) -> &'tcx Item<'tcx> {
785        match self.expect_hir_owner_node(id) {
786            OwnerNode::Item(item) => item,
787            _ => crate::util::bug::bug_fmt(format_args!("expected item, found {0}",
        self.hir_id_to_string(HirId::make_owner(id))))bug!("expected item, found {}", self.hir_id_to_string(HirId::make_owner(id))),
788        }
789    }
790
791    pub fn hir_expect_impl_item(self, id: LocalDefId) -> &'tcx ImplItem<'tcx> {
792        match self.expect_hir_owner_node(id) {
793            OwnerNode::ImplItem(item) => item,
794            _ => crate::util::bug::bug_fmt(format_args!("expected impl item, found {0}",
        self.hir_id_to_string(HirId::make_owner(id))))bug!("expected impl item, found {}", self.hir_id_to_string(HirId::make_owner(id))),
795        }
796    }
797
798    pub fn hir_expect_trait_item(self, id: LocalDefId) -> &'tcx TraitItem<'tcx> {
799        match self.expect_hir_owner_node(id) {
800            OwnerNode::TraitItem(item) => item,
801            _ => {
802                crate::util::bug::bug_fmt(format_args!("expected trait item, found {0}",
        self.hir_id_to_string(HirId::make_owner(id))))bug!("expected trait item, found {}", self.hir_id_to_string(HirId::make_owner(id)))
803            }
804        }
805    }
806
807    pub fn hir_get_fn_output(self, def_id: LocalDefId) -> Option<&'tcx FnRetTy<'tcx>> {
808        Some(&self.opt_hir_owner_node(def_id)?.fn_decl()?.output)
809    }
810
811    #[track_caller]
812    pub fn hir_expect_opaque_ty(self, id: LocalDefId) -> &'tcx OpaqueTy<'tcx> {
813        match self.hir_node_by_def_id(id) {
814            Node::OpaqueTy(opaq) => opaq,
815            _ => {
816                crate::util::bug::bug_fmt(format_args!("expected opaque type definition, found {0}",
        self.hir_id_to_string(self.local_def_id_to_hir_id(id))))bug!(
817                    "expected opaque type definition, found {}",
818                    self.hir_id_to_string(self.local_def_id_to_hir_id(id))
819                )
820            }
821        }
822    }
823
824    pub fn hir_expect_expr(self, id: HirId) -> &'tcx Expr<'tcx> {
825        match self.hir_node(id) {
826            Node::Expr(expr) => expr,
827            _ => crate::util::bug::bug_fmt(format_args!("expected expr, found {0}",
        self.hir_id_to_string(id)))bug!("expected expr, found {}", self.hir_id_to_string(id)),
828        }
829    }
830
831    pub fn hir_opt_delegation_sig_id(self, def_id: LocalDefId) -> Option<DefId> {
832        self.opt_hir_owner_node(def_id)?.fn_decl()?.opt_delegation_sig_id()
833    }
834
835    #[inline]
836    fn hir_opt_ident(self, id: HirId) -> Option<Ident> {
837        match self.hir_node(id) {
838            Node::Pat(&Pat { kind: PatKind::Binding(_, _, ident, _), .. }) => Some(ident),
839            // A `Ctor` doesn't have an identifier itself, but its parent
840            // struct/variant does. Compare with `hir::Map::span`.
841            Node::Ctor(..) => match self.parent_hir_node(id) {
842                Node::Item(item) => Some(item.kind.ident().unwrap()),
843                Node::Variant(variant) => Some(variant.ident),
844                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
845            },
846            node => node.ident(),
847        }
848    }
849
850    #[inline]
851    pub(super) fn hir_opt_ident_span(self, id: HirId) -> Option<Span> {
852        self.hir_opt_ident(id).map(|ident| ident.span)
853    }
854
855    #[inline]
856    pub fn hir_ident(self, id: HirId) -> Ident {
857        self.hir_opt_ident(id).unwrap()
858    }
859
860    #[inline]
861    pub fn hir_opt_name(self, id: HirId) -> Option<Symbol> {
862        self.hir_opt_ident(id).map(|ident| ident.name)
863    }
864
865    pub fn hir_name(self, id: HirId) -> Symbol {
866        self.hir_opt_name(id).unwrap_or_else(|| crate::util::bug::bug_fmt(format_args!("no name for {0}",
        self.hir_id_to_string(id)))bug!("no name for {}", self.hir_id_to_string(id)))
867    }
868
869    /// Given a node ID, gets a list of attributes associated with the AST
870    /// corresponding to the node-ID.
871    pub fn hir_attrs(self, id: HirId) -> &'tcx [Attribute] {
872        self.hir_attr_map(id.owner).get(id.local_id)
873    }
874
875    /// Gets the span of the definition of the specified HIR node.
876    /// This is used by `tcx.def_span`.
877    pub fn hir_span(self, hir_id: HirId) -> Span {
878        fn until_within(outer: Span, end: Span) -> Span {
879            if let Some(end) = end.find_ancestor_inside(outer) {
880                outer.with_hi(end.hi())
881            } else {
882                outer
883            }
884        }
885
886        fn named_span(item_span: Span, ident: Ident, generics: Option<&Generics<'_>>) -> Span {
887            let mut span = until_within(item_span, ident.span);
888            if let Some(g) = generics
889                && !g.span.is_dummy()
890                && let Some(g_span) = g.span.find_ancestor_inside(item_span)
891            {
892                span = span.to(g_span);
893            }
894            span
895        }
896
897        let span = match self.hir_node(hir_id) {
898            // Function-like.
899            Node::Item(Item { kind: ItemKind::Fn { sig, .. }, span: outer_span, .. })
900            | Node::TraitItem(TraitItem {
901                kind: TraitItemKind::Fn(sig, ..),
902                span: outer_span,
903                ..
904            })
905            | Node::ImplItem(ImplItem {
906                kind: ImplItemKind::Fn(sig, ..), span: outer_span, ..
907            })
908            | Node::ForeignItem(ForeignItem {
909                kind: ForeignItemKind::Fn(sig, ..),
910                span: outer_span,
911                ..
912            }) => {
913                // Ensure that the returned span has the item's SyntaxContext, and not the
914                // SyntaxContext of the visibility.
915                sig.span.find_ancestor_in_same_ctxt(*outer_span).unwrap_or(*outer_span)
916            }
917            // Impls, including their where clauses.
918            Node::Item(Item {
919                kind: ItemKind::Impl(Impl { generics, .. }),
920                span: outer_span,
921                ..
922            }) => until_within(*outer_span, generics.where_clause_span),
923            // Constants and Statics.
924            Node::Item(Item {
925                kind: ItemKind::Const(_, _, ty, _) | ItemKind::Static(_, _, ty, _),
926                span: outer_span,
927                ..
928            })
929            | Node::TraitItem(TraitItem {
930                kind: TraitItemKind::Const(ty, ..),
931                span: outer_span,
932                ..
933            })
934            | Node::ImplItem(ImplItem {
935                kind: ImplItemKind::Const(ty, ..),
936                span: outer_span,
937                ..
938            })
939            | Node::ForeignItem(ForeignItem {
940                kind: ForeignItemKind::Static(ty, ..),
941                span: outer_span,
942                ..
943            }) => until_within(*outer_span, ty.span),
944            // With generics and bounds.
945            Node::Item(Item {
946                kind: ItemKind::Trait(_, _, _, _, generics, bounds, _),
947                span: outer_span,
948                ..
949            })
950            | Node::TraitItem(TraitItem {
951                kind: TraitItemKind::Type(bounds, _),
952                generics,
953                span: outer_span,
954                ..
955            }) => {
956                let end = if let Some(b) = bounds.last() { b.span() } else { generics.span };
957                until_within(*outer_span, end)
958            }
959            // Other cases.
960            Node::Item(item) => match &item.kind {
961                ItemKind::Use(path, _) => {
962                    // Ensure that the returned span has the item's SyntaxContext, and not the
963                    // SyntaxContext of the path.
964                    path.span.find_ancestor_in_same_ctxt(item.span).unwrap_or(item.span)
965                }
966                _ => {
967                    if let Some(ident) = item.kind.ident() {
968                        named_span(item.span, ident, item.kind.generics())
969                    } else {
970                        item.span
971                    }
972                }
973            },
974            Node::Variant(variant) => named_span(variant.span, variant.ident, None),
975            Node::ImplItem(item) => named_span(item.span, item.ident, Some(item.generics)),
976            Node::ForeignItem(item) => named_span(item.span, item.ident, None),
977            Node::Ctor(_) => return self.hir_span(self.parent_hir_id(hir_id)),
978            Node::Expr(Expr {
979                kind: ExprKind::Closure(Closure { fn_decl_span, .. }),
980                span,
981                ..
982            }) => {
983                // Ensure that the returned span has the item's SyntaxContext.
984                fn_decl_span.find_ancestor_inside(*span).unwrap_or(*span)
985            }
986            _ => self.hir_span_with_body(hir_id),
987        };
988        if true {
    match (&span.ctxt(), &self.hir_span_with_body(hir_id).ctxt()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(span.ctxt(), self.hir_span_with_body(hir_id).ctxt());
989        span
990    }
991
992    /// Like `hir_span()`, but includes the body of items
993    /// (instead of just the item header)
994    pub fn hir_span_with_body(self, hir_id: HirId) -> Span {
995        match self.hir_node(hir_id) {
996            Node::Param(param) => param.span,
997            Node::Item(item) => item.span,
998            Node::ForeignItem(foreign_item) => foreign_item.span,
999            Node::TraitItem(trait_item) => trait_item.span,
1000            Node::ImplItem(impl_item) => impl_item.span,
1001            Node::Variant(variant) => variant.span,
1002            Node::Field(field) => field.span,
1003            Node::AnonConst(constant) => constant.span,
1004            Node::ConstBlock(constant) => self.hir_body(constant.body).value.span,
1005            Node::ConstArg(const_arg) => const_arg.span,
1006            Node::Expr(expr) => expr.span,
1007            Node::ExprField(field) => field.span,
1008            Node::ConstArgExprField(field) => field.span,
1009            Node::Stmt(stmt) => stmt.span,
1010            Node::PathSegment(seg) => {
1011                let ident_span = seg.ident.span;
1012                ident_span
1013                    .with_hi(seg.args.map_or_else(|| ident_span.hi(), |args| args.span_ext.hi()))
1014            }
1015            Node::Ty(ty) => ty.span,
1016            Node::AssocItemConstraint(constraint) => constraint.span,
1017            Node::TraitRef(tr) => tr.path.span,
1018            Node::OpaqueTy(op) => op.span,
1019            Node::Pat(pat) => pat.span,
1020            Node::TyPat(pat) => pat.span,
1021            Node::PatField(field) => field.span,
1022            Node::PatExpr(lit) => lit.span,
1023            Node::Arm(arm) => arm.span,
1024            Node::Block(block) => block.span,
1025            Node::Ctor(..) => self.hir_span_with_body(self.parent_hir_id(hir_id)),
1026            Node::Lifetime(lifetime) => lifetime.ident.span,
1027            Node::GenericParam(param) => param.span,
1028            Node::Infer(i) => i.span,
1029            Node::LetStmt(local) => local.span,
1030            Node::Crate(item) => item.spans.inner_span,
1031            Node::WherePredicate(pred) => pred.span,
1032            Node::PreciseCapturingNonLifetimeArg(param) => param.ident.span,
1033            Node::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1034            Node::Err(span) => span,
1035        }
1036    }
1037
1038    pub fn hir_span_if_local(self, id: DefId) -> Option<Span> {
1039        id.is_local().then(|| self.def_span(id))
1040    }
1041
1042    pub fn hir_res_span(self, res: Res) -> Option<Span> {
1043        match res {
1044            Res::Err => None,
1045            Res::Local(id) => Some(self.hir_span(id)),
1046            res => self.hir_span_if_local(res.opt_def_id()?),
1047        }
1048    }
1049
1050    /// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when
1051    /// called with the HirId for the `{ ... }` anon const
1052    pub fn hir_opt_const_param_default_param_def_id(self, anon_const: HirId) -> Option<LocalDefId> {
1053        let const_arg = self.parent_hir_id(anon_const);
1054        match self.parent_hir_node(const_arg) {
1055            Node::GenericParam(GenericParam {
1056                def_id: param_id,
1057                kind: GenericParamKind::Const { .. },
1058                ..
1059            }) => Some(*param_id),
1060            _ => None,
1061        }
1062    }
1063
1064    pub fn hir_maybe_get_struct_pattern_shorthand_field(self, expr: &Expr<'_>) -> Option<Symbol> {
1065        let local = match expr {
1066            Expr {
1067                kind:
1068                    ExprKind::Path(QPath::Resolved(
1069                        None,
1070                        Path {
1071                            res: def::Res::Local(_), segments: [PathSegment { ident, .. }], ..
1072                        },
1073                    )),
1074                ..
1075            } => Some(ident),
1076            _ => None,
1077        }?;
1078
1079        match self.parent_hir_node(expr.hir_id) {
1080            Node::ExprField(field) => {
1081                if field.ident.name == local.name && field.is_shorthand {
1082                    return Some(local.name);
1083                }
1084            }
1085            _ => {}
1086        }
1087
1088        None
1089    }
1090}
1091
1092impl<'tcx> intravisit::HirTyCtxt<'tcx> for TyCtxt<'tcx> {
1093    fn hir_node(&self, hir_id: HirId) -> Node<'tcx> {
1094        (*self).hir_node(hir_id)
1095    }
1096
1097    fn hir_body(&self, id: BodyId) -> &'tcx Body<'tcx> {
1098        (*self).hir_body(id)
1099    }
1100
1101    fn hir_item(&self, id: ItemId) -> &'tcx Item<'tcx> {
1102        (*self).hir_item(id)
1103    }
1104
1105    fn hir_trait_item(&self, id: TraitItemId) -> &'tcx TraitItem<'tcx> {
1106        (*self).hir_trait_item(id)
1107    }
1108
1109    fn hir_impl_item(&self, id: ImplItemId) -> &'tcx ImplItem<'tcx> {
1110        (*self).hir_impl_item(id)
1111    }
1112
1113    fn hir_foreign_item(&self, id: ForeignItemId) -> &'tcx ForeignItem<'tcx> {
1114        (*self).hir_foreign_item(id)
1115    }
1116}
1117
1118impl<'tcx> pprust_hir::PpAnn for TyCtxt<'tcx> {
1119    fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
1120        pprust_hir::PpAnn::nested(&(self as &dyn intravisit::HirTyCtxt<'_>), state, nested)
1121    }
1122}
1123
1124pub(super) fn crate_hash(tcx: TyCtxt<'_>, _: LocalCrate) -> Svh {
1125    let krate = tcx.hir_crate(());
1126    let hir_body_hash = krate.opt_hir_hash.expect("HIR hash missing while computing crate hash");
1127
1128    let upstream_crates = upstream_crates(tcx);
1129
1130    let resolutions = tcx.resolutions(());
1131
1132    // We hash the final, remapped names of all local source files so we
1133    // don't have to include the path prefix remapping commandline args.
1134    // If we included the full mapping in the SVH, we could only have
1135    // reproducible builds by compiling from the same directory. So we just
1136    // hash the result of the mapping instead of the mapping itself.
1137    let mut source_file_names: Vec<_> = tcx
1138        .sess
1139        .source_map()
1140        .files()
1141        .iter()
1142        .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1143        .map(|source_file| source_file.stable_id)
1144        .collect();
1145
1146    source_file_names.sort_unstable();
1147
1148    // We have to take care of debugger visualizers explicitly. The HIR (and
1149    // thus `hir_body_hash`) contains the #[debugger_visualizer] attributes but
1150    // these attributes only store the file path to the visualizer file, not
1151    // their content. Yet that content is exported into crate metadata, so any
1152    // changes to it need to be reflected in the crate hash.
1153    let debugger_visualizers: Vec<_> = tcx
1154        .debugger_visualizers(LOCAL_CRATE)
1155        .iter()
1156        // We ignore the path to the visualizer file since it's not going to be
1157        // encoded in crate metadata and we already hash the full contents of
1158        // the file.
1159        .map(DebuggerVisualizerFile::path_erased)
1160        .collect();
1161
1162    let crate_hash: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
1163        let mut stable_hasher = StableHasher::new();
1164        hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher);
1165        upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1166        source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1167        debugger_visualizers.hash_stable(&mut hcx, &mut stable_hasher);
1168        if tcx.sess.opts.incremental.is_some() {
1169            let definitions = tcx.untracked().definitions.freeze();
1170            let mut owner_spans: Vec<_> = tcx
1171                .hir_crate_items(())
1172                .definitions()
1173                .map(|def_id| {
1174                    let def_path_hash = definitions.def_path_hash(def_id);
1175                    let span = tcx.source_span(def_id);
1176                    if true {
    match (&span.parent(), &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(span.parent(), None);
1177                    (def_path_hash, span)
1178                })
1179                .collect();
1180            owner_spans.sort_unstable_by_key(|bn| bn.0);
1181            owner_spans.hash_stable(&mut hcx, &mut stable_hasher);
1182        }
1183        tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1184        tcx.stable_crate_id(LOCAL_CRATE).hash_stable(&mut hcx, &mut stable_hasher);
1185        // Hash visibility information since it does not appear in HIR.
1186        // FIXME: Figure out how to remove `visibilities_for_hashing` by hashing visibilities on
1187        // the fly in the resolver, storing only their accumulated hash in `ResolverGlobalCtxt`,
1188        // and combining it with other hashes here.
1189        resolutions.visibilities_for_hashing.hash_stable(&mut hcx, &mut stable_hasher);
1190        with_metavar_spans(|mspans| {
1191            mspans.freeze_and_get_read_spans().hash_stable(&mut hcx, &mut stable_hasher);
1192        });
1193        stable_hasher.finish()
1194    });
1195
1196    Svh::new(crate_hash)
1197}
1198
1199fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1200    let mut upstream_crates: Vec<_> = tcx
1201        .crates(())
1202        .iter()
1203        .map(|&cnum| {
1204            let stable_crate_id = tcx.stable_crate_id(cnum);
1205            let hash = tcx.crate_hash(cnum);
1206            (stable_crate_id, hash)
1207        })
1208        .collect();
1209    upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1210    upstream_crates
1211}
1212
1213pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalModDefId) -> ModuleItems {
1214    let mut collector = ItemCollector::new(tcx, false);
1215
1216    let (hir_mod, span, hir_id) = tcx.hir_get_module(module_id);
1217    collector.visit_mod(hir_mod, span, hir_id);
1218
1219    let ItemCollector {
1220        submodules,
1221        items,
1222        trait_items,
1223        impl_items,
1224        foreign_items,
1225        body_owners,
1226        opaques,
1227        nested_bodies,
1228        eiis,
1229        ..
1230    } = collector;
1231    ModuleItems {
1232        add_root: false,
1233        submodules: submodules.into_boxed_slice(),
1234        free_items: items.into_boxed_slice(),
1235        trait_items: trait_items.into_boxed_slice(),
1236        impl_items: impl_items.into_boxed_slice(),
1237        foreign_items: foreign_items.into_boxed_slice(),
1238        body_owners: body_owners.into_boxed_slice(),
1239        opaques: opaques.into_boxed_slice(),
1240        nested_bodies: nested_bodies.into_boxed_slice(),
1241        delayed_lint_items: Box::new([]),
1242        eiis: eiis.into_boxed_slice(),
1243    }
1244}
1245
1246pub(crate) fn hir_crate_items(tcx: TyCtxt<'_>, _: ()) -> ModuleItems {
1247    let mut collector = ItemCollector::new(tcx, true);
1248
1249    // A "crate collector" and "module collector" start at a
1250    // module item (the former starts at the crate root) but only
1251    // the former needs to collect it. ItemCollector does not do this for us.
1252    collector.submodules.push(CRATE_OWNER_ID);
1253    tcx.hir_walk_toplevel_module(&mut collector);
1254
1255    let ItemCollector {
1256        submodules,
1257        items,
1258        trait_items,
1259        impl_items,
1260        foreign_items,
1261        body_owners,
1262        opaques,
1263        nested_bodies,
1264        mut delayed_lint_items,
1265        eiis,
1266        ..
1267    } = collector;
1268
1269    // The crate could have delayed lints too, but would not be picked up by the visitor.
1270    // The `delayed_lint_items` list is smart - it only contains items which we know from
1271    // earlier passes is guaranteed to contain lints. It's a little harder to determine that
1272    // for sure here, so we simply always add the crate to the list. If it has no lints,
1273    // we'll discover that later. The cost of this should be low, there's only one crate
1274    // after all compared to the many items we have we wouldn't want to iterate over later.
1275    delayed_lint_items.push(CRATE_OWNER_ID);
1276
1277    ModuleItems {
1278        add_root: true,
1279        submodules: submodules.into_boxed_slice(),
1280        free_items: items.into_boxed_slice(),
1281        trait_items: trait_items.into_boxed_slice(),
1282        impl_items: impl_items.into_boxed_slice(),
1283        foreign_items: foreign_items.into_boxed_slice(),
1284        body_owners: body_owners.into_boxed_slice(),
1285        opaques: opaques.into_boxed_slice(),
1286        nested_bodies: nested_bodies.into_boxed_slice(),
1287        delayed_lint_items: delayed_lint_items.into_boxed_slice(),
1288        eiis: eiis.into_boxed_slice(),
1289    }
1290}
1291
1292struct ItemCollector<'tcx> {
1293    // When true, it collects all items in the create,
1294    // otherwise it collects items in some module.
1295    crate_collector: bool,
1296    tcx: TyCtxt<'tcx>,
1297    submodules: Vec<OwnerId>,
1298    items: Vec<ItemId>,
1299    trait_items: Vec<TraitItemId>,
1300    impl_items: Vec<ImplItemId>,
1301    foreign_items: Vec<ForeignItemId>,
1302    body_owners: Vec<LocalDefId>,
1303    opaques: Vec<LocalDefId>,
1304    nested_bodies: Vec<LocalDefId>,
1305    delayed_lint_items: Vec<OwnerId>,
1306    eiis: Vec<LocalDefId>,
1307}
1308
1309impl<'tcx> ItemCollector<'tcx> {
1310    fn new(tcx: TyCtxt<'tcx>, crate_collector: bool) -> ItemCollector<'tcx> {
1311        ItemCollector {
1312            crate_collector,
1313            tcx,
1314            submodules: Vec::default(),
1315            items: Vec::default(),
1316            trait_items: Vec::default(),
1317            impl_items: Vec::default(),
1318            foreign_items: Vec::default(),
1319            body_owners: Vec::default(),
1320            opaques: Vec::default(),
1321            nested_bodies: Vec::default(),
1322            delayed_lint_items: Vec::default(),
1323            eiis: Vec::default(),
1324        }
1325    }
1326}
1327
1328impl<'hir> Visitor<'hir> for ItemCollector<'hir> {
1329    type NestedFilter = nested_filter::All;
1330
1331    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1332        self.tcx
1333    }
1334
1335    fn visit_item(&mut self, item: &'hir Item<'hir>) {
1336        if Node::Item(item).associated_body().is_some() {
1337            self.body_owners.push(item.owner_id.def_id);
1338        }
1339
1340        self.items.push(item.item_id());
1341        if self.crate_collector && item.has_delayed_lints {
1342            self.delayed_lint_items.push(item.item_id().owner_id);
1343        }
1344
1345        if let ItemKind::Static(..) | ItemKind::Fn { .. } | ItemKind::Macro(..) = &item.kind
1346            && item.eii
1347        {
1348            self.eiis.push(item.owner_id.def_id)
1349        }
1350
1351        // Items that are modules are handled here instead of in visit_mod.
1352        if let ItemKind::Mod(_, module) = &item.kind {
1353            self.submodules.push(item.owner_id);
1354            // A module collector does not recurse inside nested modules.
1355            if self.crate_collector {
1356                intravisit::walk_mod(self, module);
1357            }
1358        } else {
1359            intravisit::walk_item(self, item)
1360        }
1361    }
1362
1363    fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) {
1364        self.foreign_items.push(item.foreign_item_id());
1365        if self.crate_collector && item.has_delayed_lints {
1366            self.delayed_lint_items.push(item.foreign_item_id().owner_id);
1367        }
1368        intravisit::walk_foreign_item(self, item)
1369    }
1370
1371    fn visit_anon_const(&mut self, c: &'hir AnonConst) {
1372        self.body_owners.push(c.def_id);
1373        intravisit::walk_anon_const(self, c)
1374    }
1375
1376    fn visit_inline_const(&mut self, c: &'hir ConstBlock) {
1377        self.body_owners.push(c.def_id);
1378        self.nested_bodies.push(c.def_id);
1379        intravisit::walk_inline_const(self, c)
1380    }
1381
1382    fn visit_opaque_ty(&mut self, o: &'hir OpaqueTy<'hir>) {
1383        self.opaques.push(o.def_id);
1384        intravisit::walk_opaque_ty(self, o)
1385    }
1386
1387    fn visit_expr(&mut self, ex: &'hir Expr<'hir>) {
1388        if let ExprKind::Closure(closure) = ex.kind {
1389            self.body_owners.push(closure.def_id);
1390            self.nested_bodies.push(closure.def_id);
1391        }
1392        intravisit::walk_expr(self, ex)
1393    }
1394
1395    fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) {
1396        if Node::TraitItem(item).associated_body().is_some() {
1397            self.body_owners.push(item.owner_id.def_id);
1398        }
1399
1400        self.trait_items.push(item.trait_item_id());
1401        if self.crate_collector && item.has_delayed_lints {
1402            self.delayed_lint_items.push(item.trait_item_id().owner_id);
1403        }
1404
1405        intravisit::walk_trait_item(self, item)
1406    }
1407
1408    fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) {
1409        if Node::ImplItem(item).associated_body().is_some() {
1410            self.body_owners.push(item.owner_id.def_id);
1411        }
1412
1413        self.impl_items.push(item.impl_item_id());
1414        if self.crate_collector && item.has_delayed_lints {
1415            self.delayed_lint_items.push(item.impl_item_id().owner_id);
1416        }
1417
1418        intravisit::walk_impl_item(self, item)
1419    }
1420}