rustc_public_bridge/context/
impls.rs

1//! Implementation of CompilerCtxt.
2
3#![allow(rustc::usage_of_qualified_ty)]
4
5use std::iter;
6
7use rustc_abi::{Endian, Layout, ReprOptions};
8use rustc_hir::def::DefKind;
9use rustc_hir::{Attribute, LangItem};
10use rustc_middle::mir::interpret::{AllocId, ConstAllocation, ErrorHandled, GlobalAlloc, Scalar};
11use rustc_middle::mir::{BinOp, Body, Const as MirConst, ConstValue, UnOp};
12use rustc_middle::ty::layout::{FnAbiOf, LayoutOf};
13use rustc_middle::ty::print::{
14    with_forced_trimmed_paths, with_no_trimmed_paths, with_resolve_crate_name,
15};
16use rustc_middle::ty::util::Discr;
17use rustc_middle::ty::{
18    AdtDef, AdtKind, AssocItem, Binder, ClosureKind, CoroutineArgsExt, EarlyBinder,
19    ExistentialTraitRef, FnSig, GenericArgsRef, Instance, InstanceKind, IntrinsicDef, List,
20    PolyFnSig, ScalarInt, TraitDef, TraitRef, Ty, TyCtxt, TyKind, TypeVisitableExt, UintTy,
21    ValTree, VariantDef,
22};
23use rustc_middle::{mir, ty};
24use rustc_session::cstore::ForeignModule;
25use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE};
26use rustc_span::{Span, Symbol};
27use rustc_target::callconv::FnAbi;
28
29use super::{AllocRangeHelpers, CompilerCtxt, TyHelpers, TypingEnvHelpers};
30use crate::builder::BodyBuilder;
31use crate::{Bridge, Error, Tables, filter_def_ids};
32
33impl<'tcx, B: Bridge> TyHelpers<'tcx> for CompilerCtxt<'tcx, B> {
34    fn new_foreign(&self, def_id: DefId) -> ty::Ty<'tcx> {
35        ty::Ty::new_foreign(self.tcx, def_id)
36    }
37}
38
39impl<'tcx, B: Bridge> TypingEnvHelpers<'tcx> for CompilerCtxt<'tcx, B> {
40    fn fully_monomorphized(&self) -> ty::TypingEnv<'tcx> {
41        ty::TypingEnv::fully_monomorphized()
42    }
43}
44
45impl<'tcx, B: Bridge> AllocRangeHelpers<'tcx> for CompilerCtxt<'tcx, B> {
46    fn alloc_range(
47        &self,
48        offset: rustc_abi::Size,
49        size: rustc_abi::Size,
50    ) -> mir::interpret::AllocRange {
51        rustc_middle::mir::interpret::alloc_range(offset, size)
52    }
53}
54
55impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> {
56    pub fn lift<T: ty::Lift<TyCtxt<'tcx>>>(&self, value: T) -> Option<T::Lifted> {
57        self.tcx.lift(value)
58    }
59
60    pub fn adt_def(&self, def_id: DefId) -> AdtDef<'tcx> {
61        self.tcx.adt_def(def_id)
62    }
63
64    pub fn coroutine_movability(&self, def_id: DefId) -> ty::Movability {
65        self.tcx.coroutine_movability(def_id)
66    }
67
68    pub fn valtree_to_const_val(&self, key: ty::Value<'tcx>) -> ConstValue {
69        self.tcx.valtree_to_const_val(key)
70    }
71
72    /// Return whether the instance as a body available.
73    ///
74    /// Items and intrinsics may have a body available from its definition.
75    /// Shims body may be generated depending on their type.
76    pub(crate) fn instance_has_body(&self, instance: Instance<'tcx>) -> bool {
77        let def_id = instance.def_id();
78        self.item_has_body(def_id)
79            || !matches!(
80                instance.def,
81                ty::InstanceKind::Virtual(..)
82                    | ty::InstanceKind::Intrinsic(..)
83                    | ty::InstanceKind::Item(..)
84            )
85    }
86
87    /// Return whether the item has a body defined by the user.
88    ///
89    /// Note that intrinsics may have a placeholder body that shouldn't be used in practice.
90    /// In rustc_public, we handle this case as if the body is not available.
91    pub(crate) fn item_has_body(&self, def_id: DefId) -> bool {
92        let must_override = if let Some(intrinsic) = self.tcx.intrinsic(def_id) {
93            intrinsic.must_be_overridden
94        } else {
95            false
96        };
97        // FIXME: A good reason to make is_mir_available or mir_keys change behavior
98        !must_override && self.tcx.is_mir_available(def_id) && !self.tcx.is_trivial_const(def_id)
99    }
100
101    fn filter_fn_def(&self, def_id: DefId) -> Option<DefId> {
102        if matches!(self.tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
103            Some(def_id)
104        } else {
105            None
106        }
107    }
108
109    fn filter_static_def(&self, def_id: DefId) -> Option<DefId> {
110        matches!(self.tcx.def_kind(def_id), DefKind::Static { .. }).then(|| def_id)
111    }
112
113    pub fn target_endian(&self) -> Endian {
114        self.tcx.data_layout.endian
115    }
116
117    pub fn target_pointer_size(&self) -> usize {
118        self.tcx.data_layout.pointer_size().bits().try_into().unwrap()
119    }
120
121    pub fn entry_fn(&self) -> Option<DefId> {
122        Some(self.tcx.entry_fn(())?.0)
123    }
124
125    /// Retrieve all items of the local crate that have a MIR associated with them.
126    pub fn all_local_items(&self) -> Vec<DefId> {
127        self.tcx.mir_keys(()).iter().map(|item| item.to_def_id()).collect()
128    }
129
130    /// Retrieve the body of a function.
131    /// This function will panic if the body is not available.
132    pub fn mir_body(&self, item: DefId) -> &'tcx Body<'tcx> {
133        self.tcx.instance_mir(InstanceKind::Item(item))
134    }
135
136    /// Check whether the body of a function is available.
137    pub fn has_body(&self, def: DefId) -> bool {
138        self.item_has_body(def)
139    }
140
141    pub fn foreign_modules(&self, crate_num: CrateNum) -> Vec<DefId> {
142        self.tcx.foreign_modules(crate_num).keys().map(|mod_def_id| *mod_def_id).collect()
143    }
144
145    /// Retrieve all functions defined in this crate.
146    pub fn crate_functions(&self, crate_num: CrateNum) -> Vec<DefId> {
147        filter_def_ids(self.tcx, crate_num, |def_id| self.filter_fn_def(def_id))
148    }
149
150    /// Retrieve all static items defined in this crate.
151    pub fn crate_statics(&self, crate_num: CrateNum) -> Vec<DefId> {
152        filter_def_ids(self.tcx, crate_num, |def_id| self.filter_static_def(def_id))
153    }
154
155    pub fn foreign_module(&self, mod_def: DefId) -> &ForeignModule {
156        self.tcx.foreign_modules(mod_def.krate).get(&mod_def).unwrap()
157    }
158
159    pub fn foreign_items(&self, mod_def: DefId) -> Vec<DefId> {
160        self.tcx
161            .foreign_modules(mod_def.krate)
162            .get(&mod_def)
163            .unwrap()
164            .foreign_items
165            .iter()
166            .map(|item_def| *item_def)
167            .collect()
168    }
169
170    pub fn all_trait_decls(&self) -> impl Iterator<Item = DefId> {
171        self.tcx.all_traits_including_private()
172    }
173
174    pub fn trait_decls(&self, crate_num: CrateNum) -> Vec<DefId> {
175        self.tcx.traits(crate_num).iter().map(|trait_def_id| *trait_def_id).collect()
176    }
177
178    pub fn trait_decl(&self, trait_def: DefId) -> &'tcx TraitDef {
179        self.tcx.trait_def(trait_def)
180    }
181
182    pub fn all_trait_impls(&self) -> Vec<DefId> {
183        iter::once(LOCAL_CRATE)
184            .chain(self.tcx.crates(()).iter().copied())
185            .flat_map(|cnum| self.tcx.trait_impls_in_crate(cnum).iter())
186            .map(|impl_def_id| *impl_def_id)
187            .collect()
188    }
189
190    pub fn trait_impls(&self, crate_num: CrateNum) -> Vec<DefId> {
191        self.tcx.trait_impls_in_crate(crate_num).iter().map(|impl_def_id| *impl_def_id).collect()
192    }
193
194    pub fn trait_impl(&self, impl_def: DefId) -> EarlyBinder<'tcx, TraitRef<'tcx>> {
195        self.tcx.impl_trait_ref(impl_def)
196    }
197
198    pub fn generics_of(&self, def_id: DefId) -> &'tcx ty::Generics {
199        self.tcx.generics_of(def_id)
200    }
201
202    pub fn predicates_of(
203        &self,
204        def_id: DefId,
205    ) -> (Option<DefId>, Vec<(ty::PredicateKind<'tcx>, Span)>) {
206        let ty::GenericPredicates { parent, predicates } = self.tcx.predicates_of(def_id);
207        (
208            parent,
209            predicates
210                .iter()
211                .map(|(clause, span)| (clause.as_predicate().kind().skip_binder(), *span))
212                .collect(),
213        )
214    }
215
216    pub fn explicit_predicates_of(
217        &self,
218        def_id: DefId,
219    ) -> (Option<DefId>, Vec<(ty::PredicateKind<'tcx>, Span)>) {
220        let ty::GenericPredicates { parent, predicates } = self.tcx.explicit_predicates_of(def_id);
221        (
222            parent,
223            predicates
224                .iter()
225                .map(|(clause, span)| (clause.as_predicate().kind().skip_binder(), *span))
226                .collect(),
227        )
228    }
229
230    pub fn crate_name(&self, crate_num: CrateNum) -> String {
231        self.tcx.crate_name(crate_num).to_string()
232    }
233
234    pub fn crate_is_local(&self, crate_num: CrateNum) -> bool {
235        crate_num == LOCAL_CRATE
236    }
237
238    pub fn crate_num_id(&self, crate_num: CrateNum) -> usize {
239        crate_num.into()
240    }
241
242    pub fn local_crate_num(&self) -> CrateNum {
243        LOCAL_CRATE
244    }
245
246    /// Retrieve a list of all external crates.
247    pub fn external_crates(&self) -> Vec<CrateNum> {
248        self.tcx.crates(()).iter().map(|crate_num| *crate_num).collect()
249    }
250
251    /// Find a crate with the given name.
252    pub fn find_crates(&self, name: &str) -> Vec<CrateNum> {
253        let crates: Vec<CrateNum> = [LOCAL_CRATE]
254            .iter()
255            .chain(self.tcx.crates(()).iter())
256            .filter_map(|crate_num| {
257                let crate_name = self.tcx.crate_name(*crate_num).to_string();
258                (name == crate_name).then(|| *crate_num)
259            })
260            .collect();
261        crates
262    }
263
264    /// Returns the name of given `DefId`.
265    pub fn def_name(&self, def_id: DefId, trimmed: bool) -> String {
266        if trimmed {
267            with_forced_trimmed_paths!(self.tcx.def_path_str(def_id))
268        } else {
269            // For local definitions, we need to prepend with crate name.
270            with_resolve_crate_name!(with_no_trimmed_paths!(self.tcx.def_path_str(def_id)))
271        }
272    }
273
274    /// Returns the parent of the given `DefId`.
275    pub fn def_parent(&self, def_id: DefId) -> Option<DefId> {
276        self.tcx.opt_parent(def_id)
277    }
278
279    /// Return registered tool attributes with the given attribute name.
280    ///
281    /// FIXME(jdonszelmann): may panic on non-tool attributes. After more attribute work, non-tool
282    /// attributes will simply return an empty list.
283    ///
284    /// Single segmented name like `#[clippy]` is specified as `&["clippy".to_string()]`.
285    /// Multi-segmented name like `#[rustfmt::skip]` is specified as `&["rustfmt".to_string(), "skip".to_string()]`.
286    pub fn tool_attrs(&self, def_id: DefId, attr: &[String]) -> Vec<(String, Span)> {
287        let attr_name: Vec<_> = attr.iter().map(|seg| Symbol::intern(&seg)).collect();
288        self.tcx
289            .get_attrs_by_path(def_id, &attr_name)
290            .filter_map(|attribute| {
291                if let Attribute::Unparsed(u) = attribute {
292                    let attr_str = rustc_hir_pretty::attribute_to_string(&self.tcx, attribute);
293                    Some((attr_str, u.span))
294                } else {
295                    None
296                }
297            })
298            .collect()
299    }
300
301    /// Get all tool attributes of a definition.
302    pub fn all_tool_attrs(&self, did: DefId) -> Vec<(String, Span)> {
303        let attrs_iter = if let Some(did) = did.as_local() {
304            self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(did)).iter()
305        } else {
306            self.tcx.attrs_for_def(did).iter()
307        };
308        attrs_iter
309            .filter_map(|attribute| {
310                if let Attribute::Unparsed(u) = attribute {
311                    let attr_str = rustc_hir_pretty::attribute_to_string(&self.tcx, attribute);
312                    Some((attr_str, u.span))
313                } else {
314                    None
315                }
316            })
317            .collect()
318    }
319
320    /// Returns printable, human readable form of `Span`.
321    pub fn span_to_string(&self, span: Span) -> String {
322        self.tcx.sess.source_map().span_to_diagnostic_string(span)
323    }
324
325    /// Return filename from given `Span`, for diagnostic purposes.
326    pub fn get_filename(&self, span: Span) -> String {
327        self.tcx.sess.source_map().span_to_filename(span).prefer_local_unconditionally().to_string()
328    }
329
330    /// Return lines corresponding to this `Span`.
331    pub fn get_lines(&self, span: Span) -> (usize, usize, usize, usize) {
332        let lines = &self.tcx.sess.source_map().span_to_location_info(span);
333        (lines.1, lines.2, lines.3, lines.4)
334    }
335
336    /// Returns the `kind` of given `DefId`.
337    pub fn def_kind(&self, item: DefId) -> DefKind {
338        self.tcx.def_kind(item)
339    }
340
341    /// Returns whether this is a foreign item.
342    pub fn is_foreign_item(&self, item: DefId) -> bool {
343        self.tcx.is_foreign_item(item)
344    }
345
346    /// Returns the kind of a given foreign item.
347    pub fn foreign_item_kind(&self, def_id: DefId) -> DefKind {
348        self.tcx.def_kind(def_id)
349    }
350
351    /// Returns the kind of a given algebraic data type.
352    pub fn adt_kind(&self, def: AdtDef<'tcx>) -> AdtKind {
353        def.adt_kind()
354    }
355
356    /// Returns if the ADT is a box.
357    pub fn adt_is_box(&self, def: AdtDef<'tcx>) -> bool {
358        def.is_box()
359    }
360
361    /// Returns whether this ADT is simd.
362    pub fn adt_is_simd(&self, def: AdtDef<'tcx>) -> bool {
363        def.repr().simd()
364    }
365
366    /// Returns whether this definition is a C string.
367    pub fn adt_is_cstr(&self, def_id: DefId) -> bool {
368        self.tcx.is_lang_item(def_id, LangItem::CStr)
369    }
370
371    /// Returns the representation options for this ADT.
372    pub fn adt_repr(&self, def: AdtDef<'tcx>) -> ReprOptions {
373        def.repr()
374    }
375
376    /// Retrieve the function signature for the given generic arguments.
377    pub fn fn_sig(
378        &self,
379        def_id: DefId,
380        args_ref: GenericArgsRef<'tcx>,
381    ) -> Binder<'tcx, FnSig<'tcx>> {
382        let sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args_ref);
383        sig
384    }
385
386    /// Retrieve the intrinsic definition if the item corresponds one.
387    pub fn intrinsic(&self, def_id: DefId) -> Option<IntrinsicDef> {
388        let intrinsic = self.tcx.intrinsic_raw(def_id);
389        intrinsic
390    }
391
392    /// Retrieve the plain function name of an intrinsic.
393    pub fn intrinsic_name(&self, def_id: DefId) -> String {
394        self.tcx.intrinsic(def_id).unwrap().name.to_string()
395    }
396
397    /// Retrieve the closure signature for the given generic arguments.
398    pub fn closure_sig(&self, args_ref: GenericArgsRef<'tcx>) -> Binder<'tcx, FnSig<'tcx>> {
399        args_ref.as_closure().sig()
400    }
401
402    /// The number of variants in this ADT.
403    pub fn adt_variants_len(&self, def: AdtDef<'tcx>) -> usize {
404        def.variants().len()
405    }
406
407    /// Discriminant for a given variant index of AdtDef.
408    pub fn adt_discr_for_variant(
409        &self,
410        adt: AdtDef<'tcx>,
411        variant: rustc_abi::VariantIdx,
412    ) -> Discr<'tcx> {
413        adt.discriminant_for_variant(self.tcx, variant)
414    }
415
416    /// Discriminant for a given variand index and args of a coroutine.
417    pub fn coroutine_discr_for_variant(
418        &self,
419        coroutine: DefId,
420        args: GenericArgsRef<'tcx>,
421        variant: rustc_abi::VariantIdx,
422    ) -> Discr<'tcx> {
423        args.as_coroutine().discriminant_for_variant(coroutine, self.tcx, variant)
424    }
425
426    /// The name of a variant.
427    pub fn variant_name(&self, def: &'tcx VariantDef) -> String {
428        def.name.to_string()
429    }
430
431    /// Evaluate constant as a target usize.
432    pub fn eval_target_usize(&self, cnst: MirConst<'tcx>) -> Result<u64, B::Error> {
433        use crate::context::TypingEnvHelpers;
434        cnst.try_eval_target_usize(self.tcx, self.fully_monomorphized())
435            .ok_or_else(|| B::Error::new(format!("Const `{cnst:?}` cannot be encoded as u64")))
436    }
437
438    pub fn eval_target_usize_ty(&self, cnst: ty::Const<'tcx>) -> Result<u64, B::Error> {
439        cnst.try_to_target_usize(self.tcx)
440            .ok_or_else(|| B::Error::new(format!("Const `{cnst:?}` cannot be encoded as u64")))
441    }
442
443    pub fn try_new_const_zst(&self, ty_internal: Ty<'tcx>) -> Result<MirConst<'tcx>, B::Error> {
444        let size = self
445            .tcx
446            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))
447            .map_err(|err| {
448                B::Error::new(format!(
449                    "Cannot create a zero-sized constant for type `{ty_internal}`: {err}"
450                ))
451            })?
452            .size;
453        if size.bytes() != 0 {
454            return Err(B::Error::new(format!(
455                "Cannot create a zero-sized constant for type `{ty_internal}`: \
456                Type `{ty_internal}` has {} bytes",
457                size.bytes()
458            )));
459        }
460
461        Ok(MirConst::Ty(ty_internal, self.const_zero_sized(ty_internal)))
462    }
463
464    pub fn const_zero_sized(&self, ty_internal: Ty<'tcx>) -> ty::Const<'tcx> {
465        ty::Const::zero_sized(self.tcx, ty_internal)
466    }
467
468    /// Create a new constant that represents the given string value.
469    pub fn new_const_str(&self, value: &str) -> MirConst<'tcx> {
470        let ty = Ty::new_static_str(self.tcx);
471        let bytes = value.as_bytes();
472        let valtree = ValTree::from_raw_bytes(self.tcx, bytes);
473        let cv = ty::Value { ty, valtree };
474        let val = self.tcx.valtree_to_const_val(cv);
475        MirConst::from_value(val, ty)
476    }
477
478    /// Create a new constant that represents the given boolean value.
479    pub fn new_const_bool(&self, value: bool) -> MirConst<'tcx> {
480        MirConst::from_bool(self.tcx, value)
481    }
482
483    pub fn try_new_const_uint(
484        &self,
485        value: u128,
486        ty_internal: Ty<'tcx>,
487    ) -> Result<MirConst<'tcx>, B::Error> {
488        let size = self
489            .tcx
490            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))
491            .unwrap()
492            .size;
493        let scalar = ScalarInt::try_from_uint(value, size).ok_or_else(|| {
494            B::Error::new(format!("Value overflow: cannot convert `{value}` to `{ty_internal}`."))
495        })?;
496        Ok(self.mir_const_from_scalar(Scalar::Int(scalar), ty_internal))
497    }
498
499    pub fn try_new_ty_const_uint(
500        &self,
501        value: u128,
502        ty_internal: Ty<'tcx>,
503    ) -> Result<ty::Const<'tcx>, B::Error> {
504        let size = self
505            .tcx
506            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))
507            .unwrap()
508            .size;
509        let scalar = ScalarInt::try_from_uint(value, size).ok_or_else(|| {
510            B::Error::new(format!("Value overflow: cannot convert `{value}` to `{ty_internal}`."))
511        })?;
512
513        Ok(self.ty_const_new_value(ValTree::from_scalar_int(self.tcx, scalar), ty_internal))
514    }
515
516    pub fn ty_new_uint(&self, ty: UintTy) -> Ty<'tcx> {
517        Ty::new_uint(self.tcx, ty)
518    }
519
520    pub fn mir_const_from_scalar(&self, s: Scalar, ty: Ty<'tcx>) -> MirConst<'tcx> {
521        MirConst::from_scalar(self.tcx, s, ty)
522    }
523
524    pub fn ty_const_new_value(&self, valtree: ValTree<'tcx>, ty: Ty<'tcx>) -> ty::Const<'tcx> {
525        ty::Const::new_value(self.tcx, valtree, ty)
526    }
527
528    pub fn ty_valtree_from_scalar_int(&self, i: ScalarInt) -> ValTree<'tcx> {
529        ValTree::from_scalar_int(self.tcx, i)
530    }
531
532    /// Create a new type from the given kind.
533    pub fn new_rigid_ty(&self, internal_kind: TyKind<'tcx>) -> Ty<'tcx> {
534        self.tcx.mk_ty_from_kind(internal_kind)
535    }
536
537    /// Create a new box type, `Box<T>`, for the given inner type `T`.
538    pub fn new_box_ty(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
539        ty::Ty::new_box(self.tcx, ty)
540    }
541
542    /// Returns the type of given crate item.
543    pub fn def_ty(&self, item: DefId) -> Ty<'tcx> {
544        self.tcx.type_of(item).instantiate_identity()
545    }
546
547    /// Returns the type of given definition instantiated with the given arguments.
548    pub fn def_ty_with_args(&self, item: DefId, args_ref: GenericArgsRef<'tcx>) -> Ty<'tcx> {
549        let def_ty = self.tcx.type_of(item);
550        self.tcx.instantiate_and_normalize_erasing_regions(
551            args_ref,
552            self.fully_monomorphized(),
553            def_ty,
554        )
555    }
556
557    /// `Span` of an item.
558    pub fn span_of_an_item(&self, def_id: DefId) -> Span {
559        self.tcx.def_span(def_id)
560    }
561
562    pub fn ty_const_pretty(&self, ct: ty::Const<'tcx>) -> String {
563        ct.to_string()
564    }
565
566    /// Obtain the representation of a type.
567    pub fn ty_pretty(&self, ty: Ty<'tcx>) -> String {
568        ty.to_string()
569    }
570
571    /// Obtain the kind of a type.
572    pub fn ty_kind(&self, ty: Ty<'tcx>) -> &'tcx TyKind<'tcx> {
573        ty.kind()
574    }
575
576    /// Get the discriminant Ty for this Ty if there's one.
577    pub fn rigid_ty_discriminant_ty(&self, internal_kind: TyKind<'tcx>) -> Ty<'tcx> {
578        let internal_ty = self.tcx.mk_ty_from_kind(internal_kind);
579        internal_ty.discriminant_ty(self.tcx)
580    }
581
582    /// Get the body of an Instance which is already monomorphized.
583    pub fn instance_body(&self, instance: ty::Instance<'tcx>) -> Option<Body<'tcx>> {
584        self.instance_has_body(instance).then(|| BodyBuilder::new(self.tcx, instance).build())
585    }
586
587    /// Get the instance type with generic instantiations applied and lifetimes erased.
588    pub fn instance_ty(&self, instance: ty::Instance<'tcx>) -> Ty<'tcx> {
589        assert!(!instance.has_non_region_param(), "{instance:?} needs further instantiation");
590        instance.ty(self.tcx, self.fully_monomorphized())
591    }
592
593    /// Get the instantiation types.
594    pub fn instance_args(&self, instance: ty::Instance<'tcx>) -> GenericArgsRef<'tcx> {
595        instance.args
596    }
597
598    /// Get an instance ABI.
599    pub fn instance_abi(
600        &self,
601        instance: ty::Instance<'tcx>,
602    ) -> Result<&FnAbi<'tcx, Ty<'tcx>>, B::Error> {
603        Ok(self.fn_abi_of_instance(instance, List::empty())?)
604    }
605
606    /// Get the ABI of a function pointer.
607    pub fn fn_ptr_abi(&self, sig: PolyFnSig<'tcx>) -> Result<&FnAbi<'tcx, Ty<'tcx>>, B::Error> {
608        Ok(self.fn_abi_of_fn_ptr(sig, List::empty())?)
609    }
610
611    /// Get the instance.
612    pub fn instance_def_id(
613        &self,
614        instances: ty::Instance<'tcx>,
615        tables: &mut Tables<'_, B>,
616    ) -> B::DefId {
617        let def_id = instances.def_id();
618        tables.create_def_id(def_id)
619    }
620
621    /// Get the instance mangled name.
622    pub fn instance_mangled_name(&self, instance: ty::Instance<'tcx>) -> String {
623        self.tcx.symbol_name(instance).name.to_string()
624    }
625
626    /// Check if this is an empty DropGlue shim.
627    pub fn is_empty_drop_shim(&self, instance: ty::Instance<'tcx>) -> bool {
628        matches!(instance.def, ty::InstanceKind::DropGlue(_, None))
629    }
630
631    /// Convert a non-generic crate item into an instance.
632    /// This function will panic if the item is generic.
633    pub fn mono_instance(&self, def_id: DefId) -> Instance<'tcx> {
634        Instance::mono(self.tcx, def_id)
635    }
636
637    /// Item requires monomorphization.
638    pub fn requires_monomorphization(&self, def_id: DefId) -> bool {
639        let generics = self.tcx.generics_of(def_id);
640        let result = generics.requires_monomorphization(self.tcx);
641        result
642    }
643
644    /// Resolve an instance from the given function definition and generic arguments.
645    pub fn resolve_instance(
646        &self,
647        def_id: DefId,
648        args_ref: GenericArgsRef<'tcx>,
649    ) -> Option<Instance<'tcx>> {
650        match Instance::try_resolve(self.tcx, self.fully_monomorphized(), def_id, args_ref) {
651            Ok(Some(instance)) => Some(instance),
652            Ok(None) | Err(_) => None,
653        }
654    }
655
656    /// Resolve an instance for drop_in_place for the given type.
657    pub fn resolve_drop_in_place(&self, internal_ty: Ty<'tcx>) -> Instance<'tcx> {
658        let instance = Instance::resolve_drop_in_place(self.tcx, internal_ty);
659        instance
660    }
661
662    /// Resolve instance for a function pointer.
663    pub fn resolve_for_fn_ptr(
664        &self,
665        def_id: DefId,
666        args_ref: GenericArgsRef<'tcx>,
667    ) -> Option<Instance<'tcx>> {
668        Instance::resolve_for_fn_ptr(self.tcx, self.fully_monomorphized(), def_id, args_ref)
669    }
670
671    /// Resolve instance for a closure with the requested type.
672    pub fn resolve_closure(
673        &self,
674        def_id: DefId,
675        args_ref: GenericArgsRef<'tcx>,
676        closure_kind: ClosureKind,
677    ) -> Option<Instance<'tcx>> {
678        Some(Instance::resolve_closure(self.tcx, def_id, args_ref, closure_kind))
679    }
680
681    /// Try to evaluate an instance into a constant.
682    pub fn eval_instance(&self, instance: ty::Instance<'tcx>) -> Result<ConstValue, ErrorHandled> {
683        self.tcx.const_eval_instance(
684            self.fully_monomorphized(),
685            instance,
686            self.tcx.def_span(instance.def_id()),
687        )
688    }
689
690    /// Evaluate a static's initializer.
691    pub fn eval_static_initializer(
692        &self,
693        def_id: DefId,
694    ) -> Result<ConstAllocation<'tcx>, ErrorHandled> {
695        self.tcx.eval_static_initializer(def_id)
696    }
697
698    /// Retrieve global allocation for the given allocation ID.
699    pub fn global_alloc(&self, alloc_id: AllocId) -> GlobalAlloc<'tcx> {
700        self.tcx.global_alloc(alloc_id)
701    }
702
703    /// Retrieve the id for the virtual table.
704    pub fn vtable_allocation(
705        &self,
706        ty: Ty<'tcx>,
707        trait_ref: Option<Binder<'tcx, ExistentialTraitRef<'tcx>>>,
708    ) -> AllocId {
709        let alloc_id = self.tcx.vtable_allocation((
710            ty,
711            trait_ref.map(|principal| self.tcx.instantiate_bound_regions_with_erased(principal)),
712        ));
713        alloc_id
714    }
715
716    /// Retrieve the instance name for diagnostic messages.
717    ///
718    /// This will return the specialized name, e.g., `Vec<char>::new`.
719    pub fn instance_name(&self, instance: ty::Instance<'tcx>, trimmed: bool) -> String {
720        if trimmed {
721            with_forced_trimmed_paths!(
722                self.tcx.def_path_str_with_args(instance.def_id(), instance.args)
723            )
724        } else {
725            with_resolve_crate_name!(with_no_trimmed_paths!(
726                self.tcx.def_path_str_with_args(instance.def_id(), instance.args)
727            ))
728        }
729    }
730
731    /// Get the layout of a type.
732    pub fn ty_layout(&self, ty: Ty<'tcx>) -> Result<Layout<'tcx>, B::Error> {
733        let layout = self.layout_of(ty)?.layout;
734        Ok(layout)
735    }
736
737    /// Get the resulting type of binary operation.
738    pub fn binop_ty(&self, bin_op: BinOp, rhs: Ty<'tcx>, lhs: Ty<'tcx>) -> Ty<'tcx> {
739        bin_op.ty(self.tcx, rhs, lhs)
740    }
741
742    /// Get the resulting type of unary operation.
743    pub fn unop_ty(&self, un_op: UnOp, arg: Ty<'tcx>) -> Ty<'tcx> {
744        un_op.ty(self.tcx, arg)
745    }
746
747    /// Get all associated items of a definition.
748    pub fn associated_items(&self, def_id: DefId) -> Vec<AssocItem> {
749        let assoc_items = if self.tcx.is_trait_alias(def_id) {
750            Vec::new()
751        } else {
752            self.tcx
753                .associated_item_def_ids(def_id)
754                .iter()
755                .map(|did| self.tcx.associated_item(*did))
756                .collect()
757        };
758        assoc_items
759    }
760}