Remove DefId from CrateItem in favor of a lookup table

This commit is contained in:
Oli Scherer 2023-03-16 14:53:57 +00:00
parent 18e305dfca
commit 6fe982283d
3 changed files with 24 additions and 8 deletions

View File

@ -3,11 +3,28 @@
//! For that, we define APIs that will temporarily be public to 3P that exposes rustc internal APIs
//! until stable MIR is complete.
use std::sync::RwLock;
use crate::stable_mir;
pub use rustc_span::def_id::{CrateNum, DefId};
static DEF_ID_MAP: RwLock<Vec<DefId>> = RwLock::new(Vec::new());
pub fn item_def_id(item: &stable_mir::CrateItem) -> DefId {
item.0
DEF_ID_MAP.read().unwrap()[item.0]
}
pub fn crate_item(did: DefId) -> stable_mir::CrateItem {
// FIXME: this becomes inefficient when we have too many ids
let mut map = DEF_ID_MAP.write().unwrap();
for (i, &d) in map.iter().enumerate() {
if d == did {
return stable_mir::CrateItem(i);
}
}
let id = map.len();
map.push(did);
stable_mir::CrateItem(id)
}
pub fn crate_num(item: &stable_mir::Crate) -> CrateNum {

View File

@ -7,7 +7,10 @@
//!
//! For now, we are developing everything inside `rustc`, thus, we keep this module private.
use crate::stable_mir::{self};
use crate::{
rustc_internal::crate_item,
stable_mir::{self},
};
use rustc_middle::ty::{tls::with, TyCtxt};
use rustc_span::def_id::{CrateNum, LOCAL_CRATE};
use tracing::debug;
@ -34,9 +37,7 @@ pub fn find_crate(name: &str) -> Option<stable_mir::Crate> {
/// Retrieve all items of the local crate that have a MIR associated with them.
pub fn all_local_items() -> stable_mir::CrateItems {
with(|tcx| {
tcx.mir_keys(()).iter().map(|item| stable_mir::CrateItem(item.to_def_id())).collect()
})
with(|tcx| tcx.mir_keys(()).iter().map(|item| crate_item(item.to_def_id())).collect())
}
/// Build a stable mir crate from a given crate number.

View File

@ -11,8 +11,6 @@
//! There shouldn't be any direct references to internal compiler constructs in this module.
//! If you need an internal construct, consider using `rustc_internal` or `rustc_smir`.
use crate::rustc_internal;
/// Use String for now but we should replace it.
pub type Symbol = String;
@ -37,7 +35,7 @@ pub struct Crate {
/// For now, it only stores the item DefId. Use functions inside `rustc_internal` module to
/// use this item.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct CrateItem(pub(crate) rustc_internal::DefId);
pub struct CrateItem(pub(crate) DefId);
/// Access to the local crate.
pub fn local_crate() -> Crate {