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