Skip to content

Commit b18de52

Browse files
Declare DefIndex with the newtype_index macro
1 parent 548add7 commit b18de52

File tree

14 files changed

+36
-58
lines changed

14 files changed

+36
-58
lines changed

src/librustc/hir/def_id.rs

+12-34
Original file line numberDiff line numberDiff line change
@@ -96,34 +96,20 @@ impl fmt::Display for CrateNum {
9696
impl serialize::UseSpecializedEncodable for CrateNum {}
9797
impl serialize::UseSpecializedDecodable for CrateNum {}
9898

99-
/// A DefIndex is an index into the hir-map for a crate, identifying a
100-
/// particular definition. It should really be considered an interned
101-
/// shorthand for a particular DefPath.
102-
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
103-
pub struct DefIndex(u32);
104-
105-
/// The crate root is always assigned index 0 by the AST Map code,
106-
/// thanks to `NodeCollector::new`.
107-
pub const CRATE_DEF_INDEX: DefIndex = DefIndex(0);
99+
newtype_index! {
100+
/// A DefIndex is an index into the hir-map for a crate, identifying a
101+
/// particular definition. It should really be considered an interned
102+
/// shorthand for a particular DefPath.
103+
pub struct DefIndex {
104+
DEBUG_FORMAT = "DefIndex({})",
108105

109-
impl fmt::Debug for DefIndex {
110-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111-
write!(f, "DefIndex({})", self.as_array_index())
106+
/// The crate root is always assigned index 0 by the AST Map code,
107+
/// thanks to `NodeCollector::new`.
108+
const CRATE_DEF_INDEX = 0,
112109
}
113110
}
114111

115112
impl DefIndex {
116-
/// Converts this DefIndex into a zero-based array index.
117-
#[inline]
118-
pub fn as_array_index(&self) -> usize {
119-
self.0 as usize
120-
}
121-
122-
#[inline]
123-
pub fn from_array_index(i: usize) -> DefIndex {
124-
DefIndex(i as u32)
125-
}
126-
127113
// Proc macros from a proc-macro crate have a kind of virtual DefIndex. This
128114
// function maps the index of the macro within the crate (which is also the
129115
// index of the macro in the CrateMetadata::proc_macros array) to the
@@ -132,7 +118,7 @@ impl DefIndex {
132118
// DefIndex for proc macros start from FIRST_FREE_DEF_INDEX,
133119
// because the first FIRST_FREE_DEF_INDEX indexes are reserved
134120
// for internal use.
135-
let def_index = DefIndex::from_array_index(
121+
let def_index = DefIndex::from(
136122
proc_macro_index.checked_add(FIRST_FREE_DEF_INDEX)
137123
.expect("integer overflow adding `proc_macro_index`"));
138124
assert!(def_index != CRATE_DEF_INDEX);
@@ -141,19 +127,11 @@ impl DefIndex {
141127

142128
// This function is the reverse of from_proc_macro_index() above.
143129
pub fn to_proc_macro_index(self: DefIndex) -> usize {
144-
self.as_array_index().checked_sub(FIRST_FREE_DEF_INDEX)
130+
self.index().checked_sub(FIRST_FREE_DEF_INDEX)
145131
.unwrap_or_else(|| {
146132
bug!("using local index {:?} as proc-macro index", self)
147133
})
148134
}
149-
150-
pub fn from_raw_u32(x: u32) -> DefIndex {
151-
DefIndex(x)
152-
}
153-
154-
pub fn as_raw_u32(&self) -> u32 {
155-
self.0
156-
}
157135
}
158136

159137
impl serialize::UseSpecializedEncodable for DefIndex {}
@@ -169,7 +147,7 @@ pub struct DefId {
169147

170148
impl fmt::Debug for DefId {
171149
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172-
write!(f, "DefId({}:{}", self.krate, self.index.as_array_index())?;
150+
write!(f, "DefId({}:{}", self.krate, self.index.index())?;
173151

174152
ty::tls::with_opt(|opt_tcx| {
175153
if let Some(tcx) = opt_tcx {

src/librustc/hir/map/collector.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
226226

227227
fn insert_entry(&mut self, id: HirId, entry: Entry<'hir>) {
228228
debug!("hir_map: {:?} => {:?}", id, entry);
229-
let local_map = &mut self.map[id.owner.as_array_index()];
229+
let local_map = &mut self.map[id.owner.index()];
230230
let i = id.local_id.as_u32() as usize;
231231
if local_map.is_none() {
232232
*local_map = Some(IndexVec::with_capacity(i + 1));

src/librustc/hir/map/definitions.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ impl DefPathTable {
3838
def_path_hash: DefPathHash)
3939
-> DefIndex {
4040
let index = {
41-
let index = DefIndex::from_array_index(self.index_to_key.len());
41+
let index = DefIndex::from(self.index_to_key.len());
4242
debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
4343
self.index_to_key.push(key);
4444
index
@@ -49,17 +49,17 @@ impl DefPathTable {
4949
}
5050

5151
pub fn next_id(&self) -> DefIndex {
52-
DefIndex::from_array_index(self.index_to_key.len())
52+
DefIndex::from(self.index_to_key.len())
5353
}
5454

5555
#[inline(always)]
5656
pub fn def_key(&self, index: DefIndex) -> DefKey {
57-
self.index_to_key[index.as_array_index()].clone()
57+
self.index_to_key[index.index()].clone()
5858
}
5959

6060
#[inline(always)]
6161
pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
62-
let ret = self.def_path_hashes[index.as_array_index()];
62+
let ret = self.def_path_hashes[index.index()];
6363
debug!("def_path_hash({:?}) = {:?}", index, ret);
6464
return ret
6565
}
@@ -74,7 +74,7 @@ impl DefPathTable {
7474
.map(|(index, &hash)| {
7575
let def_id = DefId {
7676
krate: cnum,
77-
index: DefIndex::from_array_index(index),
77+
index: DefIndex::from(index),
7878
};
7979
(hash, def_id)
8080
})
@@ -387,7 +387,7 @@ impl Definitions {
387387
#[inline]
388388
pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
389389
if def_id.krate == LOCAL_CRATE {
390-
let node_id = self.def_index_to_node[def_id.index.as_array_index()];
390+
let node_id = self.def_index_to_node[def_id.index.index()];
391391
if node_id != ast::DUMMY_NODE_ID {
392392
return Some(node_id);
393393
}
@@ -417,7 +417,7 @@ impl Definitions {
417417

418418
#[inline]
419419
pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> hir::HirId {
420-
let node_id = self.def_index_to_node[def_index.as_array_index()];
420+
let node_id = self.def_index_to_node[def_index.index()];
421421
self.node_to_hir_id[node_id]
422422
}
423423

@@ -508,7 +508,7 @@ impl Definitions {
508508

509509
// Create the definition.
510510
let index = self.table.allocate(key, def_path_hash);
511-
assert_eq!(index.as_array_index(), self.def_index_to_node.len());
511+
assert_eq!(index.index(), self.def_index_to_node.len());
512512
self.def_index_to_node.push(node_id);
513513

514514
// Some things for which we allocate DefIndices don't correspond to
@@ -653,7 +653,7 @@ macro_rules! define_global_metadata_kind {
653653
.position(|k| *k == def_key)
654654
.unwrap();
655655

656-
DefIndex::from_array_index(index)
656+
DefIndex::from(index)
657657
}
658658

659659
fn name(&self) -> Symbol {

src/librustc/hir/map/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ pub struct Map<'hir> {
189189
impl<'hir> Map<'hir> {
190190
#[inline]
191191
fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
192-
let local_map = self.map.get(id.owner.as_array_index())?;
192+
let local_map = self.map.get(id.owner.index())?;
193193
local_map.as_ref()?.get(id.local_id)?.as_ref()
194194
}
195195

@@ -1023,7 +1023,7 @@ impl<'hir> Map<'hir> {
10231023
local_map.iter_enumerated().filter_map(move |(i, entry)| entry.map(move |_| {
10241024
// Reconstruct the HirId based on the 3 indices we used to find it
10251025
HirId {
1026-
owner: DefIndex::from_array_index(array_index),
1026+
owner: DefIndex::from(array_index),
10271027
local_id: i,
10281028
}
10291029
}))

src/librustc/infer/lexical_region_resolve/graphviz.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ pub fn maybe_print_constraints_for<'a, 'gcx, 'tcx>(
5656
}
5757

5858
let requested_node = env::var("RUST_REGION_GRAPH_NODE")
59-
.ok().and_then(|s| s.parse().map(DefIndex::from_raw_u32).ok());
59+
.ok().and_then(|s| s.parse().map(DefIndex::from_u32).ok());
6060

6161
if requested_node.is_some() && requested_node != Some(context.index) {
6262
return;
@@ -90,7 +90,7 @@ pub fn maybe_print_constraints_for<'a, 'gcx, 'tcx>(
9090
let mut new_str = String::new();
9191
for c in output_template.chars() {
9292
if c == '%' {
93-
new_str.push_str(&context.index.as_raw_u32().to_string());
93+
new_str.push_str(&context.index.as_u32().to_string());
9494
} else {
9595
new_str.push(c);
9696
}

src/librustc/traits/specialize/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ pub(super) fn specialization_graph_provider<'a, 'tcx>(
298298
// negated `CrateNum` (so remote definitions are visited first) and then
299299
// by a flattened version of the `DefIndex`.
300300
trait_impls.sort_unstable_by_key(|def_id| {
301-
(-(def_id.krate.as_u32() as i64), def_id.index.as_array_index())
301+
(-(def_id.krate.as_u32() as i64), def_id.index.index())
302302
});
303303

304304
for impl_def_id in trait_impls {

src/librustc_driver/pretty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -648,7 +648,7 @@ fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
648648
// have to be user friendly.
649649
let name = format!(
650650
"hir_id_{}_{}",
651-
hir_id.owner.as_array_index(),
651+
hir_id.owner.index(),
652652
hir_id.local_id.index(),
653653
);
654654
let lcfg = LabelledCFG {

src/librustc_metadata/decoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
264264
impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
265265
#[inline]
266266
fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
267-
Ok(DefIndex::from_raw_u32(self.read_u32()?))
267+
Ok(DefIndex::from_u32(self.read_u32()?))
268268
}
269269
}
270270

src/librustc_metadata/encoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
134134
impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
135135
#[inline]
136136
fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
137-
self.emit_u32(def_index.as_raw_u32())
137+
self.emit_u32(def_index.as_u32())
138138
}
139139
}
140140

src/librustc_metadata/index.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ impl Index {
9393
pub fn record_index(&mut self, item: DefIndex, entry: Lazy<Entry<'_>>) {
9494
assert!(entry.position < (u32::MAX as usize));
9595
let position = entry.position as u32;
96-
let array_index = item.as_array_index();
96+
let array_index = item.index();
9797

9898
let positions = &mut self.positions;
9999
assert!(u32::read_from_bytes_at(positions, array_index) == u32::MAX,
@@ -126,7 +126,7 @@ impl<'tcx> LazySeq<Index> {
126126
def_index,
127127
self.len);
128128

129-
let position = u32::read_from_bytes_at(bytes, 1 + def_index.as_array_index());
129+
let position = u32::read_from_bytes_at(bytes, 1 + def_index.index());
130130
if position == u32::MAX {
131131
debug!("Index::lookup: position=u32::MAX");
132132
None

src/librustc_mir/util/graphviz.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ pub fn graphviz_safe_def_name(def_id: DefId) -> String {
2727
format!(
2828
"{}_{}",
2929
def_id.krate.index(),
30-
def_id.index.as_array_index(),
30+
def_id.index.index(),
3131
)
3232
}
3333

src/librustc_resolve/macros.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ impl<'a> base::Resolver for Resolver<'a> {
172172
fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
173173
let def_id = DefId {
174174
krate: CrateNum::BuiltinMacros,
175-
index: DefIndex::from_array_index(self.macro_map.len()),
175+
index: DefIndex::from(self.macro_map.len()),
176176
};
177177
let kind = ext.kind();
178178
self.macro_map.insert(def_id, ext);

src/librustc_save_analysis/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1170,7 +1170,7 @@ fn generated_code(span: Span) -> bool {
11701170
fn id_from_def_id(id: DefId) -> rls_data::Id {
11711171
rls_data::Id {
11721172
krate: id.krate.as_u32(),
1173-
index: id.index.as_raw_u32(),
1173+
index: id.index.as_u32(),
11741174
}
11751175
}
11761176

src/librustdoc/core.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ impl<'tcx> DocContext<'tcx> {
143143
crate_num,
144144
DefId {
145145
krate: crate_num,
146-
index: DefIndex::from_array_index(def_id.index.as_array_index() + 1),
146+
index: DefIndex::from(def_id.index.index() + 1),
147147
},
148148
);
149149

0 commit comments

Comments
 (0)