use crate::ich::NodeIdHashingMode;
use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use crate::ty::fold::TypeFolder;
use crate::ty::layout::IntegerExt;
use crate::ty::query::TyCtxtAt;
use crate::ty::subst::{GenericArgKind, Subst, SubstsRef};
use crate::ty::TyKind::*;
use crate::ty::{self, DefIdTree, List, Ty, TyCtxt, TypeFoldable};
use rustc_apfloat::Float as _;
use rustc_ast as ast;
use rustc_attr::{self as attr, SignedInt, UnsignedInt};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId;
use rustc_macros::HashStable;
use rustc_span::Span;
use rustc_target::abi::{Integer, Size, TargetDataLayout};
use smallvec::SmallVec;
use std::{cmp, fmt};
#[derive(Copy, Clone, Debug)]
pub struct Discr<'tcx> {
pub val: u128,
pub ty: Ty<'tcx>,
}
impl<'tcx> fmt::Display for Discr<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self.ty.kind() {
ty::Int(ity) => {
let size = ty::tls::with(|tcx| Integer::from_attr(&tcx, SignedInt(ity)).size());
let x = self.val;
let x = size.sign_extend(x) as i128;
write!(fmt, "{}", x)
}
_ => write!(fmt, "{}", self.val),
}
}
}
fn signed_min(size: Size) -> i128 {
size.sign_extend(1_u128 << (size.bits() - 1)) as i128
}
fn signed_max(size: Size) -> i128 {
i128::MAX >> (128 - size.bits())
}
fn unsigned_max(size: Size) -> u128 {
u128::MAX >> (128 - size.bits())
}
fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) {
let (int, signed) = match *ty.kind() {
Int(ity) => (Integer::from_attr(&tcx, SignedInt(ity)), true),
Uint(uty) => (Integer::from_attr(&tcx, UnsignedInt(uty)), false),
_ => bug!("non integer discriminant"),
};
(int.size(), signed)
}
impl<'tcx> Discr<'tcx> {
pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
self.checked_add(tcx, 1).0
}
pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
let (size, signed) = int_size_and_signed(tcx, self.ty);
let (val, oflo) = if signed {
let min = signed_min(size);
let max = signed_max(size);
let val = size.sign_extend(self.val) as i128;
assert!(n < (i128::MAX as u128));
let n = n as i128;
let oflo = val > max - n;
let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
let val = val as u128;
let val = size.truncate(val);
(val, oflo)
} else {
let max = unsigned_max(size);
let val = self.val;
let oflo = val > max - n;
let val = if oflo { n - (max - val) - 1 } else { val + n };
(val, oflo)
};
(Self { val, ty: self.ty }, oflo)
}
}
pub trait IntTypeExt {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>;
fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>>;
fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>;
}
impl IntTypeExt for attr::IntType {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match *self {
SignedInt(ast::IntTy::I8) => tcx.types.i8,
SignedInt(ast::IntTy::I16) => tcx.types.i16,
SignedInt(ast::IntTy::I32) => tcx.types.i32,
SignedInt(ast::IntTy::I64) => tcx.types.i64,
SignedInt(ast::IntTy::I128) => tcx.types.i128,
SignedInt(ast::IntTy::Isize) => tcx.types.isize,
UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
}
}
fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
Discr { val: 0, ty: self.to_ty(tcx) }
}
fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
if let Some(val) = val {
assert_eq!(self.to_ty(tcx), val.ty);
let (new, oflo) = val.checked_add(tcx, 1);
if oflo { None } else { Some(new) }
} else {
Some(self.initial_discriminant(tcx))
}
}
}
#[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
pub enum Representability {
Representable,
ContainsRecursive,
SelfRecursive(Vec<Span>),
}
impl<'tcx> TyCtxt<'tcx> {
pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
let mut hasher = StableHasher::new();
let mut hcx = self.create_stable_hashing_context();
let ty = self.erase_regions(ty);
hcx.while_hashing_spans(false, |hcx| {
hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
ty.hash_stable(hcx, &mut hasher);
});
});
hasher.finish()
}
pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
if let ty::Adt(def, substs) = *ty.kind() {
for field in def.all_fields() {
let field_ty = field.ty(self, substs);
if let Error(_) = field_ty.kind() {
return true;
}
}
}
false
}
pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> {
let tcx = self;
tcx.struct_tail_with_normalize(ty, |ty| ty)
}
pub fn struct_tail_erasing_lifetimes(
self,
ty: Ty<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> Ty<'tcx> {
let tcx = self;
tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty))
}
pub fn struct_tail_with_normalize(
self,
mut ty: Ty<'tcx>,
normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
) -> Ty<'tcx> {
loop {
match *ty.kind() {
ty::Adt(def, substs) => {
if !def.is_struct() {
break;
}
match def.non_enum_variant().fields.last() {
Some(f) => ty = f.ty(self, substs),
None => break,
}
}
ty::Tuple(tys) => {
if let Some((&last_ty, _)) = tys.split_last() {
ty = last_ty.expect_ty();
} else {
break;
}
}
ty::Projection(_) | ty::Opaque(..) => {
let normalized = normalize(ty);
if ty == normalized {
return ty;
} else {
ty = normalized;
}
}
_ => {
break;
}
}
}
ty
}
pub fn struct_lockstep_tails_erasing_lifetimes(
self,
source: Ty<'tcx>,
target: Ty<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> (Ty<'tcx>, Ty<'tcx>) {
let tcx = self;
tcx.struct_lockstep_tails_with_normalize(source, target, |ty| {
tcx.normalize_erasing_regions(param_env, ty)
})
}
pub fn struct_lockstep_tails_with_normalize(
self,
source: Ty<'tcx>,
target: Ty<'tcx>,
normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
) -> (Ty<'tcx>, Ty<'tcx>) {
let (mut a, mut b) = (source, target);
loop {
match (&a.kind(), &b.kind()) {
(&Adt(a_def, a_substs), &Adt(b_def, b_substs))
if a_def == b_def && a_def.is_struct() =>
{
if let Some(f) = a_def.non_enum_variant().fields.last() {
a = f.ty(self, a_substs);
b = f.ty(self, b_substs);
} else {
break;
}
}
(&Tuple(a_tys), &Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
if let Some(a_last) = a_tys.last() {
a = a_last.expect_ty();
b = b_tys.last().unwrap().expect_ty();
} else {
break;
}
}
(ty::Projection(_) | ty::Opaque(..), _)
| (_, ty::Projection(_) | ty::Opaque(..)) => {
let a_norm = normalize(a);
let b_norm = normalize(b);
if a == a_norm && b == b_norm {
break;
} else {
a = a_norm;
b = b_norm;
}
}
_ => break,
}
}
(a, b)
}
pub fn calculate_dtor(
self,
adt_did: DefId,
validate: impl Fn(Self, DefId) -> Result<(), ErrorReported>,
) -> Option<ty::Destructor> {
let drop_trait = self.lang_items().drop_trait()?;
self.ensure().coherent_trait(drop_trait);
let ty = self.type_of(adt_did);
let dtor_did = self.find_map_relevant_impl(drop_trait, ty, |impl_did| {
if let Some(item) = self.associated_items(impl_did).in_definition_order().next() {
if validate(self, impl_did).is_ok() {
return Some(item.def_id);
}
}
None
});
Some(ty::Destructor { did: dtor_did? })
}
pub fn destructor_constraints(self, def: &'tcx ty::AdtDef) -> Vec<ty::subst::GenericArg<'tcx>> {
let dtor = match def.destructor(self) {
None => {
debug!("destructor_constraints({:?}) - no dtor", def.did);
return vec![];
}
Some(dtor) => dtor.did,
};
let impl_def_id = self.associated_item(dtor).container.id();
let impl_generics = self.generics_of(impl_def_id);
let impl_substs = match *self.type_of(impl_def_id).kind() {
ty::Adt(def_, substs) if def_ == def => substs,
_ => bug!(),
};
let item_substs = match *self.type_of(def.did).kind() {
ty::Adt(def_, substs) if def_ == def => substs,
_ => bug!(),
};
let result = item_substs
.iter()
.zip(impl_substs.iter())
.filter(|&(_, k)| {
match k.unpack() {
GenericArgKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => {
!impl_generics.region_param(ebr, self).pure_wrt_drop
}
GenericArgKind::Type(&ty::TyS { kind: ty::Param(ref pt), .. }) => {
!impl_generics.type_param(pt, self).pure_wrt_drop
}
GenericArgKind::Const(&ty::Const {
val: ty::ConstKind::Param(ref pc), ..
}) => !impl_generics.const_param(pc, self).pure_wrt_drop,
GenericArgKind::Lifetime(_)
| GenericArgKind::Type(_)
| GenericArgKind::Const(_) => {
false
}
}
})
.map(|(item_param, _)| item_param)
.collect();
debug!("destructor_constraint({:?}) = {:?}", def.did, result);
result
}
pub fn is_closure(self, def_id: DefId) -> bool {
matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator)
}
pub fn is_trait(self, def_id: DefId) -> bool {
self.def_kind(def_id) == DefKind::Trait
}
pub fn is_trait_alias(self, def_id: DefId) -> bool {
self.def_kind(def_id) == DefKind::TraitAlias
}
pub fn is_constructor(self, def_id: DefId) -> bool {
matches!(self.def_kind(def_id), DefKind::Ctor(..))
}
pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
let mut def_id = def_id;
while self.is_closure(def_id) {
def_id = self.parent(def_id).unwrap_or_else(|| {
bug!("closure {:?} has no parent", def_id);
});
}
def_id
}
pub fn closure_env_ty(
self,
closure_def_id: DefId,
closure_substs: SubstsRef<'tcx>,
) -> Option<ty::Binder<Ty<'tcx>>> {
let closure_ty = self.mk_closure(closure_def_id, closure_substs);
let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
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(self.mk_region(env_region), closure_ty),
ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
ty::ClosureKind::FnOnce => closure_ty,
};
Some(ty::Binder::bind(env_ty))
}
pub fn is_static(self, def_id: DefId) -> bool {
self.static_mutability(def_id).is_some()
}
pub fn is_thread_local_static(self, def_id: DefId) -> bool {
self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
}
pub fn is_mutable_static(self, def_id: DefId) -> bool {
self.static_mutability(def_id) == Some(hir::Mutability::Mut)
}
pub fn static_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
let static_ty = self.normalize_erasing_regions(ty::ParamEnv::empty(), self.type_of(def_id));
if self.is_mutable_static(def_id) {
self.mk_mut_ptr(static_ty)
} else if self.is_foreign_item(def_id) {
self.mk_imm_ptr(static_ty)
} else {
self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
}
}
pub fn try_expand_impl_trait_type(
self,
def_id: DefId,
substs: SubstsRef<'tcx>,
) -> Result<Ty<'tcx>, Ty<'tcx>> {
let mut visitor = OpaqueTypeExpander {
seen_opaque_tys: FxHashSet::default(),
expanded_cache: FxHashMap::default(),
primary_def_id: Some(def_id),
found_recursion: false,
check_recursion: true,
tcx: self,
};
let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
}
}
struct OpaqueTypeExpander<'tcx> {
seen_opaque_tys: FxHashSet<DefId>,
expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
primary_def_id: Option<DefId>,
found_recursion: bool,
check_recursion: bool,
tcx: TyCtxt<'tcx>,
}
impl<'tcx> OpaqueTypeExpander<'tcx> {
fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
if self.found_recursion {
return None;
}
let substs = substs.fold_with(self);
if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
Some(expanded_ty) => expanded_ty,
None => {
let generic_ty = self.tcx.type_of(def_id);
let concrete_ty = generic_ty.subst(self.tcx, substs);
let expanded_ty = self.fold_ty(concrete_ty);
self.expanded_cache.insert((def_id, substs), expanded_ty);
expanded_ty
}
};
if self.check_recursion {
self.seen_opaque_tys.remove(&def_id);
}
Some(expanded_ty)
} else {
self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
None
}
}
}
impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
if let ty::Opaque(def_id, substs) = t.kind {
self.expand_opaque_ty(def_id, substs).unwrap_or(t)
} else if t.has_opaque_types() {
t.super_fold_with(self)
} else {
t
}
}
}
impl<'tcx> ty::TyS<'tcx> {
pub fn numeric_max_val(&'tcx self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ty::Const<'tcx>> {
let val = match self.kind() {
ty::Int(_) | ty::Uint(_) => {
let (size, signed) = int_size_and_signed(tcx, self);
let val = if signed { signed_max(size) as u128 } else { unsigned_max(size) };
Some(val)
}
ty::Char => Some(std::char::MAX as u128),
ty::Float(fty) => Some(match fty {
ast::FloatTy::F32 => rustc_apfloat::ieee::Single::INFINITY.to_bits(),
ast::FloatTy::F64 => rustc_apfloat::ieee::Double::INFINITY.to_bits(),
}),
_ => None,
};
val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
}
pub fn numeric_min_val(&'tcx self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ty::Const<'tcx>> {
let val = match self.kind() {
ty::Int(_) | ty::Uint(_) => {
let (size, signed) = int_size_and_signed(tcx, self);
let val = if signed { size.truncate(signed_min(size) as u128) } else { 0 };
Some(val)
}
ty::Char => Some(0),
ty::Float(fty) => Some(match fty {
ast::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
ast::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
}),
_ => None,
};
val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
}
pub fn is_copy_modulo_regions(
&'tcx self,
tcx_at: TyCtxtAt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> bool {
tcx_at.is_copy_raw(param_env.and(self))
}
pub fn is_sized(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self))
}
pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
}
fn is_trivially_freeze(&self) -> bool {
match self.kind() {
ty::Int(_)
| ty::Uint(_)
| ty::Float(_)
| ty::Bool
| ty::Char
| ty::Str
| ty::Never
| ty::Ref(..)
| ty::RawPtr(_)
| ty::FnDef(..)
| ty::Error(_)
| ty::FnPtr(_) => true,
ty::Tuple(_) => self.tuple_fields().all(Self::is_trivially_freeze),
ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
ty::Adt(..)
| ty::Bound(..)
| ty::Closure(..)
| ty::Dynamic(..)
| ty::Foreign(_)
| ty::Generator(..)
| ty::GeneratorWitness(_)
| ty::Infer(_)
| ty::Opaque(..)
| ty::Param(_)
| ty::Placeholder(_)
| ty::Projection(_) => false,
}
}
#[inline]
pub fn needs_drop(&'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
match needs_drop_components(self, &tcx.data_layout) {
Err(AlwaysRequiresDrop) => true,
Ok(components) => {
let query_ty = match *components {
[] => return false,
[component_ty] => component_ty,
_ => self,
};
let erased = tcx.normalize_erasing_regions(param_env, query_ty);
tcx.needs_drop_raw(param_env.and(erased))
}
}
}
#[inline]
pub fn is_structural_eq_shallow(&'tcx self, tcx: TyCtxt<'tcx>) -> bool {
match self.kind() {
Adt(..) => tcx.has_structural_eq_impls(self),
Bool | Char | Int(_) | Uint(_) | Str | Never => true,
Ref(..) | Array(..) | Slice(_) | Tuple(..) => true,
RawPtr(_) | FnPtr(_) => true,
Float(_) => false,
FnDef(..) | Closure(..) | Dynamic(..) | Generator(..) => false,
Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false,
Foreign(_) | GeneratorWitness(..) | Error(_) => false,
}
}
pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
match (&a.kind(), &b.kind()) {
(&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => {
if did_a != did_b {
return false;
}
substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b))
}
_ => a == b,
}
}
pub fn is_representable(&'tcx self, tcx: TyCtxt<'tcx>, sp: Span) -> Representability {
fn fold_repr<It: Iterator<Item = Representability>>(iter: It) -> Representability {
iter.fold(Representability::Representable, |r1, r2| match (r1, r2) {
(Representability::SelfRecursive(v1), Representability::SelfRecursive(v2)) => {
Representability::SelfRecursive(v1.into_iter().chain(v2).collect())
}
(r1, r2) => cmp::max(r1, r2),
})
}
fn are_inner_types_recursive<'tcx>(
tcx: TyCtxt<'tcx>,
sp: Span,
seen: &mut Vec<Ty<'tcx>>,
representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
ty: Ty<'tcx>,
) -> Representability {
match ty.kind() {
Tuple(..) => {
fold_repr(ty.tuple_fields().map(|ty| {
is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
}))
}
Array(ty, _) => {
is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
}
Adt(def, substs) => {
fold_repr(def.all_fields().map(|field| {
let ty = field.ty(tcx, substs);
let span = match field
.did
.as_local()
.map(|id| tcx.hir().local_def_id_to_hir_id(id))
.and_then(|id| tcx.hir().find(id))
{
Some(hir::Node::Field(field)) => field.ty.span,
_ => sp,
};
match is_type_structurally_recursive(
tcx,
span,
seen,
representable_cache,
ty,
) {
Representability::SelfRecursive(_) => {
Representability::SelfRecursive(vec![span])
}
x => x,
}
}))
}
Closure(..) => {
bug!("requires check invoked on inapplicable type: {:?}", ty)
}
_ => Representability::Representable,
}
}
fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
match *ty.kind() {
Adt(ty_def, _) => ty_def == def,
_ => false,
}
}
fn is_type_structurally_recursive<'tcx>(
tcx: TyCtxt<'tcx>,
sp: Span,
seen: &mut Vec<Ty<'tcx>>,
representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
ty: Ty<'tcx>,
) -> Representability {
debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
if let Some(representability) = representable_cache.get(ty) {
debug!(
"is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
ty, sp, representability
);
return representability.clone();
}
let representability =
is_type_structurally_recursive_inner(tcx, sp, seen, representable_cache, ty);
representable_cache.insert(ty, representability.clone());
representability
}
fn is_type_structurally_recursive_inner<'tcx>(
tcx: TyCtxt<'tcx>,
sp: Span,
seen: &mut Vec<Ty<'tcx>>,
representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
ty: Ty<'tcx>,
) -> Representability {
match ty.kind() {
Adt(def, _) => {
{
let mut iter = seen.iter();
if let Some(&seen_type) = iter.next() {
if same_struct_or_enum(seen_type, *def) {
debug!("SelfRecursive: {:?} contains {:?}", seen_type, ty);
return Representability::SelfRecursive(vec![sp]);
}
}
for &seen_type in iter {
if ty::TyS::same_type(ty, seen_type) {
debug!("ContainsRecursive: {:?} contains {:?}", seen_type, ty);
return Representability::ContainsRecursive;
}
}
}
seen.push(ty);
let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
seen.pop();
out
}
_ => {
are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
}
}
}
debug!("is_type_representable: {:?}", self);
let mut seen: Vec<Ty<'_>> = Vec::new();
let mut representable_cache = FxHashMap::default();
let r = is_type_structurally_recursive(tcx, sp, &mut seen, &mut representable_cache, self);
debug!("is_type_representable: {:?} is {:?}", self, r);
r
}
pub fn peel_refs(&'tcx self) -> Ty<'tcx> {
let mut ty = self;
while let Ref(_, inner_ty, _) = ty.kind() {
ty = inner_ty;
}
ty
}
}
pub enum ExplicitSelf<'tcx> {
ByValue,
ByReference(ty::Region<'tcx>, hir::Mutability),
ByRawPointer(hir::Mutability),
ByBox,
Other,
}
impl<'tcx> ExplicitSelf<'tcx> {
pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
where
P: Fn(Ty<'tcx>) -> bool,
{
use self::ExplicitSelf::*;
match *self_arg_ty.kind() {
_ if is_self_ty(self_arg_ty) => ByValue,
ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
_ => Other,
}
}
}
pub fn needs_drop_components(
ty: Ty<'tcx>,
target_layout: &TargetDataLayout,
) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
match ty.kind() {
ty::Infer(ty::FreshIntTy(_))
| ty::Infer(ty::FreshFloatTy(_))
| ty::Bool
| ty::Int(_)
| ty::Uint(_)
| ty::Float(_)
| ty::Never
| ty::FnDef(..)
| ty::FnPtr(_)
| ty::Char
| ty::GeneratorWitness(..)
| ty::RawPtr(_)
| ty::Ref(..)
| ty::Str => Ok(SmallVec::new()),
ty::Foreign(..) => Ok(SmallVec::new()),
ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
ty::Slice(ty) => needs_drop_components(ty, target_layout),
ty::Array(elem_ty, size) => {
match needs_drop_components(elem_ty, target_layout) {
Ok(v) if v.is_empty() => Ok(v),
res => match size.val.try_to_bits(target_layout.pointer_size) {
Some(0) => Ok(SmallVec::new()),
Some(_) => res,
None => Ok(smallvec![ty]),
},
}
}
ty::Tuple(..) => ty.tuple_fields().try_fold(SmallVec::new(), move |mut acc, elem| {
acc.extend(needs_drop_components(elem, target_layout)?);
Ok(acc)
}),
ty::Adt(..)
| ty::Projection(..)
| ty::Param(_)
| ty::Bound(..)
| ty::Placeholder(..)
| ty::Opaque(..)
| ty::Infer(_)
| ty::Closure(..)
| ty::Generator(..) => Ok(smallvec![ty]),
}
}
pub fn fold_list<'tcx, F, T>(
list: &'tcx ty::List<T>,
folder: &mut F,
intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List<T>,
) -> &'tcx ty::List<T>
where
F: TypeFolder<'tcx>,
T: TypeFoldable<'tcx> + PartialEq + Copy,
{
let mut iter = list.iter();
if let Some((i, new_t)) = iter.by_ref().enumerate().find_map(|(i, t)| {
let new_t = t.fold_with(folder);
if new_t == t { None } else { Some((i, new_t)) }
}) {
let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len());
new_list.extend_from_slice(&list[..i]);
new_list.push(new_t);
new_list.extend(iter.map(|t| t.fold_with(folder)));
intern(folder.tcx(), &new_list)
} else {
list
}
}
#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
pub struct AlwaysRequiresDrop;
pub fn normalize_opaque_types(
tcx: TyCtxt<'tcx>,
val: &'tcx List<ty::Predicate<'tcx>>,
) -> &'tcx List<ty::Predicate<'tcx>> {
let mut visitor = OpaqueTypeExpander {
seen_opaque_tys: FxHashSet::default(),
expanded_cache: FxHashMap::default(),
primary_def_id: None,
found_recursion: false,
check_recursion: false,
tcx,
};
val.fold_with(&mut visitor)
}
pub fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { normalize_opaque_types, ..*providers }
}