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