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