Skip to content

Commit b66db7e

Browse files
committed
Create new rustc_smir struct to map future crates
+ Add some information to the README.md
1 parent 40185db commit b66db7e

File tree

9 files changed

+271
-27
lines changed

9 files changed

+271
-27
lines changed

Cargo.lock

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4654,15 +4654,9 @@ dependencies = [
46544654
name = "rustc_smir"
46554655
version = "0.0.0"
46564656
dependencies = [
4657-
"rustc_borrowck",
4658-
"rustc_driver",
4659-
"rustc_hir",
4660-
"rustc_interface",
46614657
"rustc_middle",
4662-
"rustc_mir_dataflow",
4663-
"rustc_mir_transform",
4664-
"rustc_serialize",
4665-
"rustc_trait_selection",
4658+
"rustc_span",
4659+
"tracing",
46664660
]
46674661

46684662
[[package]]

compiler/rustc_smir/Cargo.toml

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,12 @@ version = "0.0.0"
44
edition = "2021"
55

66
[dependencies]
7-
rustc_borrowck = { path = "../rustc_borrowck", optional = true }
8-
rustc_driver = { path = "../rustc_driver", optional = true }
9-
rustc_hir = { path = "../rustc_hir", optional = true }
10-
rustc_interface = { path = "../rustc_interface", optional = true }
117
rustc_middle = { path = "../rustc_middle", optional = true }
12-
rustc_mir_dataflow = { path = "../rustc_mir_dataflow", optional = true }
13-
rustc_mir_transform = { path = "../rustc_mir_transform", optional = true }
14-
rustc_serialize = { path = "../rustc_serialize", optional = true }
15-
rustc_trait_selection = { path = "../rustc_trait_selection", optional = true }
8+
rustc_span = { path = "../rustc_span", optional = true }
9+
tracing = "0.1"
1610

1711
[features]
1812
default = [
19-
"rustc_borrowck",
20-
"rustc_driver",
21-
"rustc_hir",
22-
"rustc_interface",
2313
"rustc_middle",
24-
"rustc_mir_dataflow",
25-
"rustc_mir_transform",
26-
"rustc_serialize",
27-
"rustc_trait_selection",
14+
"rustc_span",
2815
]

compiler/rustc_smir/README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,40 @@ git subtree pull --prefix=compiler/rustc_smir https://github.com/rust-lang/proje
7373
Note: only ever sync to rustc from the project-stable-mir's `smir` branch. Do not sync with your own forks.
7474

7575
Then open a PR against rustc just like a regular PR.
76+
77+
## Stable MIR Design
78+
79+
The stable-mir will follow a similar approach to proc-macro2. It’s
80+
implementation will eventually be broken down into two main crates:
81+
82+
- `stable_mir`: Public crate, to be published on crates.io, which will contain
83+
the stable data structure as well as proxy APIs to make calls to the
84+
compiler.
85+
- `rustc_smir`: The compiler crate that will translate from internal MIR to
86+
SMIR. This crate will also implement APIs that will be invoked by
87+
stable-mir to query the compiler for more information.
88+
89+
This will help tools to communicate with the rust compiler via stable APIs. Tools will depend on
90+
`stable_mir` crate, which will invoke the compiler using APIs defined in `rustc_smir`. I.e.:
91+
92+
```
93+
┌──────────────────────────────────┐ ┌──────────────────────────────────┐
94+
│ External Tool ┌──────────┐ │ │ ┌──────────┐ Rust Compiler │
95+
│ │ │ │ │ │ │ │
96+
│ │stable_mir| │ │ │rustc_smir│ │
97+
│ │ │ ├──────────►| │ │ │
98+
│ │ │ │◄──────────┤ │ │ │
99+
│ │ │ │ │ │ │ │
100+
│ │ │ │ │ │ │ │
101+
│ └──────────┘ │ │ └──────────┘ │
102+
└──────────────────────────────────┘ └──────────────────────────────────┘
103+
```
104+
105+
More details can be found here:
106+
https://hackmd.io/XhnYHKKuR6-LChhobvlT-g?view
107+
108+
For now, the code for these two crates are in separate modules of this crate.
109+
The modules have the same name for simplicity. We also have a third module,
110+
`rustc_internal` which will expose APIs and definitions that allow users to
111+
gather information from internal MIR constructs that haven't been exposed in
112+
the `stable_mir` module.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
[toolchain]
2-
channel = "nightly-2022-06-01"
2+
channel = "nightly-2023-02-28"
33
components = [ "rustfmt", "rustc-dev" ]

compiler/rustc_smir/src/lib.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,9 @@
1111
test(attr(allow(unused_variables), deny(warnings)))
1212
)]
1313
#![cfg_attr(not(feature = "default"), feature(rustc_private))]
14-
#![deny(rustc::untranslatable_diagnostic)]
15-
#![deny(rustc::diagnostic_outside_of_impl)]
14+
15+
pub mod rustc_internal;
16+
pub mod stable_mir;
17+
18+
// Make this module private for now since external users should not call these directly.
19+
mod rustc_smir;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
//! Module that implements the bridge between Stable MIR and internal compiler MIR.
2+
//!
3+
//! For that, we define APIs that will temporarily be public to 3P that exposes rustc internal APIs
4+
//! until stable MIR is complete.
5+
6+
use crate::stable_mir::CrateItem;
7+
8+
pub type DefId = rustc_span::def_id::DefId;
9+
10+
pub fn item_def_id(item: &CrateItem) -> DefId {
11+
item.0
12+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//! Module that implements what will become the rustc side of Stable MIR.
2+
//!
3+
//! This module is responsible for building Stable MIR components from internal components.
4+
//!
5+
//! This module is not intended to be invoked directly by users. It will eventually
6+
//! become the public API of rustc that will be invoked by the `stable_mir` crate.
7+
//!
8+
//! For now, we are developing everything inside `rustc`, thus, we keep this module private.
9+
10+
use crate::stable_mir::{self};
11+
use rustc_middle::ty::{tls::with, TyCtxt};
12+
use rustc_span::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13+
use tracing::debug;
14+
15+
/// Get information about the local crate.
16+
pub fn local_crate() -> stable_mir::Crate {
17+
with(|tcx| smir_crate(tcx, LOCAL_CRATE))
18+
}
19+
20+
/// Find a crate with the given name.
21+
pub fn find_crate(name: &str) -> Option<stable_mir::Crate> {
22+
with(|tcx| {
23+
[LOCAL_CRATE].iter().chain(tcx.crates(()).iter()).find_map(|crate_num| {
24+
let crate_name = tcx.crate_name(*crate_num).to_string();
25+
(name == crate_name).then(|| smir_crate(tcx, *crate_num))
26+
})
27+
})
28+
}
29+
30+
/// Build a stable mir crate from a given crate number.
31+
fn smir_crate(tcx: TyCtxt<'_>, crate_num: CrateNum) -> stable_mir::Crate {
32+
let crate_name = tcx.crate_name(crate_num).to_string();
33+
let is_local = crate_num == LOCAL_CRATE;
34+
let mod_id = DefId { index: CRATE_DEF_INDEX, krate: crate_num };
35+
let items = if is_local {
36+
tcx.hir_module_items(mod_id.expect_local())
37+
.items()
38+
.map(|item| {
39+
let def_id = item.owner_id.def_id.to_def_id();
40+
stable_mir::CrateItem(def_id)
41+
})
42+
.collect()
43+
} else {
44+
tcx.module_children(mod_id)
45+
.iter()
46+
.filter_map(|item| item.res.opt_def_id())
47+
.map(stable_mir::CrateItem)
48+
.collect::<Vec<_>>()
49+
};
50+
debug!(?crate_name, ?crate_num, "smir_crate");
51+
stable_mir::Crate { id: crate_num.into(), name: crate_name, is_local, root_items: items }
52+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//! Module that implements the public interface to the Stable MIR.
2+
//!
3+
//! This module shall contain all type definitions and APIs that we expect 3P tools to invoke to
4+
//! interact with the compiler.
5+
//!
6+
//! The goal is to eventually move this module to its own crate which shall be published on
7+
//! [crates.io](https://crates.io).
8+
//!
9+
//! ## Note:
10+
//!
11+
//! There shouldn't be any direct references to internal compiler constructs in this module.
12+
//! If you need an internal construct, consider using `rustc_internal` or `rustc_smir`.
13+
14+
use crate::rustc_internal;
15+
16+
/// Use String for now but we should replace it.
17+
pub type Symbol = String;
18+
19+
/// The number that identifies a crate.
20+
pub type CrateNum = usize;
21+
22+
/// A unique identification number for each item accessible for the current compilation unit.
23+
pub type DefId = usize;
24+
25+
/// A list of crate items.
26+
pub type CrateItems = Vec<CrateItem>;
27+
28+
/// Holds information about a crate.
29+
#[derive(Clone, PartialEq, Eq, Debug)]
30+
pub struct Crate {
31+
pub(crate) id: CrateNum,
32+
pub name: Symbol,
33+
pub is_local: bool,
34+
/// The items defined in the root of this crate.
35+
pub root_items: CrateItems,
36+
}
37+
38+
/// Holds information about an item in the crate.
39+
/// For now, it only stores the item DefId. Use functions inside `rustc_internal` module to
40+
/// use this item.
41+
#[derive(Clone, PartialEq, Eq, Debug)]
42+
pub struct CrateItem(pub(crate) rustc_internal::DefId);
43+
44+
/// Access to the local crate.
45+
pub fn local_crate() -> Crate {
46+
crate::rustc_smir::local_crate()
47+
}
48+
49+
/// Try to find a crate with the given name.
50+
pub fn find_crate(name: &str) -> Option<Crate> {
51+
crate::rustc_smir::find_crate(name)
52+
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// run-pass
2+
// Test that users are able to use stable mir APIs to retrieve information of the current crate
3+
4+
// ignore-stage-1
5+
// ignore-cross-compile
6+
// ignore-remote
7+
8+
#![feature(rustc_private)]
9+
10+
extern crate rustc_driver;
11+
extern crate rustc_hir;
12+
extern crate rustc_interface;
13+
extern crate rustc_middle;
14+
extern crate rustc_smir;
15+
16+
use rustc_driver::{Callbacks, Compilation, RunCompiler};
17+
use rustc_hir::def::DefKind;
18+
use rustc_interface::{interface, Queries};
19+
use rustc_middle::ty::TyCtxt;
20+
use rustc_smir::{rustc_internal, stable_mir};
21+
use std::io::Write;
22+
23+
const CRATE_NAME: &str = "input";
24+
25+
/// This function uses the Stable MIR APIs to get information about the test crate.
26+
fn test_stable_mir(tcx: TyCtxt<'_>) {
27+
// Get the local crate using stable_mir API.
28+
let local = stable_mir::local_crate();
29+
assert_eq!(&local.name, CRATE_NAME);
30+
31+
// Find items in the local crate.
32+
assert!(has_root_item(tcx, &local, (DefKind::Fn, "foo_bar")));
33+
assert!(has_root_item(tcx, &local, (DefKind::Mod, "foo")));
34+
assert!(!has_root_item(tcx, &local, (DefKind::Fn, "foo::bar")));
35+
36+
// Check that we can find items in the `std` crate.
37+
let std_crate = stable_mir::find_crate("std").unwrap();
38+
assert!(has_root_item(tcx, &std_crate, (DefKind::Mod, "std::any")));
39+
assert!(!has_root_item(tcx, &std_crate, (DefKind::Fn, "std::any::type_name")));
40+
}
41+
42+
// Use internal API to find a function in a crate.
43+
fn has_root_item(tcx: TyCtxt, krate: &stable_mir::Crate, item: (DefKind, &str)) -> bool {
44+
krate.root_items.iter().any(|crate_item| {
45+
let def_id = rustc_internal::item_def_id(crate_item);
46+
tcx.def_kind(def_id) == item.0 && tcx.def_path_str(def_id) == item.1
47+
})
48+
}
49+
50+
/// This test will generate and analyze a dummy crate using the stable mir.
51+
/// For that, it will first write the dummy crate into a file.
52+
/// It will invoke the compiler using a custom Callback implementation, which will
53+
/// invoke Stable MIR APIs after the compiler has finished its analysis.
54+
fn main() {
55+
let path = "input.rs";
56+
generate_input(&path).unwrap();
57+
let args = vec![
58+
"rustc".to_string(),
59+
"--crate-type=lib".to_string(),
60+
"--crate-name".to_string(),
61+
CRATE_NAME.to_string(),
62+
path.to_string(),
63+
];
64+
rustc_driver::catch_fatal_errors(|| {
65+
RunCompiler::new(&args, &mut SMirCalls {}).run().unwrap();
66+
})
67+
.unwrap();
68+
}
69+
70+
struct SMirCalls {}
71+
72+
impl Callbacks for SMirCalls {
73+
/// Called after analysis. Return value instructs the compiler whether to
74+
/// continue the compilation afterwards (defaults to `Compilation::Continue`)
75+
fn after_analysis<'tcx>(
76+
&mut self,
77+
_compiler: &interface::Compiler,
78+
queries: &'tcx Queries<'tcx>,
79+
) -> Compilation {
80+
queries.global_ctxt().unwrap().enter(|tcx| {
81+
test_stable_mir(tcx);
82+
});
83+
// No need to keep going.
84+
Compilation::Stop
85+
}
86+
}
87+
88+
fn generate_input(path: &str) -> std::io::Result<()> {
89+
let mut file = std::fs::File::create(path)?;
90+
write!(
91+
file,
92+
r#"
93+
mod foo {{
94+
pub fn bar(i: i32) -> i64 {{
95+
i as i64
96+
}}
97+
}}
98+
99+
pub fn foo_bar(x: i32, y: i32) -> i64 {{
100+
let x_64 = foo::bar(x);
101+
let y_64 = foo::bar(y);
102+
x_64.wrapping_add(y_64)
103+
}}"#
104+
)?;
105+
Ok(())
106+
}

0 commit comments

Comments
 (0)