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