Skip to main content

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, VtblEntry,
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) -> 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            || !#[allow(non_exhaustive_omitted_patterns)] match instance.def {
    ty::InstanceKind::Virtual(..) | ty::InstanceKind::Intrinsic(..) |
        ty::InstanceKind::Item(..) => true,
    _ => false,
}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 #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}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        #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Static { .. } => true,
    _ => false,
}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            { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(def_id) }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            {
    let _guard = CrateNamePrefixGuard::new();
    { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(def_id) }
}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).skip_norm_wip();
383        sig
384    }
385
386    /// Retrieve the constness for the given function definition.
387    pub fn constness(&self, def_id: DefId) -> rustc_hir::Constness {
388        self.tcx.constness(def_id)
389    }
390
391    /// Retrieve the asyncness for the given function definition.
392    pub fn asyncness(&self, def_id: DefId) -> ty::Asyncness {
393        self.tcx.asyncness(def_id)
394    }
395
396    /// Retrieve the intrinsic definition if the item corresponds one.
397    pub fn intrinsic(&self, def_id: DefId) -> Option<IntrinsicDef> {
398        let intrinsic = self.tcx.intrinsic_raw(def_id);
399        intrinsic
400    }
401
402    /// Retrieve the plain function name of an intrinsic.
403    pub fn intrinsic_name(&self, def_id: DefId) -> String {
404        self.tcx.intrinsic(def_id).unwrap().name.to_string()
405    }
406
407    /// Retrieve the closure signature for the given generic arguments.
408    pub fn closure_sig(&self, args_ref: GenericArgsRef<'tcx>) -> Binder<'tcx, FnSig<'tcx>> {
409        args_ref.as_closure().sig()
410    }
411
412    /// The number of variants in this ADT.
413    pub fn adt_variants_len(&self, def: AdtDef<'tcx>) -> usize {
414        def.variants().len()
415    }
416
417    /// Discriminant for a given variant index of AdtDef.
418    pub fn adt_discr_for_variant(
419        &self,
420        adt: AdtDef<'tcx>,
421        variant: rustc_abi::VariantIdx,
422    ) -> Discr<'tcx> {
423        adt.discriminant_for_variant(self.tcx, variant)
424    }
425
426    /// Discriminant for a given variand index and args of a coroutine.
427    pub fn coroutine_discr_for_variant(
428        &self,
429        coroutine: DefId,
430        args: GenericArgsRef<'tcx>,
431        variant: rustc_abi::VariantIdx,
432    ) -> Discr<'tcx> {
433        args.as_coroutine().discriminant_for_variant(coroutine, self.tcx, variant)
434    }
435
436    /// The name of a variant.
437    pub fn variant_name(&self, def: &'tcx VariantDef) -> String {
438        def.name.to_string()
439    }
440
441    /// Evaluate constant as a target usize.
442    pub fn eval_target_usize(&self, cnst: MirConst<'tcx>) -> Result<u64, B::Error> {
443        use crate::context::TypingEnvHelpers;
444        cnst.try_eval_target_usize(self.tcx, self.fully_monomorphized())
445            .ok_or_else(|| B::Error::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Const `{0:?}` cannot be encoded as u64",
                cnst))
    })format!("Const `{cnst:?}` cannot be encoded as u64")))
446    }
447
448    pub fn eval_target_usize_ty(&self, cnst: ty::Const<'tcx>) -> Result<u64, B::Error> {
449        cnst.try_to_target_usize(self.tcx)
450            .ok_or_else(|| B::Error::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Const `{0:?}` cannot be encoded as u64",
                cnst))
    })format!("Const `{cnst:?}` cannot be encoded as u64")))
451    }
452
453    pub fn try_new_const_zst(&self, ty_internal: Ty<'tcx>) -> Result<MirConst<'tcx>, B::Error> {
454        let size = self
455            .tcx
456            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))
457            .map_err(|err| {
458                B::Error::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Cannot create a zero-sized constant for type `{0}`: {1}",
                ty_internal, err))
    })format!(
459                    "Cannot create a zero-sized constant for type `{ty_internal}`: {err}"
460                ))
461            })?
462            .size;
463        if size.bytes() != 0 {
464            return Err(B::Error::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Cannot create a zero-sized constant for type `{1}`: Type `{1}` has {0} bytes",
                size.bytes(), ty_internal))
    })format!(
465                "Cannot create a zero-sized constant for type `{ty_internal}`: \
466                Type `{ty_internal}` has {} bytes",
467                size.bytes()
468            )));
469        }
470
471        Ok(MirConst::Ty(ty_internal, self.const_zero_sized(ty_internal)))
472    }
473
474    pub fn const_zero_sized(&self, ty_internal: Ty<'tcx>) -> ty::Const<'tcx> {
475        ty::Const::zero_sized(self.tcx, ty_internal)
476    }
477
478    /// Create a new constant that represents the given string value.
479    pub fn new_const_str(&self, value: &str) -> MirConst<'tcx> {
480        let ty = Ty::new_static_str(self.tcx);
481        let bytes = value.as_bytes();
482        let valtree = ValTree::from_raw_bytes(self.tcx, bytes);
483        let cv = ty::Value { ty, valtree };
484        let val = self.tcx.valtree_to_const_val(cv);
485        MirConst::from_value(val, ty)
486    }
487
488    /// Create a new constant that represents the given boolean value.
489    pub fn new_const_bool(&self, value: bool) -> MirConst<'tcx> {
490        MirConst::from_bool(self.tcx, value)
491    }
492
493    pub fn try_new_const_uint(
494        &self,
495        value: u128,
496        ty_internal: Ty<'tcx>,
497    ) -> Result<MirConst<'tcx>, B::Error> {
498        let size = self
499            .tcx
500            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))
501            .unwrap()
502            .size;
503        let scalar = ScalarInt::try_from_uint(value, size).ok_or_else(|| {
504            B::Error::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Value overflow: cannot convert `{0}` to `{1}`.",
                value, ty_internal))
    })format!("Value overflow: cannot convert `{value}` to `{ty_internal}`."))
505        })?;
506        Ok(self.mir_const_from_scalar(Scalar::Int(scalar), ty_internal))
507    }
508
509    pub fn try_new_ty_const_uint(
510        &self,
511        value: u128,
512        ty_internal: Ty<'tcx>,
513    ) -> Result<ty::Const<'tcx>, B::Error> {
514        let size = self
515            .tcx
516            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))
517            .unwrap()
518            .size;
519        let scalar = ScalarInt::try_from_uint(value, size).ok_or_else(|| {
520            B::Error::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Value overflow: cannot convert `{0}` to `{1}`.",
                value, ty_internal))
    })format!("Value overflow: cannot convert `{value}` to `{ty_internal}`."))
521        })?;
522
523        Ok(self.ty_const_new_value(ValTree::from_scalar_int(self.tcx, scalar), ty_internal))
524    }
525
526    pub fn ty_new_uint(&self, ty: UintTy) -> Ty<'tcx> {
527        Ty::new_uint(self.tcx, ty)
528    }
529
530    pub fn mir_const_from_scalar(&self, s: Scalar, ty: Ty<'tcx>) -> MirConst<'tcx> {
531        MirConst::from_scalar(self.tcx, s, ty)
532    }
533
534    pub fn ty_const_new_value(&self, valtree: ValTree<'tcx>, ty: Ty<'tcx>) -> ty::Const<'tcx> {
535        ty::Const::new_value(self.tcx, valtree, ty)
536    }
537
538    pub fn ty_valtree_from_scalar_int(&self, i: ScalarInt) -> ValTree<'tcx> {
539        ValTree::from_scalar_int(self.tcx, i)
540    }
541
542    /// Create a new type from the given kind.
543    pub fn new_rigid_ty(&self, internal_kind: TyKind<'tcx>) -> Ty<'tcx> {
544        self.tcx.mk_ty_from_kind(internal_kind)
545    }
546
547    /// Create a new box type, `Box<T>`, for the given inner type `T`.
548    pub fn new_box_ty(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
549        ty::Ty::new_box(self.tcx, ty)
550    }
551
552    /// Returns the type of given crate item.
553    pub fn def_ty(&self, item: DefId) -> Ty<'tcx> {
554        self.tcx.type_of(item).instantiate_identity().skip_norm_wip()
555    }
556
557    /// Returns the type of given definition instantiated with the given arguments.
558    pub fn def_ty_with_args(&self, item: DefId, args_ref: GenericArgsRef<'tcx>) -> Ty<'tcx> {
559        let def_ty = self.tcx.type_of(item);
560        self.tcx.instantiate_and_normalize_erasing_regions(
561            args_ref,
562            self.fully_monomorphized(),
563            def_ty,
564        )
565    }
566
567    /// `Span` of a `DefId`.
568    pub fn span_of_a_def(&self, def_id: DefId) -> Span {
569        self.tcx.def_span(def_id)
570    }
571
572    pub fn ty_const_pretty(&self, ct: ty::Const<'tcx>) -> String {
573        ct.to_string()
574    }
575
576    /// Obtain the representation of a type.
577    pub fn ty_pretty(&self, ty: Ty<'tcx>) -> String {
578        ty.to_string()
579    }
580
581    /// Obtain the kind of a type.
582    pub fn ty_kind(&self, ty: Ty<'tcx>) -> &'tcx TyKind<'tcx> {
583        ty.kind()
584    }
585
586    /// Get the discriminant Ty for this Ty if there's one.
587    pub fn rigid_ty_discriminant_ty(&self, internal_kind: TyKind<'tcx>) -> Ty<'tcx> {
588        let internal_ty = self.tcx.mk_ty_from_kind(internal_kind);
589        internal_ty.discriminant_ty(self.tcx)
590    }
591
592    /// Get the body of an Instance which is already monomorphized.
593    pub fn instance_body(&self, instance: ty::Instance<'tcx>) -> Option<Body<'tcx>> {
594        self.instance_has_body(instance).then(|| BodyBuilder::new(self.tcx, instance).build())
595    }
596
597    /// Get the instance type with generic instantiations applied and lifetimes erased.
598    pub fn instance_ty(&self, instance: ty::Instance<'tcx>) -> Ty<'tcx> {
599        if !!instance.has_non_region_param() {
    {
        ::core::panicking::panic_fmt(format_args!("{0:?} needs further instantiation",
                instance));
    }
};assert!(!instance.has_non_region_param(), "{instance:?} needs further instantiation");
600        instance.ty(self.tcx, self.fully_monomorphized())
601    }
602
603    /// Get the instantiation types.
604    pub fn instance_args(&self, instance: ty::Instance<'tcx>) -> GenericArgsRef<'tcx> {
605        instance.args
606    }
607
608    /// Get an instance ABI.
609    pub fn instance_abi(
610        &self,
611        instance: ty::Instance<'tcx>,
612    ) -> Result<&FnAbi<'tcx, Ty<'tcx>>, B::Error> {
613        Ok(self.fn_abi_of_instance(instance, List::empty())?)
614    }
615
616    /// Get the ABI of a function pointer.
617    pub fn fn_ptr_abi(&self, sig: PolyFnSig<'tcx>) -> Result<&FnAbi<'tcx, Ty<'tcx>>, B::Error> {
618        Ok(self.fn_abi_of_fn_ptr(sig, List::empty())?)
619    }
620
621    /// Get the instance.
622    pub fn instance_def_id(
623        &self,
624        instances: ty::Instance<'tcx>,
625        tables: &mut Tables<'_, B>,
626    ) -> B::DefId {
627        let def_id = instances.def_id();
628        tables.create_def_id(def_id)
629    }
630
631    /// Get the instance mangled name.
632    pub fn instance_mangled_name(&self, instance: ty::Instance<'tcx>) -> String {
633        self.tcx.symbol_name(instance).name.to_string()
634    }
635
636    /// Check if this is an empty DropGlue shim.
637    pub fn is_empty_drop_shim(&self, instance: ty::Instance<'tcx>) -> bool {
638        #[allow(non_exhaustive_omitted_patterns)] match instance.def {
    ty::InstanceKind::DropGlue(_, None) => true,
    _ => false,
}matches!(instance.def, ty::InstanceKind::DropGlue(_, None))
639    }
640
641    /// Convert a non-generic crate item into an instance.
642    /// This function will panic if the item is generic.
643    pub fn mono_instance(&self, def_id: DefId) -> Instance<'tcx> {
644        Instance::mono(self.tcx, def_id)
645    }
646
647    /// Item requires monomorphization.
648    pub fn requires_monomorphization(&self, def_id: DefId) -> bool {
649        let generics = self.tcx.generics_of(def_id);
650        let result = generics.requires_monomorphization(self.tcx);
651        result
652    }
653
654    /// Resolve an instance from the given function definition and generic arguments.
655    pub fn resolve_instance(
656        &self,
657        def_id: DefId,
658        args_ref: GenericArgsRef<'tcx>,
659    ) -> Option<Instance<'tcx>> {
660        match Instance::try_resolve(self.tcx, self.fully_monomorphized(), def_id, args_ref) {
661            Ok(Some(instance)) => Some(instance),
662            Ok(None) | Err(_) => None,
663        }
664    }
665
666    /// Resolve an instance for drop_in_place for the given type.
667    pub fn resolve_drop_in_place(&self, internal_ty: Ty<'tcx>) -> Instance<'tcx> {
668        let instance = Instance::resolve_drop_in_place(self.tcx, internal_ty);
669        instance
670    }
671
672    /// Resolve instance for a function pointer.
673    pub fn resolve_for_fn_ptr(
674        &self,
675        def_id: DefId,
676        args_ref: GenericArgsRef<'tcx>,
677    ) -> Option<Instance<'tcx>> {
678        Instance::resolve_for_fn_ptr(self.tcx, self.fully_monomorphized(), def_id, args_ref)
679    }
680
681    /// Resolve instance for a closure with the requested type.
682    pub fn resolve_closure(
683        &self,
684        def_id: DefId,
685        args_ref: GenericArgsRef<'tcx>,
686        closure_kind: ClosureKind,
687    ) -> Option<Instance<'tcx>> {
688        Some(Instance::resolve_closure(self.tcx, def_id, args_ref, closure_kind))
689    }
690
691    /// Try to evaluate an instance into a constant.
692    pub fn eval_instance(&self, instance: ty::Instance<'tcx>) -> Result<ConstValue, ErrorHandled> {
693        self.tcx.const_eval_instance(
694            self.fully_monomorphized(),
695            instance,
696            self.tcx.def_span(instance.def_id()),
697        )
698    }
699
700    /// Evaluate a static's initializer.
701    pub fn eval_static_initializer(
702        &self,
703        def_id: DefId,
704    ) -> Result<ConstAllocation<'tcx>, ErrorHandled> {
705        self.tcx.eval_static_initializer(def_id)
706    }
707
708    /// Retrieve global allocation for the given allocation ID.
709    pub fn global_alloc(&self, alloc_id: AllocId) -> GlobalAlloc<'tcx> {
710        self.tcx.global_alloc(alloc_id)
711    }
712
713    /// Retrieve the id for the virtual table.
714    pub fn vtable_allocation(
715        &self,
716        ty: Ty<'tcx>,
717        trait_ref: Option<Binder<'tcx, ExistentialTraitRef<'tcx>>>,
718    ) -> AllocId {
719        let alloc_id = self.tcx.vtable_allocation((
720            ty,
721            trait_ref.map(|principal| self.tcx.instantiate_bound_regions_with_erased(principal)),
722        ));
723        alloc_id
724    }
725
726    /// Retrieve the instance name for diagnostic messages.
727    ///
728    /// This will return the specialized name, e.g., `Vec<char>::new`.
729    pub fn instance_name(&self, instance: ty::Instance<'tcx>, trimmed: bool) -> String {
730        if trimmed {
731            {
    let _guard = ForceTrimmedGuard::new();
    self.tcx.def_path_str_with_args(instance.def_id(), instance.args)
}with_forced_trimmed_paths!(
732                self.tcx.def_path_str_with_args(instance.def_id(), instance.args)
733            )
734        } else {
735            {
    let _guard = CrateNamePrefixGuard::new();
    {
        let _guard = NoTrimmedGuard::new();
        self.tcx.def_path_str_with_args(instance.def_id(), instance.args)
    }
}with_resolve_crate_name!(with_no_trimmed_paths!(
736                self.tcx.def_path_str_with_args(instance.def_id(), instance.args)
737            ))
738        }
739    }
740
741    /// Get the layout of a type.
742    pub fn ty_layout(&self, ty: Ty<'tcx>) -> Result<Layout<'tcx>, B::Error> {
743        let layout = self.layout_of(ty)?.layout;
744        Ok(layout)
745    }
746
747    /// Get the resulting type of binary operation.
748    pub fn binop_ty(&self, bin_op: BinOp, rhs: Ty<'tcx>, lhs: Ty<'tcx>) -> Ty<'tcx> {
749        bin_op.ty(self.tcx, rhs, lhs)
750    }
751
752    /// Get the resulting type of unary operation.
753    pub fn unop_ty(&self, un_op: UnOp, arg: Ty<'tcx>) -> Ty<'tcx> {
754        un_op.ty(self.tcx, arg)
755    }
756
757    /// Get all associated items of a definition.
758    pub fn associated_items(&self, def_id: DefId) -> Vec<AssocItem> {
759        let assoc_items = if self.tcx.is_trait_alias(def_id) {
760            Vec::new()
761        } else {
762            self.tcx
763                .associated_item_def_ids(def_id)
764                .iter()
765                .map(|did| self.tcx.associated_item(*did))
766                .collect()
767        };
768        assoc_items
769    }
770
771    /// Get all vtable entries of a trait.
772    pub fn vtable_entries(&self, trait_ref: TraitRef<'tcx>) -> Vec<VtblEntry<'tcx>> {
773        self.tcx.vtable_entries(trait_ref).to_vec()
774    }
775
776    /// Returns the vtable entry at the given index.
777    ///
778    /// Returns `None` if the index is out of bounds.
779    pub fn vtable_entry(&self, trait_ref: TraitRef<'tcx>, idx: usize) -> Option<VtblEntry<'tcx>> {
780        self.vtable_entries(trait_ref).get(idx).copied()
781    }
782}