1
Fork 0

Auto merge of #113377 - BoxyUwU:move_ty_ctors_to_ty, r=compiler-errors

Move `TyCtxt::mk_x` to `Ty::new_x` where applicable

Part of rust-lang/compiler-team#616

turns out there's a lot of places we construct `Ty` this is a ridiculously huge PR :S

r? `@oli-obk`
This commit is contained in:
bors 2023-07-06 08:10:42 +00:00
commit 4dd1719b34
165 changed files with 1388 additions and 1187 deletions

View file

@ -433,7 +433,8 @@ impl<'tcx> CanonicalVarValues<'tcx> {
|(i, info)| -> ty::GenericArg<'tcx> {
match info.kind {
CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) => {
tcx.mk_bound(ty::INNERMOST, ty::BoundVar::from_usize(i).into()).into()
Ty::new_bound(tcx, ty::INNERMOST, ty::BoundVar::from_usize(i).into())
.into()
}
CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => {
let br = ty::BoundRegion {

View file

@ -90,15 +90,15 @@ impl<'tcx> UnifyValue for UnifiedRegion<'tcx> {
impl ToType for ty::IntVarValue {
fn to_type<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match *self {
ty::IntType(i) => tcx.mk_mach_int(i),
ty::UintType(i) => tcx.mk_mach_uint(i),
ty::IntType(i) => Ty::new_int(tcx, i),
ty::UintType(i) => Ty::new_uint(tcx, i),
}
}
}
impl ToType for ty::FloatVarValue {
fn to_type<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
tcx.mk_mach_float(self.0)
Ty::new_float(tcx, self.0)
}
}

View file

@ -1913,7 +1913,7 @@ impl<'tcx> Operand<'tcx> {
substs: impl IntoIterator<Item = GenericArg<'tcx>>,
span: Span,
) -> Self {
let ty = tcx.mk_fn_def(def_id, substs);
let ty = Ty::new_fn_def(tcx, def_id, substs);
Operand::Constant(Box::new(Constant {
span,
user_ty: None,

View file

@ -95,11 +95,13 @@ impl<'tcx> PlaceTy<'tcx> {
ProjectionElem::Subslice { from, to, from_end } => {
PlaceTy::from_ty(match self.ty.kind() {
ty::Slice(..) => self.ty,
ty::Array(inner, _) if !from_end => tcx.mk_array(*inner, (to - from) as u64),
ty::Array(inner, _) if !from_end => {
Ty::new_array(tcx, *inner, (to - from) as u64)
}
ty::Array(inner, size) if from_end => {
let size = size.eval_target_usize(tcx, param_env);
let len = size - from - to;
tcx.mk_array(*inner, len)
Ty::new_array(tcx, *inner, len)
}
_ => bug!("cannot subslice non-array type: `{:?}`", self),
})
@ -162,16 +164,16 @@ impl<'tcx> Rvalue<'tcx> {
match *self {
Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
Rvalue::Repeat(ref operand, count) => {
tcx.mk_array_with_const_len(operand.ty(local_decls, tcx), count)
Ty::new_array_with_const_len(tcx, operand.ty(local_decls, tcx), count)
}
Rvalue::ThreadLocalRef(did) => tcx.thread_local_ptr_ty(did),
Rvalue::Ref(reg, bk, ref place) => {
let place_ty = place.ty(local_decls, tcx).ty;
tcx.mk_ref(reg, ty::TypeAndMut { ty: place_ty, mutbl: bk.to_mutbl_lossy() })
Ty::new_ref(tcx, reg, ty::TypeAndMut { ty: place_ty, mutbl: bk.to_mutbl_lossy() })
}
Rvalue::AddressOf(mutability, ref place) => {
let place_ty = place.ty(local_decls, tcx).ty;
tcx.mk_ptr(ty::TypeAndMut { ty: place_ty, mutbl: mutability })
Ty::new_ptr(tcx, ty::TypeAndMut { ty: place_ty, mutbl: mutability })
}
Rvalue::Len(..) => tcx.types.usize,
Rvalue::Cast(.., ty) => ty,
@ -184,7 +186,7 @@ impl<'tcx> Rvalue<'tcx> {
let lhs_ty = lhs.ty(local_decls, tcx);
let rhs_ty = rhs.ty(local_decls, tcx);
let ty = op.ty(tcx, lhs_ty, rhs_ty);
tcx.mk_tup(&[ty, tcx.types.bool])
Ty::new_tup(tcx, &[ty, tcx.types.bool])
}
Rvalue::UnaryOp(UnOp::Not | UnOp::Neg, ref operand) => operand.ty(local_decls, tcx),
Rvalue::Discriminant(ref place) => place.ty(local_decls, tcx).ty.discriminant_ty(tcx),
@ -192,17 +194,17 @@ impl<'tcx> Rvalue<'tcx> {
tcx.types.usize
}
Rvalue::Aggregate(ref ak, ref ops) => match **ak {
AggregateKind::Array(ty) => tcx.mk_array(ty, ops.len() as u64),
AggregateKind::Array(ty) => Ty::new_array(tcx, ty, ops.len() as u64),
AggregateKind::Tuple => {
tcx.mk_tup_from_iter(ops.iter().map(|op| op.ty(local_decls, tcx)))
Ty::new_tup_from_iter(tcx, ops.iter().map(|op| op.ty(local_decls, tcx)))
}
AggregateKind::Adt(did, _, substs, _, _) => tcx.type_of(did).subst(tcx, substs),
AggregateKind::Closure(did, substs) => tcx.mk_closure(did, substs),
AggregateKind::Closure(did, substs) => Ty::new_closure(tcx, did, substs),
AggregateKind::Generator(did, substs, movability) => {
tcx.mk_generator(did, substs, movability)
Ty::new_generator(tcx, did, substs, movability)
}
},
Rvalue::ShallowInitBox(_, ty) => tcx.mk_box(ty),
Rvalue::ShallowInitBox(_, ty) => Ty::new_box(tcx, ty),
Rvalue::CopyForDeref(ref place) => place.ty(local_decls, tcx).ty,
}
}

View file

@ -81,7 +81,7 @@ impl<'tcx> TypeRelation<'tcx> for Match<'tcx> {
Err(TypeError::Sorts(relate::expected_found(self, a, b)))
}
(&ty::Error(guar), _) | (_, &ty::Error(guar)) => Ok(self.tcx().ty_error(guar)),
(&ty::Error(guar), _) | (_, &ty::Error(guar)) => Ok(Ty::new_error(self.tcx(), guar)),
_ => relate::structurally_relate_tys(self, a, b),
}

View file

@ -132,7 +132,7 @@ impl<'tcx> OverloadedDeref<'tcx> {
.find(|m| m.kind == ty::AssocKind::Fn)
.unwrap()
.def_id;
tcx.mk_fn_def(method_def_id, [source])
Ty::new_fn_def(tcx, method_def_id, [source])
}
}

View file

@ -125,7 +125,7 @@ impl<'tcx> Const<'tcx> {
Const::new(tcx, ty::ConstKind::Error(e), ty)
}
/// Like [TyCtxt::ty_error] but for constants.
/// Like [Ty::new_error] but for constants.
#[track_caller]
pub fn new_misc_error(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
Const::new_error_with_message(
@ -136,7 +136,7 @@ impl<'tcx> Const<'tcx> {
)
}
/// Like [TyCtxt::ty_error_with_message] but for constants.
/// Like [Ty::new_error_with_message] but for constants.
#[track_caller]
pub fn new_error_with_message<S: Into<MultiSpan>>(
tcx: TyCtxt<'tcx>,

View file

@ -25,10 +25,10 @@ use crate::traits::solve::{
ExternalConstraints, ExternalConstraintsData, PredefinedOpaques, PredefinedOpaquesData,
};
use crate::ty::{
self, AdtDef, AdtDefData, AdtKind, Binder, Clause, Const, ConstData, FloatTy, FloatVar,
FloatVid, GenericParamDefKind, ImplPolarity, InferTy, IntTy, IntVar, IntVid, List, ParamConst,
ParamTy, PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, Region, RegionKind,
ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVar, TyVid, TypeAndMut, UintTy, Visibility,
self, AdtDef, AdtDefData, AdtKind, Binder, Clause, Const, ConstData, GenericParamDefKind,
ImplPolarity, InferTy, List, ParamConst, ParamTy, PolyExistentialPredicate, PolyFnSig,
Predicate, PredicateKind, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind,
TyVid, TypeAndMut, Visibility,
};
use crate::ty::{GenericArg, InternalSubsts, SubstsRef};
use rustc_ast::{self as ast, attr};
@ -70,10 +70,9 @@ use rustc_target::abi::{FieldIdx, Layout, LayoutS, TargetDataLayout, VariantIdx}
use rustc_target::spec::abi;
use rustc_type_ir::sty::TyKind::*;
use rustc_type_ir::WithCachedTypeInfo;
use rustc_type_ir::{CollectAndApply, DynKind, Interner, TypeFlags};
use rustc_type_ir::{CollectAndApply, Interner, TypeFlags};
use std::any::Any;
use std::assert_matches::debug_assert_matches;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt;
@ -727,30 +726,6 @@ impl<'tcx> TyCtxt<'tcx> {
}
}
/// Constructs a `TyKind::Error` type with current `ErrorGuaranteed`
#[track_caller]
pub fn ty_error(self, reported: ErrorGuaranteed) -> Ty<'tcx> {
self.mk_ty_from_kind(Error(reported))
}
/// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
#[track_caller]
pub fn ty_error_misc(self) -> Ty<'tcx> {
self.ty_error_with_message(DUMMY_SP, "TyKind::Error constructed but no error reported")
}
/// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to
/// ensure it gets used.
#[track_caller]
pub fn ty_error_with_message<S: Into<MultiSpan>>(
self,
span: S,
msg: impl Into<DiagnosticMessage>,
) -> Ty<'tcx> {
let reported = self.sess.delay_span_bug(span, msg);
self.mk_ty_from_kind(Error(reported))
}
pub fn consider_optimizing<T: Fn() -> String>(self, msg: T) -> bool {
self.sess.consider_optimizing(|| self.crate_name(LOCAL_CRATE), msg)
}
@ -1144,7 +1119,8 @@ impl<'tcx> TyCtxt<'tcx> {
/// Returns `&'static core::panic::Location<'static>`.
pub fn caller_location_ty(self) -> Ty<'tcx> {
self.mk_imm_ref(
Ty::new_imm_ref(
self,
self.lifetimes.re_static,
self.type_of(self.require_lang_item(LangItem::PanicLocation, None))
.subst(self, self.mk_substs(&[self.lifetimes.re_static.into()])),
@ -1542,7 +1518,10 @@ impl<'tcx> TyCtxt<'tcx> {
/// unsafe.
pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
assert_eq!(sig.unsafety(), hir::Unsafety::Normal);
self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }))
Ty::new_fn_ptr(
self,
sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }),
)
}
/// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name`
@ -1616,18 +1595,6 @@ impl<'tcx> TyCtxt<'tcx> {
})
}
// Avoid this in favour of more specific `mk_*` methods, where possible.
#[allow(rustc::usage_of_ty_tykind)]
#[inline]
pub fn mk_ty_from_kind(self, st: TyKind<'tcx>) -> Ty<'tcx> {
self.interners.intern_ty(
st,
self.sess,
// This is only used to create a stable hashing context.
&self.untracked,
)
}
#[inline]
pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
self.interners.intern_predicate(
@ -1647,174 +1614,6 @@ impl<'tcx> TyCtxt<'tcx> {
if pred.kind() != binder { self.mk_predicate(binder) } else { pred }
}
pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> {
match tm {
IntTy::Isize => self.types.isize,
IntTy::I8 => self.types.i8,
IntTy::I16 => self.types.i16,
IntTy::I32 => self.types.i32,
IntTy::I64 => self.types.i64,
IntTy::I128 => self.types.i128,
}
}
pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> {
match tm {
UintTy::Usize => self.types.usize,
UintTy::U8 => self.types.u8,
UintTy::U16 => self.types.u16,
UintTy::U32 => self.types.u32,
UintTy::U64 => self.types.u64,
UintTy::U128 => self.types.u128,
}
}
pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> {
match tm {
FloatTy::F32 => self.types.f32,
FloatTy::F64 => self.types.f64,
}
}
#[inline]
pub fn mk_static_str(self) -> Ty<'tcx> {
self.mk_imm_ref(self.lifetimes.re_static, self.types.str_)
}
#[inline]
pub fn mk_adt(self, def: AdtDef<'tcx>, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
// Take a copy of substs so that we own the vectors inside.
self.mk_ty_from_kind(Adt(def, substs))
}
#[inline]
pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> {
self.mk_ty_from_kind(Foreign(def_id))
}
fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
let adt_def = self.adt_def(wrapper_def_id);
let substs =
InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind {
GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
GenericParamDefKind::Type { has_default, .. } => {
if param.index == 0 {
ty_param.into()
} else {
assert!(has_default);
self.type_of(param.def_id).subst(self, substs).into()
}
}
});
self.mk_ty_from_kind(Adt(adt_def, substs))
}
#[inline]
pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> {
let def_id = self.require_lang_item(LangItem::OwnedBox, None);
self.mk_generic_adt(def_id, ty)
}
#[inline]
pub fn mk_lang_item(self, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
let def_id = self.lang_items().get(item)?;
Some(self.mk_generic_adt(def_id, ty))
}
#[inline]
pub fn mk_diagnostic_item(self, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
let def_id = self.get_diagnostic_item(name)?;
Some(self.mk_generic_adt(def_id, ty))
}
#[inline]
pub fn mk_maybe_uninit(self, ty: Ty<'tcx>) -> Ty<'tcx> {
let def_id = self.require_lang_item(LangItem::MaybeUninit, None);
self.mk_generic_adt(def_id, ty)
}
#[inline]
pub fn mk_ptr(self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
self.mk_ty_from_kind(RawPtr(tm))
}
#[inline]
pub fn mk_ref(self, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
self.mk_ty_from_kind(Ref(r, tm.ty, tm.mutbl))
}
#[inline]
pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
}
#[inline]
pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
self.mk_ref(r, TypeAndMut { ty, mutbl: hir::Mutability::Not })
}
#[inline]
pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Mut })
}
#[inline]
pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> {
self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not })
}
#[inline]
pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
self.mk_ty_from_kind(Array(ty, ty::Const::from_target_usize(self, n)))
}
#[inline]
pub fn mk_array_with_const_len(self, ty: Ty<'tcx>, ct: Const<'tcx>) -> Ty<'tcx> {
self.mk_ty_from_kind(Array(ty, ct))
}
#[inline]
pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> {
self.mk_ty_from_kind(Slice(ty))
}
#[inline]
pub fn mk_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
if ts.is_empty() {
self.types.unit
} else {
self.mk_ty_from_kind(Tuple(self.mk_type_list(&ts)))
}
}
pub fn mk_tup_from_iter<I, T>(self, iter: I) -> T::Output
where
I: Iterator<Item = T>,
T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
{
T::collect_and_apply(iter, |ts| self.mk_tup(ts))
}
#[inline]
pub fn mk_unit(self) -> Ty<'tcx> {
self.types.unit
}
#[inline]
pub fn mk_diverging_default(self) -> Ty<'tcx> {
if self.features().never_type_fallback { self.types.never } else { self.types.unit }
}
#[inline]
pub fn mk_fn_def(
self,
def_id: DefId,
substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
) -> Ty<'tcx> {
let substs = self.check_and_mk_substs(def_id, substs);
self.mk_ty_from_kind(FnDef(def_id, substs))
}
#[inline(always)]
pub(crate) fn check_and_mk_substs(
self,
@ -1845,132 +1644,21 @@ impl<'tcx> TyCtxt<'tcx> {
self.mk_substs_from_iter(substs)
}
#[inline]
pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
self.mk_ty_from_kind(FnPtr(fty))
}
#[inline]
pub fn mk_dynamic(
self,
obj: &'tcx List<PolyExistentialPredicate<'tcx>>,
reg: ty::Region<'tcx>,
repr: DynKind,
) -> Ty<'tcx> {
self.mk_ty_from_kind(Dynamic(obj, reg, repr))
}
#[inline]
pub fn mk_projection(
self,
item_def_id: DefId,
substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
) -> Ty<'tcx> {
self.mk_alias(ty::Projection, self.mk_alias_ty(item_def_id, substs))
}
#[inline]
pub fn mk_closure(self, def_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> {
debug_assert_eq!(
closure_substs.len(),
self.generics_of(self.typeck_root_def_id(def_id)).count() + 3,
"closure constructed with incorrect substitutions"
);
self.mk_ty_from_kind(Closure(def_id, closure_substs))
}
#[inline]
pub fn mk_generator(
self,
def_id: DefId,
generator_substs: SubstsRef<'tcx>,
movability: hir::Movability,
) -> Ty<'tcx> {
debug_assert_eq!(
generator_substs.len(),
self.generics_of(self.typeck_root_def_id(def_id)).count() + 5,
"generator constructed with incorrect number of substitutions"
);
self.mk_ty_from_kind(Generator(def_id, generator_substs, movability))
}
#[inline]
pub fn mk_generator_witness(self, types: ty::Binder<'tcx, &'tcx List<Ty<'tcx>>>) -> Ty<'tcx> {
self.mk_ty_from_kind(GeneratorWitness(types))
}
/// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
pub fn mk_task_context(self) -> Ty<'tcx> {
let context_did = self.require_lang_item(LangItem::Context, None);
let context_adt_ref = self.adt_def(context_did);
let context_substs = self.mk_substs(&[self.lifetimes.re_erased.into()]);
let context_ty = self.mk_adt(context_adt_ref, context_substs);
self.mk_mut_ref(self.lifetimes.re_erased, context_ty)
}
#[inline]
pub fn mk_generator_witness_mir(self, id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
self.mk_ty_from_kind(GeneratorWitnessMIR(id, substs))
}
#[inline]
pub fn mk_ct_from_kind(self, kind: ty::ConstKind<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
self.intern_const(ty::ConstData { kind, ty })
}
// Avoid this in favour of more specific `Ty::new_*` methods, where possible.
#[allow(rustc::usage_of_ty_tykind)]
#[inline]
pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> {
// Use a pre-interned one when possible.
self.types
.ty_vars
.get(v.as_usize())
.copied()
.unwrap_or_else(|| self.mk_ty_from_kind(Infer(TyVar(v))))
}
#[inline]
pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> {
self.mk_ty_from_kind(Infer(IntVar(v)))
}
#[inline]
pub fn mk_float_var(self, v: FloatVid) -> Ty<'tcx> {
self.mk_ty_from_kind(Infer(FloatVar(v)))
}
#[inline]
pub fn mk_fresh_ty(self, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
self.types
.fresh_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| self.mk_ty_from_kind(Infer(ty::FreshTy(n))))
}
#[inline]
pub fn mk_fresh_int_ty(self, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
self.types
.fresh_int_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| self.mk_ty_from_kind(Infer(ty::FreshIntTy(n))))
}
#[inline]
pub fn mk_fresh_float_ty(self, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
self.types
.fresh_float_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| self.mk_ty_from_kind(Infer(ty::FreshFloatTy(n))))
}
#[inline]
pub fn mk_ty_param(self, index: u32, name: Symbol) -> Ty<'tcx> {
self.mk_ty_from_kind(Param(ParamTy { index, name }))
pub fn mk_ty_from_kind(self, st: TyKind<'tcx>) -> Ty<'tcx> {
self.interners.intern_ty(
st,
self.sess,
// This is only used to create a stable hashing context.
&self.untracked,
)
}
pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
@ -1978,7 +1666,7 @@ impl<'tcx> TyCtxt<'tcx> {
GenericParamDefKind::Lifetime => {
ty::Region::new_early_bound(self, param.to_early_bound_region_data()).into()
}
GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(),
GenericParamDefKind::Type { .. } => Ty::new_param(self, param.index, param.name).into(),
GenericParamDefKind::Const { .. } => ty::Const::new_param(
self,
ParamConst { index: param.index, name: param.name },
@ -1990,33 +1678,6 @@ impl<'tcx> TyCtxt<'tcx> {
}
}
#[inline]
pub fn mk_bound(self, index: ty::DebruijnIndex, bound_ty: ty::BoundTy) -> Ty<'tcx> {
self.mk_ty_from_kind(Bound(index, bound_ty))
}
#[inline]
pub fn mk_placeholder(self, placeholder: ty::PlaceholderType) -> Ty<'tcx> {
self.mk_ty_from_kind(Placeholder(placeholder))
}
#[inline]
pub fn mk_alias(self, kind: ty::AliasKind, alias_ty: ty::AliasTy<'tcx>) -> Ty<'tcx> {
debug_assert_matches!(
(kind, self.def_kind(alias_ty.def_id)),
(ty::Opaque, DefKind::OpaqueTy)
| (ty::Projection | ty::Inherent, DefKind::AssocTy)
| (ty::Opaque | ty::Projection, DefKind::ImplTraitPlaceholder)
| (ty::Weak, DefKind::TyAlias)
);
self.mk_ty_from_kind(Alias(kind, alias_ty))
}
#[inline]
pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
self.mk_alias(ty::Opaque, self.mk_alias_ty(def_id, substs))
}
pub fn mk_place_field(self, place: Place<'tcx>, f: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
self.mk_place_elem(place, PlaceElem::Field(f, ty))
}
@ -2367,21 +2028,6 @@ impl<'tcx> TyCtxt<'tcx> {
}
}
impl<'tcx> TyCtxtAt<'tcx> {
/// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
#[track_caller]
pub fn ty_error_misc(self) -> Ty<'tcx> {
self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported")
}
/// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to
/// ensure it gets used.
#[track_caller]
pub fn ty_error_with_message(self, msg: impl Into<DiagnosticMessage>) -> Ty<'tcx> {
self.tcx.ty_error_with_message(self.span, msg)
}
}
/// Parameter attributes that can only be determined by examining the body of a function instead
/// of just its signature.
///

View file

@ -559,7 +559,7 @@ impl<'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for MakeSuggestableFolder<'tcx> {
Infer(InferTy::TyVar(_)) if self.infer_suggestable => t,
FnDef(def_id, substs) => {
self.tcx.mk_fn_ptr(self.tcx.fn_sig(def_id).subst(self.tcx, substs))
Ty::new_fn_ptr(self.tcx, self.tcx.fn_sig(def_id).subst(self.tcx, substs))
}
// FIXME(compiler-errors): We could replace these with infer, I guess.

View file

@ -348,7 +348,11 @@ impl<'tcx> TyCtxt<'tcx> {
)
},
types: &mut |t: ty::BoundTy| {
self.mk_bound(ty::INNERMOST, ty::BoundTy { var: shift_bv(t.var), kind: t.kind })
Ty::new_bound(
self,
ty::INNERMOST,
ty::BoundTy { var: shift_bv(t.var), kind: t.kind },
)
},
consts: &mut |c, ty: Ty<'tcx>| {
ty::Const::new_bound(self, ty::INNERMOST, shift_bv(c), ty)
@ -393,7 +397,7 @@ impl<'tcx> TyCtxt<'tcx> {
let kind = entry
.or_insert_with(|| ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon))
.expect_ty();
self.tcx.mk_bound(ty::INNERMOST, BoundTy { var, kind })
Ty::new_bound(self.tcx, ty::INNERMOST, BoundTy { var, kind })
}
fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
let entry = self.map.entry(bv);
@ -462,7 +466,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for Shifter<'tcx> {
match *ty.kind() {
ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => {
let debruijn = debruijn.shifted_in(self.amount);
self.tcx.mk_bound(debruijn, bound_ty)
Ty::new_bound(self.tcx, debruijn, bound_ty)
}
_ if ty.has_vars_bound_at_or_above(self.current_index) => ty.super_fold_with(self),

View file

@ -6,7 +6,7 @@ use rustc_hir::def_id::DefId;
use rustc_span::symbol::{kw, Symbol};
use rustc_span::Span;
use super::{Clause, EarlyBoundRegion, InstantiatedPredicates, ParamConst, ParamTy, TyCtxt};
use super::{Clause, EarlyBoundRegion, InstantiatedPredicates, ParamConst, ParamTy, Ty, TyCtxt};
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
pub enum GenericParamDefKind {
@ -101,7 +101,7 @@ impl GenericParamDef {
) -> ty::GenericArg<'tcx> {
match &self.kind {
ty::GenericParamDefKind::Lifetime => ty::Region::new_error_misc(tcx).into(),
ty::GenericParamDefKind::Type { .. } => tcx.ty_error_misc().into(),
ty::GenericParamDefKind::Type { .. } => Ty::new_misc_error(tcx).into(),
ty::GenericParamDefKind::Const { .. } => ty::Const::new_misc_error(
tcx,
tcx.type_of(self.def_id).subst(tcx, preceding_substs),

View file

@ -552,7 +552,7 @@ impl<'tcx> Instance<'tcx> {
tcx.codegen_fn_attrs(closure_did).flags.contains(CodegenFnAttrFlags::TRACK_CALLER);
let def = ty::InstanceDef::ClosureOnceShim { call_once, track_caller };
let self_ty = tcx.mk_closure(closure_did, substs);
let self_ty = Ty::new_closure(tcx, closure_did, substs);
let sig = substs.as_closure().sig();
let sig =
@ -680,7 +680,7 @@ fn polymorphize<'tcx>(
if substs == polymorphized_substs {
ty
} else {
self.tcx.mk_closure(def_id, polymorphized_substs)
Ty::new_closure(self.tcx, def_id, polymorphized_substs)
}
}
ty::Generator(def_id, substs, movability) => {
@ -689,7 +689,7 @@ fn polymorphize<'tcx>(
if substs == polymorphized_substs {
ty
} else {
self.tcx.mk_generator(def_id, polymorphized_substs, movability)
Ty::new_generator(self.tcx, def_id, polymorphized_substs, movability)
}
}
_ => ty.super_fold_with(self),

View file

@ -133,7 +133,7 @@ impl PrimitiveExt for Primitive {
F32 => tcx.types.f32,
F64 => tcx.types.f64,
// FIXME(erikdesjardins): handle non-default addrspace ptr sizes
Pointer(_) => tcx.mk_mut_ptr(tcx.mk_unit()),
Pointer(_) => Ty::new_mut_ptr(tcx, Ty::new_unit(tcx)),
}
}
@ -810,11 +810,11 @@ where
// (which may have no non-DST form), and will work as long
// as the `Abi` or `FieldsShape` is checked by users.
if i == 0 {
let nil = tcx.mk_unit();
let nil = Ty::new_unit(tcx);
let unit_ptr_ty = if this.ty.is_unsafe_ptr() {
tcx.mk_mut_ptr(nil)
Ty::new_mut_ptr(tcx, nil)
} else {
tcx.mk_mut_ref(tcx.lifetimes.re_static, nil)
Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
};
// NOTE(eddyb) using an empty `ParamEnv`, and `unwrap`-ing
@ -827,7 +827,11 @@ where
}
let mk_dyn_vtable = || {
tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_array(tcx.types.usize, 3))
Ty::new_imm_ref(
tcx,
tcx.lifetimes.re_static,
Ty::new_array(tcx, tcx.types.usize, 3),
)
/* FIXME: use actual fn pointers
Warning: naively computing the number of entries in the
vtable by counting the methods on the trait + methods on
@ -836,9 +840,9 @@ where
Increase this counter if you tried to implement this but
failed to do it without duplicating a lot of code from
other places in the compiler: 2
tcx.mk_tup(&[
tcx.mk_array(tcx.types.usize, 3),
tcx.mk_array(Option<fn()>),
Ty::new_tup(tcx,&[
Ty::new_array(tcx,tcx.types.usize, 3),
Ty::new_array(tcx,Option<fn()>),
])
*/
};
@ -850,7 +854,7 @@ where
{
let metadata = tcx.normalize_erasing_regions(
cx.param_env(),
tcx.mk_projection(metadata_def_id, [pointee]),
Ty::new_projection(tcx,metadata_def_id, [pointee]),
);
// Map `Metadata = DynMetadata<dyn Trait>` back to a vtable, since it
@ -925,15 +929,14 @@ where
ty::Dynamic(_, _, ty::DynStar) => {
if i == 0 {
TyMaybeWithLayout::Ty(tcx.mk_mut_ptr(tcx.types.unit))
TyMaybeWithLayout::Ty(Ty::new_mut_ptr(tcx, tcx.types.unit))
} else if i == 1 {
// FIXME(dyn-star) same FIXME as above applies here too
TyMaybeWithLayout::Ty(
tcx.mk_imm_ref(
tcx.lifetimes.re_static,
tcx.mk_array(tcx.types.usize, 3),
),
)
TyMaybeWithLayout::Ty(Ty::new_imm_ref(
tcx,
tcx.lifetimes.re_static,
Ty::new_array(tcx, tcx.types.usize, 3),
))
} else {
bug!("no field {i} on dyn*")
}
@ -978,10 +981,8 @@ where
})
}
ty::FnPtr(fn_sig) if offset.bytes() == 0 => {
tcx.layout_of(param_env.and(tcx.mk_fn_ptr(fn_sig))).ok().map(|layout| PointeeInfo {
size: layout.size,
align: layout.align.abi,
safe: None,
tcx.layout_of(param_env.and(Ty::new_fn_ptr(tcx, fn_sig))).ok().map(|layout| {
PointeeInfo { size: layout.size, align: layout.align.abi, safe: None }
})
}
ty::Ref(_, ty, mt) if offset.bytes() == 0 => {

View file

@ -150,17 +150,17 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> {
match *ty.kind() {
ty::Closure(def_id, substs) => {
let substs = self.fold_closure_substs(def_id, substs);
self.tcx.mk_closure(def_id, substs)
Ty::new_closure(self.tcx, def_id, substs)
}
ty::Generator(def_id, substs, movability) => {
let substs = self.fold_closure_substs(def_id, substs);
self.tcx.mk_generator(def_id, substs, movability)
Ty::new_generator(self.tcx, def_id, substs, movability)
}
ty::GeneratorWitnessMIR(def_id, substs) => {
let substs = self.fold_closure_substs(def_id, substs);
self.tcx.mk_generator_witness_mir(def_id, substs)
Ty::new_generator_witness_mir(self.tcx, def_id, substs)
}
ty::Param(param) => {
@ -186,7 +186,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> {
.emit();
}
self.interner().ty_error_misc()
Ty::new_misc_error(self.tcx)
}
}
}

View file

@ -1228,7 +1228,7 @@ pub trait PrettyPrinter<'tcx>:
// in order to place the projections inside the `<...>`.
if !resugared {
// Use a type that can't appear in defaults of type parameters.
let dummy_cx = cx.tcx().mk_fresh_ty(0);
let dummy_cx = Ty::new_fresh(cx.tcx(), 0);
let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
let args = cx
@ -2736,7 +2736,7 @@ define_print_and_forward_display! {
ty::ExistentialTraitRef<'tcx> {
// Use a type that can't appear in defaults of type parameters.
let dummy_self = cx.tcx().mk_fresh_ty(0);
let dummy_self = Ty::new_fresh(cx.tcx(),0);
let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
p!(print(trait_ref.print_only_trait_path()))
}

View file

@ -408,7 +408,7 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
bug!("bound types encountered in structurally_relate_tys")
}
(&ty::Error(guar), _) | (_, &ty::Error(guar)) => Ok(tcx.ty_error(guar)),
(&ty::Error(guar), _) | (_, &ty::Error(guar)) => Ok(Ty::new_error(tcx, guar)),
(&ty::Never, _)
| (&ty::Char, _)
@ -428,10 +428,10 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
(&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
let substs = relation.relate_item_substs(a_def.did(), a_substs, b_substs)?;
Ok(tcx.mk_adt(a_def, substs))
Ok(Ty::new_adt(tcx, a_def, substs))
}
(&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
(&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(Ty::new_foreign(tcx, a_id)),
(&ty::Dynamic(a_obj, a_region, a_repr), &ty::Dynamic(b_obj, b_region, b_repr))
if a_repr == b_repr =>
@ -439,7 +439,7 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
relation.relate(a_region, b_region)
})?;
Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound, a_repr))
Ok(Ty::new_dynamic(tcx, relation.relate(a_obj, b_obj)?, region_bound, a_repr))
}
(&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
@ -449,7 +449,7 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
// the (anonymous) type of the same generator expression. So
// all of their regions should be equated.
let substs = relation.relate(a_substs, b_substs)?;
Ok(tcx.mk_generator(a_id, substs, movability))
Ok(Ty::new_generator(tcx, a_id, substs, movability))
}
(&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
@ -459,7 +459,7 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
let b_types = b_types.map_bound(GeneratorWitness);
// Then remove the GeneratorWitness for the result
let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
Ok(tcx.mk_generator_witness(types))
Ok(Ty::new_generator_witness(tcx, types))
}
(&ty::GeneratorWitnessMIR(a_id, a_substs), &ty::GeneratorWitnessMIR(b_id, b_substs))
@ -469,7 +469,7 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
// the (anonymous) type of the same generator expression. So
// all of their regions should be equated.
let substs = relation.relate(a_substs, b_substs)?;
Ok(tcx.mk_generator_witness_mir(a_id, substs))
Ok(Ty::new_generator_witness_mir(tcx, a_id, substs))
}
(&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
@ -477,12 +477,12 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
// the (anonymous) type of the same closure expression. So
// all of their regions should be equated.
let substs = relation.relate(a_substs, b_substs)?;
Ok(tcx.mk_closure(a_id, &substs))
Ok(Ty::new_closure(tcx, a_id, &substs))
}
(&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
Ok(tcx.mk_ptr(mt))
Ok(Ty::new_ptr(tcx, mt))
}
(&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
@ -490,13 +490,13 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
Ok(tcx.mk_ref(r, mt))
Ok(Ty::new_ref(tcx, r, mt))
}
(&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
let t = relation.relate(a_t, b_t)?;
match relation.relate(sz_a, sz_b) {
Ok(sz) => Ok(tcx.mk_array_with_const_len(t, sz)),
Ok(sz) => Ok(Ty::new_array_with_const_len(tcx, t, sz)),
Err(err) => {
// Check whether the lengths are both concrete/known values,
// but are unequal, for better diagnostics.
@ -519,12 +519,15 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
(&ty::Slice(a_t), &ty::Slice(b_t)) => {
let t = relation.relate(a_t, b_t)?;
Ok(tcx.mk_slice(t))
Ok(Ty::new_slice(tcx, t))
}
(&ty::Tuple(as_), &ty::Tuple(bs)) => {
if as_.len() == bs.len() {
Ok(tcx.mk_tup_from_iter(iter::zip(as_, bs).map(|(a, b)| relation.relate(a, b)))?)
Ok(Ty::new_tup_from_iter(
tcx,
iter::zip(as_, bs).map(|(a, b)| relation.relate(a, b)),
)?)
} else if !(as_.is_empty() || bs.is_empty()) {
Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
} else {
@ -536,12 +539,12 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
if a_def_id == b_def_id =>
{
let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
Ok(tcx.mk_fn_def(a_def_id, substs))
Ok(Ty::new_fn_def(tcx, a_def_id, substs))
}
(&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
let fty = relation.relate(a_fty, b_fty)?;
Ok(tcx.mk_fn_ptr(fty))
Ok(Ty::new_fn_ptr(tcx, fty))
}
// The substs of opaque types may not all be invariant, so we have
@ -559,7 +562,7 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
b_substs,
false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle
)?;
Ok(tcx.mk_opaque(a_def_id, substs))
Ok(Ty::new_opaque(tcx, a_def_id, substs))
}
// Alias tend to mostly already be handled downstream due to normalization.
@ -569,7 +572,7 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>(
if a_kind == b_kind {
let alias_ty = relation.relate(a_data, b_data)?;
// assert_eq!(a_kind, b_kind);
Ok(tcx.mk_alias(a_kind, alias_ty))
Ok(Ty::new_alias(tcx, a_kind, alias_ty))
} else {
Err(TypeError::Sorts(expected_found(relation, a, b)))
}

View file

@ -15,6 +15,7 @@ use hir::def::DefKind;
use polonius_engine::Atom;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::intern::Interned;
use rustc_error_messages::DiagnosticMessage;
use rustc_errors::{DiagnosticArgValue, ErrorGuaranteed, IntoDiagnosticArg, MultiSpan};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
@ -25,6 +26,7 @@ use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT};
use rustc_target::spec::abi::{self, Abi};
use std::assert_matches::debug_assert_matches;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;
@ -33,9 +35,11 @@ use std::ops::{ControlFlow, Deref, Range};
use ty::util::IntTypeExt;
use rustc_type_ir::sty::TyKind::*;
use rustc_type_ir::ConstKind as IrConstKind;
use rustc_type_ir::RegionKind as IrRegionKind;
use rustc_type_ir::TyKind as IrTyKind;
use rustc_type_ir::{CollectAndApply, ConstKind as IrConstKind};
use rustc_type_ir::{DynKind, RegionKind as IrRegionKind};
use super::GenericParamDefKind;
// Re-export the `TyKind` from `rustc_type_ir` here for convenience
#[rustc_diagnostic_item = "TyKind"]
@ -1241,7 +1245,7 @@ impl<'tcx> AliasTy<'tcx> {
}
pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
tcx.mk_alias(self.kind(tcx), self)
Ty::new_alias(tcx, self.kind(tcx), self)
}
}
@ -1432,7 +1436,7 @@ impl<'tcx> ParamTy {
#[inline]
pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
tcx.mk_ty_param(self.index, self.name)
Ty::new_param(tcx, self.index, self.name)
}
pub fn span_from_generics(&self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
@ -1873,6 +1877,390 @@ impl<'tcx> Region<'tcx> {
}
}
/// Constructors for `Ty`
impl<'tcx> Ty<'tcx> {
// Avoid this in favour of more specific `new_*` methods, where possible.
#[allow(rustc::usage_of_ty_tykind)]
#[inline]
pub fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
tcx.mk_ty_from_kind(st)
}
#[inline]
pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
Ty::new(tcx, TyKind::Infer(infer))
}
#[inline]
pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
// Use a pre-interned one when possible.
tcx.types
.ty_vars
.get(v.as_usize())
.copied()
.unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
}
#[inline]
pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
Ty::new_infer(tcx, IntVar(v))
}
#[inline]
pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
Ty::new_infer(tcx, FloatVar(v))
}
#[inline]
pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
tcx.types
.fresh_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
}
#[inline]
pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
tcx.types
.fresh_int_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
}
#[inline]
pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
tcx.types
.fresh_float_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
}
#[inline]
pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
tcx.mk_ty_from_kind(Param(ParamTy { index, name }))
}
#[inline]
pub fn new_bound(
tcx: TyCtxt<'tcx>,
index: ty::DebruijnIndex,
bound_ty: ty::BoundTy,
) -> Ty<'tcx> {
Ty::new(tcx, Bound(index, bound_ty))
}
#[inline]
pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Ty<'tcx> {
Ty::new(tcx, Placeholder(placeholder))
}
#[inline]
pub fn new_alias(
tcx: TyCtxt<'tcx>,
kind: ty::AliasKind,
alias_ty: ty::AliasTy<'tcx>,
) -> Ty<'tcx> {
debug_assert_matches!(
(kind, tcx.def_kind(alias_ty.def_id)),
(ty::Opaque, DefKind::OpaqueTy)
| (ty::Projection | ty::Inherent, DefKind::AssocTy)
| (ty::Opaque | ty::Projection, DefKind::ImplTraitPlaceholder)
| (ty::Weak, DefKind::TyAlias)
);
Ty::new(tcx, Alias(kind, alias_ty))
}
#[inline]
pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
Ty::new_alias(tcx, ty::Opaque, tcx.mk_alias_ty(def_id, substs))
}
/// Constructs a `TyKind::Error` type with current `ErrorGuaranteed`
pub fn new_error(tcx: TyCtxt<'tcx>, reported: ErrorGuaranteed) -> Ty<'tcx> {
Ty::new(tcx, Error(reported))
}
/// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used.
#[track_caller]
pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
}
/// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to
/// ensure it gets used.
#[track_caller]
pub fn new_error_with_message<S: Into<MultiSpan>>(
tcx: TyCtxt<'tcx>,
span: S,
msg: impl Into<DiagnosticMessage>,
) -> Ty<'tcx> {
let reported = tcx.sess.delay_span_bug(span, msg);
Ty::new(tcx, Error(reported))
}
#[inline]
pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
use ty::IntTy::*;
match i {
Isize => tcx.types.isize,
I8 => tcx.types.i8,
I16 => tcx.types.i16,
I32 => tcx.types.i32,
I64 => tcx.types.i64,
I128 => tcx.types.i128,
}
}
#[inline]
pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
use ty::UintTy::*;
match ui {
Usize => tcx.types.usize,
U8 => tcx.types.u8,
U16 => tcx.types.u16,
U32 => tcx.types.u32,
U64 => tcx.types.u64,
U128 => tcx.types.u128,
}
}
#[inline]
pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
use ty::FloatTy::*;
match f {
F32 => tcx.types.f32,
F64 => tcx.types.f64,
}
}
#[inline]
pub fn new_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
Ty::new(tcx, Ref(r, tm.ty, tm.mutbl))
}
#[inline]
pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new_ref(tcx, r, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
}
#[inline]
pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new_ref(tcx, r, TypeAndMut { ty, mutbl: hir::Mutability::Not })
}
#[inline]
pub fn new_ptr(tcx: TyCtxt<'tcx>, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
Ty::new(tcx, RawPtr(tm))
}
#[inline]
pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new_ptr(tcx, TypeAndMut { ty, mutbl: hir::Mutability::Mut })
}
#[inline]
pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new_ptr(tcx, TypeAndMut { ty, mutbl: hir::Mutability::Not })
}
#[inline]
pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, substs: SubstsRef<'tcx>) -> Ty<'tcx> {
Ty::new(tcx, Adt(def, substs))
}
#[inline]
pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
Ty::new(tcx, Foreign(def_id))
}
#[inline]
pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
}
#[inline]
pub fn new_array_with_const_len(
tcx: TyCtxt<'tcx>,
ty: Ty<'tcx>,
ct: ty::Const<'tcx>,
) -> Ty<'tcx> {
Ty::new(tcx, Array(ty, ct))
}
#[inline]
pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new(tcx, Slice(ty))
}
#[inline]
pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(&ts))) }
}
pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
where
I: Iterator<Item = T>,
T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
{
T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
}
#[inline]
pub fn new_fn_def(
tcx: TyCtxt<'tcx>,
def_id: DefId,
substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
) -> Ty<'tcx> {
let substs = tcx.check_and_mk_substs(def_id, substs);
Ty::new(tcx, FnDef(def_id, substs))
}
#[inline]
pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
Ty::new(tcx, FnPtr(fty))
}
#[inline]
pub fn new_dynamic(
tcx: TyCtxt<'tcx>,
obj: &'tcx List<PolyExistentialPredicate<'tcx>>,
reg: ty::Region<'tcx>,
repr: DynKind,
) -> Ty<'tcx> {
Ty::new(tcx, Dynamic(obj, reg, repr))
}
#[inline]
pub fn new_projection(
tcx: TyCtxt<'tcx>,
item_def_id: DefId,
substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
) -> Ty<'tcx> {
Ty::new_alias(tcx, ty::Projection, tcx.mk_alias_ty(item_def_id, substs))
}
#[inline]
pub fn new_closure(
tcx: TyCtxt<'tcx>,
def_id: DefId,
closure_substs: SubstsRef<'tcx>,
) -> Ty<'tcx> {
debug_assert_eq!(
closure_substs.len(),
tcx.generics_of(tcx.typeck_root_def_id(def_id)).count() + 3,
"closure constructed with incorrect substitutions"
);
Ty::new(tcx, Closure(def_id, closure_substs))
}
#[inline]
pub fn new_generator(
tcx: TyCtxt<'tcx>,
def_id: DefId,
generator_substs: SubstsRef<'tcx>,
movability: hir::Movability,
) -> Ty<'tcx> {
debug_assert_eq!(
generator_substs.len(),
tcx.generics_of(tcx.typeck_root_def_id(def_id)).count() + 5,
"generator constructed with incorrect number of substitutions"
);
Ty::new(tcx, Generator(def_id, generator_substs, movability))
}
#[inline]
pub fn new_generator_witness(
tcx: TyCtxt<'tcx>,
types: ty::Binder<'tcx, &'tcx List<Ty<'tcx>>>,
) -> Ty<'tcx> {
Ty::new(tcx, GeneratorWitness(types))
}
#[inline]
pub fn new_generator_witness_mir(
tcx: TyCtxt<'tcx>,
id: DefId,
substs: SubstsRef<'tcx>,
) -> Ty<'tcx> {
Ty::new(tcx, GeneratorWitnessMIR(id, substs))
}
// misc
#[inline]
pub fn new_unit(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
tcx.types.unit
}
#[inline]
pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
}
#[inline]
pub fn new_diverging_default(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
if tcx.features().never_type_fallback { tcx.types.never } else { tcx.types.unit }
}
// lang and diagnostic tys
fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
let adt_def = tcx.adt_def(wrapper_def_id);
let substs =
InternalSubsts::for_item(tcx, wrapper_def_id, |param, substs| match param.kind {
GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
GenericParamDefKind::Type { has_default, .. } => {
if param.index == 0 {
ty_param.into()
} else {
assert!(has_default);
tcx.type_of(param.def_id).subst(tcx, substs).into()
}
}
});
Ty::new(tcx, Adt(adt_def, substs))
}
#[inline]
pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
let def_id = tcx.lang_items().get(item)?;
Some(Ty::new_generic_adt(tcx, def_id, ty))
}
#[inline]
pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
let def_id = tcx.get_diagnostic_item(name)?;
Some(Ty::new_generic_adt(tcx, def_id, ty))
}
#[inline]
pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
let def_id = tcx.require_lang_item(LangItem::OwnedBox, None);
Ty::new_generic_adt(tcx, def_id, ty)
}
#[inline]
pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
let def_id = tcx.require_lang_item(LangItem::MaybeUninit, None);
Ty::new_generic_adt(tcx, def_id, ty)
}
/// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
let context_did = tcx.require_lang_item(LangItem::Context, None);
let context_adt_ref = tcx.adt_def(context_did);
let context_substs = tcx.mk_substs(&[tcx.lifetimes.re_erased.into()]);
let context_ty = Ty::new_adt(tcx, context_adt_ref, context_substs);
Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
}
}
/// Type utilities
impl<'tcx> Ty<'tcx> {
#[inline(always)]
@ -2316,7 +2704,7 @@ impl<'tcx> Ty<'tcx> {
let assoc_items = tcx.associated_item_def_ids(
tcx.require_lang_item(hir::LangItem::DiscriminantKind, None),
);
tcx.mk_projection(assoc_items[0], tcx.mk_substs(&[self.into()]))
Ty::new_projection(tcx, assoc_items[0], tcx.mk_substs(&[self.into()]))
}
ty::Bool

View file

@ -223,7 +223,7 @@ impl<'tcx> TyCtxt<'tcx> {
};
let reported =
self.sess.emit_err(crate::error::RecursionLimitReached { ty, suggested_limit });
return self.ty_error(reported);
return Ty::new_error(self, reported);
}
match *ty.kind() {
ty::Adt(def, substs) => {
@ -610,12 +610,12 @@ impl<'tcx> TyCtxt<'tcx> {
closure_substs: SubstsRef<'tcx>,
env_region: ty::Region<'tcx>,
) -> Option<Ty<'tcx>> {
let closure_ty = self.mk_closure(closure_def_id, closure_substs);
let closure_ty = Ty::new_closure(self, closure_def_id, closure_substs);
let closure_kind_ty = closure_substs.as_closure().kind_ty();
let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
let env_ty = match closure_kind {
ty::ClosureKind::Fn => self.mk_imm_ref(env_region, closure_ty),
ty::ClosureKind::FnMut => self.mk_mut_ref(env_region, closure_ty),
ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
ty::ClosureKind::FnOnce => closure_ty,
};
Some(env_ty)
@ -656,12 +656,12 @@ impl<'tcx> TyCtxt<'tcx> {
pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
let static_ty = self.type_of(def_id).subst_identity();
if self.is_mutable_static(def_id) {
self.mk_mut_ptr(static_ty)
Ty::new_mut_ptr(self, static_ty)
} else if self.is_foreign_item(def_id) {
self.mk_imm_ptr(static_ty)
Ty::new_imm_ptr(self, static_ty)
} else {
// FIXME: These things don't *really* have 'static lifetime.
self.mk_imm_ref(self.lifetimes.re_static, static_ty)
Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
}
}
@ -676,11 +676,11 @@ impl<'tcx> TyCtxt<'tcx> {
// Make sure that accesses to unsafe statics end up using raw pointers.
// For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
if self.is_mutable_static(def_id) {
self.mk_mut_ptr(static_ty)
Ty::new_mut_ptr(self, static_ty)
} else if self.is_foreign_item(def_id) {
self.mk_imm_ptr(static_ty)
Ty::new_imm_ptr(self, static_ty)
} else {
self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
}
}
@ -854,7 +854,7 @@ impl<'tcx> OpaqueTypeExpander<'tcx> {
let hidden_ty = bty.subst(self.tcx, substs);
self.fold_ty(hidden_ty);
}
let expanded_ty = self.tcx.mk_generator_witness_mir(def_id, substs);
let expanded_ty = Ty::new_generator_witness_mir(self.tcx, def_id, substs);
self.expanded_cache.insert((def_id, substs), expanded_ty);
expanded_ty
}

View file

@ -16,7 +16,7 @@ impl<'tcx> Value<TyCtxt<'tcx>, DepKind> for Ty<'_> {
fn from_cycle_error(tcx: TyCtxt<'tcx>, _: &[QueryInfo<DepKind>]) -> Self {
// SAFETY: This is never called when `Self` is not `Ty<'tcx>`.
// FIXME: Represent the above fact in the trait system somehow.
unsafe { std::mem::transmute::<Ty<'tcx>, Ty<'_>>(tcx.ty_error_misc()) }
unsafe { std::mem::transmute::<Ty<'tcx>, Ty<'_>>(Ty::new_misc_error(tcx)) }
}
}
@ -34,7 +34,7 @@ impl<'tcx> Value<TyCtxt<'tcx>, DepKind> for ty::SymbolName<'_> {
impl<'tcx> Value<TyCtxt<'tcx>, DepKind> for ty::Binder<'_, ty::FnSig<'_>> {
fn from_cycle_error(tcx: TyCtxt<'tcx>, stack: &[QueryInfo<DepKind>]) -> Self {
let err = tcx.ty_error_misc();
let err = Ty::new_misc_error(tcx);
let arity = if let Some(frame) = stack.get(0)
&& frame.query.dep_kind == DepKind::fn_sig