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