stable_mir/
compiler_interface.rs

1//! Define the interface with the Rust compiler.
2//!
3//! StableMIR users should not use any of the items in this module directly.
4//! These APIs have no stability guarantee.
5
6use std::cell::Cell;
7
8use crate::abi::{FnAbi, Layout, LayoutShape};
9use crate::crate_def::Attribute;
10use crate::mir::alloc::{AllocId, GlobalAlloc};
11use crate::mir::mono::{Instance, InstanceDef, StaticDef};
12use crate::mir::{BinOp, Body, Place, UnOp};
13use crate::target::MachineInfo;
14use crate::ty::{
15    AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, FieldDef, FnDef, ForeignDef,
16    ForeignItemKind, ForeignModule, ForeignModuleDef, GenericArgs, GenericPredicates, Generics,
17    ImplDef, ImplTrait, IntrinsicDef, LineInfo, MirConst, PolyFnSig, RigidTy, Span, TraitDecl,
18    TraitDef, Ty, TyConst, TyConstId, TyKind, UintTy, VariantDef,
19};
20use crate::{
21    Crate, CrateItem, CrateItems, CrateNum, DefId, Error, Filename, ImplTraitDecls, ItemKind,
22    Symbol, TraitDecls, mir,
23};
24
25/// This trait defines the interface between stable_mir and the Rust compiler.
26/// Do not use this directly.
27pub trait Context {
28    fn entry_fn(&self) -> Option<CrateItem>;
29    /// Retrieve all items of the local crate that have a MIR associated with them.
30    fn all_local_items(&self) -> CrateItems;
31    /// Retrieve the body of a function.
32    /// This function will panic if the body is not available.
33    fn mir_body(&self, item: DefId) -> mir::Body;
34    /// Check whether the body of a function is available.
35    fn has_body(&self, item: DefId) -> bool;
36    fn foreign_modules(&self, crate_num: CrateNum) -> Vec<ForeignModuleDef>;
37
38    /// Retrieve all functions defined in this crate.
39    fn crate_functions(&self, crate_num: CrateNum) -> Vec<FnDef>;
40
41    /// Retrieve all static items defined in this crate.
42    fn crate_statics(&self, crate_num: CrateNum) -> Vec<StaticDef>;
43    fn foreign_module(&self, mod_def: ForeignModuleDef) -> ForeignModule;
44    fn foreign_items(&self, mod_def: ForeignModuleDef) -> Vec<ForeignDef>;
45    fn all_trait_decls(&self) -> TraitDecls;
46    fn trait_decls(&self, crate_num: CrateNum) -> TraitDecls;
47    fn trait_decl(&self, trait_def: &TraitDef) -> TraitDecl;
48    fn all_trait_impls(&self) -> ImplTraitDecls;
49    fn trait_impls(&self, crate_num: CrateNum) -> ImplTraitDecls;
50    fn trait_impl(&self, trait_impl: &ImplDef) -> ImplTrait;
51    fn generics_of(&self, def_id: DefId) -> Generics;
52    fn predicates_of(&self, def_id: DefId) -> GenericPredicates;
53    fn explicit_predicates_of(&self, def_id: DefId) -> GenericPredicates;
54    /// Get information about the local crate.
55    fn local_crate(&self) -> Crate;
56    /// Retrieve a list of all external crates.
57    fn external_crates(&self) -> Vec<Crate>;
58
59    /// Find a crate with the given name.
60    fn find_crates(&self, name: &str) -> Vec<Crate>;
61
62    /// Returns the name of given `DefId`
63    fn def_name(&self, def_id: DefId, trimmed: bool) -> Symbol;
64
65    /// Return registered tool attributes with the given attribute name.
66    ///
67    /// FIXME(jdonszelmann): may panic on non-tool attributes. After more attribute work, non-tool
68    /// attributes will simply return an empty list.
69    ///
70    /// Single segmented name like `#[clippy]` is specified as `&["clippy".to_string()]`.
71    /// Multi-segmented name like `#[rustfmt::skip]` is specified as `&["rustfmt".to_string(), "skip".to_string()]`.
72    fn tool_attrs(&self, def_id: DefId, attr: &[Symbol]) -> Vec<Attribute>;
73
74    /// Get all tool attributes of a definition.
75    fn all_tool_attrs(&self, def_id: DefId) -> Vec<Attribute>;
76
77    /// Returns printable, human readable form of `Span`
78    fn span_to_string(&self, span: Span) -> String;
79
80    /// Return filename from given `Span`, for diagnostic purposes
81    fn get_filename(&self, span: &Span) -> Filename;
82
83    /// Return lines corresponding to this `Span`
84    fn get_lines(&self, span: &Span) -> LineInfo;
85
86    /// Returns the `kind` of given `DefId`
87    fn item_kind(&self, item: CrateItem) -> ItemKind;
88
89    /// Returns whether this is a foreign item.
90    fn is_foreign_item(&self, item: DefId) -> bool;
91
92    /// Returns the kind of a given foreign item.
93    fn foreign_item_kind(&self, def: ForeignDef) -> ForeignItemKind;
94
95    /// Returns the kind of a given algebraic data type
96    fn adt_kind(&self, def: AdtDef) -> AdtKind;
97
98    /// Returns if the ADT is a box.
99    fn adt_is_box(&self, def: AdtDef) -> bool;
100
101    /// Returns whether this ADT is simd.
102    fn adt_is_simd(&self, def: AdtDef) -> bool;
103
104    /// Returns whether this definition is a C string.
105    fn adt_is_cstr(&self, def: AdtDef) -> bool;
106
107    /// Retrieve the function signature for the given generic arguments.
108    fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig;
109
110    /// Retrieve the intrinsic definition if the item corresponds one.
111    fn intrinsic(&self, item: DefId) -> Option<IntrinsicDef>;
112
113    /// Retrieve the plain function name of an intrinsic.
114    fn intrinsic_name(&self, def: IntrinsicDef) -> Symbol;
115
116    /// Retrieve the closure signature for the given generic arguments.
117    fn closure_sig(&self, args: &GenericArgs) -> PolyFnSig;
118
119    /// The number of variants in this ADT.
120    fn adt_variants_len(&self, def: AdtDef) -> usize;
121
122    /// The name of a variant.
123    fn variant_name(&self, def: VariantDef) -> Symbol;
124    fn variant_fields(&self, def: VariantDef) -> Vec<FieldDef>;
125
126    /// Evaluate constant as a target usize.
127    fn eval_target_usize(&self, cnst: &MirConst) -> Result<u64, Error>;
128    fn eval_target_usize_ty(&self, cnst: &TyConst) -> Result<u64, Error>;
129
130    /// Create a new zero-sized constant.
131    fn try_new_const_zst(&self, ty: Ty) -> Result<MirConst, Error>;
132
133    /// Create a new constant that represents the given string value.
134    fn new_const_str(&self, value: &str) -> MirConst;
135
136    /// Create a new constant that represents the given boolean value.
137    fn new_const_bool(&self, value: bool) -> MirConst;
138
139    /// Create a new constant that represents the given value.
140    fn try_new_const_uint(&self, value: u128, uint_ty: UintTy) -> Result<MirConst, Error>;
141    fn try_new_ty_const_uint(&self, value: u128, uint_ty: UintTy) -> Result<TyConst, Error>;
142
143    /// Create a new type from the given kind.
144    fn new_rigid_ty(&self, kind: RigidTy) -> Ty;
145
146    /// Create a new box type, `Box<T>`, for the given inner type `T`.
147    fn new_box_ty(&self, ty: Ty) -> Ty;
148
149    /// Returns the type of given crate item.
150    fn def_ty(&self, item: DefId) -> Ty;
151
152    /// Returns the type of given definition instantiated with the given arguments.
153    fn def_ty_with_args(&self, item: DefId, args: &GenericArgs) -> Ty;
154
155    /// Returns literal value of a const as a string.
156    fn mir_const_pretty(&self, cnst: &MirConst) -> String;
157
158    /// `Span` of an item
159    fn span_of_an_item(&self, def_id: DefId) -> Span;
160
161    fn ty_const_pretty(&self, ct: TyConstId) -> String;
162
163    /// Obtain the representation of a type.
164    fn ty_pretty(&self, ty: Ty) -> String;
165
166    /// Obtain the representation of a type.
167    fn ty_kind(&self, ty: Ty) -> TyKind;
168
169    // Get the discriminant Ty for this Ty if there's one.
170    fn rigid_ty_discriminant_ty(&self, ty: &RigidTy) -> Ty;
171
172    /// Get the body of an Instance which is already monomorphized.
173    fn instance_body(&self, instance: InstanceDef) -> Option<Body>;
174
175    /// Get the instance type with generic instantiations applied and lifetimes erased.
176    fn instance_ty(&self, instance: InstanceDef) -> Ty;
177
178    /// Get the instantiation types.
179    fn instance_args(&self, def: InstanceDef) -> GenericArgs;
180
181    /// Get the instance.
182    fn instance_def_id(&self, instance: InstanceDef) -> DefId;
183
184    /// Get the instance mangled name.
185    fn instance_mangled_name(&self, instance: InstanceDef) -> Symbol;
186
187    /// Check if this is an empty DropGlue shim.
188    fn is_empty_drop_shim(&self, def: InstanceDef) -> bool;
189
190    /// Check if this is an empty AsyncDropGlueCtor shim.
191    fn is_empty_async_drop_ctor_shim(&self, def: InstanceDef) -> bool;
192
193    /// Convert a non-generic crate item into an instance.
194    /// This function will panic if the item is generic.
195    fn mono_instance(&self, def_id: DefId) -> Instance;
196
197    /// Item requires monomorphization.
198    fn requires_monomorphization(&self, def_id: DefId) -> bool;
199
200    /// Resolve an instance from the given function definition and generic arguments.
201    fn resolve_instance(&self, def: FnDef, args: &GenericArgs) -> Option<Instance>;
202
203    /// Resolve an instance for drop_in_place for the given type.
204    fn resolve_drop_in_place(&self, ty: Ty) -> Instance;
205
206    /// Resolve instance for a function pointer.
207    fn resolve_for_fn_ptr(&self, def: FnDef, args: &GenericArgs) -> Option<Instance>;
208
209    /// Resolve instance for a closure with the requested type.
210    fn resolve_closure(
211        &self,
212        def: ClosureDef,
213        args: &GenericArgs,
214        kind: ClosureKind,
215    ) -> Option<Instance>;
216
217    /// Evaluate a static's initializer.
218    fn eval_static_initializer(&self, def: StaticDef) -> Result<Allocation, Error>;
219
220    /// Try to evaluate an instance into a constant.
221    fn eval_instance(&self, def: InstanceDef, const_ty: Ty) -> Result<Allocation, Error>;
222
223    /// Retrieve global allocation for the given allocation ID.
224    fn global_alloc(&self, id: AllocId) -> GlobalAlloc;
225
226    /// Retrieve the id for the virtual table.
227    fn vtable_allocation(&self, global_alloc: &GlobalAlloc) -> Option<AllocId>;
228    fn krate(&self, def_id: DefId) -> Crate;
229    fn instance_name(&self, def: InstanceDef, trimmed: bool) -> Symbol;
230
231    /// Return information about the target machine.
232    fn target_info(&self) -> MachineInfo;
233
234    /// Get an instance ABI.
235    fn instance_abi(&self, def: InstanceDef) -> Result<FnAbi, Error>;
236
237    /// Get the ABI of a function pointer.
238    fn fn_ptr_abi(&self, fn_ptr: PolyFnSig) -> Result<FnAbi, Error>;
239
240    /// Get the layout of a type.
241    fn ty_layout(&self, ty: Ty) -> Result<Layout, Error>;
242
243    /// Get the layout shape.
244    fn layout_shape(&self, id: Layout) -> LayoutShape;
245
246    /// Get a debug string representation of a place.
247    fn place_pretty(&self, place: &Place) -> String;
248
249    /// Get the resulting type of binary operation.
250    fn binop_ty(&self, bin_op: BinOp, rhs: Ty, lhs: Ty) -> Ty;
251
252    /// Get the resulting type of unary operation.
253    fn unop_ty(&self, un_op: UnOp, arg: Ty) -> Ty;
254}
255
256// A thread local variable that stores a pointer to the tables mapping between TyCtxt
257// datastructures and stable MIR datastructures
258scoped_tls::scoped_thread_local!(static TLV: Cell<*const ()>);
259
260pub fn run<F, T>(context: &dyn Context, f: F) -> Result<T, Error>
261where
262    F: FnOnce() -> T,
263{
264    if TLV.is_set() {
265        Err(Error::from("StableMIR already running"))
266    } else {
267        let ptr: *const () = (&raw const context) as _;
268        TLV.set(&Cell::new(ptr), || Ok(f()))
269    }
270}
271
272/// Execute the given function with access the compiler [Context].
273///
274/// I.e., This function will load the current context and calls a function with it.
275/// Do not nest these, as that will ICE.
276pub(crate) fn with<R>(f: impl FnOnce(&dyn Context) -> R) -> R {
277    assert!(TLV.is_set());
278    TLV.with(|tlv| {
279        let ptr = tlv.get();
280        assert!(!ptr.is_null());
281        f(unsafe { *(ptr as *const &dyn Context) })
282    })
283}