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