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 attributes with the given attribute name.
66    ///
67    /// Single segmented name like `#[inline]` is specified as `&["inline".to_string()]`.
68    /// Multi-segmented name like `#[rustfmt::skip]` is specified as `&["rustfmt".to_string(), "skip".to_string()]`.
69    fn get_attrs_by_path(&self, def_id: DefId, attr: &[Symbol]) -> Vec<Attribute>;
70
71    /// Get all attributes of a definition.
72    fn get_all_attrs(&self, def_id: DefId) -> Vec<Attribute>;
73
74    /// Returns printable, human readable form of `Span`
75    fn span_to_string(&self, span: Span) -> String;
76
77    /// Return filename from given `Span`, for diagnostic purposes
78    fn get_filename(&self, span: &Span) -> Filename;
79
80    /// Return lines corresponding to this `Span`
81    fn get_lines(&self, span: &Span) -> LineInfo;
82
83    /// Returns the `kind` of given `DefId`
84    fn item_kind(&self, item: CrateItem) -> ItemKind;
85
86    /// Returns whether this is a foreign item.
87    fn is_foreign_item(&self, item: DefId) -> bool;
88
89    /// Returns the kind of a given foreign item.
90    fn foreign_item_kind(&self, def: ForeignDef) -> ForeignItemKind;
91
92    /// Returns the kind of a given algebraic data type
93    fn adt_kind(&self, def: AdtDef) -> AdtKind;
94
95    /// Returns if the ADT is a box.
96    fn adt_is_box(&self, def: AdtDef) -> bool;
97
98    /// Returns whether this ADT is simd.
99    fn adt_is_simd(&self, def: AdtDef) -> bool;
100
101    /// Returns whether this definition is a C string.
102    fn adt_is_cstr(&self, def: AdtDef) -> bool;
103
104    /// Retrieve the function signature for the given generic arguments.
105    fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig;
106
107    /// Retrieve the intrinsic definition if the item corresponds one.
108    fn intrinsic(&self, item: DefId) -> Option<IntrinsicDef>;
109
110    /// Retrieve the plain function name of an intrinsic.
111    fn intrinsic_name(&self, def: IntrinsicDef) -> Symbol;
112
113    /// Retrieve the closure signature for the given generic arguments.
114    fn closure_sig(&self, args: &GenericArgs) -> PolyFnSig;
115
116    /// The number of variants in this ADT.
117    fn adt_variants_len(&self, def: AdtDef) -> usize;
118
119    /// The name of a variant.
120    fn variant_name(&self, def: VariantDef) -> Symbol;
121    fn variant_fields(&self, def: VariantDef) -> Vec<FieldDef>;
122
123    /// Evaluate constant as a target usize.
124    fn eval_target_usize(&self, cnst: &MirConst) -> Result<u64, Error>;
125    fn eval_target_usize_ty(&self, cnst: &TyConst) -> Result<u64, Error>;
126
127    /// Create a new zero-sized constant.
128    fn try_new_const_zst(&self, ty: Ty) -> Result<MirConst, Error>;
129
130    /// Create a new constant that represents the given string value.
131    fn new_const_str(&self, value: &str) -> MirConst;
132
133    /// Create a new constant that represents the given boolean value.
134    fn new_const_bool(&self, value: bool) -> MirConst;
135
136    /// Create a new constant that represents the given value.
137    fn try_new_const_uint(&self, value: u128, uint_ty: UintTy) -> Result<MirConst, Error>;
138    fn try_new_ty_const_uint(&self, value: u128, uint_ty: UintTy) -> Result<TyConst, Error>;
139
140    /// Create a new type from the given kind.
141    fn new_rigid_ty(&self, kind: RigidTy) -> Ty;
142
143    /// Create a new box type, `Box<T>`, for the given inner type `T`.
144    fn new_box_ty(&self, ty: Ty) -> Ty;
145
146    /// Returns the type of given crate item.
147    fn def_ty(&self, item: DefId) -> Ty;
148
149    /// Returns the type of given definition instantiated with the given arguments.
150    fn def_ty_with_args(&self, item: DefId, args: &GenericArgs) -> Ty;
151
152    /// Returns literal value of a const as a string.
153    fn mir_const_pretty(&self, cnst: &MirConst) -> String;
154
155    /// `Span` of an item
156    fn span_of_an_item(&self, def_id: DefId) -> Span;
157
158    fn ty_const_pretty(&self, ct: TyConstId) -> String;
159
160    /// Obtain the representation of a type.
161    fn ty_pretty(&self, ty: Ty) -> String;
162
163    /// Obtain the representation of a type.
164    fn ty_kind(&self, ty: Ty) -> TyKind;
165
166    // Get the discriminant Ty for this Ty if there's one.
167    fn rigid_ty_discriminant_ty(&self, ty: &RigidTy) -> Ty;
168
169    /// Get the body of an Instance which is already monomorphized.
170    fn instance_body(&self, instance: InstanceDef) -> Option<Body>;
171
172    /// Get the instance type with generic instantiations applied and lifetimes erased.
173    fn instance_ty(&self, instance: InstanceDef) -> Ty;
174
175    /// Get the instantiation types.
176    fn instance_args(&self, def: InstanceDef) -> GenericArgs;
177
178    /// Get the instance.
179    fn instance_def_id(&self, instance: InstanceDef) -> DefId;
180
181    /// Get the instance mangled name.
182    fn instance_mangled_name(&self, instance: InstanceDef) -> Symbol;
183
184    /// Check if this is an empty DropGlue shim.
185    fn is_empty_drop_shim(&self, def: InstanceDef) -> bool;
186
187    /// Check if this is an empty AsyncDropGlueCtor shim.
188    fn is_empty_async_drop_ctor_shim(&self, def: InstanceDef) -> bool;
189
190    /// Convert a non-generic crate item into an instance.
191    /// This function will panic if the item is generic.
192    fn mono_instance(&self, def_id: DefId) -> Instance;
193
194    /// Item requires monomorphization.
195    fn requires_monomorphization(&self, def_id: DefId) -> bool;
196
197    /// Resolve an instance from the given function definition and generic arguments.
198    fn resolve_instance(&self, def: FnDef, args: &GenericArgs) -> Option<Instance>;
199
200    /// Resolve an instance for drop_in_place for the given type.
201    fn resolve_drop_in_place(&self, ty: Ty) -> Instance;
202
203    /// Resolve instance for a function pointer.
204    fn resolve_for_fn_ptr(&self, def: FnDef, args: &GenericArgs) -> Option<Instance>;
205
206    /// Resolve instance for a closure with the requested type.
207    fn resolve_closure(
208        &self,
209        def: ClosureDef,
210        args: &GenericArgs,
211        kind: ClosureKind,
212    ) -> Option<Instance>;
213
214    /// Evaluate a static's initializer.
215    fn eval_static_initializer(&self, def: StaticDef) -> Result<Allocation, Error>;
216
217    /// Try to evaluate an instance into a constant.
218    fn eval_instance(&self, def: InstanceDef, const_ty: Ty) -> Result<Allocation, Error>;
219
220    /// Retrieve global allocation for the given allocation ID.
221    fn global_alloc(&self, id: AllocId) -> GlobalAlloc;
222
223    /// Retrieve the id for the virtual table.
224    fn vtable_allocation(&self, global_alloc: &GlobalAlloc) -> Option<AllocId>;
225    fn krate(&self, def_id: DefId) -> Crate;
226    fn instance_name(&self, def: InstanceDef, trimmed: bool) -> Symbol;
227
228    /// Return information about the target machine.
229    fn target_info(&self) -> MachineInfo;
230
231    /// Get an instance ABI.
232    fn instance_abi(&self, def: InstanceDef) -> Result<FnAbi, Error>;
233
234    /// Get the ABI of a function pointer.
235    fn fn_ptr_abi(&self, fn_ptr: PolyFnSig) -> Result<FnAbi, Error>;
236
237    /// Get the layout of a type.
238    fn ty_layout(&self, ty: Ty) -> Result<Layout, Error>;
239
240    /// Get the layout shape.
241    fn layout_shape(&self, id: Layout) -> LayoutShape;
242
243    /// Get a debug string representation of a place.
244    fn place_pretty(&self, place: &Place) -> String;
245
246    /// Get the resulting type of binary operation.
247    fn binop_ty(&self, bin_op: BinOp, rhs: Ty, lhs: Ty) -> Ty;
248
249    /// Get the resulting type of unary operation.
250    fn unop_ty(&self, un_op: UnOp, arg: Ty) -> Ty;
251}
252
253// A thread local variable that stores a pointer to the tables mapping between TyCtxt
254// datastructures and stable MIR datastructures
255scoped_tls::scoped_thread_local!(static TLV: Cell<*const ()>);
256
257pub fn run<F, T>(context: &dyn Context, f: F) -> Result<T, Error>
258where
259    F: FnOnce() -> T,
260{
261    if TLV.is_set() {
262        Err(Error::from("StableMIR already running"))
263    } else {
264        let ptr: *const () = (&raw const context) as _;
265        TLV.set(&Cell::new(ptr), || Ok(f()))
266    }
267}
268
269/// Execute the given function with access the compiler [Context].
270///
271/// I.e., This function will load the current context and calls a function with it.
272/// Do not nest these, as that will ICE.
273pub(crate) fn with<R>(f: impl FnOnce(&dyn Context) -> R) -> R {
274    assert!(TLV.is_set());
275    TLV.with(|tlv| {
276        let ptr = tlv.get();
277        assert!(!ptr.is_null());
278        f(unsafe { *(ptr as *const &dyn Context) })
279    })
280}