Skip to content

Commit ca09293

Browse files
committed
Auto merge of #47181 - michaelwoerister:var-len-def-index, r=eddyb
Use DefIndex encoding that works better with on-disk variable length integer representations. Use the least instead of the most significant bit for representing the address space. r? @eddyb
2 parents 6cf081c + c9d25e3 commit ca09293

File tree

10 files changed

+64
-65
lines changed

10 files changed

+64
-65
lines changed

src/librustc/hir/def_id.rs

+43-42
Original file line numberDiff line numberDiff line change
@@ -71,27 +71,23 @@ impl serialize::UseSpecializedDecodable for CrateNum {}
7171
/// particular definition. It should really be considered an interned
7272
/// shorthand for a particular DefPath.
7373
///
74-
/// At the moment we are allocating the numerical values of DefIndexes into two
75-
/// ranges: the "low" range (starting at zero) and the "high" range (starting at
76-
/// DEF_INDEX_HI_START). This allows us to allocate the DefIndexes of all
77-
/// item-likes (Items, TraitItems, and ImplItems) into one of these ranges and
74+
/// At the moment we are allocating the numerical values of DefIndexes from two
75+
/// address spaces: DefIndexAddressSpace::Low and DefIndexAddressSpace::High.
76+
/// This allows us to allocate the DefIndexes of all item-likes
77+
/// (Items, TraitItems, and ImplItems) into one of these spaces and
7878
/// consequently use a simple array for lookup tables keyed by DefIndex and
7979
/// known to be densely populated. This is especially important for the HIR map.
8080
///
8181
/// Since the DefIndex is mostly treated as an opaque ID, you probably
82-
/// don't have to care about these ranges.
83-
newtype_index!(DefIndex
84-
{
85-
ENCODABLE = custom
86-
DEBUG_FORMAT = custom,
82+
/// don't have to care about these address spaces.
8783
88-
/// The start of the "high" range of DefIndexes.
89-
const DEF_INDEX_HI_START = 1 << 31,
84+
#[derive(Clone, Eq, Ord, PartialOrd, PartialEq, Hash, Copy)]
85+
pub struct DefIndex(u32);
86+
87+
/// The crate root is always assigned index 0 by the AST Map code,
88+
/// thanks to `NodeCollector::new`.
89+
pub const CRATE_DEF_INDEX: DefIndex = DefIndex(0);
9090

91-
/// The crate root is always assigned index 0 by the AST Map code,
92-
/// thanks to `NodeCollector::new`.
93-
const CRATE_DEF_INDEX = 0,
94-
});
9591

9692
impl fmt::Debug for DefIndex {
9793
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -104,40 +100,50 @@ impl fmt::Debug for DefIndex {
104100

105101
impl DefIndex {
106102
#[inline]
107-
pub fn from_u32(x: u32) -> DefIndex {
108-
DefIndex(x)
103+
pub fn address_space(&self) -> DefIndexAddressSpace {
104+
match self.0 & 1 {
105+
0 => DefIndexAddressSpace::Low,
106+
1 => DefIndexAddressSpace::High,
107+
_ => unreachable!()
108+
}
109109
}
110110

111+
/// Converts this DefIndex into a zero-based array index.
112+
/// This index is the offset within the given DefIndexAddressSpace.
111113
#[inline]
112-
pub fn as_usize(&self) -> usize {
113-
self.0 as usize
114+
pub fn as_array_index(&self) -> usize {
115+
(self.0 >> 1) as usize
114116
}
115117

116118
#[inline]
117-
pub fn as_u32(&self) -> u32 {
118-
self.0
119+
pub fn from_array_index(i: usize, address_space: DefIndexAddressSpace) -> DefIndex {
120+
DefIndex::from_raw_u32(((i << 1) | (address_space as usize)) as u32)
119121
}
120122

121-
#[inline]
122-
pub fn address_space(&self) -> DefIndexAddressSpace {
123-
if self.0 < DEF_INDEX_HI_START.0 {
124-
DefIndexAddressSpace::Low
125-
} else {
126-
DefIndexAddressSpace::High
127-
}
123+
// Proc macros from a proc-macro crate have a kind of virtual DefIndex. This
124+
// function maps the index of the macro within the crate (which is also the
125+
// index of the macro in the CrateMetadata::proc_macros array) to the
126+
// corresponding DefIndex.
127+
pub fn from_proc_macro_index(proc_macro_index: usize) -> DefIndex {
128+
let def_index = DefIndex::from_array_index(proc_macro_index,
129+
DefIndexAddressSpace::High);
130+
assert!(def_index != CRATE_DEF_INDEX);
131+
def_index
128132
}
129133

130-
/// Converts this DefIndex into a zero-based array index.
131-
/// This index is the offset within the given "range" of the DefIndex,
132-
/// that is, if the DefIndex is part of the "high" range, the resulting
133-
/// index will be (DefIndex - DEF_INDEX_HI_START).
134-
#[inline]
135-
pub fn as_array_index(&self) -> usize {
136-
(self.0 & !DEF_INDEX_HI_START.0) as usize
134+
// This function is the reverse of from_proc_macro_index() above.
135+
pub fn to_proc_macro_index(self: DefIndex) -> usize {
136+
self.as_array_index()
137137
}
138138

139-
pub fn from_array_index(i: usize, address_space: DefIndexAddressSpace) -> DefIndex {
140-
DefIndex::new(address_space.start() + i)
139+
// Don't use this if you don't know about the DefIndex encoding.
140+
pub fn from_raw_u32(x: u32) -> DefIndex {
141+
DefIndex(x)
142+
}
143+
144+
// Don't use this if you don't know about the DefIndex encoding.
145+
pub fn as_raw_u32(&self) -> u32 {
146+
self.0
141147
}
142148
}
143149

@@ -155,11 +161,6 @@ impl DefIndexAddressSpace {
155161
pub fn index(&self) -> usize {
156162
*self as usize
157163
}
158-
159-
#[inline]
160-
pub fn start(&self) -> usize {
161-
self.index() * DEF_INDEX_HI_START.as_usize()
162-
}
163164
}
164165

165166
/// A DefId identifies a particular *definition*, by combining a crate

src/librustc/hir/map/definitions.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, DefIndexAddressSpace,
1919
CRATE_DEF_INDEX};
2020
use ich::Fingerprint;
2121
use rustc_data_structures::fx::FxHashMap;
22-
use rustc_data_structures::indexed_vec::{IndexVec, Idx};
22+
use rustc_data_structures::indexed_vec::{IndexVec};
2323
use rustc_data_structures::stable_hasher::StableHasher;
2424
use serialize::{Encodable, Decodable, Encoder, Decoder};
2525
use session::CrateDisambiguator;
@@ -61,7 +61,7 @@ impl DefPathTable {
6161
-> DefIndex {
6262
let index = {
6363
let index_to_key = &mut self.index_to_key[address_space.index()];
64-
let index = DefIndex::new(index_to_key.len() + address_space.start());
64+
let index = DefIndex::from_array_index(index_to_key.len(), address_space);
6565
debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
6666
index_to_key.push(key);
6767
index
@@ -89,16 +89,15 @@ impl DefPathTable {
8989
pub fn add_def_path_hashes_to(&self,
9090
cnum: CrateNum,
9191
out: &mut FxHashMap<DefPathHash, DefId>) {
92-
for address_space in &[DefIndexAddressSpace::Low, DefIndexAddressSpace::High] {
93-
let start_index = address_space.start();
92+
for &address_space in &[DefIndexAddressSpace::Low, DefIndexAddressSpace::High] {
9493
out.extend(
9594
(&self.def_path_hashes[address_space.index()])
9695
.iter()
9796
.enumerate()
9897
.map(|(index, &hash)| {
9998
let def_id = DefId {
10099
krate: cnum,
101-
index: DefIndex::new(index + start_index),
100+
index: DefIndex::from_array_index(index, address_space),
102101
};
103102
(hash, def_id)
104103
})

src/librustc/infer/lexical_region_resolve/graphviz.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
use graphviz as dot;
2020

2121
use hir::def_id::DefIndex;
22-
use rustc_data_structures::indexed_vec::Idx;
2322
use ty;
2423
use middle::free_region::RegionRelations;
2524
use middle::region;
@@ -68,7 +67,7 @@ pub fn maybe_print_constraints_for<'a, 'gcx, 'tcx>(
6867
}
6968

7069
let requested_node = env::var("RUST_REGION_GRAPH_NODE")
71-
.ok().and_then(|s| s.parse().map(DefIndex::new).ok());
70+
.ok().and_then(|s| s.parse().map(DefIndex::from_raw_u32).ok());
7271

7372
if requested_node.is_some() && requested_node != Some(context.index) {
7473
return;
@@ -102,7 +101,7 @@ pub fn maybe_print_constraints_for<'a, 'gcx, 'tcx>(
102101
let mut new_str = String::new();
103102
for c in output_template.chars() {
104103
if c == '%' {
105-
new_str.push_str(&context.index.as_usize().to_string());
104+
new_str.push_str(&context.index.as_raw_u32().to_string());
106105
} else {
107106
new_str.push(c);
108107
}

src/librustc/session/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -562,14 +562,14 @@ impl Session {
562562
index: DefIndex)
563563
-> String {
564564
format!("__rustc_plugin_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
565-
index.as_usize())
565+
index.to_proc_macro_index())
566566
}
567567

568568
pub fn generate_derive_registrar_symbol(&self, disambiguator: CrateDisambiguator,
569569
index: DefIndex)
570570
-> String {
571571
format!("__rustc_derive_registrar__{}_{}", disambiguator.to_fingerprint().to_hex(),
572-
index.as_usize())
572+
index.to_proc_macro_index())
573573
}
574574

575575
pub fn sysroot<'a>(&'a self) -> &'a Path {

src/librustc_metadata/cstore_impl.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ impl CrateStore for cstore::CStore {
463463
fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
464464
let data = self.get_crate_data(id.krate);
465465
if let Some(ref proc_macros) = data.proc_macros {
466-
return LoadedMacro::ProcMacro(proc_macros[id.index.as_usize() - 1].1.clone());
466+
return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
467467
} else if data.name == "proc_macro" &&
468468
self.get_crate_data(id.krate).item_name(id.index) == "quote" {
469469
let ext = SyntaxExtension::ProcMacro(Box::new(::proc_macro::__internal::Quoter));

src/librustc_metadata/decoder.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ use rustc::hir;
1818
use rustc::middle::cstore::{LinkagePreference, ExternConstBody,
1919
ExternBodyNestedBodies};
2020
use rustc::hir::def::{self, Def, CtorKind};
21-
use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
21+
use rustc::hir::def_id::{CrateNum, DefId, DefIndex,
22+
CRATE_DEF_INDEX, LOCAL_CRATE};
2223
use rustc::ich::Fingerprint;
2324
use rustc::middle::lang_items;
2425
use rustc::mir;
@@ -36,7 +37,6 @@ use std::rc::Rc;
3637
use std::u32;
3738

3839
use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
39-
use rustc_data_structures::indexed_vec::Idx;
4040
use syntax::attr;
4141
use syntax::ast::{self, Ident};
4242
use syntax::codemap;
@@ -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_u32(self.read_u32()?))
267+
Ok(DefIndex::from_raw_u32(self.read_u32()?))
268268
}
269269
}
270270

@@ -453,7 +453,7 @@ impl<'a, 'tcx> CrateMetadata {
453453
if !self.is_proc_macro(index) {
454454
self.entry(index).kind.to_def(self.local_def_id(index))
455455
} else {
456-
let kind = self.proc_macros.as_ref().unwrap()[index.as_usize() - 1].1.kind();
456+
let kind = self.proc_macros.as_ref().unwrap()[index.to_proc_macro_index()].1.kind();
457457
Some(Def::Macro(self.local_def_id(index), kind))
458458
}
459459
}
@@ -634,7 +634,7 @@ impl<'a, 'tcx> CrateMetadata {
634634
let def = Def::Macro(
635635
DefId {
636636
krate: self.cnum,
637-
index: DefIndex::new(id + 1)
637+
index: DefIndex::from_proc_macro_index(id),
638638
},
639639
ext.kind()
640640
);

src/librustc_metadata/encoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
140140
impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
141141
#[inline]
142142
fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
143-
self.emit_u32(def_index.as_u32())
143+
self.emit_u32(def_index.as_raw_u32())
144144
}
145145
}
146146

src/librustc_metadata/index.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,9 @@ impl<'tcx> LazySeq<Index> {
7474
#[inline(never)]
7575
pub fn lookup(&self, bytes: &[u8], def_index: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
7676
let words = &bytes_to_words(&bytes[self.position..])[..self.len];
77-
let index = def_index.as_usize();
7877

7978
debug!("Index::lookup: index={:?} words.len={:?}",
80-
index,
79+
def_index,
8180
words.len());
8281

8382
let positions = match def_index.address_space() {

src/librustc_resolve/macros.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ use {Module, ModuleKind, NameBinding, NameBindingKind, PathResult};
1313
use Namespace::{self, MacroNS};
1414
use build_reduced_graph::BuildReducedGraphVisitor;
1515
use resolve_imports::ImportResolver;
16-
use rustc_data_structures::indexed_vec::Idx;
17-
use rustc::hir::def_id::{DefId, BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, DefIndex};
16+
use rustc::hir::def_id::{DefId, BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, DefIndex,
17+
DefIndexAddressSpace};
1818
use rustc::hir::def::{Def, Export};
1919
use rustc::hir::map::{self, DefCollector};
2020
use rustc::{ty, lint};
@@ -188,7 +188,8 @@ impl<'a> base::Resolver for Resolver<'a> {
188188
fn add_builtin(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>) {
189189
let def_id = DefId {
190190
krate: BUILTIN_MACROS_CRATE,
191-
index: DefIndex::new(self.macro_map.len()),
191+
index: DefIndex::from_array_index(self.macro_map.len(),
192+
DefIndexAddressSpace::Low),
192193
};
193194
let kind = ext.kind();
194195
self.macro_map.insert(def_id, ext);

src/librustc_save_analysis/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1123,7 +1123,7 @@ fn generated_code(span: Span) -> bool {
11231123
fn id_from_def_id(id: DefId) -> rls_data::Id {
11241124
rls_data::Id {
11251125
krate: id.krate.as_u32(),
1126-
index: id.index.as_u32(),
1126+
index: id.index.as_raw_u32(),
11271127
}
11281128
}
11291129

0 commit comments

Comments
 (0)