Skip to content

Commit 326fea0

Browse files
committed
Change ty_with_args to return Ty instead of Result
Although, we would like to avoid crashes whenever possible, and that's why I wanted to make this API fallible. It's looking pretty hard to do proper validation. I think many of our APIs will unfortunately depend on the user doing the correct thing since at the MIR level we are working on, we expect types to have been checked already.
1 parent 1720b10 commit 326fea0

File tree

8 files changed

+148
-33
lines changed

8 files changed

+148
-33
lines changed

compiler/rustc_smir/src/rustc_smir/context.rs

+2-7
Original file line numberDiff line numberDiff line change
@@ -255,16 +255,11 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
255255
tables.tcx.type_of(item.internal(&mut *tables)).instantiate_identity().stable(&mut *tables)
256256
}
257257

258-
fn def_ty_with_args(
259-
&self,
260-
item: stable_mir::DefId,
261-
args: &GenericArgs,
262-
) -> Result<stable_mir::ty::Ty, Error> {
258+
fn def_ty_with_args(&self, item: stable_mir::DefId, args: &GenericArgs) -> stable_mir::ty::Ty {
263259
let mut tables = self.0.borrow_mut();
264260
let args = args.internal(&mut *tables);
265261
let def_ty = tables.tcx.type_of(item.internal(&mut *tables));
266-
// FIXME(celinval): use try_fold instead to avoid crashing.
267-
Ok(def_ty.instantiate(tables.tcx, args).stable(&mut *tables))
262+
def_ty.instantiate(tables.tcx, args).stable(&mut *tables)
268263
}
269264

270265
fn const_literal(&self, cnst: &stable_mir::ty::Const) -> String {

compiler/rustc_smir/src/rustc_smir/convert/mod.rs

-21
Original file line numberDiff line numberDiff line change
@@ -75,24 +75,3 @@ impl<'tcx> Stable<'tcx> for rustc_span::Span {
7575
tables.create_span(*self)
7676
}
7777
}
78-
79-
impl<'tcx, T> Stable<'tcx> for &[T]
80-
where
81-
T: Stable<'tcx>,
82-
{
83-
type T = Vec<T::T>;
84-
fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T {
85-
self.iter().map(|e| e.stable(tables)).collect()
86-
}
87-
}
88-
89-
impl<'tcx, T, U> Stable<'tcx> for (T, U)
90-
where
91-
T: Stable<'tcx>,
92-
U: Stable<'tcx>,
93-
{
94-
type T = (T::T, U::T);
95-
fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T {
96-
(self.0.stable(tables), self.1.stable(tables))
97-
}
98-
}

compiler/rustc_smir/src/rustc_smir/mod.rs

+21
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,24 @@ where
141141
}
142142
}
143143
}
144+
145+
impl<'tcx, T> Stable<'tcx> for &[T]
146+
where
147+
T: Stable<'tcx>,
148+
{
149+
type T = Vec<T::T>;
150+
fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T {
151+
self.iter().map(|e| e.stable(tables)).collect()
152+
}
153+
}
154+
155+
impl<'tcx, T, U> Stable<'tcx> for (T, U)
156+
where
157+
T: Stable<'tcx>,
158+
U: Stable<'tcx>,
159+
{
160+
type T = (T::T, U::T);
161+
fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T {
162+
(self.0.stable(tables), self.1.stable(tables))
163+
}
164+
}

compiler/stable_mir/src/compiler_interface.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ pub trait Context {
9191
fn def_ty(&self, item: DefId) -> Ty;
9292

9393
/// Returns the type of given definition instantiated with the given arguments.
94-
fn def_ty_with_args(&self, item: DefId, args: &GenericArgs) -> Result<Ty, Error>;
94+
fn def_ty_with_args(&self, item: DefId, args: &GenericArgs) -> Ty;
9595

9696
/// Returns literal value of a const as a string.
9797
fn const_literal(&self, cnst: &Const) -> String;

compiler/stable_mir/src/error.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ pub enum CompilerError<T> {
2828
}
2929

3030
/// A generic error to represent an API request that cannot be fulfilled.
31-
#[derive(Debug)]
31+
#[derive(Clone, Debug, Eq, PartialEq)]
3232
pub struct Error(pub(crate) String);
3333

3434
impl Error {

compiler/stable_mir/src/mir/visit.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ impl Location {
452452
}
453453

454454
/// Information about a place's usage.
455-
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
455+
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
456456
pub struct PlaceContext {
457457
/// Whether the access is mutable or not. Keep this private so we can increment the type in a
458458
/// backward compatible manner.

compiler/stable_mir/src/ty.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,9 @@ impl AdtDef {
382382
}
383383

384384
/// Retrieve the type of this Adt instantiating the type with the given arguments.
385-
pub fn ty_with_args(&self, args: &GenericArgs) -> Result<Ty, Error> {
385+
///
386+
/// This will assume the type can be instantiated with these arguments.
387+
pub fn ty_with_args(&self, args: &GenericArgs) -> Ty {
386388
with(|cx| cx.def_ty_with_args(self.0, args))
387389
}
388390

@@ -441,6 +443,7 @@ impl VariantDef {
441443
}
442444
}
443445

446+
#[derive(Clone, Debug, Eq, PartialEq)]
444447
pub struct FieldDef {
445448
/// The field definition.
446449
///
@@ -454,7 +457,9 @@ pub struct FieldDef {
454457

455458
impl FieldDef {
456459
/// Retrieve the type of this field instantiating the type with the given arguments.
457-
pub fn ty_with_args(&self, args: &GenericArgs) -> Result<Ty, Error> {
460+
///
461+
/// This will assume the type can be instantiated with these arguments.
462+
pub fn ty_with_args(&self, args: &GenericArgs) -> Ty {
458463
with(|cx| cx.def_ty_with_args(self.def, args))
459464
}
460465

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
// run-pass
2+
//! Test that users are able to use stable mir APIs to retrieve monomorphized types, and that
3+
//! we have an error handling for trying to instantiate types with incorrect arguments.
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+
extern crate rustc_middle;
16+
#[macro_use]
17+
extern crate rustc_smir;
18+
extern crate rustc_driver;
19+
extern crate rustc_interface;
20+
extern crate stable_mir;
21+
22+
use rustc_middle::ty::TyCtxt;
23+
use rustc_smir::rustc_internal;
24+
use stable_mir::ty::{RigidTy, TyKind, Ty, };
25+
use stable_mir::mir::{Body, MirVisitor, FieldIdx, Place, ProjectionElem, visit::{Location,
26+
PlaceContext}};
27+
use std::io::Write;
28+
use std::ops::ControlFlow;
29+
30+
const CRATE_NAME: &str = "input";
31+
32+
/// This function uses the Stable MIR APIs to get information about the test crate.
33+
fn test_stable_mir(_tcx: TyCtxt<'_>) -> ControlFlow<()> {
34+
let main_fn = stable_mir::entry_fn();
35+
let body = main_fn.unwrap().body();
36+
let mut visitor = PlaceVisitor{ body: &body, tested: false};
37+
visitor.visit_body(&body);
38+
assert!(visitor.tested);
39+
ControlFlow::Continue(())
40+
}
41+
42+
struct PlaceVisitor<'a> {
43+
body: &'a Body,
44+
/// Used to ensure that the test was reachable. Otherwise this test would vacuously succeed.
45+
tested: bool,
46+
}
47+
48+
/// Check that `wrapper.inner` place projection can be correctly interpreted.
49+
/// Ensure that instantiation is correct.
50+
fn check_tys(local_ty: Ty, idx: FieldIdx, expected_ty: Ty) {
51+
let TyKind::RigidTy(RigidTy::Adt(def, args)) = local_ty.kind() else { unreachable!() };
52+
assert_eq!(def.ty_with_args(&args), local_ty);
53+
54+
let field_def = &def.variants_iter().next().unwrap().fields()[idx];
55+
let field_ty = field_def.ty_with_args(&args);
56+
assert_eq!(field_ty, expected_ty);
57+
58+
// Check that the generic version is different than the instantiated one.
59+
let field_ty_gen = field_def.ty();
60+
assert_ne!(field_ty_gen, field_ty);
61+
}
62+
63+
impl<'a> MirVisitor for PlaceVisitor<'a> {
64+
fn visit_place(&mut self, place: &Place, _ptx: PlaceContext, _loc: Location) {
65+
let start_ty = self.body.locals()[place.local].ty;
66+
match place.projection.as_slice() {
67+
[ProjectionElem::Field(idx, ty)] => {
68+
check_tys(start_ty, *idx, *ty);
69+
self.tested = true;
70+
}
71+
_ => {}
72+
}
73+
}
74+
}
75+
76+
/// This test will generate and analyze a dummy crate using the stable mir.
77+
/// For that, it will first write the dummy crate into a file.
78+
/// Then it will create a `StableMir` using custom arguments and then
79+
/// it will run the compiler.
80+
fn main() {
81+
let path = "ty_fold_input.rs";
82+
generate_input(&path).unwrap();
83+
let args = vec![
84+
"rustc".to_string(),
85+
"-Cpanic=abort".to_string(),
86+
"--crate-name".to_string(),
87+
CRATE_NAME.to_string(),
88+
path.to_string(),
89+
];
90+
run!(args, tcx, test_stable_mir(tcx)).unwrap();
91+
}
92+
93+
fn generate_input(path: &str) -> std::io::Result<()> {
94+
let mut file = std::fs::File::create(path)?;
95+
write!(
96+
file,
97+
r#"
98+
struct Wrapper<T: Default> {{
99+
pub inner: T
100+
}}
101+
102+
impl<T: Default> Wrapper<T> {{
103+
pub fn new() -> Wrapper<T> {{
104+
Wrapper {{ inner: T::default() }}
105+
}}
106+
}}
107+
108+
fn main() {{
109+
let wrapper = Wrapper::<u8>::new();
110+
let _inner = wrapper.inner;
111+
}}
112+
"#
113+
)?;
114+
Ok(())
115+
}

0 commit comments

Comments
 (0)