]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/hir_id.rs
Rollup merge of #81575 - camelid:rustdoc-wrongnamespace-cleanup, r=jyn514
[rust.git] / compiler / rustc_hir / src / hir_id.rs
1 use crate::def_id::{LocalDefId, CRATE_DEF_INDEX};
2 use std::fmt;
3
4 /// Uniquely identifies a node in the HIR of the current crate. It is
5 /// composed of the `owner`, which is the `LocalDefId` of the directly enclosing
6 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
7 /// and the `local_id` which is unique within the given owner.
8 ///
9 /// This two-level structure makes for more stable values: One can move an item
10 /// around within the source code, or add or remove stuff before it, without
11 /// the `local_id` part of the `HirId` changing, which is a very useful property in
12 /// incremental compilation where we have to persist things through changes to
13 /// the code base.
14 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
15 #[derive(Encodable, Decodable)]
16 pub struct HirId {
17     pub owner: LocalDefId,
18     pub local_id: ItemLocalId,
19 }
20
21 impl HirId {
22     pub fn expect_owner(self) -> LocalDefId {
23         assert_eq!(self.local_id.index(), 0);
24         self.owner
25     }
26
27     pub fn as_owner(self) -> Option<LocalDefId> {
28         if self.local_id.index() == 0 { Some(self.owner) } else { None }
29     }
30
31     pub fn make_owner(owner: LocalDefId) -> Self {
32         Self { owner, local_id: ItemLocalId::from_u32(0) }
33     }
34 }
35
36 impl fmt::Display for HirId {
37     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38         write!(f, "{:?}", self)
39     }
40 }
41
42 rustc_data_structures::define_id_collections!(HirIdMap, HirIdSet, HirId);
43 rustc_data_structures::define_id_collections!(ItemLocalMap, ItemLocalSet, ItemLocalId);
44
45 rustc_index::newtype_index! {
46     /// An `ItemLocalId` uniquely identifies something within a given "item-like";
47     /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
48     /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
49     /// the node's position within the owning item in any way, but there is a
50     /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
51     /// integers starting at zero, so a mapping that maps all or most nodes within
52     /// an "item-like" to something else can be implemented by a `Vec` instead of a
53     /// tree or hash map.
54     pub struct ItemLocalId { .. }
55 }
56 rustc_data_structures::impl_stable_hash_via_hash!(ItemLocalId);
57
58 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
59 pub const CRATE_HIR_ID: HirId = HirId {
60     owner: LocalDefId { local_def_index: CRATE_DEF_INDEX },
61     local_id: ItemLocalId::from_u32(0),
62 };