]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_middle/src/ty/util.rs
New upstream version 1.70.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;
9c376795 4use crate::mir;
353b0b11 5use crate::ty::fast_reject::TreatProjections;
ba9703b0 6use crate::ty::layout::IntegerExt;
5099ac24 7use crate::ty::{
353b0b11
FG
8 self, FallibleTypeFolder, ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
9 TypeVisitableExt,
5099ac24 10};
2b03887a 11use crate::ty::{GenericArgKind, SubstsRef};
dfeec247 12use rustc_apfloat::Float as _;
0731742a 13use rustc_data_structures::fx::{FxHashMap, FxHashSet};
dfeec247 14use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
5e7ed085 15use rustc_errors::ErrorGuaranteed;
dfeec247 16use rustc_hir as hir;
5099ac24 17use rustc_hir::def::{CtorOf, DefKind, Res};
353b0b11 18use rustc_hir::def_id::{DefId, LocalDefId};
923072b8 19use rustc_index::bit_set::GrowableBitSet;
9c376795 20use rustc_index::vec::{Idx, IndexVec};
532ac7d7 21use rustc_macros::HashStable;
353b0b11
FG
22use rustc_session::Limit;
23use rustc_span::sym;
487cf647 24use rustc_target::abi::{Integer, IntegerType, Size, TargetDataLayout};
923072b8 25use rustc_target::spec::abi::Abi;
74b04a01 26use smallvec::SmallVec;
cdc7bbd5 27use std::{fmt, iter};
e9174d1e 28
0531ce1d
XL
29#[derive(Copy, Clone, Debug)]
30pub struct Discr<'tcx> {
9fa01778 31 /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`).
0531ce1d 32 pub val: u128,
dfeec247 33 pub ty: Ty<'tcx>,
0531ce1d 34}
8bb4bdeb 35
923072b8
FG
36/// Used as an input to [`TyCtxt::uses_unique_generic_params`].
37#[derive(Copy, Clone, Debug, PartialEq, Eq)]
38pub enum IgnoreRegions {
39 Yes,
40 No,
41}
42
43#[derive(Copy, Clone, Debug)]
44pub enum NotUniqueParam<'tcx> {
45 DuplicateParam(ty::GenericArg<'tcx>),
46 NotParam(ty::GenericArg<'tcx>),
47}
48
0531ce1d 49impl<'tcx> fmt::Display for Discr<'tcx> {
0bf4aa26 50 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1b1a35ee 51 match *self.ty.kind() {
b7449926 52 ty::Int(ity) => {
5869c6ff 53 let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
532ac7d7 54 let x = self.val;
0531ce1d 55 // sign extend the raw representation to be an i128
29967ef6 56 let x = size.sign_extend(x) as i128;
0531ce1d 57 write!(fmt, "{}", x)
dfeec247 58 }
0531ce1d
XL
59 _ => write!(fmt, "{}", self.val),
60 }
61 }
cc61c64b 62}
8bb4bdeb 63
0531ce1d 64impl<'tcx> Discr<'tcx> {
9fa01778 65 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
dc9dc135 66 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
0531ce1d
XL
67 self.checked_add(tcx, 1).0
68 }
dc9dc135 69 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
353b0b11 70 let (size, signed) = self.ty.int_size_and_signed(tcx);
dfeec247 71 let (val, oflo) = if signed {
c295e0f8
XL
72 let min = size.signed_int_min();
73 let max = size.signed_int_max();
29967ef6 74 let val = size.sign_extend(self.val) as i128;
74b04a01 75 assert!(n < (i128::MAX as u128));
0531ce1d
XL
76 let n = n as i128;
77 let oflo = val > max - n;
dfeec247 78 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
0531ce1d
XL
79 // zero the upper bits
80 let val = val as u128;
29967ef6 81 let val = size.truncate(val);
dfeec247 82 (val, oflo)
0531ce1d 83 } else {
c295e0f8 84 let max = size.unsigned_int_max();
0531ce1d
XL
85 let val = self.val;
86 let oflo = val > max - n;
dfeec247
XL
87 let val = if oflo { n - (max - val) - 1 } else { val + n };
88 (val, oflo)
89 };
90 (Self { val, ty: self.ty }, oflo)
8bb4bdeb 91 }
e9174d1e
SL
92}
93
0531ce1d 94pub trait IntTypeExt {
dc9dc135
XL
95 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>;
96 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>>;
97 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>;
0531ce1d
XL
98}
99
487cf647 100impl IntTypeExt for IntegerType {
dc9dc135 101 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
487cf647
FG
102 match self {
103 IntegerType::Pointer(true) => tcx.types.isize,
104 IntegerType::Pointer(false) => tcx.types.usize,
105 IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
e9174d1e
SL
106 }
107 }
108
dc9dc135 109 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
dfeec247 110 Discr { val: 0, ty: self.to_ty(tcx) }
e9174d1e
SL
111 }
112
dc9dc135 113 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
a7813a04 114 if let Some(val) = val {
0531ce1d
XL
115 assert_eq!(self.to_ty(tcx), val.ty);
116 let (new, oflo) = val.checked_add(tcx, 1);
dfeec247 117 if oflo { None } else { Some(new) }
a7813a04
XL
118 } else {
119 Some(self.initial_discriminant(tcx))
120 }
e9174d1e
SL
121 }
122}
123
dc9dc135 124impl<'tcx> TyCtxt<'tcx> {
cc61c64b
XL
125 /// Creates a hash of the type `Ty` which will be the same no matter what crate
126 /// context it's calculated within. This is used by the `type_id` intrinsic.
127 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
3b2f2976
XL
128 // We want the type_id be independent of the types free regions, so we
129 // erase them. The erase_regions() call will also anonymize bound
130 // regions, which is desirable too.
fc512014 131 let ty = self.erase_regions(ty);
3b2f2976 132
064997fb
FG
133 self.with_stable_hashing_context(|mut hcx| {
134 let mut hasher = StableHasher::new();
135 hcx.while_hashing_spans(false, |hcx| ty.hash_stable(hcx, &mut hasher));
136 hasher.finish()
137 })
cc61c64b 138 }
cc61c64b 139
5099ac24
FG
140 pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
141 match res {
142 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
04454e1e 143 Some(self.parent(self.parent(def_id)))
5099ac24
FG
144 }
145 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
04454e1e 146 Some(self.parent(def_id))
5099ac24
FG
147 }
148 // Other `DefKind`s don't have generics and would ICE when calling
149 // `generics_of`.
150 Res::Def(
151 DefKind::Struct
152 | DefKind::Union
153 | DefKind::Enum
154 | DefKind::Trait
155 | DefKind::OpaqueTy
156 | DefKind::TyAlias
157 | DefKind::ForeignTy
158 | DefKind::TraitAlias
159 | DefKind::AssocTy
160 | DefKind::Fn
161 | DefKind::AssocFn
162 | DefKind::AssocConst
9ffffee4 163 | DefKind::Impl { .. },
5099ac24
FG
164 def_id,
165 ) => Some(def_id),
166 Res::Err => None,
167 _ => None,
168 }
169 }
170
5bcae85e 171 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
1b1a35ee 172 if let ty::Adt(def, substs) = *ty.kind() {
0bf4aa26
XL
173 for field in def.all_fields() {
174 let field_ty = field.ty(self, substs);
923072b8 175 if let ty::Error(_) = field_ty.kind() {
0bf4aa26 176 return true;
5bcae85e
SL
177 }
178 }
5bcae85e
SL
179 }
180 false
181 }
182
416331ca
XL
183 /// Attempts to returns the deeply last field of nested structures, but
184 /// does not apply any normalization in its search. Returns the same type
185 /// if input `ty` is not a structure at all.
dfeec247 186 pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> {
416331ca 187 let tcx = self;
04454e1e 188 tcx.struct_tail_with_normalize(ty, |ty| ty, || {})
416331ca
XL
189 }
190
191 /// Returns the deeply last field of nested structures, or the same type if
192 /// not a structure at all. Corresponds to the only possible unsized field,
193 /// and its type can be used to determine unsizing strategy.
194 ///
195 /// Should only be called if `ty` has no inference variables and does not
196 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
197 /// normalization attempt may cause compiler bugs.
dfeec247
XL
198 pub fn struct_tail_erasing_lifetimes(
199 self,
200 ty: Ty<'tcx>,
201 param_env: ty::ParamEnv<'tcx>,
202 ) -> Ty<'tcx> {
416331ca 203 let tcx = self;
04454e1e 204 tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty), || {})
416331ca
XL
205 }
206
207 /// Returns the deeply last field of nested structures, or the same type if
208 /// not a structure at all. Corresponds to the only possible unsized field,
209 /// and its type can be used to determine unsizing strategy.
210 ///
211 /// This is parameterized over the normalization strategy (i.e. how to
212 /// handle `<T as Trait>::Assoc` and `impl Trait`); pass the identity
213 /// function to indicate no normalization should take place.
214 ///
215 /// See also `struct_tail_erasing_lifetimes`, which is suitable for use
216 /// during codegen.
dfeec247
XL
217 pub fn struct_tail_with_normalize(
218 self,
219 mut ty: Ty<'tcx>,
5099ac24 220 mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
04454e1e
FG
221 // This is currently used to allow us to walk a ValTree
222 // in lockstep with the type in order to get the ValTree branch that
223 // corresponds to an unsized field.
224 mut f: impl FnMut() -> (),
dfeec247 225 ) -> Ty<'tcx> {
136023e0 226 let recursion_limit = self.recursion_limit();
fc512014 227 for iteration in 0.. {
136023e0 228 if !recursion_limit.value_within_limit(iteration) {
353b0b11
FG
229 let suggested_limit = match recursion_limit {
230 Limit(0) => Limit(2),
231 limit => limit * 2,
232 };
233 let reported =
234 self.sess.emit_err(crate::error::RecursionLimitReached { ty, suggested_limit });
235 return self.ty_error(reported);
fc512014 236 }
1b1a35ee 237 match *ty.kind() {
b7449926 238 ty::Adt(def, substs) => {
7cac9316
XL
239 if !def.is_struct() {
240 break;
241 }
353b0b11 242 match def.non_enum_variant().fields.raw.last() {
04454e1e
FG
243 Some(field) => {
244 f();
245 ty = field.ty(self, substs);
246 }
7cac9316
XL
247 None => break,
248 }
249 }
250
94222f64 251 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
04454e1e 252 f();
5e7ed085 253 ty = last_ty;
7cac9316
XL
254 }
255
94222f64
XL
256 ty::Tuple(_) => break,
257
9c376795 258 ty::Alias(..) => {
416331ca
XL
259 let normalized = normalize(ty);
260 if ty == normalized {
261 return ty;
262 } else {
263 ty = normalized;
264 }
265 }
266
7cac9316
XL
267 _ => {
268 break;
269 }
e9174d1e
SL
270 }
271 }
272 ty
273 }
274
60c5eb7d 275 /// Same as applying `struct_tail` on `source` and `target`, but only
e9174d1e
SL
276 /// keeps going as long as the two types are instances of the same
277 /// structure definitions.
a1dfa0c6 278 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
e9174d1e 279 /// whereas struct_tail produces `T`, and `Trait`, respectively.
416331ca
XL
280 ///
281 /// Should only be called if the types have no inference variables and do
60c5eb7d 282 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
416331ca 283 /// normalization attempt may cause compiler bugs.
dfeec247
XL
284 pub fn struct_lockstep_tails_erasing_lifetimes(
285 self,
286 source: Ty<'tcx>,
287 target: Ty<'tcx>,
288 param_env: ty::ParamEnv<'tcx>,
289 ) -> (Ty<'tcx>, Ty<'tcx>) {
416331ca 290 let tcx = self;
dfeec247
XL
291 tcx.struct_lockstep_tails_with_normalize(source, target, |ty| {
292 tcx.normalize_erasing_regions(param_env, ty)
293 })
416331ca
XL
294 }
295
60c5eb7d 296 /// Same as applying `struct_tail` on `source` and `target`, but only
416331ca
XL
297 /// keeps going as long as the two types are instances of the same
298 /// structure definitions.
299 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
300 /// whereas struct_tail produces `T`, and `Trait`, respectively.
301 ///
302 /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use
303 /// during codegen.
dfeec247
XL
304 pub fn struct_lockstep_tails_with_normalize(
305 self,
306 source: Ty<'tcx>,
307 target: Ty<'tcx>,
308 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
309 ) -> (Ty<'tcx>, Ty<'tcx>) {
e9174d1e 310 let (mut a, mut b) = (source, target);
041b39d2 311 loop {
1b1a35ee 312 match (&a.kind(), &b.kind()) {
923072b8 313 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs))
dfeec247
XL
314 if a_def == b_def && a_def.is_struct() =>
315 {
353b0b11 316 if let Some(f) = a_def.non_enum_variant().fields.raw.last() {
041b39d2
XL
317 a = f.ty(self, a_substs);
318 b = f.ty(self, b_substs);
319 } else {
320 break;
321 }
dfeec247 322 }
923072b8 323 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
5e7ed085
FG
324 if let Some(&a_last) = a_tys.last() {
325 a = a_last;
326 b = *b_tys.last().unwrap();
041b39d2
XL
327 } else {
328 break;
329 }
dfeec247 330 }
9c376795 331 (ty::Alias(..), _) | (_, ty::Alias(..)) => {
416331ca
XL
332 // If either side is a projection, attempt to
333 // progress via normalization. (Should be safe to
334 // apply to both sides as normalization is
335 // idempotent.)
336 let a_norm = normalize(a);
337 let b_norm = normalize(b);
338 if a == a_norm && b == b_norm {
339 break;
340 } else {
341 a = a_norm;
342 b = b_norm;
343 }
344 }
345
cc61c64b 346 _ => break,
e9174d1e
SL
347 }
348 }
349 (a, b)
350 }
351
8bb4bdeb
XL
352 /// Calculate the destructor of a given type.
353 pub fn calculate_dtor(
354 self,
355 adt_did: DefId,
5e7ed085 356 validate: impl Fn(Self, DefId) -> Result<(), ErrorGuaranteed>,
8bb4bdeb 357 ) -> Option<ty::Destructor> {
ba9703b0 358 let drop_trait = self.lang_items().drop_trait()?;
9fa01778 359 self.ensure().coherent_trait(drop_trait);
8bb4bdeb 360
9ffffee4 361 let ty = self.type_of(adt_did).subst_identity();
353b0b11
FG
362 let (did, constness) = self.find_map_relevant_impl(
363 drop_trait,
364 ty,
365 // FIXME: This could also be some other mode, like "unexpected"
366 TreatProjections::ForLookup,
367 |impl_did| {
368 if let Some(item_id) = self.associated_item_def_ids(impl_did).first() {
369 if validate(self, impl_did).is_ok() {
370 return Some((*item_id, self.constness(impl_did)));
371 }
8bb4bdeb 372 }
353b0b11
FG
373 None
374 },
375 )?;
8bb4bdeb 376
c295e0f8 377 Some(ty::Destructor { did, constness })
cc61c64b
XL
378 }
379
9fa01778 380 /// Returns the set of types that are required to be alive in
cc61c64b
XL
381 /// order to run the destructor of `def` (see RFCs 769 and
382 /// 1238).
383 ///
384 /// Note that this returns only the constraints for the
385 /// destructor of `def` itself. For the destructors of the
386 /// contents, you need `adt_dtorck_constraint`.
5e7ed085 387 pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::subst::GenericArg<'tcx>> {
cc61c64b
XL
388 let dtor = match def.destructor(self) {
389 None => {
5e7ed085 390 debug!("destructor_constraints({:?}) - no dtor", def.did());
dfeec247 391 return vec![];
cc61c64b 392 }
dfeec247 393 Some(dtor) => dtor.did,
e9174d1e 394 };
b039eaaf 395
064997fb 396 let impl_def_id = self.parent(dtor);
7cac9316 397 let impl_generics = self.generics_of(impl_def_id);
cc61c64b
XL
398
399 // We have a destructor - all the parameters that are not
400 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
401 // must be live.
402
403 // We need to return the list of parameters from the ADTs
404 // generics/substs that correspond to impure parameters on the
405 // impl's generics. This is a bit ugly, but conceptually simple:
406 //
407 // Suppose our ADT looks like the following
408 //
409 // struct S<X, Y, Z>(X, Y, Z);
410 //
411 // and the impl is
412 //
413 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
414 //
415 // We want to return the parameters (X, Y). For that, we match
416 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
417 // <P1, P2, P0>, and then look up which of the impl substs refer to
418 // parameters marked as pure.
419
9ffffee4 420 let impl_substs = match *self.type_of(impl_def_id).subst_identity().kind() {
b7449926 421 ty::Adt(def_, substs) if def_ == def => substs,
dfeec247 422 _ => bug!(),
cc61c64b
XL
423 };
424
9ffffee4 425 let item_substs = match *self.type_of(def.did()).subst_identity().kind() {
b7449926 426 ty::Adt(def_, substs) if def_ == def => substs,
dfeec247 427 _ => bug!(),
cc61c64b
XL
428 };
429
cdc7bbd5 430 let result = iter::zip(item_substs, impl_substs)
f9f354fc 431 .filter(|&(_, k)| {
0531ce1d 432 match k.unpack() {
04454e1e 433 GenericArgKind::Lifetime(region) => match region.kind() {
923072b8 434 ty::ReEarlyBound(ref ebr) => {
04454e1e
FG
435 !impl_generics.region_param(ebr, self).pure_wrt_drop
436 }
437 // Error: not a region param
438 _ => false,
439 },
440 GenericArgKind::Type(ty) => match ty.kind() {
441 ty::Param(ref pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
442 // Error: not a type param
443 _ => false,
444 },
923072b8 445 GenericArgKind::Const(ct) => match ct.kind() {
04454e1e
FG
446 ty::ConstKind::Param(ref pc) => {
447 !impl_generics.const_param(pc, self).pure_wrt_drop
448 }
449 // Error: not a const param
450 _ => false,
451 },
cc61c64b 452 }
0bf4aa26 453 })
f9f354fc 454 .map(|(item_param, _)| item_param)
0bf4aa26 455 .collect();
5e7ed085 456 debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
cc61c64b 457 result
b039eaaf 458 }
9e0c209e 459
923072b8
FG
460 /// Checks whether each generic argument is simply a unique generic parameter.
461 pub fn uses_unique_generic_params(
462 self,
463 substs: SubstsRef<'tcx>,
464 ignore_regions: IgnoreRegions,
465 ) -> Result<(), NotUniqueParam<'tcx>> {
466 let mut seen = GrowableBitSet::default();
467 for arg in substs {
468 match arg.unpack() {
469 GenericArgKind::Lifetime(lt) => {
470 if ignore_regions == IgnoreRegions::No {
471 let ty::ReEarlyBound(p) = lt.kind() else {
472 return Err(NotUniqueParam::NotParam(lt.into()))
473 };
474 if !seen.insert(p.index) {
475 return Err(NotUniqueParam::DuplicateParam(lt.into()));
476 }
477 }
478 }
479 GenericArgKind::Type(t) => match t.kind() {
480 ty::Param(p) => {
481 if !seen.insert(p.index) {
482 return Err(NotUniqueParam::DuplicateParam(t.into()));
483 }
484 }
485 _ => return Err(NotUniqueParam::NotParam(t.into())),
486 },
487 GenericArgKind::Const(c) => match c.kind() {
488 ty::ConstKind::Param(p) => {
489 if !seen.insert(p.index) {
490 return Err(NotUniqueParam::DuplicateParam(c.into()));
491 }
492 }
493 _ => return Err(NotUniqueParam::NotParam(c.into())),
494 },
495 }
496 }
497
498 Ok(())
499 }
500
9fa01778
XL
501 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
502 /// that closures have a `DefId`, but the closure *expression* also
8faf50e0
XL
503 /// has a `HirId` that is located within the context where the
504 /// closure appears (and, sadly, a corresponding `NodeId`, since
505 /// those are not yet phased out). The parent of the closure's
9fa01778 506 /// `DefId` will also be the context where it appears.
abe05a73 507 pub fn is_closure(self, def_id: DefId) -> bool {
f9f354fc 508 matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator)
abe05a73
XL
509 }
510
3c0e092e
XL
511 /// Returns `true` if `def_id` refers to a definition that does not have its own
512 /// type-checking context, i.e. closure, generator or inline const.
513 pub fn is_typeck_child(self, def_id: DefId) -> bool {
514 matches!(
515 self.def_kind(def_id),
516 DefKind::Closure | DefKind::Generator | DefKind::InlineConst
517 )
518 }
519
9fa01778 520 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
8faf50e0 521 pub fn is_trait(self, def_id: DefId) -> bool {
f9f354fc 522 self.def_kind(def_id) == DefKind::Trait
8faf50e0
XL
523 }
524
9fa01778
XL
525 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
526 /// and `false` otherwise.
527 pub fn is_trait_alias(self, def_id: DefId) -> bool {
f9f354fc 528 self.def_kind(def_id) == DefKind::TraitAlias
9fa01778
XL
529 }
530
531 /// Returns `true` if this `DefId` refers to the implicit constructor for
532 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
532ac7d7 533 pub fn is_constructor(self, def_id: DefId) -> bool {
f9f354fc 534 matches!(self.def_kind(def_id), DefKind::Ctor(..))
8faf50e0
XL
535 }
536
3c0e092e 537 /// Given the `DefId`, returns the `DefId` of the innermost item that
5e7ed085 538 /// has its own type-checking context or "inference environment".
3c0e092e
XL
539 ///
540 /// For example, a closure has its own `DefId`, but it is type-checked
541 /// with the containing item. Similarly, an inline const block has its
542 /// own `DefId` but it is type-checked together with the containing item.
543 ///
544 /// Therefore, when we fetch the
3dfed10e
XL
545 /// `typeck` the closure, for example, we really wind up
546 /// fetching the `typeck` the enclosing fn item.
3c0e092e 547 pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
476ff2be 548 let mut def_id = def_id;
3c0e092e 549 while self.is_typeck_child(def_id) {
04454e1e 550 def_id = self.parent(def_id);
476ff2be
SL
551 }
552 def_id
9e0c209e 553 }
cc61c64b 554
9fa01778 555 /// Given the `DefId` and substs a closure, creates the type of
ff7c6d11
XL
556 /// `self` argument that the closure expects. For example, for a
557 /// `Fn` closure, this would return a reference type `&T` where
9fa01778 558 /// `T = closure_ty`.
ff7c6d11
XL
559 ///
560 /// Returns `None` if this closure's kind has not yet been inferred.
561 /// This should only be possible during type checking.
562 ///
563 /// Note that the return value is a late-bound region and hence
564 /// wrapped in a binder.
dfeec247
XL
565 pub fn closure_env_ty(
566 self,
567 closure_def_id: DefId,
568 closure_substs: SubstsRef<'tcx>,
9ffffee4 569 env_region: ty::Region<'tcx>,
cdc7bbd5 570 ) -> Option<Ty<'tcx>> {
ff7c6d11 571 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
ba9703b0 572 let closure_kind_ty = closure_substs.as_closure().kind_ty();
ff7c6d11
XL
573 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
574 let env_ty = match closure_kind {
9ffffee4
FG
575 ty::ClosureKind::Fn => self.mk_imm_ref(env_region, closure_ty),
576 ty::ClosureKind::FnMut => self.mk_mut_ref(env_region, closure_ty),
ff7c6d11
XL
577 ty::ClosureKind::FnOnce => closure_ty,
578 };
cdc7bbd5 579 Some(env_ty)
ff7c6d11
XL
580 }
581
48663c56 582 /// Returns `true` if the node pointed to by `def_id` is a `static` item.
5e7ed085 583 #[inline]
1b1a35ee 584 pub fn is_static(self, def_id: DefId) -> bool {
5e7ed085
FG
585 matches!(self.def_kind(def_id), DefKind::Static(_))
586 }
587
588 #[inline]
589 pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
590 if let DefKind::Static(mt) = self.def_kind(def_id) { Some(mt) } else { None }
48663c56
XL
591 }
592
f9f354fc 593 /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
1b1a35ee 594 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
f9f354fc
XL
595 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
596 }
597
48663c56 598 /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
5e7ed085 599 #[inline]
1b1a35ee 600 pub fn is_mutable_static(self, def_id: DefId) -> bool {
dfeec247 601 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
60c5eb7d
XL
602 }
603
353b0b11
FG
604 /// Returns `true` if the item pointed to by `def_id` is a thread local which needs a
605 /// thread local shim generated.
606 #[inline]
607 pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
608 !self.sess.target.dll_tls_export
609 && self.is_thread_local_static(def_id)
610 && !self.is_foreign_item(def_id)
611 }
612
613 /// Returns the type a reference to the thread local takes in MIR.
614 pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
615 let static_ty = self.type_of(def_id).subst_identity();
616 if self.is_mutable_static(def_id) {
617 self.mk_mut_ptr(static_ty)
618 } else if self.is_foreign_item(def_id) {
619 self.mk_imm_ptr(static_ty)
620 } else {
621 // FIXME: These things don't *really* have 'static lifetime.
622 self.mk_imm_ref(self.lifetimes.re_static, static_ty)
623 }
624 }
625
60c5eb7d 626 /// Get the type of the pointer to the static that we use in MIR.
1b1a35ee 627 pub fn static_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
60c5eb7d 628 // Make sure that any constants in the static's type are evaluated.
9ffffee4
FG
629 let static_ty = self.normalize_erasing_regions(
630 ty::ParamEnv::empty(),
631 self.type_of(def_id).subst_identity(),
632 );
60c5eb7d 633
29967ef6
XL
634 // Make sure that accesses to unsafe statics end up using raw pointers.
635 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
60c5eb7d
XL
636 if self.is_mutable_static(def_id) {
637 self.mk_mut_ptr(static_ty)
29967ef6
XL
638 } else if self.is_foreign_item(def_id) {
639 self.mk_imm_ptr(static_ty)
60c5eb7d
XL
640 } else {
641 self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
642 }
abe05a73 643 }
0731742a 644
9ffffee4
FG
645 /// Return the set of types that should be taken into accound when checking
646 /// trait bounds on a generator's internal state.
647 pub fn generator_hidden_types(
648 self,
649 def_id: DefId,
650 ) -> impl Iterator<Item = ty::EarlyBinder<Ty<'tcx>>> {
651 let generator_layout = &self.mir_generator_witnesses(def_id);
652 generator_layout
653 .field_tys
654 .iter()
655 .filter(|decl| !decl.ignore_for_traits)
656 .map(|decl| ty::EarlyBinder(decl.ty))
657 }
658
659 /// Normalizes all opaque types in the given value, replacing them
660 /// with their underlying types.
661 pub fn expand_opaque_types(self, val: Ty<'tcx>) -> Ty<'tcx> {
662 let mut visitor = OpaqueTypeExpander {
663 seen_opaque_tys: FxHashSet::default(),
664 expanded_cache: FxHashMap::default(),
665 primary_def_id: None,
666 found_recursion: false,
667 found_any_recursion: false,
668 check_recursion: false,
669 expand_generators: false,
670 tcx: self,
671 };
672 val.fold_with(&mut visitor)
673 }
674
0731742a 675 /// Expands the given impl trait type, stopping if the type is recursive.
f2b60f7d 676 #[instrument(skip(self), level = "debug", ret)]
0731742a
XL
677 pub fn try_expand_impl_trait_type(
678 self,
679 def_id: DefId,
532ac7d7 680 substs: SubstsRef<'tcx>,
0731742a 681 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
0731742a
XL
682 let mut visitor = OpaqueTypeExpander {
683 seen_opaque_tys: FxHashSet::default(),
e1599b0c 684 expanded_cache: FxHashMap::default(),
3dfed10e 685 primary_def_id: Some(def_id),
0731742a 686 found_recursion: false,
94222f64 687 found_any_recursion: false,
3dfed10e 688 check_recursion: true,
9ffffee4 689 expand_generators: true,
0731742a
XL
690 tcx: self,
691 };
3dfed10e 692
0731742a 693 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
dfeec247 694 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
0731742a 695 }
04454e1e 696
9c376795 697 pub fn bound_return_position_impl_trait_in_trait_tys(
f2b60f7d
FG
698 self,
699 def_id: DefId,
700 ) -> ty::EarlyBinder<Result<&'tcx FxHashMap<DefId, Ty<'tcx>>, ErrorGuaranteed>> {
9c376795 701 ty::EarlyBinder(self.collect_return_position_impl_trait_in_trait_tys(def_id))
f2b60f7d
FG
702 }
703
04454e1e
FG
704 pub fn bound_explicit_item_bounds(
705 self,
706 def_id: DefId,
923072b8
FG
707 ) -> ty::EarlyBinder<&'tcx [(ty::Predicate<'tcx>, rustc_span::Span)]> {
708 ty::EarlyBinder(self.explicit_item_bounds(def_id))
04454e1e
FG
709 }
710
9c376795
FG
711 /// Returns names of captured upvars for closures and generators.
712 ///
713 /// Here are some examples:
714 /// - `name__field1__field2` when the upvar is captured by value.
715 /// - `_ref__name__field` when the upvar is captured by reference.
716 ///
717 /// For generators this only contains upvars that are shared by all states.
718 pub fn closure_saved_names_of_captured_variables(
064997fb
FG
719 self,
720 def_id: DefId,
9c376795
FG
721 ) -> SmallVec<[String; 16]> {
722 let body = self.optimized_mir(def_id);
723
724 body.var_debug_info
725 .iter()
726 .filter_map(|var| {
727 let is_ref = match var.value {
728 mir::VarDebugInfoContents::Place(place)
729 if place.local == mir::Local::new(1) =>
730 {
731 // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
732 // implies whether the variable is captured by value or by reference.
733 matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
734 }
735 _ => return None,
736 };
737 let prefix = if is_ref { "_ref__" } else { "" };
738 Some(prefix.to_owned() + var.name.as_str())
739 })
740 .collect()
064997fb
FG
741 }
742
9c376795
FG
743 // FIXME(eddyb) maybe precompute this? Right now it's computed once
744 // per generator monomorphization, but it doesn't depend on substs.
745 pub fn generator_layout_and_saved_local_names(
064997fb
FG
746 self,
747 def_id: DefId,
9c376795
FG
748 ) -> (
749 &'tcx ty::GeneratorLayout<'tcx>,
750 IndexVec<mir::GeneratorSavedLocal, Option<rustc_span::Symbol>>,
751 ) {
752 let tcx = self;
753 let body = tcx.optimized_mir(def_id);
754 let generator_layout = body.generator_layout().unwrap();
755 let mut generator_saved_local_names =
756 IndexVec::from_elem(None, &generator_layout.field_tys);
757
758 let state_arg = mir::Local::new(1);
759 for var in &body.var_debug_info {
760 let mir::VarDebugInfoContents::Place(place) = &var.value else { continue };
761 if place.local != state_arg {
762 continue;
763 }
764 match place.projection[..] {
765 [
766 // Deref of the `Pin<&mut Self>` state argument.
767 mir::ProjectionElem::Field(..),
768 mir::ProjectionElem::Deref,
769 // Field of a variant of the state.
770 mir::ProjectionElem::Downcast(_, variant),
771 mir::ProjectionElem::Field(field, _),
772 ] => {
773 let name = &mut generator_saved_local_names
774 [generator_layout.variant_fields[variant][field]];
775 if name.is_none() {
776 name.replace(var.name);
777 }
778 }
779 _ => {}
780 }
781 }
782 (generator_layout, generator_saved_local_names)
064997fb
FG
783 }
784
9ffffee4
FG
785 /// Query and get an English description for the item's kind.
786 pub fn def_descr(self, def_id: DefId) -> &'static str {
787 self.def_kind_descr(self.def_kind(def_id), def_id)
788 }
789
790 /// Get an English description for the item's kind.
791 pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
792 match def_kind {
793 DefKind::AssocFn if self.associated_item(def_id).fn_has_self_parameter => "method",
794 DefKind::Generator => match self.generator_kind(def_id).unwrap() {
795 rustc_hir::GeneratorKind::Async(..) => "async closure",
796 rustc_hir::GeneratorKind::Gen => "generator",
797 },
798 _ => def_kind.descr(def_id),
799 }
800 }
801
802 /// Gets an English article for the [`TyCtxt::def_descr`].
803 pub fn def_descr_article(self, def_id: DefId) -> &'static str {
804 self.def_kind_descr_article(self.def_kind(def_id), def_id)
805 }
806
807 /// Gets an English article for the [`TyCtxt::def_kind_descr`].
808 pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
809 match def_kind {
810 DefKind::AssocFn if self.associated_item(def_id).fn_has_self_parameter => "a",
811 DefKind::Generator => match self.generator_kind(def_id).unwrap() {
812 rustc_hir::GeneratorKind::Async(..) => "an",
813 rustc_hir::GeneratorKind::Gen => "a",
814 },
815 _ => def_kind.article(),
816 }
064997fb 817 }
9e0c209e
SL
818}
819
3dfed10e
XL
820struct OpaqueTypeExpander<'tcx> {
821 // Contains the DefIds of the opaque types that are currently being
822 // expanded. When we expand an opaque type we insert the DefId of
823 // that type, and when we finish expanding that type we remove the
824 // its DefId.
825 seen_opaque_tys: FxHashSet<DefId>,
826 // Cache of all expansions we've seen so far. This is a critical
827 // optimization for some large types produced by async fn trees.
828 expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
829 primary_def_id: Option<DefId>,
830 found_recursion: bool,
94222f64 831 found_any_recursion: bool,
9ffffee4 832 expand_generators: bool,
3dfed10e
XL
833 /// Whether or not to check for recursive opaque types.
834 /// This is `true` when we're explicitly checking for opaque type
835 /// recursion, and 'false' otherwise to avoid unnecessary work.
836 check_recursion: bool,
837 tcx: TyCtxt<'tcx>,
838}
839
840impl<'tcx> OpaqueTypeExpander<'tcx> {
841 fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
94222f64 842 if self.found_any_recursion {
3dfed10e
XL
843 return None;
844 }
845 let substs = substs.fold_with(self);
846 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
847 let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
5099ac24 848 Some(expanded_ty) => *expanded_ty,
3dfed10e 849 None => {
9ffffee4 850 let generic_ty = self.tcx.type_of(def_id);
3dfed10e
XL
851 let concrete_ty = generic_ty.subst(self.tcx, substs);
852 let expanded_ty = self.fold_ty(concrete_ty);
853 self.expanded_cache.insert((def_id, substs), expanded_ty);
854 expanded_ty
855 }
856 };
857 if self.check_recursion {
858 self.seen_opaque_tys.remove(&def_id);
859 }
860 Some(expanded_ty)
861 } else {
862 // If another opaque type that we contain is recursive, then it
863 // will report the error, so we don't have to.
94222f64 864 self.found_any_recursion = true;
3dfed10e
XL
865 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
866 None
867 }
868 }
9ffffee4
FG
869
870 fn expand_generator(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
871 if self.found_any_recursion {
872 return None;
873 }
874 let substs = substs.fold_with(self);
875 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
876 let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
877 Some(expanded_ty) => *expanded_ty,
878 None => {
879 for bty in self.tcx.generator_hidden_types(def_id) {
880 let hidden_ty = bty.subst(self.tcx, substs);
881 self.fold_ty(hidden_ty);
882 }
883 let expanded_ty = self.tcx.mk_generator_witness_mir(def_id, substs);
884 self.expanded_cache.insert((def_id, substs), expanded_ty);
885 expanded_ty
886 }
887 };
888 if self.check_recursion {
889 self.seen_opaque_tys.remove(&def_id);
890 }
891 Some(expanded_ty)
892 } else {
893 // If another opaque type that we contain is recursive, then it
894 // will report the error, so we don't have to.
895 self.found_any_recursion = true;
896 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
897 None
898 }
899 }
3dfed10e
XL
900}
901
9ffffee4
FG
902impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
903 fn interner(&self) -> TyCtxt<'tcx> {
3dfed10e
XL
904 self.tcx
905 }
906
907 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
9ffffee4 908 let mut t = if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) = *t.kind() {
3dfed10e 909 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
9ffffee4 910 } else if t.has_opaque_types() || t.has_generators() {
3dfed10e
XL
911 t.super_fold_with(self)
912 } else {
913 t
9ffffee4
FG
914 };
915 if self.expand_generators {
916 if let ty::GeneratorWitnessMIR(def_id, substs) = *t.kind() {
917 t = self.expand_generator(def_id, substs).unwrap_or(t);
918 }
919 }
920 t
921 }
922
923 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
924 if let ty::PredicateKind::Clause(clause) = p.kind().skip_binder()
925 && let ty::Clause::Projection(projection_pred) = clause
926 {
927 p.kind()
928 .rebind(ty::ProjectionPredicate {
929 projection_ty: projection_pred.projection_ty.fold_with(self),
930 // Don't fold the term on the RHS of the projection predicate.
931 // This is because for default trait methods with RPITITs, we
932 // install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`
933 // predicate, which would trivially cause a cycle when we do
934 // anything that requires `ParamEnv::with_reveal_all_normalized`.
935 term: projection_pred.term,
936 })
937 .to_predicate(self.tcx)
938 } else {
939 p.super_fold_with(self)
3dfed10e
XL
940 }
941 }
942}
943
5099ac24 944impl<'tcx> Ty<'tcx> {
353b0b11
FG
945 pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
946 let (int, signed) = match *self.kind() {
947 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity), true),
948 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false),
949 _ => bug!("non integer discriminant"),
950 };
951 (int.size(), signed)
952 }
953
dfeec247
XL
954 /// Returns the maximum value for the given numeric type (including `char`s)
955 /// or returns `None` if the type is not numeric.
923072b8 956 pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
1b1a35ee 957 let val = match self.kind() {
dfeec247 958 ty::Int(_) | ty::Uint(_) => {
353b0b11 959 let (size, signed) = self.int_size_and_signed(tcx);
c295e0f8
XL
960 let val =
961 if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
dfeec247
XL
962 Some(val)
963 }
964 ty::Char => Some(std::char::MAX as u128),
965 ty::Float(fty) => Some(match fty {
5869c6ff
XL
966 ty::FloatTy::F32 => rustc_apfloat::ieee::Single::INFINITY.to_bits(),
967 ty::FloatTy::F64 => rustc_apfloat::ieee::Double::INFINITY.to_bits(),
dfeec247
XL
968 }),
969 _ => None,
970 };
923072b8
FG
971
972 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
dfeec247
XL
973 }
974
975 /// Returns the minimum value for the given numeric type (including `char`s)
976 /// or returns `None` if the type is not numeric.
923072b8 977 pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
1b1a35ee 978 let val = match self.kind() {
dfeec247 979 ty::Int(_) | ty::Uint(_) => {
353b0b11 980 let (size, signed) = self.int_size_and_signed(tcx);
c295e0f8 981 let val = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
dfeec247
XL
982 Some(val)
983 }
984 ty::Char => Some(0),
985 ty::Float(fty) => Some(match fty {
5869c6ff
XL
986 ty::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
987 ty::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
dfeec247
XL
988 }),
989 _ => None,
990 };
923072b8
FG
991
992 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
dfeec247
XL
993 }
994
0731742a
XL
995 /// Checks whether values of this type `T` are *moved* or *copied*
996 /// when referenced -- this amounts to a check for whether `T:
997 /// Copy`, but note that we **don't** consider lifetimes when
998 /// doing this check. This means that we may generate MIR which
999 /// does copies even when the type actually doesn't satisfy the
1000 /// full requirements for the `Copy` trait (cc #29149) -- this
1001 /// winds up being reported as an error during NLL borrow check.
2b03887a
FG
1002 pub fn is_copy_modulo_regions(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
1003 self.is_trivially_pure_clone_copy() || tcx.is_copy_raw(param_env.and(self))
e9174d1e
SL
1004 }
1005
0731742a
XL
1006 /// Checks whether values of this type `T` have a size known at
1007 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
1008 /// for the purposes of this check, so it can be an
1009 /// over-approximation in generic contexts, where one can have
1010 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
1011 /// actually carry lifetime requirements.
2b03887a
FG
1012 pub fn is_sized(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
1013 self.is_trivially_sized(tcx) || tcx.is_sized_raw(param_env.and(self))
e9174d1e
SL
1014 }
1015
0731742a 1016 /// Checks whether values of this type `T` implement the `Freeze`
94222f64 1017 /// trait -- frozen types are those that do not contain an
9fa01778 1018 /// `UnsafeCell` anywhere. This is a language concept used to
0731742a
XL
1019 /// distinguish "true immutability", which is relevant to
1020 /// optimization as well as the rules around static values. Note
1021 /// that the `Freeze` trait is not exposed to end users and is
1022 /// effectively an implementation detail.
2b03887a
FG
1023 pub fn is_freeze(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
1024 self.is_trivially_freeze() || tcx.is_freeze_raw(param_env.and(self))
74b04a01
XL
1025 }
1026
1027 /// Fast path helper for testing if a type is `Freeze`.
1028 ///
1029 /// Returning true means the type is known to be `Freeze`. Returning
1030 /// `false` means nothing -- could be `Freeze`, might not be.
5099ac24 1031 fn is_trivially_freeze(self) -> bool {
1b1a35ee 1032 match self.kind() {
74b04a01
XL
1033 ty::Int(_)
1034 | ty::Uint(_)
1035 | ty::Float(_)
1036 | ty::Bool
1037 | ty::Char
1038 | ty::Str
1039 | ty::Never
1040 | ty::Ref(..)
1041 | ty::RawPtr(_)
1042 | ty::FnDef(..)
f035d41b 1043 | ty::Error(_)
74b04a01 1044 | ty::FnPtr(_) => true,
5e7ed085 1045 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
74b04a01
XL
1046 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
1047 ty::Adt(..)
1048 | ty::Bound(..)
1049 | ty::Closure(..)
1050 | ty::Dynamic(..)
1051 | ty::Foreign(_)
1052 | ty::Generator(..)
1053 | ty::GeneratorWitness(_)
9ffffee4 1054 | ty::GeneratorWitnessMIR(..)
74b04a01 1055 | ty::Infer(_)
9c376795 1056 | ty::Alias(..)
74b04a01 1057 | ty::Param(_)
9c376795 1058 | ty::Placeholder(_) => false,
74b04a01 1059 }
cc61c64b
XL
1060 }
1061
cdc7bbd5 1062 /// Checks whether values of this type `T` implement the `Unpin` trait.
2b03887a
FG
1063 pub fn is_unpin(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
1064 self.is_trivially_unpin() || tcx.is_unpin_raw(param_env.and(self))
cdc7bbd5
XL
1065 }
1066
1067 /// Fast path helper for testing if a type is `Unpin`.
1068 ///
1069 /// Returning true means the type is known to be `Unpin`. Returning
1070 /// `false` means nothing -- could be `Unpin`, might not be.
5099ac24 1071 fn is_trivially_unpin(self) -> bool {
cdc7bbd5
XL
1072 match self.kind() {
1073 ty::Int(_)
1074 | ty::Uint(_)
1075 | ty::Float(_)
1076 | ty::Bool
1077 | ty::Char
1078 | ty::Str
1079 | ty::Never
1080 | ty::Ref(..)
1081 | ty::RawPtr(_)
1082 | ty::FnDef(..)
1083 | ty::Error(_)
1084 | ty::FnPtr(_) => true,
5e7ed085 1085 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
cdc7bbd5
XL
1086 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(),
1087 ty::Adt(..)
1088 | ty::Bound(..)
1089 | ty::Closure(..)
1090 | ty::Dynamic(..)
1091 | ty::Foreign(_)
1092 | ty::Generator(..)
1093 | ty::GeneratorWitness(_)
9ffffee4 1094 | ty::GeneratorWitnessMIR(..)
cdc7bbd5 1095 | ty::Infer(_)
9c376795 1096 | ty::Alias(..)
cdc7bbd5 1097 | ty::Param(_)
9c376795 1098 | ty::Placeholder(_) => false,
cdc7bbd5
XL
1099 }
1100 }
1101
cc61c64b
XL
1102 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
1103 /// non-copy and *might* have a destructor attached; if it returns
0731742a 1104 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
cc61c64b
XL
1105 ///
1106 /// (Note that this implies that if `ty` has a destructor attached,
1107 /// then `needs_drop` will definitely return `true` for `ty`.)
e74abb32
XL
1108 ///
1109 /// Note that this method is used to check eligible types in unions.
cc61c64b 1110 #[inline]
5099ac24 1111 pub fn needs_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
74b04a01
XL
1112 // Avoid querying in simple cases.
1113 match needs_drop_components(self, &tcx.data_layout) {
1114 Err(AlwaysRequiresDrop) => true,
1115 Ok(components) => {
1116 let query_ty = match *components {
1117 [] => return false,
1118 // If we've got a single component, call the query with that
1119 // to increase the chance that we hit the query cache.
1120 [component_ty] => component_ty,
1121 _ => self,
1122 };
a2a8927a 1123
74b04a01
XL
1124 // This doesn't depend on regions, so try to minimize distinct
1125 // query keys used.
a2a8927a
XL
1126 // If normalization fails, we just use `query_ty`.
1127 let query_ty =
1128 tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty);
1129
1130 tcx.needs_drop_raw(param_env.and(query_ty))
74b04a01
XL
1131 }
1132 }
cc61c64b
XL
1133 }
1134
2b03887a 1135 /// Checks if `ty` has a significant drop.
17df50a5
XL
1136 ///
1137 /// Note that this method can return false even if `ty` has a destructor
1138 /// attached; even if that is the case then the adt has been marked with
1139 /// the attribute `rustc_insignificant_dtor`.
1140 ///
1141 /// Note that this method is used to check for change in drop order for
1142 /// 2229 drop reorder migration analysis.
1143 #[inline]
5099ac24 1144 pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
17df50a5
XL
1145 // Avoid querying in simple cases.
1146 match needs_drop_components(self, &tcx.data_layout) {
1147 Err(AlwaysRequiresDrop) => true,
1148 Ok(components) => {
1149 let query_ty = match *components {
1150 [] => return false,
1151 // If we've got a single component, call the query with that
1152 // to increase the chance that we hit the query cache.
1153 [component_ty] => component_ty,
1154 _ => self,
1155 };
136023e0
XL
1156
1157 // FIXME(#86868): We should be canonicalizing, or else moving this to a method of inference
1158 // context, or *something* like that, but for now just avoid passing inference
1159 // variables to queries that can't cope with them. Instead, conservatively
1160 // return "true" (may change drop order).
1161 if query_ty.needs_infer() {
1162 return true;
1163 }
1164
17df50a5
XL
1165 // This doesn't depend on regions, so try to minimize distinct
1166 // query keys used.
1167 let erased = tcx.normalize_erasing_regions(param_env, query_ty);
1168 tcx.has_significant_drop_raw(param_env.and(erased))
1169 }
1170 }
1171 }
1172
f035d41b
XL
1173 /// Returns `true` if equality for this type is both reflexive and structural.
1174 ///
1175 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
1176 ///
1177 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
1178 /// types, equality for the type as a whole is structural when it is the same as equality
1179 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1180 /// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
1181 /// that type.
1182 ///
1183 /// This function is "shallow" because it may return `true` for a composite type whose fields
1184 /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
1185 /// because equality for arrays is determined by the equality of each array element. If you
1186 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1187 /// down, you will need to use a type visitor.
1188 #[inline]
5099ac24 1189 pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1b1a35ee 1190 match self.kind() {
f035d41b 1191 // Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
923072b8 1192 ty::Adt(..) => tcx.has_structural_eq_impls(self),
f035d41b
XL
1193
1194 // Primitive types that satisfy `Eq`.
923072b8 1195 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
f035d41b
XL
1196
1197 // Composite types that satisfy `Eq` when all of their fields do.
1198 //
1199 // Because this function is "shallow", we return `true` for these composites regardless
1200 // of the type(s) contained within.
923072b8 1201 ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
f035d41b
XL
1202
1203 // Raw pointers use bitwise comparison.
923072b8 1204 ty::RawPtr(_) | ty::FnPtr(_) => true,
f035d41b
XL
1205
1206 // Floating point numbers are not `Eq`.
923072b8 1207 ty::Float(_) => false,
f035d41b
XL
1208
1209 // Conservatively return `false` for all others...
1210
1211 // Anonymous function types
923072b8 1212 ty::FnDef(..) | ty::Closure(..) | ty::Dynamic(..) | ty::Generator(..) => false,
f035d41b
XL
1213
1214 // Generic or inferred types
1215 //
1216 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1217 // called for known, fully-monomorphized types.
9c376795
FG
1218 ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1219 false
1220 }
f035d41b 1221
9ffffee4
FG
1222 ty::Foreign(_)
1223 | ty::GeneratorWitness(..)
1224 | ty::GeneratorWitnessMIR(..)
1225 | ty::Error(_) => false,
f035d41b
XL
1226 }
1227 }
1228
e1599b0c
XL
1229 /// Peel off all reference types in this type until there are none left.
1230 ///
1231 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1232 ///
1233 /// # Examples
1234 ///
1235 /// - `u8` -> `u8`
1236 /// - `&'a mut u8` -> `u8`
1237 /// - `&'a &'b u8` -> `u8`
1238 /// - `&'a *const &'b u8 -> *const &'b u8`
5099ac24 1239 pub fn peel_refs(self) -> Ty<'tcx> {
e1599b0c 1240 let mut ty = self;
923072b8 1241 while let ty::Ref(_, inner_ty, _) = ty.kind() {
5099ac24 1242 ty = *inner_ty;
e1599b0c
XL
1243 }
1244 ty
1245 }
136023e0 1246
064997fb 1247 #[inline]
923072b8 1248 pub fn outer_exclusive_binder(self) -> ty::DebruijnIndex {
5099ac24 1249 self.0.outer_exclusive_binder
136023e0 1250 }
e9174d1e 1251}
7cac9316 1252
abe05a73
XL
1253pub enum ExplicitSelf<'tcx> {
1254 ByValue,
1255 ByReference(ty::Region<'tcx>, hir::Mutability),
ff7c6d11 1256 ByRawPointer(hir::Mutability),
abe05a73 1257 ByBox,
dfeec247 1258 Other,
abe05a73
XL
1259}
1260
1261impl<'tcx> ExplicitSelf<'tcx> {
1262 /// Categorizes an explicit self declaration like `self: SomeType`
1263 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
1264 /// `Other`.
1265 /// This is mainly used to require the arbitrary_self_types feature
1266 /// in the case of `Other`, to improve error messages in the common cases,
1267 /// and to make `Other` non-object-safe.
1268 ///
1269 /// Examples:
1270 ///
04454e1e 1271 /// ```ignore (illustrative)
abe05a73
XL
1272 /// impl<'a> Foo for &'a T {
1273 /// // Legal declarations:
1274 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
1275 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
1276 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1277 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1278 ///
1279 /// // Invalid cases will be caught by `check_method_receiver`:
1280 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1281 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1282 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
1283 /// }
1284 /// ```
1285 ///
dfeec247 1286 pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
abe05a73 1287 where
dfeec247 1288 P: Fn(Ty<'tcx>) -> bool,
abe05a73
XL
1289 {
1290 use self::ExplicitSelf::*;
1291
1b1a35ee 1292 match *self_arg_ty.kind() {
abe05a73 1293 _ if is_self_ty(self_arg_ty) => ByValue,
dfeec247
XL
1294 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
1295 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
1296 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
1297 _ => Other,
abe05a73
XL
1298 }
1299 }
1300}
74b04a01
XL
1301
1302/// Returns a list of types such that the given type needs drop if and only if
1303/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1304/// this type always needs drop.
a2a8927a 1305pub fn needs_drop_components<'tcx>(
74b04a01
XL
1306 ty: Ty<'tcx>,
1307 target_layout: &TargetDataLayout,
1308) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1b1a35ee 1309 match ty.kind() {
74b04a01
XL
1310 ty::Infer(ty::FreshIntTy(_))
1311 | ty::Infer(ty::FreshFloatTy(_))
1312 | ty::Bool
1313 | ty::Int(_)
1314 | ty::Uint(_)
1315 | ty::Float(_)
1316 | ty::Never
1317 | ty::FnDef(..)
1318 | ty::FnPtr(_)
1319 | ty::Char
1320 | ty::GeneratorWitness(..)
9ffffee4 1321 | ty::GeneratorWitnessMIR(..)
74b04a01
XL
1322 | ty::RawPtr(_)
1323 | ty::Ref(..)
1324 | ty::Str => Ok(SmallVec::new()),
1325
1326 // Foreign types can never have destructors.
1327 ty::Foreign(..) => Ok(SmallVec::new()),
1328
f035d41b 1329 ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
74b04a01 1330
5099ac24 1331 ty::Slice(ty) => needs_drop_components(*ty, target_layout),
74b04a01 1332 ty::Array(elem_ty, size) => {
5099ac24 1333 match needs_drop_components(*elem_ty, target_layout) {
74b04a01 1334 Ok(v) if v.is_empty() => Ok(v),
923072b8 1335 res => match size.kind().try_to_bits(target_layout.pointer_size) {
74b04a01
XL
1336 // Arrays of size zero don't need drop, even if their element
1337 // type does.
1338 Some(0) => Ok(SmallVec::new()),
1339 Some(_) => res,
1340 // We don't know which of the cases above we are in, so
1341 // return the whole type and let the caller decide what to
1342 // do.
1343 None => Ok(smallvec![ty]),
1344 },
1345 }
1346 }
1347 // If any field needs drop, then the whole tuple does.
5e7ed085 1348 ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
74b04a01
XL
1349 acc.extend(needs_drop_components(elem, target_layout)?);
1350 Ok(acc)
1351 }),
1352
1353 // These require checking for `Copy` bounds or `Adt` destructors.
1354 ty::Adt(..)
9c376795 1355 | ty::Alias(..)
74b04a01
XL
1356 | ty::Param(_)
1357 | ty::Bound(..)
1358 | ty::Placeholder(..)
74b04a01 1359 | ty::Infer(_)
ba9703b0
XL
1360 | ty::Closure(..)
1361 | ty::Generator(..) => Ok(smallvec![ty]),
74b04a01
XL
1362 }
1363}
1364
9c376795 1365pub fn is_trivially_const_drop(ty: Ty<'_>) -> bool {
5099ac24
FG
1366 match *ty.kind() {
1367 ty::Bool
1368 | ty::Char
1369 | ty::Int(_)
1370 | ty::Uint(_)
1371 | ty::Float(_)
1372 | ty::Infer(ty::IntVar(_))
1373 | ty::Infer(ty::FloatVar(_))
1374 | ty::Str
1375 | ty::RawPtr(_)
1376 | ty::Ref(..)
1377 | ty::FnDef(..)
1378 | ty::FnPtr(_)
1379 | ty::Never
1380 | ty::Foreign(_) => true,
1381
9c376795 1382 ty::Alias(..)
5099ac24
FG
1383 | ty::Dynamic(..)
1384 | ty::Error(_)
1385 | ty::Bound(..)
1386 | ty::Param(_)
1387 | ty::Placeholder(_)
5099ac24
FG
1388 | ty::Infer(_) => false,
1389
1390 // Not trivial because they have components, and instead of looking inside,
1391 // we'll just perform trait selection.
9ffffee4
FG
1392 ty::Closure(..)
1393 | ty::Generator(..)
1394 | ty::GeneratorWitness(_)
1395 | ty::GeneratorWitnessMIR(..)
1396 | ty::Adt(..) => false,
5099ac24
FG
1397
1398 ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty),
1399
5e7ed085 1400 ty::Tuple(tys) => tys.iter().all(|ty| is_trivially_const_drop(ty)),
5099ac24
FG
1401 }
1402}
1403
487cf647
FG
1404/// Does the equivalent of
1405/// ```ignore (ilustrative)
1406/// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1407/// folder.tcx().intern_*(&v)
1408/// ```
fc512014
XL
1409pub fn fold_list<'tcx, F, T>(
1410 list: &'tcx ty::List<T>,
1411 folder: &mut F,
1412 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List<T>,
a2a8927a 1413) -> Result<&'tcx ty::List<T>, F::Error>
fc512014 1414where
9ffffee4
FG
1415 F: FallibleTypeFolder<TyCtxt<'tcx>>,
1416 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
fc512014
XL
1417{
1418 let mut iter = list.iter();
1419 // Look for the first element that changed
a2a8927a
XL
1420 match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1421 Ok(new_t) if new_t == t => None,
1422 new_t => Some((i, new_t)),
fc512014 1423 }) {
a2a8927a
XL
1424 Some((i, Ok(new_t))) => {
1425 // An element changed, prepare to intern the resulting list
1426 let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len());
1427 new_list.extend_from_slice(&list[..i]);
1428 new_list.push(new_t);
1429 for t in iter {
1430 new_list.push(t.try_fold_with(folder)?)
1431 }
9ffffee4 1432 Ok(intern(folder.interner(), &new_list))
a2a8927a
XL
1433 }
1434 Some((_, Err(err))) => {
1435 return Err(err);
1436 }
1437 None => Ok(list),
fc512014
XL
1438 }
1439}
1440
3dfed10e 1441#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
74b04a01 1442pub struct AlwaysRequiresDrop;
3dfed10e 1443
487cf647 1444/// Reveals all opaque types in the given value, replacing them
3dfed10e 1445/// with their underlying types.
487cf647 1446pub fn reveal_opaque_types_in_bounds<'tcx>(
3dfed10e 1447 tcx: TyCtxt<'tcx>,
923072b8
FG
1448 val: &'tcx ty::List<ty::Predicate<'tcx>>,
1449) -> &'tcx ty::List<ty::Predicate<'tcx>> {
3dfed10e
XL
1450 let mut visitor = OpaqueTypeExpander {
1451 seen_opaque_tys: FxHashSet::default(),
1452 expanded_cache: FxHashMap::default(),
1453 primary_def_id: None,
1454 found_recursion: false,
94222f64 1455 found_any_recursion: false,
3dfed10e 1456 check_recursion: false,
9ffffee4 1457 expand_generators: false,
3dfed10e
XL
1458 tcx,
1459 };
1460 val.fold_with(&mut visitor)
1461}
1462
5e7ed085 1463/// Determines whether an item is annotated with `doc(hidden)`.
353b0b11 1464fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
04454e1e
FG
1465 tcx.get_attrs(def_id, sym::doc)
1466 .filter_map(|attr| attr.meta_item_list())
5e7ed085
FG
1467 .any(|items| items.iter().any(|item| item.has_name(sym::hidden)))
1468}
1469
2b03887a
FG
1470/// Determines whether an item is annotated with `doc(notable_trait)`.
1471pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1472 tcx.get_attrs(def_id, sym::doc)
1473 .filter_map(|attr| attr.meta_item_list())
1474 .any(|items| items.iter().any(|item| item.has_name(sym::notable_trait)))
1475}
1476
923072b8 1477/// Determines whether an item is an intrinsic by Abi.
353b0b11 1478pub fn is_intrinsic(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
9ffffee4 1479 matches!(tcx.fn_sig(def_id).skip_binder().abi(), Abi::RustIntrinsic | Abi::PlatformIntrinsic)
923072b8
FG
1480}
1481
3dfed10e 1482pub fn provide(providers: &mut ty::query::Providers) {
2b03887a 1483 *providers = ty::query::Providers {
487cf647 1484 reveal_opaque_types_in_bounds,
2b03887a
FG
1485 is_doc_hidden,
1486 is_doc_notable_trait,
1487 is_intrinsic,
1488 ..*providers
1489 }
3dfed10e 1490}