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