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