Skip to content

Commit d50ca3c

Browse files
committed
Introduce HirIdVec.
1 parent 736fc96 commit d50ca3c

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

compiler/rustc_hir/src/hir_id.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::def_id::{LocalDefId, CRATE_DEF_INDEX};
2+
use rustc_index::vec::IndexVec;
23
use std::fmt;
34

45
/// Uniquely identifies a node in the HIR of the current crate. It is
@@ -61,3 +62,55 @@ pub const CRATE_HIR_ID: HirId = HirId {
6162
owner: LocalDefId { local_def_index: CRATE_DEF_INDEX },
6263
local_id: ItemLocalId::from_u32(0),
6364
};
65+
66+
#[derive(Clone, Default, Debug, Encodable, Decodable)]
67+
pub struct HirIdVec<T> {
68+
map: IndexVec<LocalDefId, IndexVec<ItemLocalId, T>>,
69+
}
70+
71+
impl<T> HirIdVec<T> {
72+
pub fn push_owner(&mut self, id: LocalDefId) {
73+
self.map.ensure_contains_elem(id, IndexVec::new);
74+
}
75+
76+
pub fn push(&mut self, id: HirId, value: T) {
77+
if id.local_id == ItemLocalId::from_u32(0) {
78+
self.push_owner(id.owner);
79+
}
80+
let submap = &mut self.map[id.owner];
81+
let _ret_id = submap.push(value);
82+
debug_assert_eq!(_ret_id, id.local_id);
83+
}
84+
85+
pub fn get(&self, id: HirId) -> Option<&T> {
86+
self.map.get(id.owner)?.get(id.local_id)
87+
}
88+
89+
pub fn get_owner(&self, id: LocalDefId) -> &IndexVec<ItemLocalId, T> {
90+
&self.map[id]
91+
}
92+
93+
pub fn iter(&self) -> impl Iterator<Item = &T> {
94+
self.map.iter().flat_map(|la| la.iter())
95+
}
96+
97+
pub fn iter_enumerated(&self) -> impl Iterator<Item = (HirId, &T)> {
98+
self.map.iter_enumerated().flat_map(|(owner, la)| {
99+
la.iter_enumerated().map(move |(local_id, attr)| (HirId { owner, local_id }, attr))
100+
})
101+
}
102+
}
103+
104+
impl<T> std::ops::Index<HirId> for HirIdVec<T> {
105+
type Output = T;
106+
107+
fn index(&self, id: HirId) -> &T {
108+
&self.map[id.owner][id.local_id]
109+
}
110+
}
111+
112+
impl<T> std::ops::IndexMut<HirId> for HirIdVec<T> {
113+
fn index_mut(&mut self, id: HirId) -> &mut T {
114+
&mut self.map[id.owner][id.local_id]
115+
}
116+
}

0 commit comments

Comments
 (0)