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 rustc_smir::context::SmirCtxt;
9use stable_mir::abi::{FnAbi, Layout, LayoutShape};
10use stable_mir::crate_def::Attribute;
11use stable_mir::mir::alloc::{AllocId, GlobalAlloc};
12use stable_mir::mir::mono::{Instance, InstanceDef, StaticDef};
13use stable_mir::mir::{BinOp, Body, Place, UnOp};
14use stable_mir::target::MachineInfo;
15use stable_mir::ty::{
16    AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, FieldDef, FnDef, ForeignDef,
17    ForeignItemKind, ForeignModule, ForeignModuleDef, GenericArgs, GenericPredicates, Generics,
18    ImplDef, ImplTrait, IntrinsicDef, LineInfo, MirConst, PolyFnSig, RigidTy, Span, TraitDecl,
19    TraitDef, Ty, TyConst, TyConstId, TyKind, UintTy, VariantDef,
20};
21use stable_mir::{
22    AssocItems, Crate, CrateItem, CrateItems, CrateNum, DefId, Error, Filename, ImplTraitDecls,
23    ItemKind, Symbol, TraitDecls, mir,
24};
25
26use crate::{rustc_smir, stable_mir};
27
28/// Stable public API for querying compiler information.
29///
30/// All queries are delegated to an internal [`SmirCtxt`] that provides
31/// similar APIs but based on internal rustc constructs.
32///
33/// Do not use this directly. This is currently used in the macro expansion.
34pub(crate) struct SmirInterface<'tcx> {
35    pub(crate) cx: SmirCtxt<'tcx>,
36}
37
38impl<'tcx> SmirInterface<'tcx> {
39    pub(crate) fn entry_fn(&self) -> Option<CrateItem> {
40        self.cx.entry_fn()
41    }
42
43    /// Retrieve all items of the local crate that have a MIR associated with them.
44    pub(crate) fn all_local_items(&self) -> CrateItems {
45        self.cx.all_local_items()
46    }
47
48    /// Retrieve the body of a function.
49    /// This function will panic if the body is not available.
50    pub(crate) fn mir_body(&self, item: DefId) -> mir::Body {
51        self.cx.mir_body(item)
52    }
53
54    /// Check whether the body of a function is available.
55    pub(crate) fn has_body(&self, item: DefId) -> bool {
56        self.cx.has_body(item)
57    }
58
59    pub(crate) fn foreign_modules(&self, crate_num: CrateNum) -> Vec<ForeignModuleDef> {
60        self.cx.foreign_modules(crate_num)
61    }
62
63    /// Retrieve all functions defined in this crate.
64    pub(crate) fn crate_functions(&self, crate_num: CrateNum) -> Vec<FnDef> {
65        self.cx.crate_functions(crate_num)
66    }
67
68    /// Retrieve all static items defined in this crate.
69    pub(crate) fn crate_statics(&self, crate_num: CrateNum) -> Vec<StaticDef> {
70        self.cx.crate_statics(crate_num)
71    }
72
73    pub(crate) fn foreign_module(&self, mod_def: ForeignModuleDef) -> ForeignModule {
74        self.cx.foreign_module(mod_def)
75    }
76
77    pub(crate) fn foreign_items(&self, mod_def: ForeignModuleDef) -> Vec<ForeignDef> {
78        self.cx.foreign_items(mod_def)
79    }
80
81    pub(crate) fn all_trait_decls(&self) -> TraitDecls {
82        self.cx.all_trait_decls()
83    }
84
85    pub(crate) fn trait_decls(&self, crate_num: CrateNum) -> TraitDecls {
86        self.cx.trait_decls(crate_num)
87    }
88
89    pub(crate) fn trait_decl(&self, trait_def: &TraitDef) -> TraitDecl {
90        self.cx.trait_decl(trait_def)
91    }
92
93    pub(crate) fn all_trait_impls(&self) -> ImplTraitDecls {
94        self.cx.all_trait_impls()
95    }
96
97    pub(crate) fn trait_impls(&self, crate_num: CrateNum) -> ImplTraitDecls {
98        self.cx.trait_impls(crate_num)
99    }
100
101    pub(crate) fn trait_impl(&self, trait_impl: &ImplDef) -> ImplTrait {
102        self.cx.trait_impl(trait_impl)
103    }
104
105    pub(crate) fn generics_of(&self, def_id: DefId) -> Generics {
106        self.cx.generics_of(def_id)
107    }
108
109    pub(crate) fn predicates_of(&self, def_id: DefId) -> GenericPredicates {
110        self.cx.predicates_of(def_id)
111    }
112
113    pub(crate) fn explicit_predicates_of(&self, def_id: DefId) -> GenericPredicates {
114        self.cx.explicit_predicates_of(def_id)
115    }
116
117    /// Get information about the local crate.
118    pub(crate) fn local_crate(&self) -> Crate {
119        self.cx.local_crate()
120    }
121
122    /// Retrieve a list of all external crates.
123    pub(crate) fn external_crates(&self) -> Vec<Crate> {
124        self.cx.external_crates()
125    }
126
127    /// Find a crate with the given name.
128    pub(crate) fn find_crates(&self, name: &str) -> Vec<Crate> {
129        self.cx.find_crates(name)
130    }
131
132    /// Returns the name of given `DefId`.
133    pub(crate) fn def_name(&self, def_id: DefId, trimmed: bool) -> Symbol {
134        self.cx.def_name(def_id, trimmed)
135    }
136
137    /// Return registered tool attributes with the given attribute name.
138    ///
139    /// FIXME(jdonszelmann): may panic on non-tool attributes. After more attribute work, non-tool
140    /// attributes will simply return an empty list.
141    ///
142    /// Single segmented name like `#[clippy]` is specified as `&["clippy".to_string()]`.
143    /// Multi-segmented name like `#[rustfmt::skip]` is specified as `&["rustfmt".to_string(), "skip".to_string()]`.
144    pub(crate) fn tool_attrs(&self, def_id: DefId, attr: &[Symbol]) -> Vec<Attribute> {
145        self.cx.tool_attrs(def_id, attr)
146    }
147
148    /// Get all tool attributes of a definition.
149    pub(crate) fn all_tool_attrs(&self, def_id: DefId) -> Vec<Attribute> {
150        self.cx.all_tool_attrs(def_id)
151    }
152
153    /// Returns printable, human readable form of `Span`.
154    pub(crate) fn span_to_string(&self, span: Span) -> String {
155        self.cx.span_to_string(span)
156    }
157
158    /// Return filename from given `Span`, for diagnostic purposes.
159    pub(crate) fn get_filename(&self, span: &Span) -> Filename {
160        self.cx.get_filename(span)
161    }
162
163    /// Return lines corresponding to this `Span`.
164    pub(crate) fn get_lines(&self, span: &Span) -> LineInfo {
165        self.cx.get_lines(span)
166    }
167
168    /// Returns the `kind` of given `DefId`.
169    pub(crate) fn item_kind(&self, item: CrateItem) -> ItemKind {
170        self.cx.item_kind(item)
171    }
172
173    /// Returns whether this is a foreign item.
174    pub(crate) fn is_foreign_item(&self, item: DefId) -> bool {
175        self.cx.is_foreign_item(item)
176    }
177
178    /// Returns the kind of a given foreign item.
179    pub(crate) fn foreign_item_kind(&self, def: ForeignDef) -> ForeignItemKind {
180        self.cx.foreign_item_kind(def)
181    }
182
183    /// Returns the kind of a given algebraic data type.
184    pub(crate) fn adt_kind(&self, def: AdtDef) -> AdtKind {
185        self.cx.adt_kind(def)
186    }
187
188    /// Returns if the ADT is a box.
189    pub(crate) fn adt_is_box(&self, def: AdtDef) -> bool {
190        self.cx.adt_is_box(def)
191    }
192
193    /// Returns whether this ADT is simd.
194    pub(crate) fn adt_is_simd(&self, def: AdtDef) -> bool {
195        self.cx.adt_is_simd(def)
196    }
197
198    /// Returns whether this definition is a C string.
199    pub(crate) fn adt_is_cstr(&self, def: AdtDef) -> bool {
200        self.cx.adt_is_cstr(def)
201    }
202
203    /// Retrieve the function signature for the given generic arguments.
204    pub(crate) fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig {
205        self.cx.fn_sig(def, args)
206    }
207
208    /// Retrieve the intrinsic definition if the item corresponds one.
209    pub(crate) fn intrinsic(&self, item: DefId) -> Option<IntrinsicDef> {
210        self.cx.intrinsic(item)
211    }
212
213    /// Retrieve the plain function name of an intrinsic.
214    pub(crate) fn intrinsic_name(&self, def: IntrinsicDef) -> Symbol {
215        self.cx.intrinsic_name(def)
216    }
217
218    /// Retrieve the closure signature for the given generic arguments.
219    pub(crate) fn closure_sig(&self, args: &GenericArgs) -> PolyFnSig {
220        self.cx.closure_sig(args)
221    }
222
223    /// The number of variants in this ADT.
224    pub(crate) fn adt_variants_len(&self, def: AdtDef) -> usize {
225        self.cx.adt_variants_len(def)
226    }
227
228    /// The name of a variant.
229    pub(crate) fn variant_name(&self, def: VariantDef) -> Symbol {
230        self.cx.variant_name(def)
231    }
232
233    pub(crate) fn variant_fields(&self, def: VariantDef) -> Vec<FieldDef> {
234        self.cx.variant_fields(def)
235    }
236
237    /// Evaluate constant as a target usize.
238    pub(crate) fn eval_target_usize(&self, cnst: &MirConst) -> Result<u64, Error> {
239        self.cx.eval_target_usize(cnst)
240    }
241
242    pub(crate) fn eval_target_usize_ty(&self, cnst: &TyConst) -> Result<u64, Error> {
243        self.cx.eval_target_usize_ty(cnst)
244    }
245
246    /// Create a new zero-sized constant.
247    pub(crate) fn try_new_const_zst(&self, ty: Ty) -> Result<MirConst, Error> {
248        self.cx.try_new_const_zst(ty)
249    }
250
251    /// Create a new constant that represents the given string value.
252    pub(crate) fn new_const_str(&self, value: &str) -> MirConst {
253        self.cx.new_const_str(value)
254    }
255
256    /// Create a new constant that represents the given boolean value.
257    pub(crate) fn new_const_bool(&self, value: bool) -> MirConst {
258        self.cx.new_const_bool(value)
259    }
260
261    /// Create a new constant that represents the given value.
262    pub(crate) fn try_new_const_uint(
263        &self,
264        value: u128,
265        uint_ty: UintTy,
266    ) -> Result<MirConst, Error> {
267        self.cx.try_new_const_uint(value, uint_ty)
268    }
269
270    pub(crate) fn try_new_ty_const_uint(
271        &self,
272        value: u128,
273        uint_ty: UintTy,
274    ) -> Result<TyConst, Error> {
275        self.cx.try_new_ty_const_uint(value, uint_ty)
276    }
277
278    /// Create a new type from the given kind.
279    pub(crate) fn new_rigid_ty(&self, kind: RigidTy) -> Ty {
280        self.cx.new_rigid_ty(kind)
281    }
282
283    /// Create a new box type, `Box<T>`, for the given inner type `T`.
284    pub(crate) fn new_box_ty(&self, ty: Ty) -> Ty {
285        self.cx.new_box_ty(ty)
286    }
287
288    /// Returns the type of given crate item.
289    pub(crate) fn def_ty(&self, item: DefId) -> Ty {
290        self.cx.def_ty(item)
291    }
292
293    /// Returns the type of given definition instantiated with the given arguments.
294    pub(crate) fn def_ty_with_args(&self, item: DefId, args: &GenericArgs) -> Ty {
295        self.cx.def_ty_with_args(item, args)
296    }
297
298    /// Returns literal value of a const as a string.
299    pub(crate) fn mir_const_pretty(&self, cnst: &MirConst) -> String {
300        self.cx.mir_const_pretty(cnst)
301    }
302
303    /// `Span` of an item.
304    pub(crate) fn span_of_an_item(&self, def_id: DefId) -> Span {
305        self.cx.span_of_an_item(def_id)
306    }
307
308    pub(crate) fn ty_const_pretty(&self, ct: TyConstId) -> String {
309        self.cx.ty_const_pretty(ct)
310    }
311
312    /// Obtain the representation of a type.
313    pub(crate) fn ty_pretty(&self, ty: Ty) -> String {
314        self.cx.ty_pretty(ty)
315    }
316
317    /// Obtain the representation of a type.
318    pub(crate) fn ty_kind(&self, ty: Ty) -> TyKind {
319        self.cx.ty_kind(ty)
320    }
321
322    /// Get the discriminant Ty for this Ty if there's one.
323    pub(crate) fn rigid_ty_discriminant_ty(&self, ty: &RigidTy) -> Ty {
324        self.cx.rigid_ty_discriminant_ty(ty)
325    }
326
327    /// Get the body of an Instance which is already monomorphized.
328    pub(crate) fn instance_body(&self, instance: InstanceDef) -> Option<Body> {
329        self.cx.instance_body(instance)
330    }
331
332    /// Get the instance type with generic instantiations applied and lifetimes erased.
333    pub(crate) fn instance_ty(&self, instance: InstanceDef) -> Ty {
334        self.cx.instance_ty(instance)
335    }
336
337    /// Get the instantiation types.
338    pub(crate) fn instance_args(&self, def: InstanceDef) -> GenericArgs {
339        self.cx.instance_args(def)
340    }
341
342    /// Get the instance.
343    pub(crate) fn instance_def_id(&self, instance: InstanceDef) -> DefId {
344        self.cx.instance_def_id(instance)
345    }
346
347    /// Get the instance mangled name.
348    pub(crate) fn instance_mangled_name(&self, instance: InstanceDef) -> Symbol {
349        self.cx.instance_mangled_name(instance)
350    }
351
352    /// Check if this is an empty DropGlue shim.
353    pub(crate) fn is_empty_drop_shim(&self, def: InstanceDef) -> bool {
354        self.cx.is_empty_drop_shim(def)
355    }
356
357    /// Convert a non-generic crate item into an instance.
358    /// This function will panic if the item is generic.
359    pub(crate) fn mono_instance(&self, def_id: DefId) -> Instance {
360        self.cx.mono_instance(def_id)
361    }
362
363    /// Item requires monomorphization.
364    pub(crate) fn requires_monomorphization(&self, def_id: DefId) -> bool {
365        self.cx.requires_monomorphization(def_id)
366    }
367
368    /// Resolve an instance from the given function definition and generic arguments.
369    pub(crate) fn resolve_instance(&self, def: FnDef, args: &GenericArgs) -> Option<Instance> {
370        self.cx.resolve_instance(def, args)
371    }
372
373    /// Resolve an instance for drop_in_place for the given type.
374    pub(crate) fn resolve_drop_in_place(&self, ty: Ty) -> Instance {
375        self.cx.resolve_drop_in_place(ty)
376    }
377
378    /// Resolve instance for a function pointer.
379    pub(crate) fn resolve_for_fn_ptr(&self, def: FnDef, args: &GenericArgs) -> Option<Instance> {
380        self.cx.resolve_for_fn_ptr(def, args)
381    }
382
383    /// Resolve instance for a closure with the requested type.
384    pub(crate) fn resolve_closure(
385        &self,
386        def: ClosureDef,
387        args: &GenericArgs,
388        kind: ClosureKind,
389    ) -> Option<Instance> {
390        self.cx.resolve_closure(def, args, kind)
391    }
392
393    /// Evaluate a static's initializer.
394    pub(crate) fn eval_static_initializer(&self, def: StaticDef) -> Result<Allocation, Error> {
395        self.cx.eval_static_initializer(def)
396    }
397
398    /// Try to evaluate an instance into a constant.
399    pub(crate) fn eval_instance(
400        &self,
401        def: InstanceDef,
402        const_ty: Ty,
403    ) -> Result<Allocation, Error> {
404        self.cx.eval_instance(def, const_ty)
405    }
406
407    /// Retrieve global allocation for the given allocation ID.
408    pub(crate) fn global_alloc(&self, id: AllocId) -> GlobalAlloc {
409        self.cx.global_alloc(id)
410    }
411
412    /// Retrieve the id for the virtual table.
413    pub(crate) fn vtable_allocation(&self, global_alloc: &GlobalAlloc) -> Option<AllocId> {
414        self.cx.vtable_allocation(global_alloc)
415    }
416
417    pub(crate) fn krate(&self, def_id: DefId) -> Crate {
418        self.cx.krate(def_id)
419    }
420
421    pub(crate) fn instance_name(&self, def: InstanceDef, trimmed: bool) -> Symbol {
422        self.cx.instance_name(def, trimmed)
423    }
424
425    /// Return information about the target machine.
426    pub(crate) fn target_info(&self) -> MachineInfo {
427        self.cx.target_info()
428    }
429
430    /// Get an instance ABI.
431    pub(crate) fn instance_abi(&self, def: InstanceDef) -> Result<FnAbi, Error> {
432        self.cx.instance_abi(def)
433    }
434
435    /// Get the ABI of a function pointer.
436    pub(crate) fn fn_ptr_abi(&self, fn_ptr: PolyFnSig) -> Result<FnAbi, Error> {
437        self.cx.fn_ptr_abi(fn_ptr)
438    }
439
440    /// Get the layout of a type.
441    pub(crate) fn ty_layout(&self, ty: Ty) -> Result<Layout, Error> {
442        self.cx.ty_layout(ty)
443    }
444
445    /// Get the layout shape.
446    pub(crate) fn layout_shape(&self, id: Layout) -> LayoutShape {
447        self.cx.layout_shape(id)
448    }
449
450    /// Get a debug string representation of a place.
451    pub(crate) fn place_pretty(&self, place: &Place) -> String {
452        self.cx.place_pretty(place)
453    }
454
455    /// Get the resulting type of binary operation.
456    pub(crate) fn binop_ty(&self, bin_op: BinOp, rhs: Ty, lhs: Ty) -> Ty {
457        self.cx.binop_ty(bin_op, rhs, lhs)
458    }
459
460    /// Get the resulting type of unary operation.
461    pub(crate) fn unop_ty(&self, un_op: UnOp, arg: Ty) -> Ty {
462        self.cx.unop_ty(un_op, arg)
463    }
464
465    /// Get all associated items of a definition.
466    pub(crate) fn associated_items(&self, def_id: DefId) -> AssocItems {
467        self.cx.associated_items(def_id)
468    }
469}
470
471// A thread local variable that stores a pointer to [`SmirInterface`].
472scoped_tls::scoped_thread_local!(static TLV: Cell<*const ()>);
473
474pub(crate) fn run<'tcx, T, F>(interface: &SmirInterface<'tcx>, f: F) -> Result<T, Error>
475where
476    F: FnOnce() -> T,
477{
478    if TLV.is_set() {
479        Err(Error::from("StableMIR already running"))
480    } else {
481        let ptr: *const () = (interface as *const SmirInterface<'tcx>) as *const ();
482        TLV.set(&Cell::new(ptr), || Ok(f()))
483    }
484}
485
486/// Execute the given function with access the [`SmirInterface`].
487///
488/// I.e., This function will load the current interface and calls a function with it.
489/// Do not nest these, as that will ICE.
490pub(crate) fn with<R>(f: impl FnOnce(&SmirInterface<'_>) -> R) -> R {
491    assert!(TLV.is_set());
492    TLV.with(|tlv| {
493        let ptr = tlv.get();
494        assert!(!ptr.is_null());
495        f(unsafe { &*(ptr as *const SmirInterface<'_>) })
496    })
497}