]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/util.rs
Allow to create definitions inside the query system.
[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.associated_item(dtor).container.id();
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
681 struct OpaqueTypeExpander<'tcx> {
682     // Contains the DefIds of the opaque types that are currently being
683     // expanded. When we expand an opaque type we insert the DefId of
684     // that type, and when we finish expanding that type we remove the
685     // its DefId.
686     seen_opaque_tys: FxHashSet<DefId>,
687     // Cache of all expansions we've seen so far. This is a critical
688     // optimization for some large types produced by async fn trees.
689     expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
690     primary_def_id: Option<DefId>,
691     found_recursion: bool,
692     found_any_recursion: bool,
693     /// Whether or not to check for recursive opaque types.
694     /// This is `true` when we're explicitly checking for opaque type
695     /// recursion, and 'false' otherwise to avoid unnecessary work.
696     check_recursion: bool,
697     tcx: TyCtxt<'tcx>,
698 }
699
700 impl<'tcx> OpaqueTypeExpander<'tcx> {
701     fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
702         if self.found_any_recursion {
703             return None;
704         }
705         let substs = substs.fold_with(self);
706         if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
707             let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
708                 Some(expanded_ty) => *expanded_ty,
709                 None => {
710                     let generic_ty = self.tcx.bound_type_of(def_id);
711                     let concrete_ty = generic_ty.subst(self.tcx, substs);
712                     let expanded_ty = self.fold_ty(concrete_ty);
713                     self.expanded_cache.insert((def_id, substs), expanded_ty);
714                     expanded_ty
715                 }
716             };
717             if self.check_recursion {
718                 self.seen_opaque_tys.remove(&def_id);
719             }
720             Some(expanded_ty)
721         } else {
722             // If another opaque type that we contain is recursive, then it
723             // will report the error, so we don't have to.
724             self.found_any_recursion = true;
725             self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
726             None
727         }
728     }
729 }
730
731 impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> {
732     fn tcx(&self) -> TyCtxt<'tcx> {
733         self.tcx
734     }
735
736     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
737         if let ty::Opaque(def_id, substs) = *t.kind() {
738             self.expand_opaque_ty(def_id, substs).unwrap_or(t)
739         } else if t.has_opaque_types() {
740             t.super_fold_with(self)
741         } else {
742             t
743         }
744     }
745 }
746
747 impl<'tcx> Ty<'tcx> {
748     /// Returns the maximum value for the given numeric type (including `char`s)
749     /// or returns `None` if the type is not numeric.
750     pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
751         let val = match self.kind() {
752             ty::Int(_) | ty::Uint(_) => {
753                 let (size, signed) = int_size_and_signed(tcx, self);
754                 let val =
755                     if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
756                 Some(val)
757             }
758             ty::Char => Some(std::char::MAX as u128),
759             ty::Float(fty) => Some(match fty {
760                 ty::FloatTy::F32 => rustc_apfloat::ieee::Single::INFINITY.to_bits(),
761                 ty::FloatTy::F64 => rustc_apfloat::ieee::Double::INFINITY.to_bits(),
762             }),
763             _ => None,
764         };
765
766         val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
767     }
768
769     /// Returns the minimum value for the given numeric type (including `char`s)
770     /// or returns `None` if the type is not numeric.
771     pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
772         let val = match self.kind() {
773             ty::Int(_) | ty::Uint(_) => {
774                 let (size, signed) = int_size_and_signed(tcx, self);
775                 let val = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
776                 Some(val)
777             }
778             ty::Char => Some(0),
779             ty::Float(fty) => Some(match fty {
780                 ty::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
781                 ty::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
782             }),
783             _ => None,
784         };
785
786         val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
787     }
788
789     /// Checks whether values of this type `T` are *moved* or *copied*
790     /// when referenced -- this amounts to a check for whether `T:
791     /// Copy`, but note that we **don't** consider lifetimes when
792     /// doing this check. This means that we may generate MIR which
793     /// does copies even when the type actually doesn't satisfy the
794     /// full requirements for the `Copy` trait (cc #29149) -- this
795     /// winds up being reported as an error during NLL borrow check.
796     pub fn is_copy_modulo_regions(
797         self,
798         tcx_at: TyCtxtAt<'tcx>,
799         param_env: ty::ParamEnv<'tcx>,
800     ) -> bool {
801         self.is_trivially_pure_clone_copy() || tcx_at.is_copy_raw(param_env.and(self))
802     }
803
804     /// Checks whether values of this type `T` have a size known at
805     /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
806     /// for the purposes of this check, so it can be an
807     /// over-approximation in generic contexts, where one can have
808     /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
809     /// actually carry lifetime requirements.
810     pub fn is_sized(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
811         self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self))
812     }
813
814     /// Checks whether values of this type `T` implement the `Freeze`
815     /// trait -- frozen types are those that do not contain an
816     /// `UnsafeCell` anywhere. This is a language concept used to
817     /// distinguish "true immutability", which is relevant to
818     /// optimization as well as the rules around static values. Note
819     /// that the `Freeze` trait is not exposed to end users and is
820     /// effectively an implementation detail.
821     pub fn is_freeze(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
822         self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
823     }
824
825     /// Fast path helper for testing if a type is `Freeze`.
826     ///
827     /// Returning true means the type is known to be `Freeze`. Returning
828     /// `false` means nothing -- could be `Freeze`, might not be.
829     fn is_trivially_freeze(self) -> bool {
830         match self.kind() {
831             ty::Int(_)
832             | ty::Uint(_)
833             | ty::Float(_)
834             | ty::Bool
835             | ty::Char
836             | ty::Str
837             | ty::Never
838             | ty::Ref(..)
839             | ty::RawPtr(_)
840             | ty::FnDef(..)
841             | ty::Error(_)
842             | ty::FnPtr(_) => true,
843             ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
844             ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
845             ty::Adt(..)
846             | ty::Bound(..)
847             | ty::Closure(..)
848             | ty::Dynamic(..)
849             | ty::Foreign(_)
850             | ty::Generator(..)
851             | ty::GeneratorWitness(_)
852             | ty::Infer(_)
853             | ty::Opaque(..)
854             | ty::Param(_)
855             | ty::Placeholder(_)
856             | ty::Projection(_) => false,
857         }
858     }
859
860     /// Checks whether values of this type `T` implement the `Unpin` trait.
861     pub fn is_unpin(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
862         self.is_trivially_unpin() || tcx_at.is_unpin_raw(param_env.and(self))
863     }
864
865     /// Fast path helper for testing if a type is `Unpin`.
866     ///
867     /// Returning true means the type is known to be `Unpin`. Returning
868     /// `false` means nothing -- could be `Unpin`, might not be.
869     fn is_trivially_unpin(self) -> bool {
870         match self.kind() {
871             ty::Int(_)
872             | ty::Uint(_)
873             | ty::Float(_)
874             | ty::Bool
875             | ty::Char
876             | ty::Str
877             | ty::Never
878             | ty::Ref(..)
879             | ty::RawPtr(_)
880             | ty::FnDef(..)
881             | ty::Error(_)
882             | ty::FnPtr(_) => true,
883             ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
884             ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(),
885             ty::Adt(..)
886             | ty::Bound(..)
887             | ty::Closure(..)
888             | ty::Dynamic(..)
889             | ty::Foreign(_)
890             | ty::Generator(..)
891             | ty::GeneratorWitness(_)
892             | ty::Infer(_)
893             | ty::Opaque(..)
894             | ty::Param(_)
895             | ty::Placeholder(_)
896             | ty::Projection(_) => false,
897         }
898     }
899
900     /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
901     /// non-copy and *might* have a destructor attached; if it returns
902     /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
903     ///
904     /// (Note that this implies that if `ty` has a destructor attached,
905     /// then `needs_drop` will definitely return `true` for `ty`.)
906     ///
907     /// Note that this method is used to check eligible types in unions.
908     #[inline]
909     pub fn needs_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
910         // Avoid querying in simple cases.
911         match needs_drop_components(self, &tcx.data_layout) {
912             Err(AlwaysRequiresDrop) => true,
913             Ok(components) => {
914                 let query_ty = match *components {
915                     [] => return false,
916                     // If we've got a single component, call the query with that
917                     // to increase the chance that we hit the query cache.
918                     [component_ty] => component_ty,
919                     _ => self,
920                 };
921
922                 // This doesn't depend on regions, so try to minimize distinct
923                 // query keys used.
924                 // If normalization fails, we just use `query_ty`.
925                 let query_ty =
926                     tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty);
927
928                 tcx.needs_drop_raw(param_env.and(query_ty))
929             }
930         }
931     }
932
933     /// Checks if `ty` has has a significant drop.
934     ///
935     /// Note that this method can return false even if `ty` has a destructor
936     /// attached; even if that is the case then the adt has been marked with
937     /// the attribute `rustc_insignificant_dtor`.
938     ///
939     /// Note that this method is used to check for change in drop order for
940     /// 2229 drop reorder migration analysis.
941     #[inline]
942     pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
943         // Avoid querying in simple cases.
944         match needs_drop_components(self, &tcx.data_layout) {
945             Err(AlwaysRequiresDrop) => true,
946             Ok(components) => {
947                 let query_ty = match *components {
948                     [] => return false,
949                     // If we've got a single component, call the query with that
950                     // to increase the chance that we hit the query cache.
951                     [component_ty] => component_ty,
952                     _ => self,
953                 };
954
955                 // FIXME(#86868): We should be canonicalizing, or else moving this to a method of inference
956                 // context, or *something* like that, but for now just avoid passing inference
957                 // variables to queries that can't cope with them. Instead, conservatively
958                 // return "true" (may change drop order).
959                 if query_ty.needs_infer() {
960                     return true;
961                 }
962
963                 // This doesn't depend on regions, so try to minimize distinct
964                 // query keys used.
965                 let erased = tcx.normalize_erasing_regions(param_env, query_ty);
966                 tcx.has_significant_drop_raw(param_env.and(erased))
967             }
968         }
969     }
970
971     /// Returns `true` if equality for this type is both reflexive and structural.
972     ///
973     /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
974     ///
975     /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
976     /// types, equality for the type as a whole is structural when it is the same as equality
977     /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
978     /// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
979     /// that type.
980     ///
981     /// This function is "shallow" because it may return `true` for a composite type whose fields
982     /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
983     /// because equality for arrays is determined by the equality of each array element. If you
984     /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
985     /// down, you will need to use a type visitor.
986     #[inline]
987     pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
988         match self.kind() {
989             // Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
990             ty::Adt(..) => tcx.has_structural_eq_impls(self),
991
992             // Primitive types that satisfy `Eq`.
993             ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
994
995             // Composite types that satisfy `Eq` when all of their fields do.
996             //
997             // Because this function is "shallow", we return `true` for these composites regardless
998             // of the type(s) contained within.
999             ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
1000
1001             // Raw pointers use bitwise comparison.
1002             ty::RawPtr(_) | ty::FnPtr(_) => true,
1003
1004             // Floating point numbers are not `Eq`.
1005             ty::Float(_) => false,
1006
1007             // Conservatively return `false` for all others...
1008
1009             // Anonymous function types
1010             ty::FnDef(..) | ty::Closure(..) | ty::Dynamic(..) | ty::Generator(..) => false,
1011
1012             // Generic or inferred types
1013             //
1014             // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1015             // called for known, fully-monomorphized types.
1016             ty::Projection(_)
1017             | ty::Opaque(..)
1018             | ty::Param(_)
1019             | ty::Bound(..)
1020             | ty::Placeholder(_)
1021             | ty::Infer(_) => false,
1022
1023             ty::Foreign(_) | ty::GeneratorWitness(..) | ty::Error(_) => false,
1024         }
1025     }
1026
1027     /// Peel off all reference types in this type until there are none left.
1028     ///
1029     /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1030     ///
1031     /// # Examples
1032     ///
1033     /// - `u8` -> `u8`
1034     /// - `&'a mut u8` -> `u8`
1035     /// - `&'a &'b u8` -> `u8`
1036     /// - `&'a *const &'b u8 -> *const &'b u8`
1037     pub fn peel_refs(self) -> Ty<'tcx> {
1038         let mut ty = self;
1039         while let ty::Ref(_, inner_ty, _) = ty.kind() {
1040             ty = *inner_ty;
1041         }
1042         ty
1043     }
1044
1045     pub fn outer_exclusive_binder(self) -> ty::DebruijnIndex {
1046         self.0.outer_exclusive_binder
1047     }
1048 }
1049
1050 pub enum ExplicitSelf<'tcx> {
1051     ByValue,
1052     ByReference(ty::Region<'tcx>, hir::Mutability),
1053     ByRawPointer(hir::Mutability),
1054     ByBox,
1055     Other,
1056 }
1057
1058 impl<'tcx> ExplicitSelf<'tcx> {
1059     /// Categorizes an explicit self declaration like `self: SomeType`
1060     /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
1061     /// `Other`.
1062     /// This is mainly used to require the arbitrary_self_types feature
1063     /// in the case of `Other`, to improve error messages in the common cases,
1064     /// and to make `Other` non-object-safe.
1065     ///
1066     /// Examples:
1067     ///
1068     /// ```ignore (illustrative)
1069     /// impl<'a> Foo for &'a T {
1070     ///     // Legal declarations:
1071     ///     fn method1(self: &&'a T); // ExplicitSelf::ByReference
1072     ///     fn method2(self: &'a T); // ExplicitSelf::ByValue
1073     ///     fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1074     ///     fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1075     ///
1076     ///     // Invalid cases will be caught by `check_method_receiver`:
1077     ///     fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1078     ///     fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1079     ///     fn method_err3(self: &&T) // ExplicitSelf::ByReference
1080     /// }
1081     /// ```
1082     ///
1083     pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
1084     where
1085         P: Fn(Ty<'tcx>) -> bool,
1086     {
1087         use self::ExplicitSelf::*;
1088
1089         match *self_arg_ty.kind() {
1090             _ if is_self_ty(self_arg_ty) => ByValue,
1091             ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
1092             ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
1093             ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
1094             _ => Other,
1095         }
1096     }
1097 }
1098
1099 /// Returns a list of types such that the given type needs drop if and only if
1100 /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1101 /// this type always needs drop.
1102 pub fn needs_drop_components<'tcx>(
1103     ty: Ty<'tcx>,
1104     target_layout: &TargetDataLayout,
1105 ) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1106     match ty.kind() {
1107         ty::Infer(ty::FreshIntTy(_))
1108         | ty::Infer(ty::FreshFloatTy(_))
1109         | ty::Bool
1110         | ty::Int(_)
1111         | ty::Uint(_)
1112         | ty::Float(_)
1113         | ty::Never
1114         | ty::FnDef(..)
1115         | ty::FnPtr(_)
1116         | ty::Char
1117         | ty::GeneratorWitness(..)
1118         | ty::RawPtr(_)
1119         | ty::Ref(..)
1120         | ty::Str => Ok(SmallVec::new()),
1121
1122         // Foreign types can never have destructors.
1123         ty::Foreign(..) => Ok(SmallVec::new()),
1124
1125         ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
1126
1127         ty::Slice(ty) => needs_drop_components(*ty, target_layout),
1128         ty::Array(elem_ty, size) => {
1129             match needs_drop_components(*elem_ty, target_layout) {
1130                 Ok(v) if v.is_empty() => Ok(v),
1131                 res => match size.kind().try_to_bits(target_layout.pointer_size) {
1132                     // Arrays of size zero don't need drop, even if their element
1133                     // type does.
1134                     Some(0) => Ok(SmallVec::new()),
1135                     Some(_) => res,
1136                     // We don't know which of the cases above we are in, so
1137                     // return the whole type and let the caller decide what to
1138                     // do.
1139                     None => Ok(smallvec![ty]),
1140                 },
1141             }
1142         }
1143         // If any field needs drop, then the whole tuple does.
1144         ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1145             acc.extend(needs_drop_components(elem, target_layout)?);
1146             Ok(acc)
1147         }),
1148
1149         // These require checking for `Copy` bounds or `Adt` destructors.
1150         ty::Adt(..)
1151         | ty::Projection(..)
1152         | ty::Param(_)
1153         | ty::Bound(..)
1154         | ty::Placeholder(..)
1155         | ty::Opaque(..)
1156         | ty::Infer(_)
1157         | ty::Closure(..)
1158         | ty::Generator(..) => Ok(smallvec![ty]),
1159     }
1160 }
1161
1162 pub fn is_trivially_const_drop<'tcx>(ty: Ty<'tcx>) -> bool {
1163     match *ty.kind() {
1164         ty::Bool
1165         | ty::Char
1166         | ty::Int(_)
1167         | ty::Uint(_)
1168         | ty::Float(_)
1169         | ty::Infer(ty::IntVar(_))
1170         | ty::Infer(ty::FloatVar(_))
1171         | ty::Str
1172         | ty::RawPtr(_)
1173         | ty::Ref(..)
1174         | ty::FnDef(..)
1175         | ty::FnPtr(_)
1176         | ty::Never
1177         | ty::Foreign(_) => true,
1178
1179         ty::Opaque(..)
1180         | ty::Dynamic(..)
1181         | ty::Error(_)
1182         | ty::Bound(..)
1183         | ty::Param(_)
1184         | ty::Placeholder(_)
1185         | ty::Projection(_)
1186         | ty::Infer(_) => false,
1187
1188         // Not trivial because they have components, and instead of looking inside,
1189         // we'll just perform trait selection.
1190         ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) | ty::Adt(..) => false,
1191
1192         ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty),
1193
1194         ty::Tuple(tys) => tys.iter().all(|ty| is_trivially_const_drop(ty)),
1195     }
1196 }
1197
1198 // Does the equivalent of
1199 // ```
1200 // let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1201 // folder.tcx().intern_*(&v)
1202 // ```
1203 pub fn fold_list<'tcx, F, T>(
1204     list: &'tcx ty::List<T>,
1205     folder: &mut F,
1206     intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List<T>,
1207 ) -> Result<&'tcx ty::List<T>, F::Error>
1208 where
1209     F: FallibleTypeFolder<'tcx>,
1210     T: TypeFoldable<'tcx> + PartialEq + Copy,
1211 {
1212     let mut iter = list.iter();
1213     // Look for the first element that changed
1214     match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1215         Ok(new_t) if new_t == t => None,
1216         new_t => Some((i, new_t)),
1217     }) {
1218         Some((i, Ok(new_t))) => {
1219             // An element changed, prepare to intern the resulting list
1220             let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len());
1221             new_list.extend_from_slice(&list[..i]);
1222             new_list.push(new_t);
1223             for t in iter {
1224                 new_list.push(t.try_fold_with(folder)?)
1225             }
1226             Ok(intern(folder.tcx(), &new_list))
1227         }
1228         Some((_, Err(err))) => {
1229             return Err(err);
1230         }
1231         None => Ok(list),
1232     }
1233 }
1234
1235 #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
1236 pub struct AlwaysRequiresDrop;
1237
1238 /// Normalizes all opaque types in the given value, replacing them
1239 /// with their underlying types.
1240 pub fn normalize_opaque_types<'tcx>(
1241     tcx: TyCtxt<'tcx>,
1242     val: &'tcx ty::List<ty::Predicate<'tcx>>,
1243 ) -> &'tcx ty::List<ty::Predicate<'tcx>> {
1244     let mut visitor = OpaqueTypeExpander {
1245         seen_opaque_tys: FxHashSet::default(),
1246         expanded_cache: FxHashMap::default(),
1247         primary_def_id: None,
1248         found_recursion: false,
1249         found_any_recursion: false,
1250         check_recursion: false,
1251         tcx,
1252     };
1253     val.fold_with(&mut visitor)
1254 }
1255
1256 /// Determines whether an item is annotated with `doc(hidden)`.
1257 pub fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1258     tcx.get_attrs(def_id, sym::doc)
1259         .filter_map(|attr| attr.meta_item_list())
1260         .any(|items| items.iter().any(|item| item.has_name(sym::hidden)))
1261 }
1262
1263 /// Determines whether an item is an intrinsic by Abi.
1264 pub fn is_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1265     matches!(tcx.fn_sig(def_id).abi(), Abi::RustIntrinsic | Abi::PlatformIntrinsic)
1266 }
1267
1268 pub fn provide(providers: &mut ty::query::Providers) {
1269     *providers =
1270         ty::query::Providers { normalize_opaque_types, is_doc_hidden, is_intrinsic, ..*providers }
1271 }