Skip to main content

rustc_public/
compiler_interface.rs

1//! Define the interface with the Rust compiler.
2//!
3//! rustc_public users should not use any of the items in this module directly.
4//! These APIs have no stability guarantee.
5
6use std::cell::{Cell, RefCell};
7
8use rustc_hir::def::DefKind;
9use rustc_public_bridge::context::CompilerCtxt;
10use rustc_public_bridge::{Bridge, Tables};
11use tracing::debug;
12
13use crate::abi::{FnAbi, Layout, LayoutShape, ReprOptions};
14use crate::crate_def::Attribute;
15use crate::mir::alloc::{AllocId, GlobalAlloc};
16use crate::mir::mono::{Instance, InstanceDef, StaticDef};
17use crate::mir::{BinOp, Body, Place, UnOp};
18use crate::target::{MachineInfo, MachineSize};
19use crate::ty::{
20    AdtDef, AdtKind, Allocation, AssocItem, Asyncness, ClosureDef, ClosureKind, Constness,
21    CoroutineDef, Discr, FieldDef, FloatTy, FnDef, ForeignDef, ForeignItemKind, ForeignModule,
22    ForeignModuleDef, GenericArgs, GenericPredicates, Generics, ImplDef, ImplTrait, IntrinsicDef,
23    LineInfo, MirConst, PolyFnSig, RigidTy, Span, TraitDecl, TraitDef, TraitRef, Ty, TyConst,
24    TyConstId, TyKind, UintTy, VariantDef, VariantIdx, VtblEntry,
25};
26use crate::unstable::{RustcInternal, Stable, new_item_kind};
27use crate::{
28    AssocItems, Crate, CrateDef, CrateItem, CrateItems, CrateNum, DefId, Error, Filename,
29    ImplTraitDecls, ItemKind, Symbol, ThreadLocalIndex, TraitDecls, alloc, mir,
30};
31
32pub struct BridgeTys;
33
34impl Bridge for BridgeTys {
35    type DefId = crate::DefId;
36    type AllocId = crate::mir::alloc::AllocId;
37    type Span = crate::ty::Span;
38    type Ty = crate::ty::Ty;
39    type InstanceDef = crate::mir::mono::InstanceDef;
40    type TyConstId = crate::ty::TyConstId;
41    type MirConstId = crate::ty::MirConstId;
42    type Layout = crate::abi::Layout;
43
44    type Error = crate::Error;
45    type CrateItem = crate::CrateItem;
46    type AdtDef = crate::ty::AdtDef;
47    type ForeignModuleDef = crate::ty::ForeignModuleDef;
48    type ForeignDef = crate::ty::ForeignDef;
49    type FnDef = crate::ty::FnDef;
50    type ClosureDef = crate::ty::ClosureDef;
51    type CoroutineDef = crate::ty::CoroutineDef;
52    type CoroutineClosureDef = crate::ty::CoroutineClosureDef;
53    type AliasDef = crate::ty::AliasDef;
54    type ParamDef = crate::ty::ParamDef;
55    type BrNamedDef = crate::ty::BrNamedDef;
56    type TraitDef = crate::ty::TraitDef;
57    type GenericDef = crate::ty::GenericDef;
58    type ConstDef = crate::ty::ConstDef;
59    type ImplDef = crate::ty::ImplDef;
60    type RegionDef = crate::ty::RegionDef;
61    type CoroutineWitnessDef = crate::ty::CoroutineWitnessDef;
62    type AssocDef = crate::ty::AssocDef;
63    type OpaqueDef = crate::ty::OpaqueDef;
64    type Prov = crate::ty::Prov;
65    type StaticDef = crate::mir::mono::StaticDef;
66
67    type Allocation = crate::ty::Allocation;
68}
69
70/// Public API for querying compiler information.
71///
72/// All queries are delegated to [`rustc_public_bridge::context::CompilerCtxt`]
73/// that provides similar APIs but based on internal rustc constructs.
74///
75/// Do not use this directly. This is currently used in the macro expansion.
76pub(crate) struct CompilerInterface<'tcx> {
77    pub tables: RefCell<Tables<'tcx, BridgeTys>>,
78    pub cx: RefCell<CompilerCtxt<'tcx, BridgeTys>>,
79}
80
81impl<'tcx> CompilerInterface<'tcx> {
82    fn with_cx<R>(
83        &self,
84        f: impl FnOnce(&mut Tables<'tcx, BridgeTys>, &CompilerCtxt<'tcx, BridgeTys>) -> R,
85    ) -> R {
86        let mut tables = self.tables.borrow_mut();
87        let cx = self.cx.borrow();
88        f(&mut *tables, &*cx)
89    }
90
91    pub(crate) fn entry_fn(&self) -> Option<CrateItem> {
92        self.with_cx(|tables, cx| {
93            let did = cx.entry_fn();
94            Some(tables.crate_item(did?))
95        })
96    }
97
98    /// Retrieve all items of the local crate that have a MIR associated with them.
99    pub(crate) fn all_local_items(&self) -> CrateItems {
100        self.with_cx(|tables, cx| {
101            cx.all_local_items().iter().map(|did| tables.crate_item(*did)).collect()
102        })
103    }
104
105    /// Retrieve the body of a function.
106    /// This function will panic if the body is not available.
107    pub(crate) fn mir_body(&self, item: DefId) -> mir::Body {
108        self.with_cx(|tables, cx| {
109            let did = tables[item];
110            cx.mir_body(did).stable(tables, cx)
111        })
112    }
113
114    /// Check whether the body of a function is available.
115    pub(crate) fn has_body(&self, item: DefId) -> bool {
116        self.with_cx(|tables, cx| {
117            let def = item.internal(tables, cx.tcx);
118            cx.has_body(def)
119        })
120    }
121
122    pub(crate) fn foreign_modules(&self, crate_num: CrateNum) -> Vec<ForeignModuleDef> {
123        self.with_cx(|tables, cx| {
124            cx.foreign_modules(crate_num.internal(tables, cx.tcx))
125                .iter()
126                .map(|did| tables.foreign_module_def(*did))
127                .collect()
128        })
129    }
130
131    /// Retrieve all functions defined in this crate.
132    pub(crate) fn crate_functions(&self, crate_num: CrateNum) -> Vec<FnDef> {
133        self.with_cx(|tables, cx| {
134            let krate = crate_num.internal(tables, cx.tcx);
135            cx.crate_functions(krate).iter().map(|did| tables.fn_def(*did)).collect()
136        })
137    }
138
139    pub(crate) fn crate_adts(&self, crate_num: CrateNum) -> Vec<AdtDef> {
140        self.with_cx(|tables, cx| {
141            let krate = crate_num.internal(tables, cx.tcx);
142            cx.crate_adts(krate).iter().map(|did| tables.adt_def(*did)).collect()
143        })
144    }
145
146    /// Retrieve all static items defined in this crate.
147    pub(crate) fn crate_statics(&self, crate_num: CrateNum) -> Vec<StaticDef> {
148        self.with_cx(|tables, cx| {
149            let krate = crate_num.internal(tables, cx.tcx);
150            cx.crate_statics(krate).iter().map(|did| tables.static_def(*did)).collect()
151        })
152    }
153
154    pub(crate) fn foreign_module(&self, mod_def: ForeignModuleDef) -> ForeignModule {
155        self.with_cx(|tables, cx| {
156            let did = tables[mod_def.def_id()];
157            cx.foreign_module(did).stable(tables, cx)
158        })
159    }
160
161    pub(crate) fn foreign_items(&self, mod_def: ForeignModuleDef) -> Vec<ForeignDef> {
162        self.with_cx(|tables, cx| {
163            let did = tables[mod_def.def_id()];
164            cx.foreign_items(did).iter().map(|did| tables.foreign_def(*did)).collect()
165        })
166    }
167
168    pub(crate) fn all_trait_decls(&self) -> TraitDecls {
169        self.with_cx(|tables, cx| cx.all_trait_decls().map(|did| tables.trait_def(did)).collect())
170    }
171
172    pub(crate) fn trait_decls(&self, crate_num: CrateNum) -> TraitDecls {
173        self.with_cx(|tables, cx| {
174            let krate = crate_num.internal(tables, cx.tcx);
175            cx.trait_decls(krate).iter().map(|did| tables.trait_def(*did)).collect()
176        })
177    }
178
179    pub(crate) fn trait_decl(&self, trait_def: &TraitDef) -> TraitDecl {
180        self.with_cx(|tables, cx| {
181            let did = tables[trait_def.0];
182            cx.trait_decl(did).stable(tables, cx)
183        })
184    }
185
186    pub(crate) fn all_trait_impls(&self) -> ImplTraitDecls {
187        self.with_cx(|tables, cx| {
188            cx.all_trait_impls().iter().map(|did| tables.impl_def(*did)).collect()
189        })
190    }
191
192    pub(crate) fn trait_impls(&self, crate_num: CrateNum) -> ImplTraitDecls {
193        self.with_cx(|tables, cx| {
194            let krate = crate_num.internal(tables, cx.tcx);
195            cx.trait_impls(krate).iter().map(|did| tables.impl_def(*did)).collect()
196        })
197    }
198
199    pub(crate) fn trait_impl(&self, trait_impl: &ImplDef) -> ImplTrait {
200        self.with_cx(|tables, cx| {
201            let did = tables[trait_impl.0];
202            cx.trait_impl(did).stable(tables, cx)
203        })
204    }
205
206    pub(crate) fn generics_of(&self, def_id: DefId) -> Generics {
207        self.with_cx(|tables, cx| {
208            let did = tables[def_id];
209            cx.generics_of(did).stable(tables, cx)
210        })
211    }
212
213    /// Retrieve the inherent implementations for this ADT.
214    pub(crate) fn inherent_impls(&self, adt: AdtDef) -> Vec<ImplDef> {
215        self.with_cx(|tables, cx| {
216            let def_id = tables[adt.0];
217            cx.inherent_impls(def_id).iter().map(|&did| tables.impl_def(did)).collect()
218        })
219    }
220
221    pub(crate) fn predicates_of(&self, def_id: DefId) -> GenericPredicates {
222        self.with_cx(|tables, cx| {
223            let did = tables[def_id];
224            let (parent, kinds) = cx.predicates_of(did);
225            crate::ty::GenericPredicates {
226                parent: parent.map(|did| tables.trait_def(did)),
227                predicates: kinds
228                    .iter()
229                    .map(|(kind, span)| (kind.stable(tables, cx), span.stable(tables, cx)))
230                    .collect(),
231            }
232        })
233    }
234
235    pub(crate) fn explicit_predicates_of(&self, def_id: DefId) -> GenericPredicates {
236        self.with_cx(|tables, cx| {
237            let did = tables[def_id];
238            let (parent, kinds) = cx.explicit_predicates_of(did);
239            crate::ty::GenericPredicates {
240                parent: parent.map(|did| tables.trait_def(did)),
241                predicates: kinds
242                    .iter()
243                    .map(|(kind, span)| (kind.stable(tables, cx), span.stable(tables, cx)))
244                    .collect(),
245            }
246        })
247    }
248
249    /// Get information about the local crate.
250    pub(crate) fn local_crate(&self) -> Crate {
251        self.with_cx(|_, cx| smir_crate(cx, cx.local_crate_num()))
252    }
253
254    /// Retrieve a list of all external crates.
255    pub(crate) fn external_crates(&self) -> Vec<Crate> {
256        self.with_cx(|_, cx| {
257            cx.external_crates().iter().map(|crate_num| smir_crate(cx, *crate_num)).collect()
258        })
259    }
260
261    /// Find a crate with the given name.
262    pub(crate) fn find_crates(&self, name: &str) -> Vec<Crate> {
263        self.with_cx(|_, cx| {
264            cx.find_crates(name).iter().map(|crate_num| smir_crate(cx, *crate_num)).collect()
265        })
266    }
267
268    /// Returns the name of given `DefId`.
269    pub(crate) fn def_name(&self, def_id: DefId, trimmed: bool) -> Symbol {
270        self.with_cx(|tables, cx| {
271            let did = tables[def_id];
272            cx.def_name(did, trimmed)
273        })
274    }
275
276    /// Returns the parent of the given `DefId`.
277    pub(crate) fn def_parent(&self, def_id: DefId) -> Option<DefId> {
278        self.with_cx(|tables, cx| {
279            let did = tables[def_id];
280            cx.def_parent(did).map(|did| tables.create_def_id(did))
281        })
282    }
283
284    /// Return registered tool attributes with the given attribute name.
285    ///
286    /// FIXME(jdonszelmann): may panic on non-tool attributes. After more attribute work, non-tool
287    /// attributes will simply return an empty list.
288    ///
289    /// Single segmented name like `#[clippy]` is specified as `&["clippy".to_string()]`.
290    /// Multi-segmented name like `#[rustfmt::skip]` is specified as `&["rustfmt".to_string(), "skip".to_string()]`.
291    pub(crate) fn tool_attrs(&self, def_id: DefId, attr: &[Symbol]) -> Vec<Attribute> {
292        self.with_cx(|tables, cx| {
293            let did = tables[def_id];
294            cx.tool_attrs(did, attr)
295                .into_iter()
296                .map(|(attr_str, span)| Attribute::new(attr_str, span.stable(tables, cx)))
297                .collect()
298        })
299    }
300
301    /// Get all tool attributes of a definition.
302    pub(crate) fn all_tool_attrs(&self, def_id: DefId) -> Vec<Attribute> {
303        self.with_cx(|tables, cx| {
304            let did = tables[def_id];
305            cx.all_tool_attrs(did)
306                .into_iter()
307                .map(|(attr_str, span)| Attribute::new(attr_str, span.stable(tables, cx)))
308                .collect()
309        })
310    }
311
312    /// Returns printable, human readable form of `Span`.
313    pub(crate) fn span_to_string(&self, span: Span) -> String {
314        self.with_cx(|tables, cx| {
315            let sp = tables.spans[span];
316            cx.span_to_string(sp)
317        })
318    }
319
320    /// Return filename from given `Span`, for diagnostic purposes.
321    pub(crate) fn get_filename(&self, span: &Span) -> Filename {
322        self.with_cx(|tables, cx| {
323            let sp = tables.spans[*span];
324            cx.get_filename(sp)
325        })
326    }
327
328    /// Return lines corresponding to this `Span`.
329    pub(crate) fn get_lines(&self, span: &Span) -> LineInfo {
330        self.with_cx(|tables, cx| {
331            let sp = tables.spans[*span];
332            let lines = cx.get_lines(sp);
333            LineInfo::from(lines)
334        })
335    }
336
337    /// Returns the `kind` of given `DefId`.
338    pub(crate) fn item_kind(&self, item: CrateItem) -> ItemKind {
339        self.with_cx(|tables, cx| {
340            let did = tables[item.0];
341            new_item_kind(cx.def_kind(did))
342        })
343    }
344
345    /// Returns whether this is a foreign item.
346    pub(crate) fn is_foreign_item(&self, item: DefId) -> bool {
347        self.with_cx(|tables, cx| {
348            let did = tables[item];
349            cx.is_foreign_item(did)
350        })
351    }
352
353    /// Returns the kind of a given foreign item.
354    pub(crate) fn foreign_item_kind(&self, def: ForeignDef) -> ForeignItemKind {
355        self.with_cx(|tables, cx| {
356            let def_id = tables[def.def_id()];
357            let def_kind = cx.foreign_item_kind(def_id);
358            match def_kind {
359                DefKind::Fn => ForeignItemKind::Fn(tables.fn_def(def_id)),
360                DefKind::Static { .. } => ForeignItemKind::Static(tables.static_def(def_id)),
361                DefKind::ForeignTy => {
362                    use rustc_public_bridge::context::TyHelpers;
363                    ForeignItemKind::Type(tables.intern_ty(cx.new_foreign(def_id)))
364                }
365                def_kind => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unexpected kind for a foreign item: {0:?}",
                def_kind)));
}unreachable!("Unexpected kind for a foreign item: {:?}", def_kind),
366            }
367        })
368    }
369
370    /// Returns the kind of a given algebraic data type.
371    pub(crate) fn adt_kind(&self, def: AdtDef) -> AdtKind {
372        self.with_cx(|tables, cx| cx.adt_kind(def.internal(tables, cx.tcx)).stable(tables, cx))
373    }
374
375    /// Returns if the ADT is a box.
376    pub(crate) fn adt_is_box(&self, def: AdtDef) -> bool {
377        self.with_cx(|tables, cx| cx.adt_is_box(def.internal(tables, cx.tcx)))
378    }
379
380    /// Returns whether this ADT is simd.
381    pub(crate) fn adt_is_simd(&self, def: AdtDef) -> bool {
382        self.with_cx(|tables, cx| cx.adt_is_simd(def.internal(tables, cx.tcx)))
383    }
384
385    /// Returns whether this definition is a C string.
386    pub(crate) fn adt_is_cstr(&self, def: AdtDef) -> bool {
387        self.with_cx(|tables, cx| cx.adt_is_cstr(def.0.internal(tables, cx.tcx)))
388    }
389
390    /// Returns the representation options for this ADT
391    pub(crate) fn adt_repr(&self, def: AdtDef) -> ReprOptions {
392        self.with_cx(|tables, cx| cx.adt_repr(def.internal(tables, cx.tcx)).stable(tables, cx))
393    }
394
395    /// Retrieve the function signature for the given generic arguments.
396    pub(crate) fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig {
397        self.with_cx(|tables, cx| {
398            let def_id = def.0.internal(tables, cx.tcx);
399            let args_ref = args.internal(tables, cx.tcx);
400            cx.fn_sig(def_id, args_ref).stable(tables, cx)
401        })
402    }
403
404    /// Retrieve the constness for the given function definition.
405    pub(crate) fn constness(&self, def: FnDef) -> Constness {
406        self.with_cx(|tables, cx| {
407            let def_id = def.0.internal(tables, cx.tcx);
408            cx.constness(def_id).stable(tables, cx)
409        })
410    }
411
412    /// Retrieve the asyncness for the given function definition.
413    pub(crate) fn asyncness(&self, def: FnDef) -> Asyncness {
414        self.with_cx(|tables, cx| {
415            let def_id = def.0.internal(tables, cx.tcx);
416            cx.asyncness(def_id).stable(tables, cx)
417        })
418    }
419
420    /// Retrieve the intrinsic definition if the item corresponds one.
421    pub(crate) fn intrinsic(&self, item: DefId) -> Option<IntrinsicDef> {
422        self.with_cx(|tables, cx| {
423            let def_id = item.internal(tables, cx.tcx);
424            cx.intrinsic(def_id).map(|_| IntrinsicDef(item))
425        })
426    }
427
428    /// Retrieve the plain function name of an intrinsic.
429    pub(crate) fn intrinsic_name(&self, def: IntrinsicDef) -> Symbol {
430        self.with_cx(|tables, cx| {
431            let def_id = def.0.internal(tables, cx.tcx);
432            cx.intrinsic_name(def_id)
433        })
434    }
435
436    /// Retrieve the closure signature for the given generic arguments.
437    pub(crate) fn closure_sig(&self, args: &GenericArgs) -> PolyFnSig {
438        self.with_cx(|tables, cx| {
439            let args_ref = args.internal(tables, cx.tcx);
440            cx.closure_sig(args_ref).stable(tables, cx)
441        })
442    }
443
444    /// The number of variants in this ADT.
445    pub(crate) fn adt_variants_len(&self, def: AdtDef) -> usize {
446        self.with_cx(|tables, cx| cx.adt_variants_len(def.internal(tables, cx.tcx)))
447    }
448
449    /// Discriminant for a given variant index of AdtDef.
450    pub(crate) fn adt_discr_for_variant(&self, adt: AdtDef, variant: VariantIdx) -> Discr {
451        self.with_cx(|tables, cx| {
452            cx.adt_discr_for_variant(adt.internal(tables, cx.tcx), variant.internal(tables, cx.tcx))
453                .stable(tables, cx)
454        })
455    }
456
457    /// Discriminant for a given variand index and args of a coroutine.
458    pub(crate) fn coroutine_discr_for_variant(
459        &self,
460        coroutine: CoroutineDef,
461        args: &GenericArgs,
462        variant: VariantIdx,
463    ) -> Discr {
464        self.with_cx(|tables, cx| {
465            let tcx = cx.tcx;
466            let def = coroutine.def_id().internal(tables, tcx);
467            let args_ref = args.internal(tables, tcx);
468            cx.coroutine_discr_for_variant(def, args_ref, variant.internal(tables, tcx))
469                .stable(tables, cx)
470        })
471    }
472
473    /// The name of a variant.
474    pub(crate) fn variant_name(&self, def: VariantDef) -> Symbol {
475        self.with_cx(|tables, cx| cx.variant_name(def.internal(tables, cx.tcx)))
476    }
477
478    pub(crate) fn variant_fields(&self, def: VariantDef) -> Vec<FieldDef> {
479        self.with_cx(|tables, cx| {
480            def.internal(tables, cx.tcx).fields.iter().map(|f| f.stable(tables, cx)).collect()
481        })
482    }
483
484    /// Evaluate constant as a target usize.
485    pub(crate) fn eval_target_usize(&self, mir_const: &MirConst) -> Result<u64, Error> {
486        self.with_cx(|tables, cx| {
487            let cnst = mir_const.internal(tables, cx.tcx);
488            cx.eval_target_usize(cnst)
489        })
490    }
491
492    pub(crate) fn eval_target_usize_ty(&self, ty_const: &TyConst) -> Result<u64, Error> {
493        self.with_cx(|tables, cx| {
494            let cnst = ty_const.internal(tables, cx.tcx);
495            cx.eval_target_usize_ty(cnst)
496        })
497    }
498
499    /// Create a new zero-sized constant.
500    pub(crate) fn try_new_const_zst(&self, ty: Ty) -> Result<MirConst, Error> {
501        self.with_cx(|tables, cx| {
502            let ty_internal = ty.internal(tables, cx.tcx);
503            cx.try_new_const_zst(ty_internal).map(|cnst| cnst.stable(tables, cx))
504        })
505    }
506
507    /// Create a new constant that represents the given string value.
508    pub(crate) fn new_const_str(&self, value: &str) -> MirConst {
509        self.with_cx(|tables, cx| cx.new_const_str(value).stable(tables, cx))
510    }
511
512    /// Create a new constant that represents the given boolean value.
513    pub(crate) fn new_const_bool(&self, value: bool) -> MirConst {
514        self.with_cx(|tables, cx| cx.new_const_bool(value).stable(tables, cx))
515    }
516
517    /// Create a new integer constant that represents the given value.
518    pub(crate) fn try_new_const_uint(
519        &self,
520        value: u128,
521        uint_ty: UintTy,
522    ) -> Result<MirConst, Error> {
523        self.with_cx(|tables, cx| {
524            let ty = cx.ty_new_uint(uint_ty.internal(tables, cx.tcx));
525            cx.try_new_const_uint(value, ty).map(|cnst| cnst.stable(tables, cx))
526        })
527    }
528
529    /// Create a new float constant that represents the given value.
530    /// The value is the binary representation of the float constant.
531    /// Example: `try_new_const_float(2.5_f32.to_bits() as u128, FloatTy::F32)`.
532    pub(crate) fn try_new_const_float(
533        &self,
534        value: u128,
535        float_ty: FloatTy,
536    ) -> Result<MirConst, Error> {
537        let mut tables = self.tables.borrow_mut();
538        let cx = &*self.cx.borrow();
539        let ty = cx.new_rigid_ty(RigidTy::Float(float_ty).internal(&mut *tables, cx.tcx));
540        // We use `try_new_const_uint` here since it is capable of constructing all scalars in the mir
541        // that are not pointer.
542        cx.try_new_const_uint(value, ty).map(|cnst| cnst.stable(&mut *tables, cx))
543    }
544
545    pub(crate) fn try_new_ty_const_uint(
546        &self,
547        value: u128,
548        uint_ty: UintTy,
549    ) -> Result<TyConst, Error> {
550        self.with_cx(|tables, cx| {
551            let ty = cx.ty_new_uint(uint_ty.internal(tables, cx.tcx));
552            cx.try_new_ty_const_uint(value, ty).map(|cnst| cnst.stable(tables, cx))
553        })
554    }
555
556    /// Create a new type from the given kind.
557    pub(crate) fn new_rigid_ty(&self, kind: RigidTy) -> Ty {
558        self.with_cx(|tables, cx| {
559            let internal_kind = kind.internal(tables, cx.tcx);
560            cx.new_rigid_ty(internal_kind).stable(tables, cx)
561        })
562    }
563
564    /// Create a new box type, `Box<T>`, for the given inner type `T`.
565    pub(crate) fn new_box_ty(&self, ty: Ty) -> Ty {
566        self.with_cx(|tables, cx| {
567            let inner = ty.internal(tables, cx.tcx);
568            cx.new_box_ty(inner).stable(tables, cx)
569        })
570    }
571
572    /// Returns the type of given crate item.
573    pub(crate) fn def_ty(&self, item: DefId) -> Ty {
574        self.with_cx(|tables, cx| {
575            let inner = item.internal(tables, cx.tcx);
576            cx.def_ty(inner).stable(tables, cx)
577        })
578    }
579
580    /// Returns the type of given definition instantiated with the given arguments.
581    pub(crate) fn def_ty_with_args(&self, item: DefId, args: &GenericArgs) -> Ty {
582        self.with_cx(|tables, cx| {
583            let inner = item.internal(tables, cx.tcx);
584            let args_ref = args.internal(tables, cx.tcx);
585            cx.def_ty_with_args(inner, args_ref).stable(tables, cx)
586        })
587    }
588
589    /// Returns literal value of a const as a string.
590    pub(crate) fn mir_const_pretty(&self, cnst: &MirConst) -> String {
591        self.with_cx(|tables, cx| cnst.internal(tables, cx.tcx).to_string())
592    }
593
594    /// `Span` of a `DefId`.
595    pub(crate) fn span_of_a_def(&self, def_id: DefId) -> Span {
596        self.with_cx(|tables, cx| {
597            let did = tables[def_id];
598            cx.span_of_a_def(did).stable(tables, cx)
599        })
600    }
601
602    pub(crate) fn ty_const_pretty(&self, ct: TyConstId) -> String {
603        self.with_cx(|tables, cx| cx.ty_const_pretty(tables.ty_consts[ct]))
604    }
605
606    /// Obtain the representation of a type.
607    pub(crate) fn ty_pretty(&self, ty: Ty) -> String {
608        self.with_cx(|tables, cx| cx.ty_pretty(tables.types[ty]))
609    }
610
611    /// Obtain the kind of a type.
612    pub(crate) fn ty_kind(&self, ty: Ty) -> TyKind {
613        self.with_cx(|tables, cx| cx.ty_kind(tables.types[ty]).stable(tables, cx))
614    }
615
616    /// Get the discriminant Ty for this Ty if there's one.
617    pub(crate) fn rigid_ty_discriminant_ty(&self, ty: &RigidTy) -> Ty {
618        self.with_cx(|tables, cx| {
619            let internal_kind = ty.internal(tables, cx.tcx);
620            cx.rigid_ty_discriminant_ty(internal_kind).stable(tables, cx)
621        })
622    }
623
624    /// Get the body of an Instance which is already monomorphized.
625    pub(crate) fn instance_body(&self, instance: InstanceDef) -> Option<Body> {
626        self.with_cx(|tables, cx| {
627            let instance = tables.instances[instance];
628            cx.instance_body(instance).map(|body| body.stable(tables, cx))
629        })
630    }
631
632    /// Get the instance type with generic instantiations applied and lifetimes erased.
633    pub(crate) fn instance_ty(&self, instance: InstanceDef) -> Ty {
634        self.with_cx(|tables, cx| {
635            let instance = tables.instances[instance];
636            cx.instance_ty(instance).stable(tables, cx)
637        })
638    }
639
640    /// Get the instantiation types.
641    pub(crate) fn instance_args(&self, def: InstanceDef) -> GenericArgs {
642        self.with_cx(|tables, cx| {
643            let instance = tables.instances[def];
644            cx.instance_args(instance).stable(tables, cx)
645        })
646    }
647
648    /// Get the instance.
649    pub(crate) fn instance_def_id(&self, instance: InstanceDef) -> DefId {
650        self.with_cx(|tables, cx| {
651            let instance = tables.instances[instance];
652            cx.instance_def_id(instance, tables)
653        })
654    }
655
656    /// Get the instance mangled name.
657    pub(crate) fn instance_mangled_name(&self, instance: InstanceDef) -> Symbol {
658        self.with_cx(|tables, cx| {
659            let instance = tables.instances[instance];
660            cx.instance_mangled_name(instance)
661        })
662    }
663
664    /// Check if this is an empty DropGlue shim.
665    pub(crate) fn is_empty_drop_shim(&self, def: InstanceDef) -> bool {
666        self.with_cx(|tables, cx| {
667            let instance = tables.instances[def];
668            cx.is_empty_drop_shim(instance)
669        })
670    }
671
672    /// Convert a non-generic crate item into an instance.
673    /// This function will panic if the item is generic.
674    pub(crate) fn mono_instance(&self, def_id: DefId) -> Instance {
675        self.with_cx(|tables, cx| {
676            let did = tables[def_id];
677            cx.mono_instance(did).stable(tables, cx)
678        })
679    }
680
681    /// Item requires monomorphization.
682    pub(crate) fn requires_monomorphization(&self, def_id: DefId) -> bool {
683        self.with_cx(|tables, cx| {
684            let did = tables[def_id];
685            cx.requires_monomorphization(did)
686        })
687    }
688
689    /// Resolve an instance from the given function definition and generic arguments.
690    pub(crate) fn resolve_instance(&self, def: FnDef, args: &GenericArgs) -> Option<Instance> {
691        self.with_cx(|tables, cx| {
692            let def_id = def.0.internal(tables, cx.tcx);
693            let args_ref = args.internal(tables, cx.tcx);
694            cx.resolve_instance(def_id, args_ref).map(|inst| inst.stable(tables, cx))
695        })
696    }
697
698    /// Resolve an instance for drop_in_place for the given type.
699    pub(crate) fn resolve_drop_in_place(&self, ty: Ty) -> Instance {
700        self.with_cx(|tables, cx| {
701            let internal_ty = ty.internal(tables, cx.tcx);
702
703            cx.resolve_drop_in_place(internal_ty).stable(tables, cx)
704        })
705    }
706
707    /// Resolve instance for a function pointer.
708    pub(crate) fn resolve_for_fn_ptr(&self, def: FnDef, args: &GenericArgs) -> Option<Instance> {
709        self.with_cx(|tables, cx| {
710            let def_id = def.0.internal(tables, cx.tcx);
711            let args_ref = args.internal(tables, cx.tcx);
712            cx.resolve_for_fn_ptr(def_id, args_ref).stable(tables, cx)
713        })
714    }
715
716    /// Resolve instance for a closure with the requested type.
717    pub(crate) fn resolve_closure(
718        &self,
719        def: ClosureDef,
720        args: &GenericArgs,
721        kind: ClosureKind,
722    ) -> Option<Instance> {
723        self.with_cx(|tables, cx| {
724            let def_id = def.0.internal(tables, cx.tcx);
725            let args_ref = args.internal(tables, cx.tcx);
726            let closure_kind = kind.internal(tables, cx.tcx);
727            cx.resolve_closure(def_id, args_ref, closure_kind).map(|inst| inst.stable(tables, cx))
728        })
729    }
730
731    /// Evaluate a static's initializer.
732    pub(crate) fn eval_static_initializer(&self, def: StaticDef) -> Result<Allocation, Error> {
733        self.with_cx(|tables, cx| {
734            let def_id = def.0.internal(tables, cx.tcx);
735
736            cx.eval_static_initializer(def_id).stable(tables, cx)
737        })
738    }
739
740    /// Try to evaluate an instance into a constant.
741    pub(crate) fn eval_instance(
742        &self,
743        def: InstanceDef,
744        const_ty: Ty,
745    ) -> Result<Allocation, Error> {
746        self.with_cx(|tables, cx| {
747            let instance = tables.instances[def];
748            let const_ty = const_ty.internal(tables, cx.tcx);
749            cx.eval_instance(instance)
750                .map(|const_val| alloc::try_new_allocation(const_ty, const_val, tables, cx))
751                .map_err(|e| e.stable(tables, cx))?
752        })
753    }
754
755    /// Retrieve global allocation for the given allocation ID.
756    pub(crate) fn global_alloc(&self, id: AllocId) -> GlobalAlloc {
757        self.with_cx(|tables, cx| {
758            let alloc_id = id.internal(tables, cx.tcx);
759            cx.global_alloc(alloc_id).stable(tables, cx)
760        })
761    }
762
763    /// Retrieve the id for the virtual table.
764    pub(crate) fn vtable_allocation(&self, global_alloc: &GlobalAlloc) -> Option<AllocId> {
765        self.with_cx(|tables, cx| {
766            let GlobalAlloc::VTable(ty, trait_ref) = global_alloc else {
767                return None;
768            };
769            let ty = ty.internal(tables, cx.tcx);
770            let trait_ref = trait_ref.internal(tables, cx.tcx);
771            let alloc_id = cx.vtable_allocation(ty, trait_ref);
772            Some(alloc_id.stable(tables, cx))
773        })
774    }
775
776    pub(crate) fn krate(&self, def_id: DefId) -> Crate {
777        self.with_cx(|tables, cx| smir_crate(cx, tables[def_id].krate))
778    }
779
780    pub(crate) fn instance_name(&self, def: InstanceDef, trimmed: bool) -> Symbol {
781        self.with_cx(|tables, cx| {
782            let instance = tables.instances[def];
783            cx.instance_name(instance, trimmed)
784        })
785    }
786
787    /// Return information about the target machine.
788    pub(crate) fn target_info(&self) -> MachineInfo {
789        self.with_cx(|tables, cx| MachineInfo {
790            endian: cx.target_endian().stable(tables, cx),
791            pointer_width: MachineSize::from_bits(cx.target_pointer_size()),
792        })
793    }
794
795    /// Get an instance ABI.
796    pub(crate) fn instance_abi(&self, def: InstanceDef) -> Result<FnAbi, Error> {
797        self.with_cx(|tables, cx| {
798            let instance = tables.instances[def];
799            cx.instance_abi(instance).map(|fn_abi| fn_abi.stable(tables, cx))
800        })
801    }
802
803    /// Get the ABI of a function pointer.
804    pub(crate) fn fn_ptr_abi(&self, fn_ptr: PolyFnSig) -> Result<FnAbi, Error> {
805        self.with_cx(|tables, cx| {
806            let sig = fn_ptr.internal(tables, cx.tcx);
807            cx.fn_ptr_abi(sig).map(|fn_abi| fn_abi.stable(tables, cx))
808        })
809    }
810
811    /// Get the layout of a type.
812    pub(crate) fn ty_layout(&self, ty: Ty) -> Result<Layout, Error> {
813        self.with_cx(|tables, cx| {
814            let internal_ty = ty.internal(tables, cx.tcx);
815            cx.ty_layout(internal_ty).map(|layout| layout.stable(tables, cx))
816        })
817    }
818
819    /// Get the layout shape.
820    pub(crate) fn layout_shape(&self, id: Layout) -> LayoutShape {
821        self.with_cx(|tables, cx| id.internal(tables, cx.tcx).0.stable(tables, cx))
822    }
823
824    /// Get a debug string representation of a place.
825    pub(crate) fn place_pretty(&self, place: &Place) -> String {
826        self.with_cx(|tables, cx| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}",
                place.internal(tables, cx.tcx)))
    })format!("{:?}", place.internal(tables, cx.tcx)))
827    }
828
829    /// Get the resulting type of binary operation.
830    pub(crate) fn binop_ty(&self, bin_op: BinOp, rhs: Ty, lhs: Ty) -> Ty {
831        self.with_cx(|tables, cx| {
832            let rhs_internal = rhs.internal(tables, cx.tcx);
833            let lhs_internal = lhs.internal(tables, cx.tcx);
834            let bin_op_internal = bin_op.internal(tables, cx.tcx);
835            cx.binop_ty(bin_op_internal, rhs_internal, lhs_internal).stable(tables, cx)
836        })
837    }
838
839    /// Get the resulting type of unary operation.
840    pub(crate) fn unop_ty(&self, un_op: UnOp, arg: Ty) -> Ty {
841        self.with_cx(|tables, cx| {
842            let un_op = un_op.internal(tables, cx.tcx);
843            let arg = arg.internal(tables, cx.tcx);
844            cx.unop_ty(un_op, arg).stable(tables, cx)
845        })
846    }
847
848    /// Get the associated item of a definition if it is one.
849    pub(crate) fn associated_item(&self, def_id: DefId) -> Option<AssocItem> {
850        self.with_cx(|tables, cx| {
851            let did = tables[def_id];
852            cx.associated_item(did).map(|assoc| assoc.stable(tables, cx))
853        })
854    }
855
856    /// Get all associated items of a definition.
857    pub(crate) fn associated_items(&self, def_id: DefId) -> AssocItems {
858        self.with_cx(|tables, cx| {
859            let did = tables[def_id];
860            cx.associated_items(did).iter().map(|assoc| assoc.stable(tables, cx)).collect()
861        })
862    }
863
864    /// Get all vtable entries of a trait.
865    pub(crate) fn vtable_entries(&self, trait_ref: &TraitRef) -> Vec<VtblEntry> {
866        self.with_cx(|tables, cx| {
867            cx.vtable_entries(trait_ref.internal(tables, cx.tcx))
868                .iter()
869                .map(|v| v.stable(tables, cx))
870                .collect()
871        })
872    }
873
874    /// Returns the vtable entry at the given index.
875    ///
876    /// Returns `None` if the index is out of bounds.
877    pub(crate) fn vtable_entry(&self, trait_ref: &TraitRef, idx: usize) -> Option<VtblEntry> {
878        self.with_cx(|tables, cx| {
879            cx.vtable_entry(trait_ref.internal(tables, cx.tcx), idx).stable(tables, cx)
880        })
881    }
882}
883
884// A thread local variable that stores a pointer to [`CompilerInterface`].
885static TLV: ::scoped_tls::ScopedKey<Cell<*const ()>> =
    ::scoped_tls::ScopedKey {
        inner: {
            const FOO: ::std::thread::LocalKey<::std::cell::Cell<*const ()>> =
                {
                    const __RUST_STD_INTERNAL_INIT: ::std::cell::Cell<*const ()>
                        =
                        { ::std::cell::Cell::new(::std::ptr::null()) };
                    unsafe {
                        ::std::thread::LocalKey::new(const {
                                    if ::std::mem::needs_drop::<::std::cell::Cell<*const ()>>()
                                        {
                                        |_|
                                            {
                                                #[thread_local]
                                                static __RUST_STD_INTERNAL_VAL:
                                                    ::std::thread::local_impl::EagerStorage<::std::cell::Cell<*const ()>>
                                                    =
                                                    ::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                                __RUST_STD_INTERNAL_VAL.get()
                                            }
                                    } else {
                                        |_|
                                            {
                                                #[thread_local]
                                                static __RUST_STD_INTERNAL_VAL: ::std::cell::Cell<*const ()>
                                                    =
                                                    __RUST_STD_INTERNAL_INIT;
                                                &__RUST_STD_INTERNAL_VAL
                                            }
                                    }
                                })
                    }
                };
            &FOO
        },
        _marker: ::std::marker::PhantomData,
    };scoped_tls::scoped_thread_local!(static TLV: Cell<*const ()>);
886
887// remove this cfg when we have a stable driver.
888#[cfg(feature = "rustc_internal")]
889pub(crate) fn run<'tcx, F, T>(interface: &CompilerInterface<'tcx>, f: F) -> Result<T, Error>
890where
891    F: FnOnce() -> T,
892{
893    if TLV.is_set() {
894        Err(Error::from("rustc_public already running"))
895    } else {
896        let ptr: *const () = (&raw const interface) as _;
897        TLV.set(&Cell::new(ptr), || Ok(f()))
898    }
899}
900
901/// Execute the given function with access the [`CompilerInterface`].
902///
903/// I.e., This function will load the current interface and calls a function with it.
904/// Do not nest these, as that will ICE.
905pub(crate) fn with<R>(f: impl for<'tcx> FnOnce(&CompilerInterface<'tcx>) -> R) -> R {
906    if !TLV.is_set() {
    ::core::panicking::panic("assertion failed: TLV.is_set()")
};assert!(TLV.is_set());
907    TLV.with(|tlv| {
908        let ptr = tlv.get();
909        if !!ptr.is_null() {
    ::core::panicking::panic("assertion failed: !ptr.is_null()")
};assert!(!ptr.is_null());
910        f(unsafe { *(ptr as *const &CompilerInterface<'_>) })
911    })
912}
913
914fn smir_crate<'tcx>(
915    cx: &CompilerCtxt<'tcx, BridgeTys>,
916    crate_num: rustc_span::def_id::CrateNum,
917) -> Crate {
918    let name = cx.crate_name(crate_num);
919    let is_local = cx.crate_is_local(crate_num);
920    let id = CrateNum(cx.crate_num_id(crate_num), ThreadLocalIndex);
921    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_public/src/compiler_interface.rs:921",
                        "rustc_public::compiler_interface", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_public/src/compiler_interface.rs"),
                        ::tracing_core::__macro_support::Option::Some(921u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_public::compiler_interface"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("name")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("name");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("crate_num")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("crate_num");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("smir_crate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&crate_num)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?name, ?crate_num, "smir_crate");
922    Crate { id, name, is_local }
923}