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#![doc(
10    html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
11    test(attr(allow(unused_variables), deny(warnings)))
12)]
13//!
14//! This crate shall contain all type definitions and APIs that we expect third-party tools to invoke to
15//! interact with the compiler.
16//!
17//! The goal is to eventually be published on
18//! [crates.io](https://crates.io).
19
20use std::fmt::Debug;
21use std::{fmt, io};
22
23use serde::Serialize;
24
25use crate::compiler_interface::with;
26pub use crate::crate_def::{CrateDef, CrateDefType, DefId};
27pub use crate::error::*;
28use crate::mir::mono::StaticDef;
29use crate::mir::{Body, Mutability};
30use crate::ty::{FnDef, ForeignModuleDef, ImplDef, IndexedVal, Span, TraitDef, Ty};
31
32pub mod abi;
33#[macro_use]
34pub mod crate_def;
35pub mod compiler_interface;
36#[macro_use]
37pub mod error;
38pub mod mir;
39pub mod target;
40pub mod ty;
41pub mod visitor;
42
43/// Use String for now but we should replace it.
44pub type Symbol = String;
45
46/// The number that identifies a crate.
47pub type CrateNum = usize;
48
49impl Debug for DefId {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.debug_struct("DefId").field("id", &self.0).field("name", &self.name()).finish()
52    }
53}
54
55impl IndexedVal for DefId {
56    fn to_val(index: usize) -> Self {
57        DefId(index)
58    }
59
60    fn to_index(&self) -> usize {
61        self.0
62    }
63}
64
65/// A list of crate items.
66pub type CrateItems = Vec<CrateItem>;
67
68/// A list of trait decls.
69pub type TraitDecls = Vec<TraitDef>;
70
71/// A list of impl trait decls.
72pub type ImplTraitDecls = Vec<ImplDef>;
73
74/// Holds information about a crate.
75#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
76pub struct Crate {
77    pub id: CrateNum,
78    pub name: Symbol,
79    pub is_local: bool,
80}
81
82impl Crate {
83    /// The list of foreign modules in this crate.
84    pub fn foreign_modules(&self) -> Vec<ForeignModuleDef> {
85        with(|cx| cx.foreign_modules(self.id))
86    }
87
88    /// The list of traits declared in this crate.
89    pub fn trait_decls(&self) -> TraitDecls {
90        with(|cx| cx.trait_decls(self.id))
91    }
92
93    /// The list of trait implementations in this crate.
94    pub fn trait_impls(&self) -> ImplTraitDecls {
95        with(|cx| cx.trait_impls(self.id))
96    }
97
98    /// Return a list of function definitions from this crate independent on their visibility.
99    pub fn fn_defs(&self) -> Vec<FnDef> {
100        with(|cx| cx.crate_functions(self.id))
101    }
102
103    /// Return a list of static items defined in this crate independent on their visibility.
104    pub fn statics(&self) -> Vec<StaticDef> {
105        with(|cx| cx.crate_statics(self.id))
106    }
107}
108
109#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize)]
110pub enum ItemKind {
111    Fn,
112    Static,
113    Const,
114    Ctor(CtorKind),
115}
116
117#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize)]
118pub enum CtorKind {
119    Const,
120    Fn,
121}
122
123pub type Filename = String;
124
125crate_def_with_ty! {
126    /// Holds information about an item in a crate.
127    #[derive(Serialize)]
128    pub CrateItem;
129}
130
131impl CrateItem {
132    /// This will return the body of an item or panic if it's not available.
133    pub fn expect_body(&self) -> mir::Body {
134        with(|cx| cx.mir_body(self.0))
135    }
136
137    /// Return the body of an item if available.
138    pub fn body(&self) -> Option<mir::Body> {
139        with(|cx| cx.has_body(self.0).then(|| cx.mir_body(self.0)))
140    }
141
142    /// Check if a body is available for this item.
143    pub fn has_body(&self) -> bool {
144        with(|cx| cx.has_body(self.0))
145    }
146
147    pub fn span(&self) -> Span {
148        with(|cx| cx.span_of_an_item(self.0))
149    }
150
151    pub fn kind(&self) -> ItemKind {
152        with(|cx| cx.item_kind(*self))
153    }
154
155    pub fn requires_monomorphization(&self) -> bool {
156        with(|cx| cx.requires_monomorphization(self.0))
157    }
158
159    pub fn ty(&self) -> Ty {
160        with(|cx| cx.def_ty(self.0))
161    }
162
163    pub fn is_foreign_item(&self) -> bool {
164        with(|cx| cx.is_foreign_item(self.0))
165    }
166
167    /// Emit MIR for this item body.
168    pub fn emit_mir<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
169        self.body()
170            .ok_or_else(|| io::Error::other(format!("No body found for `{}`", self.name())))?
171            .dump(w, &self.name())
172    }
173}
174
175/// Return the function where execution starts if the current
176/// crate defines that. This is usually `main`, but could be
177/// `start` if the crate is a no-std crate.
178pub fn entry_fn() -> Option<CrateItem> {
179    with(|cx| cx.entry_fn())
180}
181
182/// Access to the local crate.
183pub fn local_crate() -> Crate {
184    with(|cx| cx.local_crate())
185}
186
187/// Try to find a crate or crates if multiple crates exist from given name.
188pub fn find_crates(name: &str) -> Vec<Crate> {
189    with(|cx| cx.find_crates(name))
190}
191
192/// Try to find a crate with the given name.
193pub fn external_crates() -> Vec<Crate> {
194    with(|cx| cx.external_crates())
195}
196
197/// Retrieve all items in the local crate that have a MIR associated with them.
198pub fn all_local_items() -> CrateItems {
199    with(|cx| cx.all_local_items())
200}
201
202pub fn all_trait_decls() -> TraitDecls {
203    with(|cx| cx.all_trait_decls())
204}
205
206pub fn all_trait_impls() -> ImplTraitDecls {
207    with(|cx| cx.all_trait_impls())
208}
209
210/// A type that provides internal information but that can still be used for debug purpose.
211#[derive(Clone, PartialEq, Eq, Hash, Serialize)]
212pub struct Opaque(String);
213
214impl std::fmt::Display for Opaque {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        write!(f, "{}", self.0)
217    }
218}
219
220impl std::fmt::Debug for Opaque {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        write!(f, "{}", self.0)
223    }
224}
225
226pub fn opaque<T: Debug>(value: &T) -> Opaque {
227    Opaque(format!("{value:?}"))
228}