1 use crate::def_id::{LocalDefId, CRATE_DEF_ID};
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.
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
14 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
15 #[derive(Encodable, Decodable, HashStable_Generic)]
16 #[rustc_pass_by_value]
18 pub owner: LocalDefId,
19 pub local_id: ItemLocalId,
23 /// Signal local id which should never be used.
24 pub const INVALID: HirId = HirId { owner: CRATE_DEF_ID, local_id: ItemLocalId::INVALID };
27 pub fn expect_owner(self) -> LocalDefId {
28 assert_eq!(self.local_id.index(), 0);
33 pub fn as_owner(self) -> Option<LocalDefId> {
34 if self.local_id.index() == 0 { Some(self.owner) } else { None }
38 pub fn is_owner(self) -> bool {
39 self.local_id.index() == 0
43 pub fn make_owner(owner: LocalDefId) -> Self {
44 Self { owner, local_id: ItemLocalId::from_u32(0) }
47 pub fn index(self) -> (usize, usize) {
48 (rustc_index::vec::Idx::index(self.owner), rustc_index::vec::Idx::index(self.local_id))
52 impl fmt::Display for HirId {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 write!(f, "{:?}", self)
59 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
60 (self.index()).cmp(&(other.index()))
64 impl PartialOrd for HirId {
65 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
66 Some(self.cmp(&other))
70 rustc_data_structures::define_stable_id_collections!(HirIdMap, HirIdSet, HirIdMapEntry, HirId);
71 rustc_data_structures::define_id_collections!(
78 rustc_index::newtype_index! {
79 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
80 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
81 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
82 /// the node's position within the owning item in any way, but there is a
83 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
84 /// integers starting at zero, so a mapping that maps all or most nodes within
85 /// an "item-like" to something else can be implemented by a `Vec` instead of a
87 #[derive(HashStable_Generic)]
88 pub struct ItemLocalId { .. }
92 /// Signal local id which should never be used.
93 pub const INVALID: ItemLocalId = ItemLocalId::MAX;
96 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_ID`.
97 pub const CRATE_HIR_ID: HirId = HirId { owner: CRATE_DEF_ID, local_id: ItemLocalId::from_u32(0) };