]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_middle/src/ty/util.rs
New upstream version 1.59.0+dfsg1
[rustc.git] / compiler / rustc_middle / src / ty / util.rs
CommitLineData
9fa01778
XL
1//! Miscellaneous type-system utilities that are too small to deserve their own modules.
2
f9f354fc 3use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
a2a8927a 4use crate::ty::fold::{FallibleTypeFolder, TypeFolder};
ba9703b0 5use crate::ty::layout::IntegerExt;
9fa01778 6use crate::ty::query::TyCtxtAt;
29967ef6 7use crate::ty::subst::{GenericArgKind, Subst, SubstsRef};
9fa01778 8use crate::ty::TyKind::*;
136023e0 9use crate::ty::{self, DebruijnIndex, DefIdTree, List, Ty, TyCtxt, TypeFoldable};
dfeec247 10use rustc_apfloat::Float as _;
3dfed10e 11use rustc_ast as ast;
74b04a01 12use rustc_attr::{self as attr, SignedInt, UnsignedInt};
0731742a 13use rustc_data_structures::fx::{FxHashMap, FxHashSet};
dfeec247 14use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
ba9703b0 15use rustc_errors::ErrorReported;
dfeec247
XL
16use rustc_hir as hir;
17use rustc_hir::def::DefKind;
18use rustc_hir::def_id::DefId;
532ac7d7 19use rustc_macros::HashStable;
c295e0f8 20use rustc_query_system::ich::NodeIdHashingMode;
cdc7bbd5 21use rustc_span::DUMMY_SP;
ba9703b0 22use rustc_target::abi::{Integer, Size, TargetDataLayout};
74b04a01 23use smallvec::SmallVec;
cdc7bbd5 24use std::{fmt, iter};
e9174d1e 25
0531ce1d
XL
26#[derive(Copy, Clone, Debug)]
27pub struct Discr<'tcx> {
9fa01778 28 /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`).
0531ce1d 29 pub val: u128,
dfeec247 30 pub ty: Ty<'tcx>,
0531ce1d 31}
8bb4bdeb 32
0531ce1d 33impl<'tcx> fmt::Display for Discr<'tcx> {
0bf4aa26 34 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1b1a35ee 35 match *self.ty.kind() {
b7449926 36 ty::Int(ity) => {
5869c6ff 37 let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
532ac7d7 38 let x = self.val;
0531ce1d 39 // sign extend the raw representation to be an i128
29967ef6 40 let x = size.sign_extend(x) as i128;
0531ce1d 41 write!(fmt, "{}", x)
dfeec247 42 }
0531ce1d
XL
43 _ => write!(fmt, "{}", self.val),
44 }
45 }
cc61c64b 46}
8bb4bdeb 47
dfeec247 48fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) {
1b1a35ee 49 let (int, signed) = match *ty.kind() {
5869c6ff
XL
50 Int(ity) => (Integer::from_int_ty(&tcx, ity), true),
51 Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false),
dfeec247
XL
52 _ => bug!("non integer discriminant"),
53 };
54 (int.size(), signed)
55}
56
0531ce1d 57impl<'tcx> Discr<'tcx> {
9fa01778 58 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
dc9dc135 59 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
0531ce1d
XL
60 self.checked_add(tcx, 1).0
61 }
dc9dc135 62 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
dfeec247
XL
63 let (size, signed) = int_size_and_signed(tcx, self.ty);
64 let (val, oflo) = if signed {
c295e0f8
XL
65 let min = size.signed_int_min();
66 let max = size.signed_int_max();
29967ef6 67 let val = size.sign_extend(self.val) as i128;
74b04a01 68 assert!(n < (i128::MAX as u128));
0531ce1d
XL
69 let n = n as i128;
70 let oflo = val > max - n;
dfeec247 71 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
0531ce1d
XL
72 // zero the upper bits
73 let val = val as u128;
29967ef6 74 let val = size.truncate(val);
dfeec247 75 (val, oflo)
0531ce1d 76 } else {
c295e0f8 77 let max = size.unsigned_int_max();
0531ce1d
XL
78 let val = self.val;
79 let oflo = val > max - n;
dfeec247
XL
80 let val = if oflo { n - (max - val) - 1 } else { val + n };
81 (val, oflo)
82 };
83 (Self { val, ty: self.ty }, oflo)
8bb4bdeb 84 }
e9174d1e
SL
85}
86
0531ce1d 87pub trait IntTypeExt {
dc9dc135
XL
88 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>;
89 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>>;
90 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>;
0531ce1d
XL
91}
92
e9174d1e 93impl IntTypeExt for attr::IntType {
dc9dc135 94 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
e9174d1e 95 match *self {
dfeec247
XL
96 SignedInt(ast::IntTy::I8) => tcx.types.i8,
97 SignedInt(ast::IntTy::I16) => tcx.types.i16,
98 SignedInt(ast::IntTy::I32) => tcx.types.i32,
99 SignedInt(ast::IntTy::I64) => tcx.types.i64,
100 SignedInt(ast::IntTy::I128) => tcx.types.i128,
101 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
102 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
103 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
104 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
105 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
106 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
2c00a5a8 107 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
e9174d1e
SL
108 }
109 }
110
dc9dc135 111 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
dfeec247 112 Discr { val: 0, ty: self.to_ty(tcx) }
e9174d1e
SL
113 }
114
dc9dc135 115 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
a7813a04 116 if let Some(val) = val {
0531ce1d
XL
117 assert_eq!(self.to_ty(tcx), val.ty);
118 let (new, oflo) = val.checked_add(tcx, 1);
dfeec247 119 if oflo { None } else { Some(new) }
a7813a04
XL
120 } else {
121 Some(self.initial_discriminant(tcx))
122 }
e9174d1e
SL
123 }
124}
125
dc9dc135 126impl<'tcx> TyCtxt<'tcx> {
cc61c64b
XL
127 /// Creates a hash of the type `Ty` which will be the same no matter what crate
128 /// context it's calculated within. This is used by the `type_id` intrinsic.
129 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
130 let mut hasher = StableHasher::new();
ea8adc8c 131 let mut hcx = self.create_stable_hashing_context();
cc61c64b 132
3b2f2976
XL
133 // We want the type_id be independent of the types free regions, so we
134 // erase them. The erase_regions() call will also anonymize bound
135 // regions, which is desirable too.
fc512014 136 let ty = self.erase_regions(ty);
3b2f2976 137
cc61c64b
XL
138 hcx.while_hashing_spans(false, |hcx| {
139 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
140 ty.hash_stable(hcx, &mut hasher);
141 });
142 });
143 hasher.finish()
144 }
cc61c64b 145
5bcae85e 146 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
1b1a35ee 147 if let ty::Adt(def, substs) = *ty.kind() {
0bf4aa26
XL
148 for field in def.all_fields() {
149 let field_ty = field.ty(self, substs);
1b1a35ee 150 if let Error(_) = field_ty.kind() {
0bf4aa26 151 return true;
5bcae85e
SL
152 }
153 }
5bcae85e
SL
154 }
155 false
156 }
157
416331ca
XL
158 /// Attempts to returns the deeply last field of nested structures, but
159 /// does not apply any normalization in its search. Returns the same type
160 /// if input `ty` is not a structure at all.
dfeec247 161 pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> {
416331ca
XL
162 let tcx = self;
163 tcx.struct_tail_with_normalize(ty, |ty| ty)
164 }
165
166 /// Returns the deeply last field of nested structures, or the same type if
167 /// not a structure at all. Corresponds to the only possible unsized field,
168 /// and its type can be used to determine unsizing strategy.
169 ///
170 /// Should only be called if `ty` has no inference variables and does not
171 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
172 /// normalization attempt may cause compiler bugs.
dfeec247
XL
173 pub fn struct_tail_erasing_lifetimes(
174 self,
175 ty: Ty<'tcx>,
176 param_env: ty::ParamEnv<'tcx>,
177 ) -> Ty<'tcx> {
416331ca
XL
178 let tcx = self;
179 tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty))
180 }
181
182 /// Returns the deeply last field of nested structures, or the same type if
183 /// not a structure at all. Corresponds to the only possible unsized field,
184 /// and its type can be used to determine unsizing strategy.
185 ///
186 /// This is parameterized over the normalization strategy (i.e. how to
187 /// handle `<T as Trait>::Assoc` and `impl Trait`); pass the identity
188 /// function to indicate no normalization should take place.
189 ///
190 /// See also `struct_tail_erasing_lifetimes`, which is suitable for use
191 /// during codegen.
dfeec247
XL
192 pub fn struct_tail_with_normalize(
193 self,
194 mut ty: Ty<'tcx>,
195 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
196 ) -> Ty<'tcx> {
136023e0 197 let recursion_limit = self.recursion_limit();
fc512014 198 for iteration in 0.. {
136023e0 199 if !recursion_limit.value_within_limit(iteration) {
fc512014
XL
200 return self.ty_error_with_message(
201 DUMMY_SP,
202 &format!("reached the recursion limit finding the struct tail for {}", ty),
203 );
204 }
1b1a35ee 205 match *ty.kind() {
b7449926 206 ty::Adt(def, substs) => {
7cac9316
XL
207 if !def.is_struct() {
208 break;
209 }
2c00a5a8 210 match def.non_enum_variant().fields.last() {
7cac9316
XL
211 Some(f) => ty = f.ty(self, substs),
212 None => break,
213 }
214 }
215
94222f64
XL
216 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
217 ty = last_ty.expect_ty();
7cac9316
XL
218 }
219
94222f64
XL
220 ty::Tuple(_) => break,
221
416331ca
XL
222 ty::Projection(_) | ty::Opaque(..) => {
223 let normalized = normalize(ty);
224 if ty == normalized {
225 return ty;
226 } else {
227 ty = normalized;
228 }
229 }
230
7cac9316
XL
231 _ => {
232 break;
233 }
e9174d1e
SL
234 }
235 }
236 ty
237 }
238
60c5eb7d 239 /// Same as applying `struct_tail` on `source` and `target`, but only
e9174d1e
SL
240 /// keeps going as long as the two types are instances of the same
241 /// structure definitions.
a1dfa0c6 242 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
e9174d1e 243 /// whereas struct_tail produces `T`, and `Trait`, respectively.
416331ca
XL
244 ///
245 /// Should only be called if the types have no inference variables and do
60c5eb7d 246 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
416331ca 247 /// normalization attempt may cause compiler bugs.
dfeec247
XL
248 pub fn struct_lockstep_tails_erasing_lifetimes(
249 self,
250 source: Ty<'tcx>,
251 target: Ty<'tcx>,
252 param_env: ty::ParamEnv<'tcx>,
253 ) -> (Ty<'tcx>, Ty<'tcx>) {
416331ca 254 let tcx = self;
dfeec247
XL
255 tcx.struct_lockstep_tails_with_normalize(source, target, |ty| {
256 tcx.normalize_erasing_regions(param_env, ty)
257 })
416331ca
XL
258 }
259
60c5eb7d 260 /// Same as applying `struct_tail` on `source` and `target`, but only
416331ca
XL
261 /// keeps going as long as the two types are instances of the same
262 /// structure definitions.
263 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
264 /// whereas struct_tail produces `T`, and `Trait`, respectively.
265 ///
266 /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use
267 /// during codegen.
dfeec247
XL
268 pub fn struct_lockstep_tails_with_normalize(
269 self,
270 source: Ty<'tcx>,
271 target: Ty<'tcx>,
272 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
273 ) -> (Ty<'tcx>, Ty<'tcx>) {
e9174d1e 274 let (mut a, mut b) = (source, target);
041b39d2 275 loop {
1b1a35ee 276 match (&a.kind(), &b.kind()) {
b7449926 277 (&Adt(a_def, a_substs), &Adt(b_def, b_substs))
dfeec247
XL
278 if a_def == b_def && a_def.is_struct() =>
279 {
2c00a5a8 280 if let Some(f) = a_def.non_enum_variant().fields.last() {
041b39d2
XL
281 a = f.ty(self, a_substs);
282 b = f.ty(self, b_substs);
283 } else {
284 break;
285 }
dfeec247
XL
286 }
287 (&Tuple(a_tys), &Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
041b39d2 288 if let Some(a_last) = a_tys.last() {
48663c56
XL
289 a = a_last.expect_ty();
290 b = b_tys.last().unwrap().expect_ty();
041b39d2
XL
291 } else {
292 break;
293 }
dfeec247 294 }
ba9703b0
XL
295 (ty::Projection(_) | ty::Opaque(..), _)
296 | (_, ty::Projection(_) | ty::Opaque(..)) => {
416331ca
XL
297 // If either side is a projection, attempt to
298 // progress via normalization. (Should be safe to
299 // apply to both sides as normalization is
300 // idempotent.)
301 let a_norm = normalize(a);
302 let b_norm = normalize(b);
303 if a == a_norm && b == b_norm {
304 break;
305 } else {
306 a = a_norm;
307 b = b_norm;
308 }
309 }
310
cc61c64b 311 _ => break,
e9174d1e
SL
312 }
313 }
314 (a, b)
315 }
316
8bb4bdeb
XL
317 /// Calculate the destructor of a given type.
318 pub fn calculate_dtor(
319 self,
320 adt_did: DefId,
29967ef6 321 validate: impl Fn(Self, DefId) -> Result<(), ErrorReported>,
8bb4bdeb 322 ) -> Option<ty::Destructor> {
ba9703b0 323 let drop_trait = self.lang_items().drop_trait()?;
9fa01778 324 self.ensure().coherent_trait(drop_trait);
8bb4bdeb 325
7cac9316 326 let ty = self.type_of(adt_did);
c295e0f8 327 let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| {
3c0e092e 328 if let Some(item_id) = self.associated_item_def_ids(impl_did).first() {
0bf4aa26 329 if validate(self, impl_did).is_ok() {
3c0e092e 330 return Some((*item_id, self.impl_constness(impl_did)));
8bb4bdeb
XL
331 }
332 }
29967ef6 333 None
c295e0f8 334 })?;
8bb4bdeb 335
c295e0f8 336 Some(ty::Destructor { did, constness })
cc61c64b
XL
337 }
338
9fa01778 339 /// Returns the set of types that are required to be alive in
cc61c64b
XL
340 /// order to run the destructor of `def` (see RFCs 769 and
341 /// 1238).
342 ///
343 /// Note that this returns only the constraints for the
344 /// destructor of `def` itself. For the destructors of the
345 /// contents, you need `adt_dtorck_constraint`.
dfeec247 346 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef) -> Vec<ty::subst::GenericArg<'tcx>> {
cc61c64b
XL
347 let dtor = match def.destructor(self) {
348 None => {
349 debug!("destructor_constraints({:?}) - no dtor", def.did);
dfeec247 350 return vec![];
cc61c64b 351 }
dfeec247 352 Some(dtor) => dtor.did,
e9174d1e 353 };
b039eaaf 354
cc61c64b 355 let impl_def_id = self.associated_item(dtor).container.id();
7cac9316 356 let impl_generics = self.generics_of(impl_def_id);
cc61c64b
XL
357
358 // We have a destructor - all the parameters that are not
359 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
360 // must be live.
361
362 // We need to return the list of parameters from the ADTs
363 // generics/substs that correspond to impure parameters on the
364 // impl's generics. This is a bit ugly, but conceptually simple:
365 //
366 // Suppose our ADT looks like the following
367 //
368 // struct S<X, Y, Z>(X, Y, Z);
369 //
370 // and the impl is
371 //
372 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
373 //
374 // We want to return the parameters (X, Y). For that, we match
375 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
376 // <P1, P2, P0>, and then look up which of the impl substs refer to
377 // parameters marked as pure.
378
1b1a35ee 379 let impl_substs = match *self.type_of(impl_def_id).kind() {
b7449926 380 ty::Adt(def_, substs) if def_ == def => substs,
dfeec247 381 _ => bug!(),
cc61c64b
XL
382 };
383
1b1a35ee 384 let item_substs = match *self.type_of(def.did).kind() {
b7449926 385 ty::Adt(def_, substs) if def_ == def => substs,
dfeec247 386 _ => bug!(),
cc61c64b
XL
387 };
388
cdc7bbd5 389 let result = iter::zip(item_substs, impl_substs)
f9f354fc 390 .filter(|&(_, k)| {
0531ce1d 391 match k.unpack() {
e74abb32 392 GenericArgKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => {
0531ce1d
XL
393 !impl_generics.region_param(ebr, self).pure_wrt_drop
394 }
dfeec247 395 GenericArgKind::Type(&ty::TyS { kind: ty::Param(ref pt), .. }) => {
0531ce1d
XL
396 !impl_generics.type_param(pt, self).pure_wrt_drop
397 }
e74abb32 398 GenericArgKind::Const(&ty::Const {
dfeec247
XL
399 val: ty::ConstKind::Param(ref pc), ..
400 }) => !impl_generics.const_param(pc, self).pure_wrt_drop,
401 GenericArgKind::Lifetime(_)
402 | GenericArgKind::Type(_)
403 | GenericArgKind::Const(_) => {
532ac7d7 404 // Not a type, const or region param: this should be reported
0531ce1d
XL
405 // as an error.
406 false
407 }
cc61c64b 408 }
0bf4aa26 409 })
f9f354fc 410 .map(|(item_param, _)| item_param)
0bf4aa26 411 .collect();
cc61c64b
XL
412 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
413 result
b039eaaf 414 }
9e0c209e 415
9fa01778
XL
416 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
417 /// that closures have a `DefId`, but the closure *expression* also
8faf50e0
XL
418 /// has a `HirId` that is located within the context where the
419 /// closure appears (and, sadly, a corresponding `NodeId`, since
420 /// those are not yet phased out). The parent of the closure's
9fa01778 421 /// `DefId` will also be the context where it appears.
abe05a73 422 pub fn is_closure(self, def_id: DefId) -> bool {
f9f354fc 423 matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator)
abe05a73
XL
424 }
425
3c0e092e
XL
426 /// Returns `true` if `def_id` refers to a definition that does not have its own
427 /// type-checking context, i.e. closure, generator or inline const.
428 pub fn is_typeck_child(self, def_id: DefId) -> bool {
429 matches!(
430 self.def_kind(def_id),
431 DefKind::Closure | DefKind::Generator | DefKind::InlineConst
432 )
433 }
434
9fa01778 435 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
8faf50e0 436 pub fn is_trait(self, def_id: DefId) -> bool {
f9f354fc 437 self.def_kind(def_id) == DefKind::Trait
8faf50e0
XL
438 }
439
9fa01778
XL
440 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
441 /// and `false` otherwise.
442 pub fn is_trait_alias(self, def_id: DefId) -> bool {
f9f354fc 443 self.def_kind(def_id) == DefKind::TraitAlias
9fa01778
XL
444 }
445
446 /// Returns `true` if this `DefId` refers to the implicit constructor for
447 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
532ac7d7 448 pub fn is_constructor(self, def_id: DefId) -> bool {
f9f354fc 449 matches!(self.def_kind(def_id), DefKind::Ctor(..))
8faf50e0
XL
450 }
451
3c0e092e
XL
452 /// Given the `DefId`, returns the `DefId` of the innermost item that
453 /// has its own type-checking context or "inference enviornment".
454 ///
455 /// For example, a closure has its own `DefId`, but it is type-checked
456 /// with the containing item. Similarly, an inline const block has its
457 /// own `DefId` but it is type-checked together with the containing item.
458 ///
459 /// Therefore, when we fetch the
3dfed10e
XL
460 /// `typeck` the closure, for example, we really wind up
461 /// fetching the `typeck` the enclosing fn item.
3c0e092e 462 pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
476ff2be 463 let mut def_id = def_id;
3c0e092e 464 while self.is_typeck_child(def_id) {
532ac7d7 465 def_id = self.parent(def_id).unwrap_or_else(|| {
476ff2be
SL
466 bug!("closure {:?} has no parent", def_id);
467 });
468 }
469 def_id
9e0c209e 470 }
cc61c64b 471
9fa01778 472 /// Given the `DefId` and substs a closure, creates the type of
ff7c6d11
XL
473 /// `self` argument that the closure expects. For example, for a
474 /// `Fn` closure, this would return a reference type `&T` where
9fa01778 475 /// `T = closure_ty`.
ff7c6d11
XL
476 ///
477 /// Returns `None` if this closure's kind has not yet been inferred.
478 /// This should only be possible during type checking.
479 ///
480 /// Note that the return value is a late-bound region and hence
481 /// wrapped in a binder.
dfeec247
XL
482 pub fn closure_env_ty(
483 self,
484 closure_def_id: DefId,
485 closure_substs: SubstsRef<'tcx>,
cdc7bbd5
XL
486 env_region: ty::RegionKind,
487 ) -> Option<Ty<'tcx>> {
ff7c6d11 488 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
ba9703b0 489 let closure_kind_ty = closure_substs.as_closure().kind_ty();
ff7c6d11
XL
490 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
491 let env_ty = match closure_kind {
492 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
493 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
494 ty::ClosureKind::FnOnce => closure_ty,
495 };
cdc7bbd5 496 Some(env_ty)
ff7c6d11
XL
497 }
498
48663c56 499 /// Returns `true` if the node pointed to by `def_id` is a `static` item.
1b1a35ee 500 pub fn is_static(self, def_id: DefId) -> bool {
48663c56
XL
501 self.static_mutability(def_id).is_some()
502 }
503
f9f354fc 504 /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
1b1a35ee 505 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
f9f354fc
XL
506 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
507 }
508
48663c56 509 /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
1b1a35ee 510 pub fn is_mutable_static(self, def_id: DefId) -> bool {
dfeec247 511 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
60c5eb7d
XL
512 }
513
514 /// Get the type of the pointer to the static that we use in MIR.
1b1a35ee 515 pub fn static_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
60c5eb7d 516 // Make sure that any constants in the static's type are evaluated.
dfeec247 517 let static_ty = self.normalize_erasing_regions(ty::ParamEnv::empty(), self.type_of(def_id));
60c5eb7d 518
29967ef6
XL
519 // Make sure that accesses to unsafe statics end up using raw pointers.
520 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
60c5eb7d
XL
521 if self.is_mutable_static(def_id) {
522 self.mk_mut_ptr(static_ty)
29967ef6
XL
523 } else if self.is_foreign_item(def_id) {
524 self.mk_imm_ptr(static_ty)
60c5eb7d
XL
525 } else {
526 self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
527 }
abe05a73 528 }
0731742a
XL
529
530 /// Expands the given impl trait type, stopping if the type is recursive.
c295e0f8 531 #[instrument(skip(self), level = "debug")]
0731742a
XL
532 pub fn try_expand_impl_trait_type(
533 self,
534 def_id: DefId,
532ac7d7 535 substs: SubstsRef<'tcx>,
0731742a 536 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
0731742a
XL
537 let mut visitor = OpaqueTypeExpander {
538 seen_opaque_tys: FxHashSet::default(),
e1599b0c 539 expanded_cache: FxHashMap::default(),
3dfed10e 540 primary_def_id: Some(def_id),
0731742a 541 found_recursion: false,
94222f64 542 found_any_recursion: false,
3dfed10e 543 check_recursion: true,
0731742a
XL
544 tcx: self,
545 };
3dfed10e 546
0731742a 547 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
c295e0f8 548 trace!(?expanded_type);
dfeec247 549 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
0731742a 550 }
9e0c209e
SL
551}
552
3dfed10e
XL
553struct OpaqueTypeExpander<'tcx> {
554 // Contains the DefIds of the opaque types that are currently being
555 // expanded. When we expand an opaque type we insert the DefId of
556 // that type, and when we finish expanding that type we remove the
557 // its DefId.
558 seen_opaque_tys: FxHashSet<DefId>,
559 // Cache of all expansions we've seen so far. This is a critical
560 // optimization for some large types produced by async fn trees.
561 expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
562 primary_def_id: Option<DefId>,
563 found_recursion: bool,
94222f64 564 found_any_recursion: bool,
3dfed10e
XL
565 /// Whether or not to check for recursive opaque types.
566 /// This is `true` when we're explicitly checking for opaque type
567 /// recursion, and 'false' otherwise to avoid unnecessary work.
568 check_recursion: bool,
569 tcx: TyCtxt<'tcx>,
570}
571
572impl<'tcx> OpaqueTypeExpander<'tcx> {
573 fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
94222f64 574 if self.found_any_recursion {
3dfed10e
XL
575 return None;
576 }
577 let substs = substs.fold_with(self);
578 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
579 let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
580 Some(expanded_ty) => expanded_ty,
581 None => {
582 let generic_ty = self.tcx.type_of(def_id);
583 let concrete_ty = generic_ty.subst(self.tcx, substs);
584 let expanded_ty = self.fold_ty(concrete_ty);
585 self.expanded_cache.insert((def_id, substs), expanded_ty);
586 expanded_ty
587 }
588 };
589 if self.check_recursion {
590 self.seen_opaque_tys.remove(&def_id);
591 }
592 Some(expanded_ty)
593 } else {
594 // If another opaque type that we contain is recursive, then it
595 // will report the error, so we don't have to.
94222f64 596 self.found_any_recursion = true;
3dfed10e
XL
597 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
598 None
599 }
600 }
601}
602
603impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> {
604 fn tcx(&self) -> TyCtxt<'tcx> {
605 self.tcx
606 }
607
608 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
609 if let ty::Opaque(def_id, substs) = t.kind {
610 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
611 } else if t.has_opaque_types() {
612 t.super_fold_with(self)
613 } else {
614 t
615 }
616 }
617}
618
dc9dc135 619impl<'tcx> ty::TyS<'tcx> {
dfeec247
XL
620 /// Returns the maximum value for the given numeric type (including `char`s)
621 /// or returns `None` if the type is not numeric.
622 pub fn numeric_max_val(&'tcx self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ty::Const<'tcx>> {
1b1a35ee 623 let val = match self.kind() {
dfeec247
XL
624 ty::Int(_) | ty::Uint(_) => {
625 let (size, signed) = int_size_and_signed(tcx, self);
c295e0f8
XL
626 let val =
627 if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
dfeec247
XL
628 Some(val)
629 }
630 ty::Char => Some(std::char::MAX as u128),
631 ty::Float(fty) => Some(match fty {
5869c6ff
XL
632 ty::FloatTy::F32 => rustc_apfloat::ieee::Single::INFINITY.to_bits(),
633 ty::FloatTy::F64 => rustc_apfloat::ieee::Double::INFINITY.to_bits(),
dfeec247
XL
634 }),
635 _ => None,
636 };
637 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
638 }
639
640 /// Returns the minimum value for the given numeric type (including `char`s)
641 /// or returns `None` if the type is not numeric.
642 pub fn numeric_min_val(&'tcx self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ty::Const<'tcx>> {
1b1a35ee 643 let val = match self.kind() {
dfeec247
XL
644 ty::Int(_) | ty::Uint(_) => {
645 let (size, signed) = int_size_and_signed(tcx, self);
c295e0f8 646 let val = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
dfeec247
XL
647 Some(val)
648 }
649 ty::Char => Some(0),
650 ty::Float(fty) => Some(match fty {
5869c6ff
XL
651 ty::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
652 ty::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
dfeec247
XL
653 }),
654 _ => None,
655 };
656 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
657 }
658
0731742a
XL
659 /// Checks whether values of this type `T` are *moved* or *copied*
660 /// when referenced -- this amounts to a check for whether `T:
661 /// Copy`, but note that we **don't** consider lifetimes when
662 /// doing this check. This means that we may generate MIR which
663 /// does copies even when the type actually doesn't satisfy the
664 /// full requirements for the `Copy` trait (cc #29149) -- this
665 /// winds up being reported as an error during NLL borrow check.
dc9dc135
XL
666 pub fn is_copy_modulo_regions(
667 &'tcx self,
f035d41b 668 tcx_at: TyCtxtAt<'tcx>,
dc9dc135 669 param_env: ty::ParamEnv<'tcx>,
dc9dc135 670 ) -> bool {
f035d41b 671 tcx_at.is_copy_raw(param_env.and(self))
e9174d1e
SL
672 }
673
0731742a
XL
674 /// Checks whether values of this type `T` have a size known at
675 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
676 /// for the purposes of this check, so it can be an
677 /// over-approximation in generic contexts, where one can have
678 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
679 /// actually carry lifetime requirements.
dc9dc135 680 pub fn is_sized(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
74b04a01 681 self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self))
e9174d1e
SL
682 }
683
0731742a 684 /// Checks whether values of this type `T` implement the `Freeze`
94222f64 685 /// trait -- frozen types are those that do not contain an
9fa01778 686 /// `UnsafeCell` anywhere. This is a language concept used to
0731742a
XL
687 /// distinguish "true immutability", which is relevant to
688 /// optimization as well as the rules around static values. Note
689 /// that the `Freeze` trait is not exposed to end users and is
690 /// effectively an implementation detail.
f035d41b
XL
691 pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
692 self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
74b04a01
XL
693 }
694
695 /// Fast path helper for testing if a type is `Freeze`.
696 ///
697 /// Returning true means the type is known to be `Freeze`. Returning
698 /// `false` means nothing -- could be `Freeze`, might not be.
699 fn is_trivially_freeze(&self) -> bool {
1b1a35ee 700 match self.kind() {
74b04a01
XL
701 ty::Int(_)
702 | ty::Uint(_)
703 | ty::Float(_)
704 | ty::Bool
705 | ty::Char
706 | ty::Str
707 | ty::Never
708 | ty::Ref(..)
709 | ty::RawPtr(_)
710 | ty::FnDef(..)
f035d41b 711 | ty::Error(_)
74b04a01
XL
712 | ty::FnPtr(_) => true,
713 ty::Tuple(_) => self.tuple_fields().all(Self::is_trivially_freeze),
714 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
715 ty::Adt(..)
716 | ty::Bound(..)
717 | ty::Closure(..)
718 | ty::Dynamic(..)
719 | ty::Foreign(_)
720 | ty::Generator(..)
721 | ty::GeneratorWitness(_)
722 | ty::Infer(_)
723 | ty::Opaque(..)
724 | ty::Param(_)
725 | ty::Placeholder(_)
f9f354fc 726 | ty::Projection(_) => false,
74b04a01 727 }
cc61c64b
XL
728 }
729
cdc7bbd5
XL
730 /// Checks whether values of this type `T` implement the `Unpin` trait.
731 pub fn is_unpin(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
732 self.is_trivially_unpin() || tcx_at.is_unpin_raw(param_env.and(self))
733 }
734
735 /// Fast path helper for testing if a type is `Unpin`.
736 ///
737 /// Returning true means the type is known to be `Unpin`. Returning
738 /// `false` means nothing -- could be `Unpin`, might not be.
739 fn is_trivially_unpin(&self) -> bool {
740 match self.kind() {
741 ty::Int(_)
742 | ty::Uint(_)
743 | ty::Float(_)
744 | ty::Bool
745 | ty::Char
746 | ty::Str
747 | ty::Never
748 | ty::Ref(..)
749 | ty::RawPtr(_)
750 | ty::FnDef(..)
751 | ty::Error(_)
752 | ty::FnPtr(_) => true,
753 ty::Tuple(_) => self.tuple_fields().all(Self::is_trivially_unpin),
754 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(),
755 ty::Adt(..)
756 | ty::Bound(..)
757 | ty::Closure(..)
758 | ty::Dynamic(..)
759 | ty::Foreign(_)
760 | ty::Generator(..)
761 | ty::GeneratorWitness(_)
762 | ty::Infer(_)
763 | ty::Opaque(..)
764 | ty::Param(_)
765 | ty::Placeholder(_)
766 | ty::Projection(_) => false,
767 }
768 }
769
cc61c64b
XL
770 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
771 /// non-copy and *might* have a destructor attached; if it returns
0731742a 772 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
cc61c64b
XL
773 ///
774 /// (Note that this implies that if `ty` has a destructor attached,
775 /// then `needs_drop` will definitely return `true` for `ty`.)
e74abb32
XL
776 ///
777 /// Note that this method is used to check eligible types in unions.
cc61c64b 778 #[inline]
dc9dc135 779 pub fn needs_drop(&'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
74b04a01
XL
780 // Avoid querying in simple cases.
781 match needs_drop_components(self, &tcx.data_layout) {
782 Err(AlwaysRequiresDrop) => true,
783 Ok(components) => {
784 let query_ty = match *components {
785 [] => return false,
786 // If we've got a single component, call the query with that
787 // to increase the chance that we hit the query cache.
788 [component_ty] => component_ty,
789 _ => self,
790 };
a2a8927a 791
74b04a01
XL
792 // This doesn't depend on regions, so try to minimize distinct
793 // query keys used.
a2a8927a
XL
794 // If normalization fails, we just use `query_ty`.
795 let query_ty =
796 tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty);
797
798 tcx.needs_drop_raw(param_env.and(query_ty))
74b04a01
XL
799 }
800 }
cc61c64b
XL
801 }
802
17df50a5
XL
803 /// Checks if `ty` has has a significant drop.
804 ///
805 /// Note that this method can return false even if `ty` has a destructor
806 /// attached; even if that is the case then the adt has been marked with
807 /// the attribute `rustc_insignificant_dtor`.
808 ///
809 /// Note that this method is used to check for change in drop order for
810 /// 2229 drop reorder migration analysis.
811 #[inline]
812 pub fn has_significant_drop(
813 &'tcx self,
814 tcx: TyCtxt<'tcx>,
815 param_env: ty::ParamEnv<'tcx>,
816 ) -> bool {
817 // Avoid querying in simple cases.
818 match needs_drop_components(self, &tcx.data_layout) {
819 Err(AlwaysRequiresDrop) => true,
820 Ok(components) => {
821 let query_ty = match *components {
822 [] => return false,
823 // If we've got a single component, call the query with that
824 // to increase the chance that we hit the query cache.
825 [component_ty] => component_ty,
826 _ => self,
827 };
136023e0
XL
828
829 // FIXME(#86868): We should be canonicalizing, or else moving this to a method of inference
830 // context, or *something* like that, but for now just avoid passing inference
831 // variables to queries that can't cope with them. Instead, conservatively
832 // return "true" (may change drop order).
833 if query_ty.needs_infer() {
834 return true;
835 }
836
17df50a5
XL
837 // This doesn't depend on regions, so try to minimize distinct
838 // query keys used.
839 let erased = tcx.normalize_erasing_regions(param_env, query_ty);
840 tcx.has_significant_drop_raw(param_env.and(erased))
841 }
842 }
843 }
844
f035d41b
XL
845 /// Returns `true` if equality for this type is both reflexive and structural.
846 ///
847 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
848 ///
849 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
850 /// types, equality for the type as a whole is structural when it is the same as equality
851 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
852 /// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
853 /// that type.
854 ///
855 /// This function is "shallow" because it may return `true` for a composite type whose fields
856 /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
857 /// because equality for arrays is determined by the equality of each array element. If you
858 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
859 /// down, you will need to use a type visitor.
860 #[inline]
861 pub fn is_structural_eq_shallow(&'tcx self, tcx: TyCtxt<'tcx>) -> bool {
1b1a35ee 862 match self.kind() {
f035d41b
XL
863 // Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
864 Adt(..) => tcx.has_structural_eq_impls(self),
865
866 // Primitive types that satisfy `Eq`.
867 Bool | Char | Int(_) | Uint(_) | Str | Never => true,
868
869 // Composite types that satisfy `Eq` when all of their fields do.
870 //
871 // Because this function is "shallow", we return `true` for these composites regardless
872 // of the type(s) contained within.
873 Ref(..) | Array(..) | Slice(_) | Tuple(..) => true,
874
875 // Raw pointers use bitwise comparison.
876 RawPtr(_) | FnPtr(_) => true,
877
878 // Floating point numbers are not `Eq`.
879 Float(_) => false,
880
881 // Conservatively return `false` for all others...
882
883 // Anonymous function types
884 FnDef(..) | Closure(..) | Dynamic(..) | Generator(..) => false,
885
886 // Generic or inferred types
887 //
888 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
889 // called for known, fully-monomorphized types.
890 Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false,
891
892 Foreign(_) | GeneratorWitness(..) | Error(_) => false,
893 }
894 }
895
0731742a 896 pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1b1a35ee 897 match (&a.kind(), &b.kind()) {
0731742a
XL
898 (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => {
899 if did_a != did_b {
900 return false;
901 }
902
903 substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b))
904 }
905 _ => a == b,
906 }
907 }
908
e1599b0c
XL
909 /// Peel off all reference types in this type until there are none left.
910 ///
911 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
912 ///
913 /// # Examples
914 ///
915 /// - `u8` -> `u8`
916 /// - `&'a mut u8` -> `u8`
917 /// - `&'a &'b u8` -> `u8`
918 /// - `&'a *const &'b u8 -> *const &'b u8`
919 pub fn peel_refs(&'tcx self) -> Ty<'tcx> {
920 let mut ty = self;
1b1a35ee 921 while let Ref(_, inner_ty, _) = ty.kind() {
e1599b0c
XL
922 ty = inner_ty;
923 }
924 ty
925 }
136023e0
XL
926
927 pub fn outer_exclusive_binder(&'tcx self) -> DebruijnIndex {
928 self.outer_exclusive_binder
929 }
e9174d1e 930}
7cac9316 931
abe05a73
XL
932pub enum ExplicitSelf<'tcx> {
933 ByValue,
934 ByReference(ty::Region<'tcx>, hir::Mutability),
ff7c6d11 935 ByRawPointer(hir::Mutability),
abe05a73 936 ByBox,
dfeec247 937 Other,
abe05a73
XL
938}
939
940impl<'tcx> ExplicitSelf<'tcx> {
941 /// Categorizes an explicit self declaration like `self: SomeType`
942 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
943 /// `Other`.
944 /// This is mainly used to require the arbitrary_self_types feature
945 /// in the case of `Other`, to improve error messages in the common cases,
946 /// and to make `Other` non-object-safe.
947 ///
948 /// Examples:
949 ///
950 /// ```
951 /// impl<'a> Foo for &'a T {
952 /// // Legal declarations:
953 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
954 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
955 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
956 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
957 ///
958 /// // Invalid cases will be caught by `check_method_receiver`:
959 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
960 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
961 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
962 /// }
963 /// ```
964 ///
dfeec247 965 pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
abe05a73 966 where
dfeec247 967 P: Fn(Ty<'tcx>) -> bool,
abe05a73
XL
968 {
969 use self::ExplicitSelf::*;
970
1b1a35ee 971 match *self_arg_ty.kind() {
abe05a73 972 _ if is_self_ty(self_arg_ty) => ByValue,
dfeec247
XL
973 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
974 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
975 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
976 _ => Other,
abe05a73
XL
977 }
978 }
979}
74b04a01
XL
980
981/// Returns a list of types such that the given type needs drop if and only if
982/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
983/// this type always needs drop.
a2a8927a 984pub fn needs_drop_components<'tcx>(
74b04a01
XL
985 ty: Ty<'tcx>,
986 target_layout: &TargetDataLayout,
987) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1b1a35ee 988 match ty.kind() {
74b04a01
XL
989 ty::Infer(ty::FreshIntTy(_))
990 | ty::Infer(ty::FreshFloatTy(_))
991 | ty::Bool
992 | ty::Int(_)
993 | ty::Uint(_)
994 | ty::Float(_)
995 | ty::Never
996 | ty::FnDef(..)
997 | ty::FnPtr(_)
998 | ty::Char
999 | ty::GeneratorWitness(..)
1000 | ty::RawPtr(_)
1001 | ty::Ref(..)
1002 | ty::Str => Ok(SmallVec::new()),
1003
1004 // Foreign types can never have destructors.
1005 ty::Foreign(..) => Ok(SmallVec::new()),
1006
f035d41b 1007 ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
74b04a01
XL
1008
1009 ty::Slice(ty) => needs_drop_components(ty, target_layout),
1010 ty::Array(elem_ty, size) => {
1011 match needs_drop_components(elem_ty, target_layout) {
1012 Ok(v) if v.is_empty() => Ok(v),
1013 res => match size.val.try_to_bits(target_layout.pointer_size) {
1014 // Arrays of size zero don't need drop, even if their element
1015 // type does.
1016 Some(0) => Ok(SmallVec::new()),
1017 Some(_) => res,
1018 // We don't know which of the cases above we are in, so
1019 // return the whole type and let the caller decide what to
1020 // do.
1021 None => Ok(smallvec![ty]),
1022 },
1023 }
1024 }
1025 // If any field needs drop, then the whole tuple does.
1026 ty::Tuple(..) => ty.tuple_fields().try_fold(SmallVec::new(), move |mut acc, elem| {
1027 acc.extend(needs_drop_components(elem, target_layout)?);
1028 Ok(acc)
1029 }),
1030
1031 // These require checking for `Copy` bounds or `Adt` destructors.
1032 ty::Adt(..)
1033 | ty::Projection(..)
74b04a01
XL
1034 | ty::Param(_)
1035 | ty::Bound(..)
1036 | ty::Placeholder(..)
1037 | ty::Opaque(..)
1038 | ty::Infer(_)
ba9703b0
XL
1039 | ty::Closure(..)
1040 | ty::Generator(..) => Ok(smallvec![ty]),
74b04a01
XL
1041 }
1042}
1043
fc512014
XL
1044// Does the equivalent of
1045// ```
1046// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1047// folder.tcx().intern_*(&v)
1048// ```
1049pub fn fold_list<'tcx, F, T>(
1050 list: &'tcx ty::List<T>,
1051 folder: &mut F,
1052 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List<T>,
a2a8927a 1053) -> Result<&'tcx ty::List<T>, F::Error>
fc512014 1054where
a2a8927a 1055 F: FallibleTypeFolder<'tcx>,
fc512014
XL
1056 T: TypeFoldable<'tcx> + PartialEq + Copy,
1057{
1058 let mut iter = list.iter();
1059 // Look for the first element that changed
a2a8927a
XL
1060 match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1061 Ok(new_t) if new_t == t => None,
1062 new_t => Some((i, new_t)),
fc512014 1063 }) {
a2a8927a
XL
1064 Some((i, Ok(new_t))) => {
1065 // An element changed, prepare to intern the resulting list
1066 let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len());
1067 new_list.extend_from_slice(&list[..i]);
1068 new_list.push(new_t);
1069 for t in iter {
1070 new_list.push(t.try_fold_with(folder)?)
1071 }
1072 Ok(intern(folder.tcx(), &new_list))
1073 }
1074 Some((_, Err(err))) => {
1075 return Err(err);
1076 }
1077 None => Ok(list),
fc512014
XL
1078 }
1079}
1080
3dfed10e 1081#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
74b04a01 1082pub struct AlwaysRequiresDrop;
3dfed10e
XL
1083
1084/// Normalizes all opaque types in the given value, replacing them
1085/// with their underlying types.
a2a8927a 1086pub fn normalize_opaque_types<'tcx>(
3dfed10e
XL
1087 tcx: TyCtxt<'tcx>,
1088 val: &'tcx List<ty::Predicate<'tcx>>,
1089) -> &'tcx List<ty::Predicate<'tcx>> {
1090 let mut visitor = OpaqueTypeExpander {
1091 seen_opaque_tys: FxHashSet::default(),
1092 expanded_cache: FxHashMap::default(),
1093 primary_def_id: None,
1094 found_recursion: false,
94222f64 1095 found_any_recursion: false,
3dfed10e
XL
1096 check_recursion: false,
1097 tcx,
1098 };
1099 val.fold_with(&mut visitor)
1100}
1101
1102pub fn provide(providers: &mut ty::query::Providers) {
1103 *providers = ty::query::Providers { normalize_opaque_types, ..*providers }
1104}