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