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