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,
24 pub fn expect_owner(self) -> LocalDefId {
25 assert_eq!(self.local_id.index(), 0);
30 pub fn as_owner(self) -> Option<LocalDefId> {
31 if self.local_id.index() == 0 { Some(self.owner) } else { None }
35 pub fn is_owner(self) -> bool {
36 self.local_id.index() == 0
40 pub fn make_owner(owner: LocalDefId) -> Self {
41 Self { owner, local_id: ItemLocalId::from_u32(0) }
44 pub fn index(self) -> (usize, usize) {
45 (rustc_index::vec::Idx::index(self.owner), rustc_index::vec::Idx::index(self.local_id))
49 impl fmt::Display for HirId {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 write!(f, "{:?}", self)
56 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
57 (self.index()).cmp(&(other.index()))
61 impl PartialOrd for HirId {
62 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
63 Some(self.cmp(&other))
67 rustc_data_structures::define_id_collections!(HirIdMap, HirIdSet, HirId);
68 rustc_data_structures::define_id_collections!(ItemLocalMap, ItemLocalSet, ItemLocalId);
70 rustc_index::newtype_index! {
71 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
72 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
73 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
74 /// the node's position within the owning item in any way, but there is a
75 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
76 /// integers starting at zero, so a mapping that maps all or most nodes within
77 /// an "item-like" to something else can be implemented by a `Vec` instead of a
79 #[derive(HashStable_Generic)]
80 pub struct ItemLocalId { .. }
84 /// Signal local id which should never be used.
85 pub const INVALID: ItemLocalId = ItemLocalId::MAX;
88 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_ID`.
89 pub const CRATE_HIR_ID: HirId = HirId { owner: CRATE_DEF_ID, local_id: ItemLocalId::from_u32(0) };