Skip to content

Commit 30f9973

Browse files
authored
Unrolled build for rust-lang#126366
Rollup merge of rust-lang#126366 - celinval:issue-0080-def-ty, r=oli-obk Add a new trait to retrieve StableMir definition Ty We implement the trait only for definitions that should have a type. It's possible that I missed a few definitions, but we can add them later if needed. Fixes rust-lang/project-stable-mir#80
2 parents 921645c + 6d4a825 commit 30f9973

File tree

4 files changed

+177
-10
lines changed

4 files changed

+177
-10
lines changed

compiler/stable_mir/src/crate_def.rs

+36-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Module that define a common trait for things that represent a crate definition,
22
//! such as, a function, a trait, an enum, and any other definitions.
33
4-
use crate::ty::Span;
4+
use crate::ty::{GenericArgs, Span, Ty};
55
use crate::{with, Crate, Symbol};
66

77
/// A unique identification number for each item accessible for the current compilation unit.
@@ -52,6 +52,23 @@ pub trait CrateDef {
5252
}
5353
}
5454

55+
/// A trait that can be used to retrieve a definition's type.
56+
///
57+
/// Note that not every CrateDef has a type `Ty`. They should not implement this trait.
58+
pub trait CrateDefType: CrateDef {
59+
/// Returns the type of this crate item.
60+
fn ty(&self) -> Ty {
61+
with(|cx| cx.def_ty(self.def_id()))
62+
}
63+
64+
/// Retrieve the type of this definition by instantiating and normalizing it with `args`.
65+
///
66+
/// This will panic if instantiation fails.
67+
fn ty_with_args(&self, args: &GenericArgs) -> Ty {
68+
with(|cx| cx.def_ty_with_args(self.def_id(), args))
69+
}
70+
}
71+
5572
macro_rules! crate_def {
5673
( $(#[$attr:meta])*
5774
$vis:vis $name:ident $(;)?
@@ -67,3 +84,21 @@ macro_rules! crate_def {
6784
}
6885
};
6986
}
87+
88+
macro_rules! crate_def_with_ty {
89+
( $(#[$attr:meta])*
90+
$vis:vis $name:ident $(;)?
91+
) => {
92+
$(#[$attr])*
93+
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
94+
$vis struct $name(pub DefId);
95+
96+
impl CrateDef for $name {
97+
fn def_id(&self) -> DefId {
98+
self.0
99+
}
100+
}
101+
102+
impl CrateDefType for $name {}
103+
};
104+
}

compiler/stable_mir/src/lib.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,7 @@ use std::fmt::Debug;
2222
use std::io;
2323

2424
use crate::compiler_interface::with;
25-
pub use crate::crate_def::CrateDef;
26-
pub use crate::crate_def::DefId;
25+
pub use crate::crate_def::{CrateDef, CrateDefType, DefId};
2726
pub use crate::error::*;
2827
use crate::mir::Body;
2928
use crate::mir::Mutability;
@@ -115,12 +114,15 @@ pub enum CtorKind {
115114

116115
pub type Filename = String;
117116

118-
crate_def! {
117+
crate_def_with_ty! {
119118
/// Holds information about an item in a crate.
120119
pub CrateItem;
121120
}
122121

123122
impl CrateItem {
123+
/// This will return the body of an item.
124+
///
125+
/// This will panic if no body is available.
124126
pub fn body(&self) -> mir::Body {
125127
with(|cx| cx.mir_body(self.0))
126128
}

compiler/stable_mir/src/ty.rs

+22-6
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ use super::{
33
with, DefId, Error, Symbol,
44
};
55
use crate::abi::Layout;
6+
use crate::crate_def::{CrateDef, CrateDefType};
67
use crate::mir::alloc::{read_target_int, read_target_uint, AllocId};
8+
use crate::mir::mono::StaticDef;
79
use crate::target::MachineInfo;
8-
use crate::{crate_def::CrateDef, mir::mono::StaticDef};
910
use crate::{Filename, Opaque};
1011
use std::fmt::{self, Debug, Display, Formatter};
1112
use std::ops::Range;
@@ -504,6 +505,15 @@ impl TyKind {
504505
pub fn discriminant_ty(&self) -> Option<Ty> {
505506
self.rigid().map(|ty| with(|cx| cx.rigid_ty_discriminant_ty(ty)))
506507
}
508+
509+
/// Deconstruct a function type if this is one.
510+
pub fn fn_def(&self) -> Option<(FnDef, &GenericArgs)> {
511+
if let TyKind::RigidTy(RigidTy::FnDef(def, args)) = self {
512+
Some((*def, args))
513+
} else {
514+
None
515+
}
516+
}
507517
}
508518

509519
pub struct TypeAndMut {
@@ -629,7 +639,7 @@ impl ForeignModule {
629639
}
630640
}
631641

632-
crate_def! {
642+
crate_def_with_ty! {
633643
/// Hold information about a ForeignItem in a crate.
634644
pub ForeignDef;
635645
}
@@ -647,7 +657,7 @@ pub enum ForeignItemKind {
647657
Type(Ty),
648658
}
649659

650-
crate_def! {
660+
crate_def_with_ty! {
651661
/// Hold information about a function definition in a crate.
652662
pub FnDef;
653663
}
@@ -668,9 +678,15 @@ impl FnDef {
668678
pub fn is_intrinsic(&self) -> bool {
669679
self.as_intrinsic().is_some()
670680
}
681+
682+
/// Get the function signature for this function definition.
683+
pub fn fn_sig(&self) -> PolyFnSig {
684+
let kind = self.ty().kind();
685+
kind.fn_sig().unwrap()
686+
}
671687
}
672688

673-
crate_def! {
689+
crate_def_with_ty! {
674690
pub IntrinsicDef;
675691
}
676692

@@ -710,7 +726,7 @@ crate_def! {
710726
pub BrNamedDef;
711727
}
712728

713-
crate_def! {
729+
crate_def_with_ty! {
714730
pub AdtDef;
715731
}
716732

@@ -866,7 +882,7 @@ crate_def! {
866882
pub GenericDef;
867883
}
868884

869-
crate_def! {
885+
crate_def_with_ty! {
870886
pub ConstDef;
871887
}
872888

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
//@ run-pass
2+
//! Test that users are able to use stable mir APIs to retrieve type information from a crate item
3+
//! definition.
4+
5+
//@ ignore-stage1
6+
//@ ignore-cross-compile
7+
//@ ignore-remote
8+
//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837
9+
//@ edition: 2021
10+
11+
#![feature(rustc_private)]
12+
#![feature(assert_matches)]
13+
#![feature(control_flow_enum)]
14+
15+
#[macro_use]
16+
extern crate rustc_smir;
17+
extern crate rustc_driver;
18+
extern crate rustc_interface;
19+
extern crate stable_mir;
20+
21+
use rustc_smir::rustc_internal;
22+
use stable_mir::ty::{Ty, ForeignItemKind};
23+
use stable_mir::*;
24+
use std::io::Write;
25+
use std::ops::ControlFlow;
26+
27+
const CRATE_NAME: &str = "crate_def_ty";
28+
29+
/// Test if we can retrieve type information from different definitions.
30+
fn test_def_tys() -> ControlFlow<()> {
31+
let items = stable_mir::all_local_items();
32+
for item in &items {
33+
// Type from crate items.
34+
let ty = item.ty();
35+
match item.name().as_str() {
36+
"STATIC_STR" => assert!(ty.kind().is_ref()),
37+
"CONST_U32" => assert!(ty.kind().is_integral()),
38+
"main" => { check_fn_def(ty) }
39+
_ => unreachable!("Unexpected item: `{item:?}`")
40+
}
41+
}
42+
43+
let foreign_items = stable_mir::local_crate().foreign_modules();
44+
for item in foreign_items[0].module().items() {
45+
// Type from foreign items.
46+
let ty = item.ty();
47+
let item_kind = item.kind();
48+
let name = item.name();
49+
match item_kind {
50+
ForeignItemKind::Fn(fn_def) => {
51+
assert_eq!(&name, "extern_fn");
52+
assert_eq!(ty, fn_def.ty());
53+
check_fn_def(ty)
54+
}
55+
ForeignItemKind::Static(def) => {
56+
assert_eq!(&name, "EXT_STATIC");
57+
assert_eq!(ty, def.ty());
58+
assert!(ty.kind().is_integral())
59+
}
60+
_ => unreachable!("Unexpected kind: {item_kind:?}")
61+
};
62+
}
63+
64+
ControlFlow::Continue(())
65+
}
66+
67+
fn check_fn_def(ty: Ty) {
68+
let kind = ty.kind();
69+
let (def, args) = kind.fn_def().expect(&format!("Expected function type, but found: {ty}"));
70+
assert!(def.ty().kind().is_fn());
71+
assert_eq!(def.ty_with_args(args), ty);
72+
}
73+
74+
/// This test will generate and analyze a dummy crate using the stable mir.
75+
/// For that, it will first write the dummy crate into a file.
76+
/// Then it will create a `StableMir` using custom arguments and then
77+
/// it will run the compiler.
78+
fn main() {
79+
let path = "defs_ty_input.rs";
80+
generate_input(&path).unwrap();
81+
let args = vec![
82+
"rustc".to_string(),
83+
"-Cpanic=abort".to_string(),
84+
"--crate-name".to_string(),
85+
CRATE_NAME.to_string(),
86+
path.to_string(),
87+
];
88+
run!(args, test_def_tys).unwrap();
89+
}
90+
91+
fn generate_input(path: &str) -> std::io::Result<()> {
92+
let mut file = std::fs::File::create(path)?;
93+
write!(
94+
file,
95+
r#"
96+
// We would like to check intrinsic definition.
97+
#![feature(core_intrinsics)]
98+
static STATIC_STR: &str = "foo";
99+
const CONST_U32: u32 = 0u32;
100+
101+
fn main() {{
102+
let _c = core::char::from_u32(99);
103+
let _v = Vec::<u8>::new();
104+
let _i = std::intrinsics::size_of::<u8>();
105+
}}
106+
107+
extern "C" {{
108+
fn extern_fn(x: i32) -> i32;
109+
static EXT_STATIC: i32;
110+
}}
111+
"#
112+
)?;
113+
Ok(())
114+
}

0 commit comments

Comments
 (0)