stable_mir/
lib.rs

1//! The WIP stable interface to rustc internals.
2//!
3//! For more information see <https://github.com/rust-lang/project-stable-mir>
4//!
5//! # Note
6//!
7//! This API is still completely unstable and subject to change.
8
9#![allow(rustc::usage_of_ty_tykind)]
10#![doc(
11    html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
12    test(attr(allow(unused_variables), deny(warnings)))
13)]
14#![feature(sized_hierarchy)]
15//!
16//! This crate shall contain all type definitions and APIs that we expect third-party tools to invoke to
17//! interact with the compiler.
18//!
19//! The goal is to eventually be published on
20//! [crates.io](https://crates.io).
21
22use std::fmt::Debug;
23use std::{fmt, io};
24
25pub(crate) use rustc_smir::IndexedVal;
26use rustc_smir::Tables;
27use rustc_smir::context::SmirCtxt;
28/// Export the rustc_internal APIs. Note that this module has no stability
29/// guarantees and it is not taken into account for semver.
30#[cfg(feature = "rustc_internal")]
31pub mod rustc_internal;
32use serde::Serialize;
33
34use crate::compiler_interface::with;
35pub use crate::crate_def::{CrateDef, CrateDefItems, CrateDefType, DefId};
36pub use crate::error::*;
37use crate::mir::mono::StaticDef;
38use crate::mir::{Body, Mutability};
39use crate::ty::{AssocItem, FnDef, ForeignModuleDef, ImplDef, ProvenanceMap, Span, TraitDef, Ty};
40use crate::unstable::Stable;
41
42pub mod abi;
43mod alloc;
44pub(crate) mod unstable;
45#[macro_use]
46pub mod crate_def;
47pub mod compiler_interface;
48#[macro_use]
49pub mod error;
50pub mod mir;
51pub mod target;
52pub mod ty;
53pub mod visitor;
54
55/// Use String for now but we should replace it.
56pub type Symbol = String;
57
58/// The number that identifies a crate.
59pub type CrateNum = usize;
60
61impl Debug for DefId {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.debug_struct("DefId").field("id", &self.0).field("name", &self.name()).finish()
64    }
65}
66
67impl IndexedVal for DefId {
68    fn to_val(index: usize) -> Self {
69        DefId(index)
70    }
71
72    fn to_index(&self) -> usize {
73        self.0
74    }
75}
76
77/// A list of crate items.
78pub type CrateItems = Vec<CrateItem>;
79
80/// A list of trait decls.
81pub type TraitDecls = Vec<TraitDef>;
82
83/// A list of impl trait decls.
84pub type ImplTraitDecls = Vec<ImplDef>;
85
86/// A list of associated items.
87pub type AssocItems = Vec<AssocItem>;
88
89/// Holds information about a crate.
90#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
91pub struct Crate {
92    pub id: CrateNum,
93    pub name: Symbol,
94    pub is_local: bool,
95}
96
97impl Crate {
98    /// The list of foreign modules in this crate.
99    pub fn foreign_modules(&self) -> Vec<ForeignModuleDef> {
100        with(|cx| cx.foreign_modules(self.id))
101    }
102
103    /// The list of traits declared in this crate.
104    pub fn trait_decls(&self) -> TraitDecls {
105        with(|cx| cx.trait_decls(self.id))
106    }
107
108    /// The list of trait implementations in this crate.
109    pub fn trait_impls(&self) -> ImplTraitDecls {
110        with(|cx| cx.trait_impls(self.id))
111    }
112
113    /// Return a list of function definitions from this crate independent on their visibility.
114    pub fn fn_defs(&self) -> Vec<FnDef> {
115        with(|cx| cx.crate_functions(self.id))
116    }
117
118    /// Return a list of static items defined in this crate independent on their visibility.
119    pub fn statics(&self) -> Vec<StaticDef> {
120        with(|cx| cx.crate_statics(self.id))
121    }
122}
123
124#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize)]
125pub enum ItemKind {
126    Fn,
127    Static,
128    Const,
129    Ctor(CtorKind),
130}
131
132#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize)]
133pub enum CtorKind {
134    Const,
135    Fn,
136}
137
138pub type Filename = String;
139
140crate_def_with_ty! {
141    /// Holds information about an item in a crate.
142    #[derive(Serialize)]
143    pub CrateItem;
144}
145
146impl CrateItem {
147    /// This will return the body of an item or panic if it's not available.
148    pub fn expect_body(&self) -> mir::Body {
149        with(|cx| cx.mir_body(self.0))
150    }
151
152    /// Return the body of an item if available.
153    pub fn body(&self) -> Option<mir::Body> {
154        with(|cx| cx.has_body(self.0).then(|| cx.mir_body(self.0)))
155    }
156
157    /// Check if a body is available for this item.
158    pub fn has_body(&self) -> bool {
159        with(|cx| cx.has_body(self.0))
160    }
161
162    pub fn span(&self) -> Span {
163        with(|cx| cx.span_of_an_item(self.0))
164    }
165
166    pub fn kind(&self) -> ItemKind {
167        with(|cx| cx.item_kind(*self))
168    }
169
170    pub fn requires_monomorphization(&self) -> bool {
171        with(|cx| cx.requires_monomorphization(self.0))
172    }
173
174    pub fn ty(&self) -> Ty {
175        with(|cx| cx.def_ty(self.0))
176    }
177
178    pub fn is_foreign_item(&self) -> bool {
179        with(|cx| cx.is_foreign_item(self.0))
180    }
181
182    /// Emit MIR for this item body.
183    pub fn emit_mir<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
184        self.body()
185            .ok_or_else(|| io::Error::other(format!("No body found for `{}`", self.name())))?
186            .dump(w, &self.name())
187    }
188}
189
190/// Return the function where execution starts if the current
191/// crate defines that. This is usually `main`, but could be
192/// `start` if the crate is a no-std crate.
193pub fn entry_fn() -> Option<CrateItem> {
194    with(|cx| cx.entry_fn())
195}
196
197/// Access to the local crate.
198pub fn local_crate() -> Crate {
199    with(|cx| cx.local_crate())
200}
201
202/// Try to find a crate or crates if multiple crates exist from given name.
203pub fn find_crates(name: &str) -> Vec<Crate> {
204    with(|cx| cx.find_crates(name))
205}
206
207/// Try to find a crate with the given name.
208pub fn external_crates() -> Vec<Crate> {
209    with(|cx| cx.external_crates())
210}
211
212/// Retrieve all items in the local crate that have a MIR associated with them.
213pub fn all_local_items() -> CrateItems {
214    with(|cx| cx.all_local_items())
215}
216
217pub fn all_trait_decls() -> TraitDecls {
218    with(|cx| cx.all_trait_decls())
219}
220
221pub fn all_trait_impls() -> ImplTraitDecls {
222    with(|cx| cx.all_trait_impls())
223}
224
225/// A type that provides internal information but that can still be used for debug purpose.
226#[derive(Clone, PartialEq, Eq, Hash, Serialize)]
227pub struct Opaque(String);
228
229impl std::fmt::Display for Opaque {
230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        write!(f, "{}", self.0)
232    }
233}
234
235impl std::fmt::Debug for Opaque {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        write!(f, "{}", self.0)
238    }
239}
240
241pub fn opaque<T: Debug>(value: &T) -> Opaque {
242    Opaque(format!("{value:?}"))
243}
244
245macro_rules! bridge_impl {
246    ($name: ident, $ty: ty) => {
247        impl rustc_smir::bridge::$name<compiler_interface::BridgeTys> for $ty {
248            fn new(def: crate::DefId) -> Self {
249                Self(def)
250            }
251        }
252    };
253}
254
255bridge_impl!(CrateItem, crate::CrateItem);
256bridge_impl!(AdtDef, crate::ty::AdtDef);
257bridge_impl!(ForeignModuleDef, crate::ty::ForeignModuleDef);
258bridge_impl!(ForeignDef, crate::ty::ForeignDef);
259bridge_impl!(FnDef, crate::ty::FnDef);
260bridge_impl!(ClosureDef, crate::ty::ClosureDef);
261bridge_impl!(CoroutineDef, crate::ty::CoroutineDef);
262bridge_impl!(CoroutineClosureDef, crate::ty::CoroutineClosureDef);
263bridge_impl!(AliasDef, crate::ty::AliasDef);
264bridge_impl!(ParamDef, crate::ty::ParamDef);
265bridge_impl!(BrNamedDef, crate::ty::BrNamedDef);
266bridge_impl!(TraitDef, crate::ty::TraitDef);
267bridge_impl!(GenericDef, crate::ty::GenericDef);
268bridge_impl!(ConstDef, crate::ty::ConstDef);
269bridge_impl!(ImplDef, crate::ty::ImplDef);
270bridge_impl!(RegionDef, crate::ty::RegionDef);
271bridge_impl!(CoroutineWitnessDef, crate::ty::CoroutineWitnessDef);
272bridge_impl!(AssocDef, crate::ty::AssocDef);
273bridge_impl!(OpaqueDef, crate::ty::OpaqueDef);
274bridge_impl!(StaticDef, crate::mir::mono::StaticDef);
275
276impl rustc_smir::bridge::Prov<compiler_interface::BridgeTys> for crate::ty::Prov {
277    fn new(aid: crate::mir::alloc::AllocId) -> Self {
278        Self(aid)
279    }
280}
281
282impl rustc_smir::bridge::Allocation<compiler_interface::BridgeTys> for crate::ty::Allocation {
283    fn new<'tcx>(
284        bytes: Vec<Option<u8>>,
285        ptrs: Vec<(usize, rustc_middle::mir::interpret::AllocId)>,
286        align: u64,
287        mutability: rustc_middle::mir::Mutability,
288        tables: &mut Tables<'tcx, compiler_interface::BridgeTys>,
289        cx: &SmirCtxt<'tcx, compiler_interface::BridgeTys>,
290    ) -> Self {
291        Self {
292            bytes,
293            provenance: ProvenanceMap {
294                ptrs: ptrs.iter().map(|(i, aid)| (*i, tables.prov(*aid))).collect(),
295            },
296            align,
297            mutability: mutability.stable(tables, cx),
298        }
299    }
300}