Skip to content

Commit 8294352

Browse files
Rollup merge of #118215 - celinval:smir-def-paths, r=ouz-a
Add common trait for crate definitions In stable mir, we specialize DefId, however some functionality is the same for every definition, such as def paths, and getting their crate. Use a trait to implement those.
2 parents ffacd54 + b6e9772 commit 8294352

File tree

11 files changed

+307
-53
lines changed

11 files changed

+307
-53
lines changed

compiler/rustc_smir/src/rustc_internal/internal.rs

+10-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ use stable_mir::mir::alloc::AllocId;
1111
use stable_mir::mir::mono::{Instance, MonoItem, StaticDef};
1212
use stable_mir::ty::{
1313
AdtDef, Binder, BoundRegionKind, BoundTyKind, BoundVariableKind, ClosureKind, Const,
14-
ExistentialTraitRef, FloatTy, GenericArgKind, GenericArgs, IntTy, Region, RigidTy, TraitRef,
15-
Ty, UintTy,
14+
ExistentialTraitRef, FloatTy, GenericArgKind, GenericArgs, IntTy, Region, RigidTy, Span,
15+
TraitRef, Ty, UintTy,
1616
};
1717
use stable_mir::{CrateItem, DefId};
1818

@@ -279,6 +279,14 @@ impl<'tcx> RustcInternal<'tcx> for AdtDef {
279279
}
280280
}
281281

282+
impl<'tcx> RustcInternal<'tcx> for Span {
283+
type T = rustc_span::Span;
284+
285+
fn internal(&self, tables: &mut Tables<'tcx>) -> Self::T {
286+
tables[*self]
287+
}
288+
}
289+
282290
impl<'tcx, T> RustcInternal<'tcx> for &T
283291
where
284292
T: RustcInternal<'tcx>,

compiler/rustc_smir/src/rustc_smir/mod.rs

+32-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use rustc_hir::def::DefKind;
1414
use rustc_middle::mir;
1515
use rustc_middle::mir::interpret::{alloc_range, AllocId};
1616
use rustc_middle::mir::mono::MonoItem;
17+
use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
1718
use rustc_middle::ty::{self, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, Variance};
1819
use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE};
1920
use rustc_target::abi::FieldIdx;
@@ -28,7 +29,7 @@ use stable_mir::ty::{
2829
EarlyParamRegion, FloatTy, FnDef, GenericArgs, GenericParamDef, IntTy, LineInfo, Movability,
2930
RigidTy, Span, TyKind, UintTy,
3031
};
31-
use stable_mir::{self, opaque, Context, CrateItem, Error, Filename, ItemKind};
32+
use stable_mir::{self, opaque, Context, Crate, CrateItem, Error, Filename, ItemKind, Symbol};
3233
use std::cell::RefCell;
3334
use tracing::debug;
3435

@@ -61,9 +62,18 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
6162
crates
6263
}
6364

64-
fn name_of_def_id(&self, def_id: stable_mir::DefId) -> String {
65+
fn def_name(&self, def_id: stable_mir::DefId, trimmed: bool) -> Symbol {
6566
let tables = self.0.borrow();
66-
tables.tcx.def_path_str(tables[def_id])
67+
if trimmed {
68+
with_forced_trimmed_paths!(tables.tcx.def_path_str(tables[def_id]))
69+
} else {
70+
with_no_trimmed_paths!(tables.tcx.def_path_str(tables[def_id]))
71+
}
72+
}
73+
74+
fn krate(&self, def_id: stable_mir::DefId) -> Crate {
75+
let tables = self.0.borrow();
76+
smir_crate(tables.tcx, tables[def_id].krate)
6777
}
6878

6979
fn span_to_string(&self, span: stable_mir::ty::Span) -> String {
@@ -240,12 +250,29 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
240250
tables.create_def_id(def_id)
241251
}
242252

243-
fn instance_mangled_name(&self, def: InstanceDef) -> String {
253+
fn instance_mangled_name(&self, instance: InstanceDef) -> Symbol {
244254
let tables = self.0.borrow_mut();
245-
let instance = tables.instances[def];
255+
let instance = tables.instances[instance];
246256
tables.tcx.symbol_name(instance).name.to_string()
247257
}
248258

259+
/// Retrieve the instance name for diagnostic messages.
260+
///
261+
/// This will return the specialized name, e.g., `Vec<char>::new`.
262+
fn instance_name(&self, def: InstanceDef, trimmed: bool) -> Symbol {
263+
let tables = self.0.borrow_mut();
264+
let instance = tables.instances[def];
265+
if trimmed {
266+
with_forced_trimmed_paths!(
267+
tables.tcx.def_path_str_with_args(instance.def_id(), instance.args)
268+
)
269+
} else {
270+
with_no_trimmed_paths!(
271+
tables.tcx.def_path_str_with_args(instance.def_id(), instance.args)
272+
)
273+
}
274+
}
275+
249276
fn mono_instance(&self, item: stable_mir::CrateItem) -> stable_mir::mir::mono::Instance {
250277
let mut tables = self.0.borrow_mut();
251278
let def_id = tables[item.0];

compiler/stable_mir/src/crate_def.rs

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
//! Module that define a common trait for things that represent a crate definition,
2+
//! such as, a function, a trait, an enum, and any other definitions.
3+
4+
use crate::ty::Span;
5+
use crate::{with, Crate, Symbol};
6+
7+
/// A unique identification number for each item accessible for the current compilation unit.
8+
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
9+
pub struct DefId(pub(crate) usize);
10+
11+
/// A trait for retrieving information about a particular definition.
12+
///
13+
/// Implementors must provide the implementation of `def_id` which will be used to retrieve
14+
/// information about a crate's definition.
15+
pub trait CrateDef {
16+
/// Retrieve the unique identifier for the current definition.
17+
fn def_id(&self) -> DefId;
18+
19+
/// Return the fully qualified name of the current definition.
20+
fn name(&self) -> Symbol {
21+
let def_id = self.def_id();
22+
with(|cx| cx.def_name(def_id, false))
23+
}
24+
25+
/// Return a trimmed name of this definition.
26+
///
27+
/// This can be used to print more user friendly diagnostic messages.
28+
///
29+
/// If a symbol name can only be imported from one place for a type, and as
30+
/// long as it was not glob-imported anywhere in the current crate, we trim its
31+
/// path and print only the name.
32+
///
33+
/// For example, this function may shorten `std::vec::Vec` to just `Vec`,
34+
/// as long as there is no other `Vec` importable anywhere.
35+
fn trimmed_name(&self) -> Symbol {
36+
let def_id = self.def_id();
37+
with(|cx| cx.def_name(def_id, true))
38+
}
39+
40+
/// Return information about the crate where this definition is declared.
41+
///
42+
/// This will return the crate number and its name.
43+
fn krate(&self) -> Crate {
44+
let def_id = self.def_id();
45+
with(|cx| cx.krate(def_id))
46+
}
47+
48+
/// Return the span of this definition.
49+
fn span(&self) -> Span {
50+
let def_id = self.def_id();
51+
with(|cx| cx.span_of_an_item(def_id))
52+
}
53+
}
54+
55+
macro_rules! crate_def {
56+
( $(#[$attr:meta])*
57+
$vis:vis $name:ident $(;)?
58+
) => {
59+
$(#[$attr])*
60+
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
61+
$vis struct $name(pub DefId);
62+
63+
impl CrateDef for $name {
64+
fn def_id(&self) -> DefId {
65+
self.0
66+
}
67+
}
68+
};
69+
}

compiler/stable_mir/src/lib.rs

+13-14
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,16 @@ use self::ty::{
3131
#[macro_use]
3232
extern crate scoped_tls;
3333

34+
#[macro_use]
35+
pub mod crate_def;
3436
#[macro_use]
3537
pub mod error;
3638
pub mod mir;
3739
pub mod ty;
3840
pub mod visitor;
3941

42+
pub use crate::crate_def::CrateDef;
43+
pub use crate::crate_def::DefId;
4044
use crate::mir::alloc::{AllocId, GlobalAlloc};
4145
use crate::mir::pretty::function_name;
4246
use crate::mir::Mutability;
@@ -51,15 +55,11 @@ pub type Symbol = String;
5155
/// The number that identifies a crate.
5256
pub type CrateNum = usize;
5357

54-
/// A unique identification number for each item accessible for the current compilation unit.
55-
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
56-
pub struct DefId(usize);
57-
5858
impl Debug for DefId {
5959
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6060
f.debug_struct("DefId")
6161
.field("id", &self.0)
62-
.field("name", &with(|cx| cx.name_of_def_id(*self)))
62+
.field("name", &with(|cx| cx.def_name(*self, false)))
6363
.finish()
6464
}
6565
}
@@ -100,9 +100,10 @@ pub enum ItemKind {
100100

101101
pub type Filename = String;
102102

103-
/// Holds information about an item in the crate.
104-
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
105-
pub struct CrateItem(pub DefId);
103+
crate_def! {
104+
/// Holds information about an item in a crate.
105+
pub CrateItem;
106+
}
106107

107108
impl CrateItem {
108109
pub fn body(&self) -> mir::Body {
@@ -113,10 +114,6 @@ impl CrateItem {
113114
with(|cx| cx.span_of_an_item(self.0))
114115
}
115116

116-
pub fn name(&self) -> String {
117-
with(|cx| cx.name_of_def_id(self.0))
118-
}
119-
120117
pub fn kind(&self) -> ItemKind {
121118
with(|cx| cx.item_kind(*self))
122119
}
@@ -205,7 +202,7 @@ pub trait Context {
205202
fn find_crates(&self, name: &str) -> Vec<Crate>;
206203

207204
/// Returns the name of given `DefId`
208-
fn name_of_def_id(&self, def_id: DefId) -> String;
205+
fn def_name(&self, def_id: DefId, trimmed: bool) -> Symbol;
209206

210207
/// Returns printable, human readable form of `Span`
211208
fn span_to_string(&self, span: Span) -> String;
@@ -260,7 +257,7 @@ pub trait Context {
260257
fn instance_def_id(&self, instance: InstanceDef) -> DefId;
261258

262259
/// Get the instance mangled name.
263-
fn instance_mangled_name(&self, instance: InstanceDef) -> String;
260+
fn instance_mangled_name(&self, instance: InstanceDef) -> Symbol;
264261

265262
/// Convert a non-generic crate item into an instance.
266263
/// This function will panic if the item is generic.
@@ -294,6 +291,8 @@ pub trait Context {
294291

295292
/// Retrieve the id for the virtual table.
296293
fn vtable_allocation(&self, global_alloc: &GlobalAlloc) -> Option<AllocId>;
294+
fn krate(&self, def_id: DefId) -> Crate;
295+
fn instance_name(&self, def: InstanceDef, trimmed: bool) -> Symbol;
297296
}
298297

299298
// A thread local variable that stores a pointer to the tables mapping between TyCtxt

compiler/stable_mir/src/mir/mono.rs

+28-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
use crate::crate_def::CrateDef;
12
use crate::mir::Body;
23
use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, GenericArgs, IndexedVal, Ty};
3-
use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque};
4+
use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque, Symbol};
45
use std::fmt::{Debug, Formatter};
56

67
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -47,10 +48,29 @@ impl Instance {
4748
with(|context| context.instance_ty(self.def))
4849
}
4950

50-
pub fn mangled_name(&self) -> String {
51+
/// Retrieve the instance's mangled name used for calling the given instance.
52+
///
53+
/// This will also look up the correct name of instances from upstream crates.
54+
pub fn mangled_name(&self) -> Symbol {
5155
with(|context| context.instance_mangled_name(self.def))
5256
}
5357

58+
/// Retrieve the instance name for diagnostic messages.
59+
///
60+
/// This will return the specialized name, e.g., `std::vec::Vec<u8>::new`.
61+
pub fn name(&self) -> Symbol {
62+
with(|context| context.instance_name(self.def, false))
63+
}
64+
65+
/// Return a trimmed name of the given instance including its args.
66+
///
67+
/// If a symbol name can only be imported from one place for a type, and as
68+
/// long as it was not glob-imported anywhere in the current crate, we trim its
69+
/// path and print only the name.
70+
pub fn trimmed_name(&self) -> Symbol {
71+
with(|context| context.instance_name(self.def, true))
72+
}
73+
5474
/// Resolve an instance starting from a function definition and generic arguments.
5575
pub fn resolve(def: FnDef, args: &GenericArgs) -> Result<Instance, crate::Error> {
5676
with(|context| {
@@ -104,6 +124,8 @@ impl TryFrom<CrateItem> for Instance {
104124

105125
fn try_from(item: CrateItem) -> Result<Self, Self::Error> {
106126
with(|context| {
127+
// FIXME(celinval):
128+
// - Return `Err` if instance does not have a body.
107129
if !context.requires_monomorphization(item.0) {
108130
Ok(context.mono_instance(item))
109131
} else {
@@ -148,8 +170,10 @@ impl From<StaticDef> for CrateItem {
148170
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
149171
pub struct InstanceDef(usize);
150172

151-
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
152-
pub struct StaticDef(pub DefId);
173+
crate_def! {
174+
/// Holds information about a static variable definition.
175+
pub StaticDef;
176+
}
153177

154178
impl TryFrom<CrateItem> for StaticDef {
155179
type Error = crate::Error;

compiler/stable_mir/src/mir/pretty.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::crate_def::CrateDef;
12
use crate::mir::{Operand, Rvalue, StatementKind};
23
use crate::ty::{DynKind, FloatTy, IntTy, RigidTy, TyKind, UintTy};
34
use crate::{with, Body, CrateItem, Mutability};

0 commit comments

Comments
 (0)