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