Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Declare DefIndex with the newtype_index macro #60934

Merged
merged 1 commit into from
May 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 12 additions & 34 deletions src/librustc/hir/def_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,34 +96,20 @@ impl fmt::Display for CrateNum {
impl serialize::UseSpecializedEncodable for CrateNum {}
impl serialize::UseSpecializedDecodable for CrateNum {}

/// A DefIndex is an index into the hir-map for a crate, identifying a
/// particular definition. It should really be considered an interned
/// shorthand for a particular DefPath.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
pub struct DefIndex(u32);

/// The crate root is always assigned index 0 by the AST Map code,
/// thanks to `NodeCollector::new`.
pub const CRATE_DEF_INDEX: DefIndex = DefIndex(0);
newtype_index! {
/// A DefIndex is an index into the hir-map for a crate, identifying a
/// particular definition. It should really be considered an interned
/// shorthand for a particular DefPath.
pub struct DefIndex {
DEBUG_FORMAT = "DefIndex({})",

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

impl DefIndex {
/// Converts this DefIndex into a zero-based array index.
#[inline]
pub fn as_array_index(&self) -> usize {
self.0 as usize
}

#[inline]
pub fn from_array_index(i: usize) -> DefIndex {
DefIndex(i as u32)
}

// Proc macros from a proc-macro crate have a kind of virtual DefIndex. This
// function maps the index of the macro within the crate (which is also the
// index of the macro in the CrateMetadata::proc_macros array) to the
Expand All @@ -132,7 +118,7 @@ impl DefIndex {
// DefIndex for proc macros start from FIRST_FREE_DEF_INDEX,
// because the first FIRST_FREE_DEF_INDEX indexes are reserved
// for internal use.
let def_index = DefIndex::from_array_index(
let def_index = DefIndex::from(
proc_macro_index.checked_add(FIRST_FREE_DEF_INDEX)
.expect("integer overflow adding `proc_macro_index`"));
assert!(def_index != CRATE_DEF_INDEX);
Expand All @@ -141,19 +127,11 @@ impl DefIndex {

// This function is the reverse of from_proc_macro_index() above.
pub fn to_proc_macro_index(self: DefIndex) -> usize {
self.as_array_index().checked_sub(FIRST_FREE_DEF_INDEX)
self.index().checked_sub(FIRST_FREE_DEF_INDEX)
.unwrap_or_else(|| {
bug!("using local index {:?} as proc-macro index", self)
})
}

pub fn from_raw_u32(x: u32) -> DefIndex {
DefIndex(x)
}

pub fn as_raw_u32(&self) -> u32 {
self.0
}
}

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

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

ty::tls::with_opt(|opt_tcx| {
if let Some(tcx) = opt_tcx {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/hir/map/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {

fn insert_entry(&mut self, id: HirId, entry: Entry<'hir>) {
debug!("hir_map: {:?} => {:?}", id, entry);
let local_map = &mut self.map[id.owner.as_array_index()];
let local_map = &mut self.map[id.owner.index()];
let i = id.local_id.as_u32() as usize;
if local_map.is_none() {
*local_map = Some(IndexVec::with_capacity(i + 1));
Expand Down
18 changes: 9 additions & 9 deletions src/librustc/hir/map/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl DefPathTable {
def_path_hash: DefPathHash)
-> DefIndex {
let index = {
let index = DefIndex::from_array_index(self.index_to_key.len());
let index = DefIndex::from(self.index_to_key.len());
debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
self.index_to_key.push(key);
index
Expand All @@ -49,17 +49,17 @@ impl DefPathTable {
}

pub fn next_id(&self) -> DefIndex {
DefIndex::from_array_index(self.index_to_key.len())
DefIndex::from(self.index_to_key.len())
}

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

#[inline(always)]
pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
let ret = self.def_path_hashes[index.as_array_index()];
let ret = self.def_path_hashes[index.index()];
debug!("def_path_hash({:?}) = {:?}", index, ret);
return ret
}
Expand All @@ -74,7 +74,7 @@ impl DefPathTable {
.map(|(index, &hash)| {
let def_id = DefId {
krate: cnum,
index: DefIndex::from_array_index(index),
index: DefIndex::from(index),
};
(hash, def_id)
})
Expand Down Expand Up @@ -387,7 +387,7 @@ impl Definitions {
#[inline]
pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
if def_id.krate == LOCAL_CRATE {
let node_id = self.def_index_to_node[def_id.index.as_array_index()];
let node_id = self.def_index_to_node[def_id.index.index()];
if node_id != ast::DUMMY_NODE_ID {
return Some(node_id);
}
Expand Down Expand Up @@ -417,7 +417,7 @@ impl Definitions {

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

Expand Down Expand Up @@ -508,7 +508,7 @@ impl Definitions {

// Create the definition.
let index = self.table.allocate(key, def_path_hash);
assert_eq!(index.as_array_index(), self.def_index_to_node.len());
assert_eq!(index.index(), self.def_index_to_node.len());
self.def_index_to_node.push(node_id);

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

DefIndex::from_array_index(index)
DefIndex::from(index)
}

fn name(&self) -> Symbol {
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/hir/map/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ pub struct Map<'hir> {
impl<'hir> Map<'hir> {
#[inline]
fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
let local_map = self.map.get(id.owner.as_array_index())?;
let local_map = self.map.get(id.owner.index())?;
local_map.as_ref()?.get(id.local_id)?.as_ref()
}

Expand Down Expand Up @@ -1023,7 +1023,7 @@ impl<'hir> Map<'hir> {
local_map.iter_enumerated().filter_map(move |(i, entry)| entry.map(move |_| {
// Reconstruct the HirId based on the 3 indices we used to find it
HirId {
owner: DefIndex::from_array_index(array_index),
owner: DefIndex::from(array_index),
local_id: i,
}
}))
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/infer/lexical_region_resolve/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub fn maybe_print_constraints_for<'a, 'gcx, 'tcx>(
}

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

if requested_node.is_some() && requested_node != Some(context.index) {
return;
Expand Down Expand Up @@ -90,7 +90,7 @@ pub fn maybe_print_constraints_for<'a, 'gcx, 'tcx>(
let mut new_str = String::new();
for c in output_template.chars() {
if c == '%' {
new_str.push_str(&context.index.as_raw_u32().to_string());
new_str.push_str(&context.index.as_u32().to_string());
} else {
new_str.push(c);
}
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/traits/specialize/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ pub(super) fn specialization_graph_provider<'a, 'tcx>(
// negated `CrateNum` (so remote definitions are visited first) and then
// by a flattened version of the `DefIndex`.
trait_impls.sort_unstable_by_key(|def_id| {
(-(def_id.krate.as_u32() as i64), def_id.index.as_array_index())
(-(def_id.krate.as_u32() as i64), def_id.index.index())
});

for impl_def_id in trait_impls {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_driver/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,7 @@ fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
// have to be user friendly.
let name = format!(
"hir_id_{}_{}",
hir_id.owner.as_array_index(),
hir_id.owner.index(),
hir_id.local_id.index(),
);
let lcfg = LabelledCFG {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_metadata/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
#[inline]
fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
Ok(DefIndex::from_raw_u32(self.read_u32()?))
Ok(DefIndex::from_u32(self.read_u32()?))
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/librustc_metadata/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
#[inline]
fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
self.emit_u32(def_index.as_raw_u32())
self.emit_u32(def_index.as_u32())
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/librustc_metadata/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl Index {
pub fn record_index(&mut self, item: DefIndex, entry: Lazy<Entry<'_>>) {
assert!(entry.position < (u32::MAX as usize));
let position = entry.position as u32;
let array_index = item.as_array_index();
let array_index = item.index();

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

let position = u32::read_from_bytes_at(bytes, 1 + def_index.as_array_index());
let position = u32::read_from_bytes_at(bytes, 1 + def_index.index());
if position == u32::MAX {
debug!("Index::lookup: position=u32::MAX");
None
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/util/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub fn graphviz_safe_def_name(def_id: DefId) -> String {
format!(
"{}_{}",
def_id.krate.index(),
def_id.index.as_array_index(),
def_id.index.index(),
)
}

Expand Down
2 changes: 1 addition & 1 deletion src/librustc_resolve/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ impl<'a> base::Resolver for Resolver<'a> {
fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
let def_id = DefId {
krate: CrateNum::BuiltinMacros,
index: DefIndex::from_array_index(self.macro_map.len()),
index: DefIndex::from(self.macro_map.len()),
};
let kind = ext.kind();
self.macro_map.insert(def_id, ext);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_save_analysis/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1170,7 +1170,7 @@ fn generated_code(span: Span) -> bool {
fn id_from_def_id(id: DefId) -> rls_data::Id {
rls_data::Id {
krate: id.krate.as_u32(),
index: id.index.as_raw_u32(),
index: id.index.as_u32(),
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ impl<'tcx> DocContext<'tcx> {
crate_num,
DefId {
krate: crate_num,
index: DefIndex::from_array_index(def_id.index.as_array_index() + 1),
index: DefIndex::from(def_id.index.index() + 1),
},
);

Expand Down