]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/hir.rs
Rollup merge of #107385 - BoxyUwU:ConstInferUnifier_is_folder, r=compiler-errors
[rust.git] / compiler / rustc_hir / src / hir.rs
1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 pub(crate) use crate::hir_id::{HirId, ItemLocalId, OwnerId};
4 use crate::intravisit::FnKind;
5 use crate::LangItem;
6
7 use rustc_ast as ast;
8 use rustc_ast::util::parser::ExprPrecedence;
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BindingAnnotation, BorrowKind, ByRef, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::sorted_map::SortedMap;
16 use rustc_error_messages::MultiSpan;
17 use rustc_index::vec::IndexVec;
18 use rustc_macros::HashStable_Generic;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::source_map::Spanned;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{def_id::LocalDefId, BytePos, Span, DUMMY_SP};
23 use rustc_target::asm::InlineAsmRegOrRegClass;
24 use rustc_target::spec::abi::Abi;
25
26 use smallvec::SmallVec;
27 use std::fmt;
28
29 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
30 pub struct Lifetime {
31     pub hir_id: HirId,
32
33     /// Either "`'a`", referring to a named lifetime definition,
34     /// `'_` referring to an anonymous lifetime (either explicitly `'_` or `&type`),
35     /// or "``" (i.e., `kw::Empty`) when appearing in path.
36     ///
37     /// See `Lifetime::suggestion_position` for practical use.
38     pub ident: Ident,
39
40     /// Semantics of this lifetime.
41     pub res: LifetimeName,
42 }
43
44 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
45 #[derive(HashStable_Generic)]
46 pub enum ParamName {
47     /// Some user-given name like `T` or `'x`.
48     Plain(Ident),
49
50     /// Synthetic name generated when user elided a lifetime in an impl header.
51     ///
52     /// E.g., the lifetimes in cases like these:
53     /// ```ignore (fragment)
54     /// impl Foo for &u32
55     /// impl Foo<'_> for u32
56     /// ```
57     /// in that case, we rewrite to
58     /// ```ignore (fragment)
59     /// impl<'f> Foo for &'f u32
60     /// impl<'f> Foo<'f> for u32
61     /// ```
62     /// where `'f` is something like `Fresh(0)`. The indices are
63     /// unique per impl, but not necessarily continuous.
64     Fresh,
65
66     /// Indicates an illegal name was given and an error has been
67     /// reported (so we should squelch other derived errors). Occurs
68     /// when, e.g., `'_` is used in the wrong place.
69     Error,
70 }
71
72 impl ParamName {
73     pub fn ident(&self) -> Ident {
74         match *self {
75             ParamName::Plain(ident) => ident,
76             ParamName::Fresh | ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
77         }
78     }
79
80     pub fn normalize_to_macros_2_0(&self) -> ParamName {
81         match *self {
82             ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
83             param_name => param_name,
84         }
85     }
86 }
87
88 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
89 #[derive(HashStable_Generic)]
90 pub enum LifetimeName {
91     /// User-given names or fresh (synthetic) names.
92     Param(LocalDefId),
93
94     /// Implicit lifetime in a context like `dyn Foo`. This is
95     /// distinguished from implicit lifetimes elsewhere because the
96     /// lifetime that they default to must appear elsewhere within the
97     /// enclosing type. This means that, in an `impl Trait` context, we
98     /// don't have to create a parameter for them. That is, `impl
99     /// Trait<Item = &u32>` expands to an opaque type like `type
100     /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
101     /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
102     /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
103     /// that surrounding code knows not to create a lifetime
104     /// parameter.
105     ImplicitObjectLifetimeDefault,
106
107     /// Indicates an error during lowering (usually `'_` in wrong place)
108     /// that was already reported.
109     Error,
110
111     /// User wrote an anonymous lifetime, either `'_` or nothing.
112     /// The semantics of this lifetime should be inferred by typechecking code.
113     Infer,
114
115     /// User wrote `'static`.
116     Static,
117 }
118
119 impl LifetimeName {
120     pub fn is_elided(&self) -> bool {
121         match self {
122             LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true,
123
124             // It might seem surprising that `Fresh` counts as not *elided*
125             // -- but this is because, as far as the code in the compiler is
126             // concerned -- `Fresh` variants act equivalently to "some fresh name".
127             // They correspond to early-bound regions on an impl, in other words.
128             LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
129         }
130     }
131 }
132
133 impl fmt::Display for Lifetime {
134     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135         if self.ident.name != kw::Empty { self.ident.name.fmt(f) } else { "'_".fmt(f) }
136     }
137 }
138
139 pub enum LifetimeSuggestionPosition {
140     /// The user wrote `'a` or `'_`.
141     Normal,
142     /// The user wrote `&type` or `&mut type`.
143     Ampersand,
144     /// The user wrote `Path` and omitted the `<'_>`.
145     ElidedPath,
146     /// The user wrote `Path<T>`, and omitted the `'_,`.
147     ElidedPathArgument,
148     /// The user wrote `dyn Trait` and omitted the `+ '_`.
149     ObjectDefault,
150 }
151
152 impl Lifetime {
153     pub fn is_elided(&self) -> bool {
154         self.res.is_elided()
155     }
156
157     pub fn is_anonymous(&self) -> bool {
158         self.ident.name == kw::Empty || self.ident.name == kw::UnderscoreLifetime
159     }
160
161     pub fn suggestion_position(&self) -> (LifetimeSuggestionPosition, Span) {
162         if self.ident.name == kw::Empty {
163             if self.ident.span.is_empty() {
164                 (LifetimeSuggestionPosition::ElidedPathArgument, self.ident.span)
165             } else {
166                 (LifetimeSuggestionPosition::ElidedPath, self.ident.span.shrink_to_hi())
167             }
168         } else if self.res == LifetimeName::ImplicitObjectLifetimeDefault {
169             (LifetimeSuggestionPosition::ObjectDefault, self.ident.span)
170         } else if self.ident.span.is_empty() {
171             (LifetimeSuggestionPosition::Ampersand, self.ident.span)
172         } else {
173             (LifetimeSuggestionPosition::Normal, self.ident.span)
174         }
175     }
176
177     pub fn is_static(&self) -> bool {
178         self.res == LifetimeName::Static
179     }
180 }
181
182 /// A `Path` is essentially Rust's notion of a name; for instance,
183 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
184 /// along with a bunch of supporting information.
185 #[derive(Debug, HashStable_Generic)]
186 pub struct Path<'hir, R = Res> {
187     pub span: Span,
188     /// The resolution for the path.
189     pub res: R,
190     /// The segments in the path: the things separated by `::`.
191     pub segments: &'hir [PathSegment<'hir>],
192 }
193
194 /// Up to three resolutions for type, value and macro namespaces.
195 pub type UsePath<'hir> = Path<'hir, SmallVec<[Res; 3]>>;
196
197 impl Path<'_> {
198     pub fn is_global(&self) -> bool {
199         !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
200     }
201 }
202
203 /// A segment of a path: an identifier, an optional lifetime, and a set of
204 /// types.
205 #[derive(Debug, HashStable_Generic)]
206 pub struct PathSegment<'hir> {
207     /// The identifier portion of this path segment.
208     pub ident: Ident,
209     pub hir_id: HirId,
210     pub res: Res,
211
212     /// Type/lifetime parameters attached to this path. They come in
213     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
214     /// this is more than just simple syntactic sugar; the use of
215     /// parens affects the region binding rules, so we preserve the
216     /// distinction.
217     pub args: Option<&'hir GenericArgs<'hir>>,
218
219     /// Whether to infer remaining type parameters, if any.
220     /// This only applies to expression and pattern paths, and
221     /// out of those only the segments with no type parameters
222     /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
223     pub infer_args: bool,
224 }
225
226 impl<'hir> PathSegment<'hir> {
227     /// Converts an identifier to the corresponding segment.
228     pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
229         PathSegment { ident, hir_id, res, infer_args: true, args: None }
230     }
231
232     pub fn invalid() -> Self {
233         Self::new(Ident::empty(), HirId::INVALID, Res::Err)
234     }
235
236     pub fn args(&self) -> &GenericArgs<'hir> {
237         if let Some(ref args) = self.args {
238             args
239         } else {
240             const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
241             DUMMY
242         }
243     }
244 }
245
246 #[derive(Encodable, Debug, HashStable_Generic)]
247 pub struct ConstArg {
248     pub value: AnonConst,
249     pub span: Span,
250 }
251
252 #[derive(Encodable, Debug, HashStable_Generic)]
253 pub struct InferArg {
254     pub hir_id: HirId,
255     pub span: Span,
256 }
257
258 impl InferArg {
259     pub fn to_ty(&self) -> Ty<'_> {
260         Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
261     }
262 }
263
264 #[derive(Debug, HashStable_Generic)]
265 pub enum GenericArg<'hir> {
266     Lifetime(&'hir Lifetime),
267     Type(&'hir Ty<'hir>),
268     Const(ConstArg),
269     Infer(InferArg),
270 }
271
272 impl GenericArg<'_> {
273     pub fn span(&self) -> Span {
274         match self {
275             GenericArg::Lifetime(l) => l.ident.span,
276             GenericArg::Type(t) => t.span,
277             GenericArg::Const(c) => c.span,
278             GenericArg::Infer(i) => i.span,
279         }
280     }
281
282     pub fn hir_id(&self) -> HirId {
283         match self {
284             GenericArg::Lifetime(l) => l.hir_id,
285             GenericArg::Type(t) => t.hir_id,
286             GenericArg::Const(c) => c.value.hir_id,
287             GenericArg::Infer(i) => i.hir_id,
288         }
289     }
290
291     pub fn is_synthetic(&self) -> bool {
292         matches!(self, GenericArg::Lifetime(lifetime) if lifetime.ident == Ident::empty())
293     }
294
295     pub fn descr(&self) -> &'static str {
296         match self {
297             GenericArg::Lifetime(_) => "lifetime",
298             GenericArg::Type(_) => "type",
299             GenericArg::Const(_) => "constant",
300             GenericArg::Infer(_) => "inferred",
301         }
302     }
303
304     pub fn to_ord(&self) -> ast::ParamKindOrd {
305         match self {
306             GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
307             GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
308                 ast::ParamKindOrd::TypeOrConst
309             }
310         }
311     }
312
313     pub fn is_ty_or_const(&self) -> bool {
314         match self {
315             GenericArg::Lifetime(_) => false,
316             GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
317         }
318     }
319 }
320
321 #[derive(Debug, HashStable_Generic)]
322 pub struct GenericArgs<'hir> {
323     /// The generic arguments for this path segment.
324     pub args: &'hir [GenericArg<'hir>],
325     /// Bindings (equality constraints) on associated types, if present.
326     /// E.g., `Foo<A = Bar>`.
327     pub bindings: &'hir [TypeBinding<'hir>],
328     /// Were arguments written in parenthesized form `Fn(T) -> U`?
329     /// This is required mostly for pretty-printing and diagnostics,
330     /// but also for changing lifetime elision rules to be "function-like".
331     pub parenthesized: bool,
332     /// The span encompassing arguments and the surrounding brackets `<>` or `()`
333     ///       Foo<A, B, AssocTy = D>           Fn(T, U, V) -> W
334     ///          ^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^
335     /// Note that this may be:
336     /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
337     /// - dummy, if this was generated while desugaring
338     pub span_ext: Span,
339 }
340
341 impl<'hir> GenericArgs<'hir> {
342     pub const fn none() -> Self {
343         Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
344     }
345
346     pub fn inputs(&self) -> &[Ty<'hir>] {
347         if self.parenthesized {
348             for arg in self.args {
349                 match arg {
350                     GenericArg::Lifetime(_) => {}
351                     GenericArg::Type(ref ty) => {
352                         if let TyKind::Tup(ref tys) = ty.kind {
353                             return tys;
354                         }
355                         break;
356                     }
357                     GenericArg::Const(_) => {}
358                     GenericArg::Infer(_) => {}
359                 }
360             }
361         }
362         panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
363     }
364
365     #[inline]
366     pub fn has_type_params(&self) -> bool {
367         self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
368     }
369
370     pub fn has_err(&self) -> bool {
371         self.args.iter().any(|arg| match arg {
372             GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
373             _ => false,
374         }) || self.bindings.iter().any(|arg| match arg.kind {
375             TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
376             _ => false,
377         })
378     }
379
380     #[inline]
381     pub fn num_type_params(&self) -> usize {
382         self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
383     }
384
385     #[inline]
386     pub fn num_lifetime_params(&self) -> usize {
387         self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
388     }
389
390     #[inline]
391     pub fn has_lifetime_params(&self) -> bool {
392         self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
393     }
394
395     #[inline]
396     /// This function returns the number of type and const generic params.
397     /// It should only be used for diagnostics.
398     pub fn num_generic_params(&self) -> usize {
399         self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
400     }
401
402     /// The span encompassing the text inside the surrounding brackets.
403     /// It will also include bindings if they aren't in the form `-> Ret`
404     /// Returns `None` if the span is empty (e.g. no brackets) or dummy
405     pub fn span(&self) -> Option<Span> {
406         let span_ext = self.span_ext()?;
407         Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
408     }
409
410     /// Returns span encompassing arguments and their surrounding `<>` or `()`
411     pub fn span_ext(&self) -> Option<Span> {
412         Some(self.span_ext).filter(|span| !span.is_empty())
413     }
414
415     pub fn is_empty(&self) -> bool {
416         self.args.is_empty()
417     }
418 }
419
420 /// A modifier on a bound, currently this is only used for `?Sized`, where the
421 /// modifier is `Maybe`. Negative bounds should also be handled here.
422 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
423 #[derive(HashStable_Generic)]
424 pub enum TraitBoundModifier {
425     None,
426     Maybe,
427     MaybeConst,
428 }
429
430 /// The AST represents all type param bounds as types.
431 /// `typeck::collect::compute_bounds` matches these against
432 /// the "special" built-in traits (see `middle::lang_items`) and
433 /// detects `Copy`, `Send` and `Sync`.
434 #[derive(Clone, Debug, HashStable_Generic)]
435 pub enum GenericBound<'hir> {
436     Trait(PolyTraitRef<'hir>, TraitBoundModifier),
437     // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
438     LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
439     Outlives(&'hir Lifetime),
440 }
441
442 impl GenericBound<'_> {
443     pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
444         match self {
445             GenericBound::Trait(data, _) => Some(&data.trait_ref),
446             _ => None,
447         }
448     }
449
450     pub fn span(&self) -> Span {
451         match self {
452             GenericBound::Trait(t, ..) => t.span,
453             GenericBound::LangItemTrait(_, span, ..) => *span,
454             GenericBound::Outlives(l) => l.ident.span,
455         }
456     }
457 }
458
459 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
460
461 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
462 pub enum LifetimeParamKind {
463     // Indicates that the lifetime definition was explicitly declared (e.g., in
464     // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
465     Explicit,
466
467     // Indication that the lifetime was elided (e.g., in both cases in
468     // `fn foo(x: &u8) -> &'_ u8 { x }`).
469     Elided,
470
471     // Indication that the lifetime name was somehow in error.
472     Error,
473 }
474
475 #[derive(Debug, HashStable_Generic)]
476 pub enum GenericParamKind<'hir> {
477     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
478     Lifetime {
479         kind: LifetimeParamKind,
480     },
481     Type {
482         default: Option<&'hir Ty<'hir>>,
483         synthetic: bool,
484     },
485     Const {
486         ty: &'hir Ty<'hir>,
487         /// Optional default value for the const generic param
488         default: Option<AnonConst>,
489     },
490 }
491
492 #[derive(Debug, HashStable_Generic)]
493 pub struct GenericParam<'hir> {
494     pub hir_id: HirId,
495     pub def_id: LocalDefId,
496     pub name: ParamName,
497     pub span: Span,
498     pub pure_wrt_drop: bool,
499     pub kind: GenericParamKind<'hir>,
500     pub colon_span: Option<Span>,
501 }
502
503 impl<'hir> GenericParam<'hir> {
504     /// Synthetic type-parameters are inserted after normal ones.
505     /// In order for normal parameters to be able to refer to synthetic ones,
506     /// scans them first.
507     pub fn is_impl_trait(&self) -> bool {
508         matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
509     }
510
511     /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
512     ///
513     /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
514     pub fn is_elided_lifetime(&self) -> bool {
515         matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
516     }
517 }
518
519 #[derive(Default)]
520 pub struct GenericParamCount {
521     pub lifetimes: usize,
522     pub types: usize,
523     pub consts: usize,
524     pub infer: usize,
525 }
526
527 /// Represents lifetimes and type parameters attached to a declaration
528 /// of a function, enum, trait, etc.
529 #[derive(Debug, HashStable_Generic)]
530 pub struct Generics<'hir> {
531     pub params: &'hir [GenericParam<'hir>],
532     pub predicates: &'hir [WherePredicate<'hir>],
533     pub has_where_clause_predicates: bool,
534     pub where_clause_span: Span,
535     pub span: Span,
536 }
537
538 impl<'hir> Generics<'hir> {
539     pub const fn empty() -> &'hir Generics<'hir> {
540         const NOPE: Generics<'_> = Generics {
541             params: &[],
542             predicates: &[],
543             has_where_clause_predicates: false,
544             where_clause_span: DUMMY_SP,
545             span: DUMMY_SP,
546         };
547         &NOPE
548     }
549
550     pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
551         self.params.iter().find(|&param| name == param.name.ident().name)
552     }
553
554     pub fn spans(&self) -> MultiSpan {
555         if self.params.is_empty() {
556             self.span.into()
557         } else {
558             self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
559         }
560     }
561
562     /// If there are generic parameters, return where to introduce a new one.
563     pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
564         if let Some(first) = self.params.first()
565             && self.span.contains(first.span)
566         {
567             // `fn foo<A>(t: impl Trait)`
568             //         ^ suggest `'a, ` here
569             Some(first.span.shrink_to_lo())
570         } else {
571             None
572         }
573     }
574
575     /// If there are generic parameters, return where to introduce a new one.
576     pub fn span_for_param_suggestion(&self) -> Option<Span> {
577         if self.params.iter().any(|p| self.span.contains(p.span)) {
578             // `fn foo<A>(t: impl Trait)`
579             //          ^ suggest `, T: Trait` here
580             let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
581             Some(span)
582         } else {
583             None
584         }
585     }
586
587     /// `Span` where further predicates would be suggested, accounting for trailing commas, like
588     ///  in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
589     pub fn tail_span_for_predicate_suggestion(&self) -> Span {
590         let end = self.where_clause_span.shrink_to_hi();
591         if self.has_where_clause_predicates {
592             self.predicates
593                 .iter()
594                 .rfind(|&p| p.in_where_clause())
595                 .map_or(end, |p| p.span())
596                 .shrink_to_hi()
597                 .to(end)
598         } else {
599             end
600         }
601     }
602
603     pub fn add_where_or_trailing_comma(&self) -> &'static str {
604         if self.has_where_clause_predicates {
605             ","
606         } else if self.where_clause_span.is_empty() {
607             " where"
608         } else {
609             // No where clause predicates, but we have `where` token
610             ""
611         }
612     }
613
614     pub fn bounds_for_param(
615         &self,
616         param_def_id: LocalDefId,
617     ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
618         self.predicates.iter().filter_map(move |pred| match pred {
619             WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
620                 Some(bp)
621             }
622             _ => None,
623         })
624     }
625
626     pub fn outlives_for_param(
627         &self,
628         param_def_id: LocalDefId,
629     ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
630         self.predicates.iter().filter_map(move |pred| match pred {
631             WherePredicate::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
632             _ => None,
633         })
634     }
635
636     pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
637         self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
638             |bound| {
639                 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
640                 // as we use this method to get a span appropriate for suggestions.
641                 let bs = bound.span();
642                 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
643             },
644         )
645     }
646
647     pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
648         let predicate = &self.predicates[pos];
649         let span = predicate.span();
650
651         if !predicate.in_where_clause() {
652             // <T: ?Sized, U>
653             //   ^^^^^^^^
654             return span;
655         }
656
657         // We need to find out which comma to remove.
658         if pos < self.predicates.len() - 1 {
659             let next_pred = &self.predicates[pos + 1];
660             if next_pred.in_where_clause() {
661                 // where T: ?Sized, Foo: Bar,
662                 //       ^^^^^^^^^^^
663                 return span.until(next_pred.span());
664             }
665         }
666
667         if pos > 0 {
668             let prev_pred = &self.predicates[pos - 1];
669             if prev_pred.in_where_clause() {
670                 // where Foo: Bar, T: ?Sized,
671                 //               ^^^^^^^^^^^
672                 return prev_pred.span().shrink_to_hi().to(span);
673             }
674         }
675
676         // This is the only predicate in the where clause.
677         // where T: ?Sized
678         // ^^^^^^^^^^^^^^^
679         self.where_clause_span
680     }
681
682     pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
683         let predicate = &self.predicates[predicate_pos];
684         let bounds = predicate.bounds();
685
686         if bounds.len() == 1 {
687             return self.span_for_predicate_removal(predicate_pos);
688         }
689
690         let span = bounds[bound_pos].span();
691         if bound_pos == 0 {
692             // where T: ?Sized + Bar, Foo: Bar,
693             //          ^^^^^^^^^
694             span.to(bounds[1].span().shrink_to_lo())
695         } else {
696             // where T: Bar + ?Sized, Foo: Bar,
697             //             ^^^^^^^^^
698             bounds[bound_pos - 1].span().shrink_to_hi().to(span)
699         }
700     }
701 }
702
703 /// A single predicate in a where-clause.
704 #[derive(Debug, HashStable_Generic)]
705 pub enum WherePredicate<'hir> {
706     /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
707     BoundPredicate(WhereBoundPredicate<'hir>),
708     /// A lifetime predicate (e.g., `'a: 'b + 'c`).
709     RegionPredicate(WhereRegionPredicate<'hir>),
710     /// An equality predicate (unsupported).
711     EqPredicate(WhereEqPredicate<'hir>),
712 }
713
714 impl<'hir> WherePredicate<'hir> {
715     pub fn span(&self) -> Span {
716         match self {
717             WherePredicate::BoundPredicate(p) => p.span,
718             WherePredicate::RegionPredicate(p) => p.span,
719             WherePredicate::EqPredicate(p) => p.span,
720         }
721     }
722
723     pub fn in_where_clause(&self) -> bool {
724         match self {
725             WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
726             WherePredicate::RegionPredicate(p) => p.in_where_clause,
727             WherePredicate::EqPredicate(_) => false,
728         }
729     }
730
731     pub fn bounds(&self) -> GenericBounds<'hir> {
732         match self {
733             WherePredicate::BoundPredicate(p) => p.bounds,
734             WherePredicate::RegionPredicate(p) => p.bounds,
735             WherePredicate::EqPredicate(_) => &[],
736         }
737     }
738 }
739
740 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
741 pub enum PredicateOrigin {
742     WhereClause,
743     GenericParam,
744     ImplTrait,
745 }
746
747 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
748 #[derive(Debug, HashStable_Generic)]
749 pub struct WhereBoundPredicate<'hir> {
750     pub hir_id: HirId,
751     pub span: Span,
752     /// Origin of the predicate.
753     pub origin: PredicateOrigin,
754     /// Any generics from a `for` binding.
755     pub bound_generic_params: &'hir [GenericParam<'hir>],
756     /// The type being bounded.
757     pub bounded_ty: &'hir Ty<'hir>,
758     /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
759     pub bounds: GenericBounds<'hir>,
760 }
761
762 impl<'hir> WhereBoundPredicate<'hir> {
763     /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
764     pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
765         self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
766     }
767 }
768
769 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
770 #[derive(Debug, HashStable_Generic)]
771 pub struct WhereRegionPredicate<'hir> {
772     pub span: Span,
773     pub in_where_clause: bool,
774     pub lifetime: &'hir Lifetime,
775     pub bounds: GenericBounds<'hir>,
776 }
777
778 impl<'hir> WhereRegionPredicate<'hir> {
779     /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
780     pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
781         self.lifetime.res == LifetimeName::Param(param_def_id)
782     }
783 }
784
785 /// An equality predicate (e.g., `T = int`); currently unsupported.
786 #[derive(Debug, HashStable_Generic)]
787 pub struct WhereEqPredicate<'hir> {
788     pub span: Span,
789     pub lhs_ty: &'hir Ty<'hir>,
790     pub rhs_ty: &'hir Ty<'hir>,
791 }
792
793 /// HIR node coupled with its parent's id in the same HIR owner.
794 ///
795 /// The parent is trash when the node is a HIR owner.
796 #[derive(Clone, Debug)]
797 pub struct ParentedNode<'tcx> {
798     pub parent: ItemLocalId,
799     pub node: Node<'tcx>,
800 }
801
802 /// Attributes owned by a HIR owner.
803 #[derive(Debug)]
804 pub struct AttributeMap<'tcx> {
805     pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
806     pub hash: Fingerprint,
807 }
808
809 impl<'tcx> AttributeMap<'tcx> {
810     pub const EMPTY: &'static AttributeMap<'static> =
811         &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
812
813     #[inline]
814     pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
815         self.map.get(&id).copied().unwrap_or(&[])
816     }
817 }
818
819 /// Map of all HIR nodes inside the current owner.
820 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
821 /// The HIR tree, including bodies, is pre-hashed.
822 pub struct OwnerNodes<'tcx> {
823     /// Pre-computed hash of the full HIR.
824     pub hash_including_bodies: Fingerprint,
825     /// Pre-computed hash of the item signature, without recursing into the body.
826     pub hash_without_bodies: Fingerprint,
827     /// Full HIR for the current owner.
828     // The zeroth node's parent should never be accessed: the owner's parent is computed by the
829     // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
830     // used.
831     pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
832     /// Content of local bodies.
833     pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
834     /// Non-owning definitions contained in this owner.
835     pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
836 }
837
838 impl<'tcx> OwnerNodes<'tcx> {
839     pub fn node(&self) -> OwnerNode<'tcx> {
840         use rustc_index::vec::Idx;
841         let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
842         let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
843         node
844     }
845 }
846
847 impl fmt::Debug for OwnerNodes<'_> {
848     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849         f.debug_struct("OwnerNodes")
850             // Do not print all the pointers to all the nodes, as it would be unreadable.
851             .field("node", &self.nodes[ItemLocalId::from_u32(0)])
852             .field(
853                 "parents",
854                 &self
855                     .nodes
856                     .iter_enumerated()
857                     .map(|(id, parented_node)| {
858                         let parented_node = parented_node.as_ref().map(|node| node.parent);
859
860                         debug_fn(move |f| write!(f, "({id:?}, {parented_node:?})"))
861                     })
862                     .collect::<Vec<_>>(),
863             )
864             .field("bodies", &self.bodies)
865             .field("local_id_to_def_id", &self.local_id_to_def_id)
866             .field("hash_without_bodies", &self.hash_without_bodies)
867             .field("hash_including_bodies", &self.hash_including_bodies)
868             .finish()
869     }
870 }
871
872 /// Full information resulting from lowering an AST node.
873 #[derive(Debug, HashStable_Generic)]
874 pub struct OwnerInfo<'hir> {
875     /// Contents of the HIR.
876     pub nodes: OwnerNodes<'hir>,
877     /// Map from each nested owner to its parent's local id.
878     pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
879     /// Collected attributes of the HIR nodes.
880     pub attrs: AttributeMap<'hir>,
881     /// Map indicating what traits are in scope for places where this
882     /// is relevant; generated by resolve.
883     pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
884 }
885
886 impl<'tcx> OwnerInfo<'tcx> {
887     #[inline]
888     pub fn node(&self) -> OwnerNode<'tcx> {
889         self.nodes.node()
890     }
891 }
892
893 #[derive(Copy, Clone, Debug, HashStable_Generic)]
894 pub enum MaybeOwner<T> {
895     Owner(T),
896     NonOwner(HirId),
897     /// Used as a placeholder for unused LocalDefId.
898     Phantom,
899 }
900
901 impl<T> MaybeOwner<T> {
902     pub fn as_owner(self) -> Option<T> {
903         match self {
904             MaybeOwner::Owner(i) => Some(i),
905             MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
906         }
907     }
908
909     pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
910         match self {
911             MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
912             MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
913             MaybeOwner::Phantom => MaybeOwner::Phantom,
914         }
915     }
916
917     pub fn unwrap(self) -> T {
918         match self {
919             MaybeOwner::Owner(i) => i,
920             MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
921         }
922     }
923 }
924
925 /// The top-level data structure that stores the entire contents of
926 /// the crate currently being compiled.
927 ///
928 /// For more details, see the [rustc dev guide].
929 ///
930 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
931 #[derive(Debug)]
932 pub struct Crate<'hir> {
933     pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
934     pub hir_hash: Fingerprint,
935 }
936
937 #[derive(Debug, HashStable_Generic)]
938 pub struct Closure<'hir> {
939     pub def_id: LocalDefId,
940     pub binder: ClosureBinder,
941     pub constness: Constness,
942     pub capture_clause: CaptureBy,
943     pub bound_generic_params: &'hir [GenericParam<'hir>],
944     pub fn_decl: &'hir FnDecl<'hir>,
945     pub body: BodyId,
946     /// The span of the declaration block: 'move |...| -> ...'
947     pub fn_decl_span: Span,
948     /// The span of the argument block `|...|`
949     pub fn_arg_span: Option<Span>,
950     pub movability: Option<Movability>,
951 }
952
953 /// A block of statements `{ .. }`, which may have a label (in this case the
954 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
955 /// the `rules` being anything but `DefaultBlock`.
956 #[derive(Debug, HashStable_Generic)]
957 pub struct Block<'hir> {
958     /// Statements in a block.
959     pub stmts: &'hir [Stmt<'hir>],
960     /// An expression at the end of the block
961     /// without a semicolon, if any.
962     pub expr: Option<&'hir Expr<'hir>>,
963     #[stable_hasher(ignore)]
964     pub hir_id: HirId,
965     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
966     pub rules: BlockCheckMode,
967     pub span: Span,
968     /// If true, then there may exist `break 'a` values that aim to
969     /// break out of this block early.
970     /// Used by `'label: {}` blocks and by `try {}` blocks.
971     pub targeted_by_break: bool,
972 }
973
974 impl<'hir> Block<'hir> {
975     pub fn innermost_block(&self) -> &Block<'hir> {
976         let mut block = self;
977         while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
978             block = inner_block;
979         }
980         block
981     }
982 }
983
984 #[derive(Debug, HashStable_Generic)]
985 pub struct Pat<'hir> {
986     #[stable_hasher(ignore)]
987     pub hir_id: HirId,
988     pub kind: PatKind<'hir>,
989     pub span: Span,
990     /// Whether to use default binding modes.
991     /// At present, this is false only for destructuring assignment.
992     pub default_binding_modes: bool,
993 }
994
995 impl<'hir> Pat<'hir> {
996     // FIXME(#19596) this is a workaround, but there should be a better way
997     fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
998         if !it(self) {
999             return false;
1000         }
1001
1002         use PatKind::*;
1003         match self.kind {
1004             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
1005             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
1006             Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1007             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1008             Slice(before, slice, after) => {
1009                 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1010             }
1011         }
1012     }
1013
1014     /// Walk the pattern in left-to-right order,
1015     /// short circuiting (with `.all(..)`) if `false` is returned.
1016     ///
1017     /// Note that when visiting e.g. `Tuple(ps)`,
1018     /// if visiting `ps[0]` returns `false`,
1019     /// then `ps[1]` will not be visited.
1020     pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1021         self.walk_short_(&mut it)
1022     }
1023
1024     // FIXME(#19596) this is a workaround, but there should be a better way
1025     fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1026         if !it(self) {
1027             return;
1028         }
1029
1030         use PatKind::*;
1031         match self.kind {
1032             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1033             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1034             Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1035             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1036             Slice(before, slice, after) => {
1037                 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1038             }
1039         }
1040     }
1041
1042     /// Walk the pattern in left-to-right order.
1043     ///
1044     /// If `it(pat)` returns `false`, the children are not visited.
1045     pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1046         self.walk_(&mut it)
1047     }
1048
1049     /// Walk the pattern in left-to-right order.
1050     ///
1051     /// If you always want to recurse, prefer this method over `walk`.
1052     pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1053         self.walk(|p| {
1054             it(p);
1055             true
1056         })
1057     }
1058 }
1059
1060 /// A single field in a struct pattern.
1061 ///
1062 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1063 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1064 /// except `is_shorthand` is true.
1065 #[derive(Debug, HashStable_Generic)]
1066 pub struct PatField<'hir> {
1067     #[stable_hasher(ignore)]
1068     pub hir_id: HirId,
1069     /// The identifier for the field.
1070     pub ident: Ident,
1071     /// The pattern the field is destructured to.
1072     pub pat: &'hir Pat<'hir>,
1073     pub is_shorthand: bool,
1074     pub span: Span,
1075 }
1076
1077 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1078 pub enum RangeEnd {
1079     Included,
1080     Excluded,
1081 }
1082
1083 impl fmt::Display for RangeEnd {
1084     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1085         f.write_str(match self {
1086             RangeEnd::Included => "..=",
1087             RangeEnd::Excluded => "..",
1088         })
1089     }
1090 }
1091
1092 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1093 // this type only takes up 4 bytes, at the cost of being restricted to a
1094 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1095 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1096 pub struct DotDotPos(u32);
1097
1098 impl DotDotPos {
1099     /// Panics if n >= u32::MAX.
1100     pub fn new(n: Option<usize>) -> Self {
1101         match n {
1102             Some(n) => {
1103                 assert!(n < u32::MAX as usize);
1104                 Self(n as u32)
1105             }
1106             None => Self(u32::MAX),
1107         }
1108     }
1109
1110     pub fn as_opt_usize(&self) -> Option<usize> {
1111         if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1112     }
1113 }
1114
1115 impl fmt::Debug for DotDotPos {
1116     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1117         self.as_opt_usize().fmt(f)
1118     }
1119 }
1120
1121 #[derive(Debug, HashStable_Generic)]
1122 pub enum PatKind<'hir> {
1123     /// Represents a wildcard pattern (i.e., `_`).
1124     Wild,
1125
1126     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1127     /// The `HirId` is the canonical ID for the variable being bound,
1128     /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1129     /// which is the pattern ID of the first `x`.
1130     Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1131
1132     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1133     /// The `bool` is `true` in the presence of a `..`.
1134     Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1135
1136     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1137     /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1138     /// `0 <= position <= subpats.len()`
1139     TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1140
1141     /// An or-pattern `A | B | C`.
1142     /// Invariant: `pats.len() >= 2`.
1143     Or(&'hir [Pat<'hir>]),
1144
1145     /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1146     Path(QPath<'hir>),
1147
1148     /// A tuple pattern (e.g., `(a, b)`).
1149     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1150     /// `0 <= position <= subpats.len()`
1151     Tuple(&'hir [Pat<'hir>], DotDotPos),
1152
1153     /// A `box` pattern.
1154     Box(&'hir Pat<'hir>),
1155
1156     /// A reference pattern (e.g., `&mut (a, b)`).
1157     Ref(&'hir Pat<'hir>, Mutability),
1158
1159     /// A literal.
1160     Lit(&'hir Expr<'hir>),
1161
1162     /// A range pattern (e.g., `1..=2` or `1..2`).
1163     Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1164
1165     /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1166     ///
1167     /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1168     /// If `slice` exists, then `after` can be non-empty.
1169     ///
1170     /// The representation for e.g., `[a, b, .., c, d]` is:
1171     /// ```ignore (illustrative)
1172     /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1173     /// ```
1174     Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1175 }
1176
1177 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1178 pub enum BinOpKind {
1179     /// The `+` operator (addition).
1180     Add,
1181     /// The `-` operator (subtraction).
1182     Sub,
1183     /// The `*` operator (multiplication).
1184     Mul,
1185     /// The `/` operator (division).
1186     Div,
1187     /// The `%` operator (modulus).
1188     Rem,
1189     /// The `&&` operator (logical and).
1190     And,
1191     /// The `||` operator (logical or).
1192     Or,
1193     /// The `^` operator (bitwise xor).
1194     BitXor,
1195     /// The `&` operator (bitwise and).
1196     BitAnd,
1197     /// The `|` operator (bitwise or).
1198     BitOr,
1199     /// The `<<` operator (shift left).
1200     Shl,
1201     /// The `>>` operator (shift right).
1202     Shr,
1203     /// The `==` operator (equality).
1204     Eq,
1205     /// The `<` operator (less than).
1206     Lt,
1207     /// The `<=` operator (less than or equal to).
1208     Le,
1209     /// The `!=` operator (not equal to).
1210     Ne,
1211     /// The `>=` operator (greater than or equal to).
1212     Ge,
1213     /// The `>` operator (greater than).
1214     Gt,
1215 }
1216
1217 impl BinOpKind {
1218     pub fn as_str(self) -> &'static str {
1219         match self {
1220             BinOpKind::Add => "+",
1221             BinOpKind::Sub => "-",
1222             BinOpKind::Mul => "*",
1223             BinOpKind::Div => "/",
1224             BinOpKind::Rem => "%",
1225             BinOpKind::And => "&&",
1226             BinOpKind::Or => "||",
1227             BinOpKind::BitXor => "^",
1228             BinOpKind::BitAnd => "&",
1229             BinOpKind::BitOr => "|",
1230             BinOpKind::Shl => "<<",
1231             BinOpKind::Shr => ">>",
1232             BinOpKind::Eq => "==",
1233             BinOpKind::Lt => "<",
1234             BinOpKind::Le => "<=",
1235             BinOpKind::Ne => "!=",
1236             BinOpKind::Ge => ">=",
1237             BinOpKind::Gt => ">",
1238         }
1239     }
1240
1241     pub fn is_lazy(self) -> bool {
1242         matches!(self, BinOpKind::And | BinOpKind::Or)
1243     }
1244
1245     pub fn is_shift(self) -> bool {
1246         matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1247     }
1248
1249     pub fn is_comparison(self) -> bool {
1250         match self {
1251             BinOpKind::Eq
1252             | BinOpKind::Lt
1253             | BinOpKind::Le
1254             | BinOpKind::Ne
1255             | BinOpKind::Gt
1256             | BinOpKind::Ge => true,
1257             BinOpKind::And
1258             | BinOpKind::Or
1259             | BinOpKind::Add
1260             | BinOpKind::Sub
1261             | BinOpKind::Mul
1262             | BinOpKind::Div
1263             | BinOpKind::Rem
1264             | BinOpKind::BitXor
1265             | BinOpKind::BitAnd
1266             | BinOpKind::BitOr
1267             | BinOpKind::Shl
1268             | BinOpKind::Shr => false,
1269         }
1270     }
1271
1272     /// Returns `true` if the binary operator takes its arguments by value.
1273     pub fn is_by_value(self) -> bool {
1274         !self.is_comparison()
1275     }
1276 }
1277
1278 impl Into<ast::BinOpKind> for BinOpKind {
1279     fn into(self) -> ast::BinOpKind {
1280         match self {
1281             BinOpKind::Add => ast::BinOpKind::Add,
1282             BinOpKind::Sub => ast::BinOpKind::Sub,
1283             BinOpKind::Mul => ast::BinOpKind::Mul,
1284             BinOpKind::Div => ast::BinOpKind::Div,
1285             BinOpKind::Rem => ast::BinOpKind::Rem,
1286             BinOpKind::And => ast::BinOpKind::And,
1287             BinOpKind::Or => ast::BinOpKind::Or,
1288             BinOpKind::BitXor => ast::BinOpKind::BitXor,
1289             BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1290             BinOpKind::BitOr => ast::BinOpKind::BitOr,
1291             BinOpKind::Shl => ast::BinOpKind::Shl,
1292             BinOpKind::Shr => ast::BinOpKind::Shr,
1293             BinOpKind::Eq => ast::BinOpKind::Eq,
1294             BinOpKind::Lt => ast::BinOpKind::Lt,
1295             BinOpKind::Le => ast::BinOpKind::Le,
1296             BinOpKind::Ne => ast::BinOpKind::Ne,
1297             BinOpKind::Ge => ast::BinOpKind::Ge,
1298             BinOpKind::Gt => ast::BinOpKind::Gt,
1299         }
1300     }
1301 }
1302
1303 pub type BinOp = Spanned<BinOpKind>;
1304
1305 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1306 pub enum UnOp {
1307     /// The `*` operator (dereferencing).
1308     Deref,
1309     /// The `!` operator (logical negation).
1310     Not,
1311     /// The `-` operator (negation).
1312     Neg,
1313 }
1314
1315 impl UnOp {
1316     pub fn as_str(self) -> &'static str {
1317         match self {
1318             Self::Deref => "*",
1319             Self::Not => "!",
1320             Self::Neg => "-",
1321         }
1322     }
1323
1324     /// Returns `true` if the unary operator takes its argument by value.
1325     pub fn is_by_value(self) -> bool {
1326         matches!(self, Self::Neg | Self::Not)
1327     }
1328 }
1329
1330 /// A statement.
1331 #[derive(Debug, HashStable_Generic)]
1332 pub struct Stmt<'hir> {
1333     pub hir_id: HirId,
1334     pub kind: StmtKind<'hir>,
1335     pub span: Span,
1336 }
1337
1338 /// The contents of a statement.
1339 #[derive(Debug, HashStable_Generic)]
1340 pub enum StmtKind<'hir> {
1341     /// A local (`let`) binding.
1342     Local(&'hir Local<'hir>),
1343
1344     /// An item binding.
1345     Item(ItemId),
1346
1347     /// An expression without a trailing semi-colon (must have unit type).
1348     Expr(&'hir Expr<'hir>),
1349
1350     /// An expression with a trailing semi-colon (may have any type).
1351     Semi(&'hir Expr<'hir>),
1352 }
1353
1354 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1355 #[derive(Debug, HashStable_Generic)]
1356 pub struct Local<'hir> {
1357     pub pat: &'hir Pat<'hir>,
1358     /// Type annotation, if any (otherwise the type will be inferred).
1359     pub ty: Option<&'hir Ty<'hir>>,
1360     /// Initializer expression to set the value, if any.
1361     pub init: Option<&'hir Expr<'hir>>,
1362     /// Else block for a `let...else` binding.
1363     pub els: Option<&'hir Block<'hir>>,
1364     pub hir_id: HirId,
1365     pub span: Span,
1366     /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1367     /// desugaring. Otherwise will be `Normal`.
1368     pub source: LocalSource,
1369 }
1370
1371 /// Represents a single arm of a `match` expression, e.g.
1372 /// `<pat> (if <guard>) => <body>`.
1373 #[derive(Debug, HashStable_Generic)]
1374 pub struct Arm<'hir> {
1375     #[stable_hasher(ignore)]
1376     pub hir_id: HirId,
1377     pub span: Span,
1378     /// If this pattern and the optional guard matches, then `body` is evaluated.
1379     pub pat: &'hir Pat<'hir>,
1380     /// Optional guard clause.
1381     pub guard: Option<Guard<'hir>>,
1382     /// The expression the arm evaluates to if this arm matches.
1383     pub body: &'hir Expr<'hir>,
1384 }
1385
1386 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1387 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1388 ///
1389 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1390 /// desugaring to if-let. Only let-else supports the type annotation at present.
1391 #[derive(Debug, HashStable_Generic)]
1392 pub struct Let<'hir> {
1393     pub hir_id: HirId,
1394     pub span: Span,
1395     pub pat: &'hir Pat<'hir>,
1396     pub ty: Option<&'hir Ty<'hir>>,
1397     pub init: &'hir Expr<'hir>,
1398 }
1399
1400 #[derive(Debug, HashStable_Generic)]
1401 pub enum Guard<'hir> {
1402     If(&'hir Expr<'hir>),
1403     IfLet(&'hir Let<'hir>),
1404 }
1405
1406 impl<'hir> Guard<'hir> {
1407     /// Returns the body of the guard
1408     ///
1409     /// In other words, returns the e in either of the following:
1410     ///
1411     /// - `if e`
1412     /// - `if let x = e`
1413     pub fn body(&self) -> &'hir Expr<'hir> {
1414         match self {
1415             Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1416         }
1417     }
1418 }
1419
1420 #[derive(Debug, HashStable_Generic)]
1421 pub struct ExprField<'hir> {
1422     #[stable_hasher(ignore)]
1423     pub hir_id: HirId,
1424     pub ident: Ident,
1425     pub expr: &'hir Expr<'hir>,
1426     pub span: Span,
1427     pub is_shorthand: bool,
1428 }
1429
1430 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1431 pub enum BlockCheckMode {
1432     DefaultBlock,
1433     UnsafeBlock(UnsafeSource),
1434 }
1435
1436 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1437 pub enum UnsafeSource {
1438     CompilerGenerated,
1439     UserProvided,
1440 }
1441
1442 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1443 pub struct BodyId {
1444     pub hir_id: HirId,
1445 }
1446
1447 /// The body of a function, closure, or constant value. In the case of
1448 /// a function, the body contains not only the function body itself
1449 /// (which is an expression), but also the argument patterns, since
1450 /// those are something that the caller doesn't really care about.
1451 ///
1452 /// # Examples
1453 ///
1454 /// ```
1455 /// fn foo((x, y): (u32, u32)) -> u32 {
1456 ///     x + y
1457 /// }
1458 /// ```
1459 ///
1460 /// Here, the `Body` associated with `foo()` would contain:
1461 ///
1462 /// - an `params` array containing the `(x, y)` pattern
1463 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1464 /// - `generator_kind` would be `None`
1465 ///
1466 /// All bodies have an **owner**, which can be accessed via the HIR
1467 /// map using `body_owner_def_id()`.
1468 #[derive(Debug, HashStable_Generic)]
1469 pub struct Body<'hir> {
1470     pub params: &'hir [Param<'hir>],
1471     pub value: &'hir Expr<'hir>,
1472     pub generator_kind: Option<GeneratorKind>,
1473 }
1474
1475 impl<'hir> Body<'hir> {
1476     pub fn id(&self) -> BodyId {
1477         BodyId { hir_id: self.value.hir_id }
1478     }
1479
1480     pub fn generator_kind(&self) -> Option<GeneratorKind> {
1481         self.generator_kind
1482     }
1483 }
1484
1485 /// The type of source expression that caused this generator to be created.
1486 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1487 #[derive(HashStable_Generic, Encodable, Decodable)]
1488 pub enum GeneratorKind {
1489     /// An explicit `async` block or the body of an async function.
1490     Async(AsyncGeneratorKind),
1491
1492     /// A generator literal created via a `yield` inside a closure.
1493     Gen,
1494 }
1495
1496 impl fmt::Display for GeneratorKind {
1497     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1498         match self {
1499             GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1500             GeneratorKind::Gen => f.write_str("generator"),
1501         }
1502     }
1503 }
1504
1505 impl GeneratorKind {
1506     pub fn descr(&self) -> &'static str {
1507         match self {
1508             GeneratorKind::Async(ask) => ask.descr(),
1509             GeneratorKind::Gen => "generator",
1510         }
1511     }
1512 }
1513
1514 /// In the case of a generator created as part of an async construct,
1515 /// which kind of async construct caused it to be created?
1516 ///
1517 /// This helps error messages but is also used to drive coercions in
1518 /// type-checking (see #60424).
1519 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1520 #[derive(HashStable_Generic, Encodable, Decodable)]
1521 pub enum AsyncGeneratorKind {
1522     /// An explicit `async` block written by the user.
1523     Block,
1524
1525     /// An explicit `async` closure written by the user.
1526     Closure,
1527
1528     /// The `async` block generated as the body of an async function.
1529     Fn,
1530 }
1531
1532 impl fmt::Display for AsyncGeneratorKind {
1533     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1534         f.write_str(match self {
1535             AsyncGeneratorKind::Block => "async block",
1536             AsyncGeneratorKind::Closure => "async closure body",
1537             AsyncGeneratorKind::Fn => "async fn body",
1538         })
1539     }
1540 }
1541
1542 impl AsyncGeneratorKind {
1543     pub fn descr(&self) -> &'static str {
1544         match self {
1545             AsyncGeneratorKind::Block => "`async` block",
1546             AsyncGeneratorKind::Closure => "`async` closure body",
1547             AsyncGeneratorKind::Fn => "`async fn` body",
1548         }
1549     }
1550 }
1551
1552 #[derive(Copy, Clone, Debug)]
1553 pub enum BodyOwnerKind {
1554     /// Functions and methods.
1555     Fn,
1556
1557     /// Closures
1558     Closure,
1559
1560     /// Constants and associated constants.
1561     Const,
1562
1563     /// Initializer of a `static` item.
1564     Static(Mutability),
1565 }
1566
1567 impl BodyOwnerKind {
1568     pub fn is_fn_or_closure(self) -> bool {
1569         match self {
1570             BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1571             BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1572         }
1573     }
1574 }
1575
1576 /// The kind of an item that requires const-checking.
1577 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1578 pub enum ConstContext {
1579     /// A `const fn`.
1580     ConstFn,
1581
1582     /// A `static` or `static mut`.
1583     Static(Mutability),
1584
1585     /// A `const`, associated `const`, or other const context.
1586     ///
1587     /// Other contexts include:
1588     /// - Array length expressions
1589     /// - Enum discriminants
1590     /// - Const generics
1591     ///
1592     /// For the most part, other contexts are treated just like a regular `const`, so they are
1593     /// lumped into the same category.
1594     Const,
1595 }
1596
1597 impl ConstContext {
1598     /// A description of this const context that can appear between backticks in an error message.
1599     ///
1600     /// E.g. `const` or `static mut`.
1601     pub fn keyword_name(self) -> &'static str {
1602         match self {
1603             Self::Const => "const",
1604             Self::Static(Mutability::Not) => "static",
1605             Self::Static(Mutability::Mut) => "static mut",
1606             Self::ConstFn => "const fn",
1607         }
1608     }
1609 }
1610
1611 /// A colloquial, trivially pluralizable description of this const context for use in error
1612 /// messages.
1613 impl fmt::Display for ConstContext {
1614     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1615         match *self {
1616             Self::Const => write!(f, "constant"),
1617             Self::Static(_) => write!(f, "static"),
1618             Self::ConstFn => write!(f, "constant function"),
1619         }
1620     }
1621 }
1622
1623 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1624 // due to a cyclical dependency between hir that crate.
1625
1626 /// A literal.
1627 pub type Lit = Spanned<LitKind>;
1628
1629 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1630 pub enum ArrayLen {
1631     Infer(HirId, Span),
1632     Body(AnonConst),
1633 }
1634
1635 impl ArrayLen {
1636     pub fn hir_id(&self) -> HirId {
1637         match self {
1638             &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, .. }) => hir_id,
1639         }
1640     }
1641 }
1642
1643 /// A constant (expression) that's not an item or associated item,
1644 /// but needs its own `DefId` for type-checking, const-eval, etc.
1645 /// These are usually found nested inside types (e.g., array lengths)
1646 /// or expressions (e.g., repeat counts), and also used to define
1647 /// explicit discriminant values for enum variants.
1648 ///
1649 /// You can check if this anon const is a default in a const param
1650 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)`
1651 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1652 pub struct AnonConst {
1653     pub hir_id: HirId,
1654     pub def_id: LocalDefId,
1655     pub body: BodyId,
1656 }
1657
1658 /// An expression.
1659 #[derive(Debug, HashStable_Generic)]
1660 pub struct Expr<'hir> {
1661     pub hir_id: HirId,
1662     pub kind: ExprKind<'hir>,
1663     pub span: Span,
1664 }
1665
1666 impl Expr<'_> {
1667     pub fn precedence(&self) -> ExprPrecedence {
1668         match self.kind {
1669             ExprKind::Box(_) => ExprPrecedence::Box,
1670             ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1671             ExprKind::Array(_) => ExprPrecedence::Array,
1672             ExprKind::Call(..) => ExprPrecedence::Call,
1673             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1674             ExprKind::Tup(_) => ExprPrecedence::Tup,
1675             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1676             ExprKind::Unary(..) => ExprPrecedence::Unary,
1677             ExprKind::Lit(_) => ExprPrecedence::Lit,
1678             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1679             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1680             ExprKind::If(..) => ExprPrecedence::If,
1681             ExprKind::Let(..) => ExprPrecedence::Let,
1682             ExprKind::Loop(..) => ExprPrecedence::Loop,
1683             ExprKind::Match(..) => ExprPrecedence::Match,
1684             ExprKind::Closure { .. } => ExprPrecedence::Closure,
1685             ExprKind::Block(..) => ExprPrecedence::Block,
1686             ExprKind::Assign(..) => ExprPrecedence::Assign,
1687             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1688             ExprKind::Field(..) => ExprPrecedence::Field,
1689             ExprKind::Index(..) => ExprPrecedence::Index,
1690             ExprKind::Path(..) => ExprPrecedence::Path,
1691             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1692             ExprKind::Break(..) => ExprPrecedence::Break,
1693             ExprKind::Continue(..) => ExprPrecedence::Continue,
1694             ExprKind::Ret(..) => ExprPrecedence::Ret,
1695             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1696             ExprKind::Struct(..) => ExprPrecedence::Struct,
1697             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1698             ExprKind::Yield(..) => ExprPrecedence::Yield,
1699             ExprKind::Err => ExprPrecedence::Err,
1700         }
1701     }
1702
1703     /// Whether this looks like a place expr, without checking for deref
1704     /// adjustments.
1705     /// This will return `true` in some potentially surprising cases such as
1706     /// `CONSTANT.field`.
1707     pub fn is_syntactic_place_expr(&self) -> bool {
1708         self.is_place_expr(|_| true)
1709     }
1710
1711     /// Whether this is a place expression.
1712     ///
1713     /// `allow_projections_from` should return `true` if indexing a field or index expression based
1714     /// on the given expression should be considered a place expression.
1715     pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1716         match self.kind {
1717             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1718                 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1719             }
1720
1721             // Type ascription inherits its place expression kind from its
1722             // operand. See:
1723             // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1724             ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1725
1726             ExprKind::Unary(UnOp::Deref, _) => true,
1727
1728             ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1729                 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1730             }
1731
1732             // Lang item paths cannot currently be local variables or statics.
1733             ExprKind::Path(QPath::LangItem(..)) => false,
1734
1735             // Partially qualified paths in expressions can only legally
1736             // refer to associated items which are always rvalues.
1737             ExprKind::Path(QPath::TypeRelative(..))
1738             | ExprKind::Call(..)
1739             | ExprKind::MethodCall(..)
1740             | ExprKind::Struct(..)
1741             | ExprKind::Tup(..)
1742             | ExprKind::If(..)
1743             | ExprKind::Match(..)
1744             | ExprKind::Closure { .. }
1745             | ExprKind::Block(..)
1746             | ExprKind::Repeat(..)
1747             | ExprKind::Array(..)
1748             | ExprKind::Break(..)
1749             | ExprKind::Continue(..)
1750             | ExprKind::Ret(..)
1751             | ExprKind::Let(..)
1752             | ExprKind::Loop(..)
1753             | ExprKind::Assign(..)
1754             | ExprKind::InlineAsm(..)
1755             | ExprKind::AssignOp(..)
1756             | ExprKind::Lit(_)
1757             | ExprKind::ConstBlock(..)
1758             | ExprKind::Unary(..)
1759             | ExprKind::Box(..)
1760             | ExprKind::AddrOf(..)
1761             | ExprKind::Binary(..)
1762             | ExprKind::Yield(..)
1763             | ExprKind::Cast(..)
1764             | ExprKind::DropTemps(..)
1765             | ExprKind::Err => false,
1766         }
1767     }
1768
1769     /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1770     /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1771     /// silent, only signaling the ownership system. By doing this, suggestions that check the
1772     /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1773     /// beyond remembering to call this function before doing analysis on it.
1774     pub fn peel_drop_temps(&self) -> &Self {
1775         let mut expr = self;
1776         while let ExprKind::DropTemps(inner) = &expr.kind {
1777             expr = inner;
1778         }
1779         expr
1780     }
1781
1782     pub fn peel_blocks(&self) -> &Self {
1783         let mut expr = self;
1784         while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1785             expr = inner;
1786         }
1787         expr
1788     }
1789
1790     pub fn peel_borrows(&self) -> &Self {
1791         let mut expr = self;
1792         while let ExprKind::AddrOf(.., inner) = &expr.kind {
1793             expr = inner;
1794         }
1795         expr
1796     }
1797
1798     pub fn can_have_side_effects(&self) -> bool {
1799         match self.peel_drop_temps().kind {
1800             ExprKind::Path(_) | ExprKind::Lit(_) => false,
1801             ExprKind::Type(base, _)
1802             | ExprKind::Unary(_, base)
1803             | ExprKind::Field(base, _)
1804             | ExprKind::Index(base, _)
1805             | ExprKind::AddrOf(.., base)
1806             | ExprKind::Cast(base, _) => {
1807                 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1808                 // method exclusively for diagnostics and there's a *cultural* pressure against
1809                 // them being used only for its side-effects.
1810                 base.can_have_side_effects()
1811             }
1812             ExprKind::Struct(_, fields, init) => fields
1813                 .iter()
1814                 .map(|field| field.expr)
1815                 .chain(init.into_iter())
1816                 .all(|e| e.can_have_side_effects()),
1817
1818             ExprKind::Array(args)
1819             | ExprKind::Tup(args)
1820             | ExprKind::Call(
1821                 Expr {
1822                     kind:
1823                         ExprKind::Path(QPath::Resolved(
1824                             None,
1825                             Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1826                         )),
1827                     ..
1828                 },
1829                 args,
1830             ) => args.iter().all(|arg| arg.can_have_side_effects()),
1831             ExprKind::If(..)
1832             | ExprKind::Match(..)
1833             | ExprKind::MethodCall(..)
1834             | ExprKind::Call(..)
1835             | ExprKind::Closure { .. }
1836             | ExprKind::Block(..)
1837             | ExprKind::Repeat(..)
1838             | ExprKind::Break(..)
1839             | ExprKind::Continue(..)
1840             | ExprKind::Ret(..)
1841             | ExprKind::Let(..)
1842             | ExprKind::Loop(..)
1843             | ExprKind::Assign(..)
1844             | ExprKind::InlineAsm(..)
1845             | ExprKind::AssignOp(..)
1846             | ExprKind::ConstBlock(..)
1847             | ExprKind::Box(..)
1848             | ExprKind::Binary(..)
1849             | ExprKind::Yield(..)
1850             | ExprKind::DropTemps(..)
1851             | ExprKind::Err => true,
1852         }
1853     }
1854
1855     /// To a first-order approximation, is this a pattern?
1856     pub fn is_approximately_pattern(&self) -> bool {
1857         match &self.kind {
1858             ExprKind::Box(_)
1859             | ExprKind::Array(_)
1860             | ExprKind::Call(..)
1861             | ExprKind::Tup(_)
1862             | ExprKind::Lit(_)
1863             | ExprKind::Path(_)
1864             | ExprKind::Struct(..) => true,
1865             _ => false,
1866         }
1867     }
1868
1869     pub fn method_ident(&self) -> Option<Ident> {
1870         match self.kind {
1871             ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1872             ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1873             _ => None,
1874         }
1875     }
1876 }
1877
1878 /// Checks if the specified expression is a built-in range literal.
1879 /// (See: `LoweringContext::lower_expr()`).
1880 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1881     match expr.kind {
1882         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1883         ExprKind::Struct(ref qpath, _, _) => matches!(
1884             **qpath,
1885             QPath::LangItem(
1886                 LangItem::Range
1887                     | LangItem::RangeTo
1888                     | LangItem::RangeFrom
1889                     | LangItem::RangeFull
1890                     | LangItem::RangeToInclusive,
1891                 ..
1892             )
1893         ),
1894
1895         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1896         ExprKind::Call(ref func, _) => {
1897             matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1898         }
1899
1900         _ => false,
1901     }
1902 }
1903
1904 #[derive(Debug, HashStable_Generic)]
1905 pub enum ExprKind<'hir> {
1906     /// A `box x` expression.
1907     Box(&'hir Expr<'hir>),
1908     /// Allow anonymous constants from an inline `const` block
1909     ConstBlock(AnonConst),
1910     /// An array (e.g., `[a, b, c, d]`).
1911     Array(&'hir [Expr<'hir>]),
1912     /// A function call.
1913     ///
1914     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1915     /// and the second field is the list of arguments.
1916     /// This also represents calling the constructor of
1917     /// tuple-like ADTs such as tuple structs and enum variants.
1918     Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1919     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1920     ///
1921     /// The `PathSegment` represents the method name and its generic arguments
1922     /// (within the angle brackets).
1923     /// The `&Expr` is the expression that evaluates
1924     /// to the object on which the method is being called on (the receiver),
1925     /// and the `&[Expr]` is the rest of the arguments.
1926     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1927     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1928     /// The final `Span` represents the span of the function and arguments
1929     /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1930     ///
1931     /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1932     /// the `hir_id` of the `MethodCall` node itself.
1933     ///
1934     /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1935     MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1936     /// A tuple (e.g., `(a, b, c, d)`).
1937     Tup(&'hir [Expr<'hir>]),
1938     /// A binary operation (e.g., `a + b`, `a * b`).
1939     Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1940     /// A unary operation (e.g., `!x`, `*x`).
1941     Unary(UnOp, &'hir Expr<'hir>),
1942     /// A literal (e.g., `1`, `"foo"`).
1943     Lit(Lit),
1944     /// A cast (e.g., `foo as f64`).
1945     Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1946     /// A type reference (e.g., `Foo`).
1947     Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1948     /// Wraps the expression in a terminating scope.
1949     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1950     ///
1951     /// This construct only exists to tweak the drop order in HIR lowering.
1952     /// An example of that is the desugaring of `for` loops.
1953     DropTemps(&'hir Expr<'hir>),
1954     /// A `let $pat = $expr` expression.
1955     ///
1956     /// These are not `Local` and only occur as expressions.
1957     /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1958     Let(&'hir Let<'hir>),
1959     /// An `if` block, with an optional else block.
1960     ///
1961     /// I.e., `if <expr> { <expr> } else { <expr> }`.
1962     If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1963     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1964     ///
1965     /// I.e., `'label: loop { <block> }`.
1966     ///
1967     /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1968     Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1969     /// A `match` block, with a source that indicates whether or not it is
1970     /// the result of a desugaring, and if so, which kind.
1971     Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1972     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1973     ///
1974     /// The `Span` is the argument block `|...|`.
1975     ///
1976     /// This may also be a generator literal or an `async block` as indicated by the
1977     /// `Option<Movability>`.
1978     Closure(&'hir Closure<'hir>),
1979     /// A block (e.g., `'label: { ... }`).
1980     Block(&'hir Block<'hir>, Option<Label>),
1981
1982     /// An assignment (e.g., `a = foo()`).
1983     Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1984     /// An assignment with an operator.
1985     ///
1986     /// E.g., `a += 1`.
1987     AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1988     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1989     Field(&'hir Expr<'hir>, Ident),
1990     /// An indexing operation (`foo[2]`).
1991     Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1992
1993     /// Path to a definition, possibly containing lifetime or type parameters.
1994     Path(QPath<'hir>),
1995
1996     /// A referencing operation (i.e., `&a` or `&mut a`).
1997     AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1998     /// A `break`, with an optional label to break.
1999     Break(Destination, Option<&'hir Expr<'hir>>),
2000     /// A `continue`, with an optional label.
2001     Continue(Destination),
2002     /// A `return`, with an optional value to be returned.
2003     Ret(Option<&'hir Expr<'hir>>),
2004
2005     /// Inline assembly (from `asm!`), with its outputs and inputs.
2006     InlineAsm(&'hir InlineAsm<'hir>),
2007
2008     /// A struct or struct-like variant literal expression.
2009     ///
2010     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2011     /// where `base` is the `Option<Expr>`.
2012     Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
2013
2014     /// An array literal constructed from one repeated element.
2015     ///
2016     /// E.g., `[1; 5]`. The first expression is the element
2017     /// to be repeated; the second is the number of times to repeat it.
2018     Repeat(&'hir Expr<'hir>, ArrayLen),
2019
2020     /// A suspension point for generators (i.e., `yield <expr>`).
2021     Yield(&'hir Expr<'hir>, YieldSource),
2022
2023     /// A placeholder for an expression that wasn't syntactically well formed in some way.
2024     Err,
2025 }
2026
2027 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2028 ///
2029 /// To resolve the path to a `DefId`, call [`qpath_res`].
2030 ///
2031 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2032 #[derive(Debug, HashStable_Generic)]
2033 pub enum QPath<'hir> {
2034     /// Path to a definition, optionally "fully-qualified" with a `Self`
2035     /// type, if the path points to an associated item in a trait.
2036     ///
2037     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2038     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2039     /// even though they both have the same two-segment `Clone::clone` `Path`.
2040     Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2041
2042     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2043     /// Will be resolved by type-checking to an associated item.
2044     ///
2045     /// UFCS source paths can desugar into this, with `Vec::new` turning into
2046     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2047     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2048     TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2049
2050     /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2051     LangItem(LangItem, Span, Option<HirId>),
2052 }
2053
2054 impl<'hir> QPath<'hir> {
2055     /// Returns the span of this `QPath`.
2056     pub fn span(&self) -> Span {
2057         match *self {
2058             QPath::Resolved(_, path) => path.span,
2059             QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2060             QPath::LangItem(_, span, _) => span,
2061         }
2062     }
2063
2064     /// Returns the span of the qself of this `QPath`. For example, `()` in
2065     /// `<() as Trait>::method`.
2066     pub fn qself_span(&self) -> Span {
2067         match *self {
2068             QPath::Resolved(_, path) => path.span,
2069             QPath::TypeRelative(qself, _) => qself.span,
2070             QPath::LangItem(_, span, _) => span,
2071         }
2072     }
2073
2074     /// Returns the span of the last segment of this `QPath`. For example, `method` in
2075     /// `<() as Trait>::method`.
2076     pub fn last_segment_span(&self) -> Span {
2077         match *self {
2078             QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2079             QPath::TypeRelative(_, segment) => segment.ident.span,
2080             QPath::LangItem(_, span, _) => span,
2081         }
2082     }
2083 }
2084
2085 /// Hints at the original code for a let statement.
2086 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2087 pub enum LocalSource {
2088     /// A `match _ { .. }`.
2089     Normal,
2090     /// When lowering async functions, we create locals within the `async move` so that
2091     /// all parameters are dropped after the future is polled.
2092     ///
2093     /// ```ignore (pseudo-Rust)
2094     /// async fn foo(<pattern> @ x: Type) {
2095     ///     async move {
2096     ///         let <pattern> = x;
2097     ///     }
2098     /// }
2099     /// ```
2100     AsyncFn,
2101     /// A desugared `<expr>.await`.
2102     AwaitDesugar,
2103     /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2104     /// The span is that of the `=` sign.
2105     AssignDesugar(Span),
2106 }
2107
2108 /// Hints at the original code for a `match _ { .. }`.
2109 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
2110 #[derive(HashStable_Generic, Encodable, Decodable)]
2111 pub enum MatchSource {
2112     /// A `match _ { .. }`.
2113     Normal,
2114     /// A desugared `for _ in _ { .. }` loop.
2115     ForLoopDesugar,
2116     /// A desugared `?` operator.
2117     TryDesugar,
2118     /// A desugared `<expr>.await`.
2119     AwaitDesugar,
2120     /// A desugared `format_args!()`.
2121     FormatArgs,
2122 }
2123
2124 impl MatchSource {
2125     #[inline]
2126     pub const fn name(self) -> &'static str {
2127         use MatchSource::*;
2128         match self {
2129             Normal => "match",
2130             ForLoopDesugar => "for",
2131             TryDesugar => "?",
2132             AwaitDesugar => ".await",
2133             FormatArgs => "format_args!()",
2134         }
2135     }
2136 }
2137
2138 /// The loop type that yielded an `ExprKind::Loop`.
2139 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2140 pub enum LoopSource {
2141     /// A `loop { .. }` loop.
2142     Loop,
2143     /// A `while _ { .. }` loop.
2144     While,
2145     /// A `for _ in _ { .. }` loop.
2146     ForLoop,
2147 }
2148
2149 impl LoopSource {
2150     pub fn name(self) -> &'static str {
2151         match self {
2152             LoopSource::Loop => "loop",
2153             LoopSource::While => "while",
2154             LoopSource::ForLoop => "for",
2155         }
2156     }
2157 }
2158
2159 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2160 pub enum LoopIdError {
2161     OutsideLoopScope,
2162     UnlabeledCfInWhileCondition,
2163     UnresolvedLabel,
2164 }
2165
2166 impl fmt::Display for LoopIdError {
2167     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2168         f.write_str(match self {
2169             LoopIdError::OutsideLoopScope => "not inside loop scope",
2170             LoopIdError::UnlabeledCfInWhileCondition => {
2171                 "unlabeled control flow (break or continue) in while condition"
2172             }
2173             LoopIdError::UnresolvedLabel => "label not found",
2174         })
2175     }
2176 }
2177
2178 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2179 pub struct Destination {
2180     /// This is `Some(_)` iff there is an explicit user-specified 'label
2181     pub label: Option<Label>,
2182
2183     /// These errors are caught and then reported during the diagnostics pass in
2184     /// `librustc_passes/loops.rs`
2185     pub target_id: Result<HirId, LoopIdError>,
2186 }
2187
2188 /// The yield kind that caused an `ExprKind::Yield`.
2189 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2190 pub enum YieldSource {
2191     /// An `<expr>.await`.
2192     Await { expr: Option<HirId> },
2193     /// A plain `yield`.
2194     Yield,
2195 }
2196
2197 impl YieldSource {
2198     pub fn is_await(&self) -> bool {
2199         matches!(self, YieldSource::Await { .. })
2200     }
2201 }
2202
2203 impl fmt::Display for YieldSource {
2204     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2205         f.write_str(match self {
2206             YieldSource::Await { .. } => "`await`",
2207             YieldSource::Yield => "`yield`",
2208         })
2209     }
2210 }
2211
2212 impl From<GeneratorKind> for YieldSource {
2213     fn from(kind: GeneratorKind) -> Self {
2214         match kind {
2215             // Guess based on the kind of the current generator.
2216             GeneratorKind::Gen => Self::Yield,
2217             GeneratorKind::Async(_) => Self::Await { expr: None },
2218         }
2219     }
2220 }
2221
2222 // N.B., if you change this, you'll probably want to change the corresponding
2223 // type structure in middle/ty.rs as well.
2224 #[derive(Debug, HashStable_Generic)]
2225 pub struct MutTy<'hir> {
2226     pub ty: &'hir Ty<'hir>,
2227     pub mutbl: Mutability,
2228 }
2229
2230 /// Represents a function's signature in a trait declaration,
2231 /// trait implementation, or a free function.
2232 #[derive(Debug, HashStable_Generic)]
2233 pub struct FnSig<'hir> {
2234     pub header: FnHeader,
2235     pub decl: &'hir FnDecl<'hir>,
2236     pub span: Span,
2237 }
2238
2239 // The bodies for items are stored "out of line", in a separate
2240 // hashmap in the `Crate`. Here we just record the hir-id of the item
2241 // so it can fetched later.
2242 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2243 pub struct TraitItemId {
2244     pub owner_id: OwnerId,
2245 }
2246
2247 impl TraitItemId {
2248     #[inline]
2249     pub fn hir_id(&self) -> HirId {
2250         // Items are always HIR owners.
2251         HirId::make_owner(self.owner_id.def_id)
2252     }
2253 }
2254
2255 /// Represents an item declaration within a trait declaration,
2256 /// possibly including a default implementation. A trait item is
2257 /// either required (meaning it doesn't have an implementation, just a
2258 /// signature) or provided (meaning it has a default implementation).
2259 #[derive(Debug, HashStable_Generic)]
2260 pub struct TraitItem<'hir> {
2261     pub ident: Ident,
2262     pub owner_id: OwnerId,
2263     pub generics: &'hir Generics<'hir>,
2264     pub kind: TraitItemKind<'hir>,
2265     pub span: Span,
2266     pub defaultness: Defaultness,
2267 }
2268
2269 impl TraitItem<'_> {
2270     #[inline]
2271     pub fn hir_id(&self) -> HirId {
2272         // Items are always HIR owners.
2273         HirId::make_owner(self.owner_id.def_id)
2274     }
2275
2276     pub fn trait_item_id(&self) -> TraitItemId {
2277         TraitItemId { owner_id: self.owner_id }
2278     }
2279 }
2280
2281 /// Represents a trait method's body (or just argument names).
2282 #[derive(Encodable, Debug, HashStable_Generic)]
2283 pub enum TraitFn<'hir> {
2284     /// No default body in the trait, just a signature.
2285     Required(&'hir [Ident]),
2286
2287     /// Both signature and body are provided in the trait.
2288     Provided(BodyId),
2289 }
2290
2291 /// Represents a trait method or associated constant or type
2292 #[derive(Debug, HashStable_Generic)]
2293 pub enum TraitItemKind<'hir> {
2294     /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2295     Const(&'hir Ty<'hir>, Option<BodyId>),
2296     /// An associated function with an optional body.
2297     Fn(FnSig<'hir>, TraitFn<'hir>),
2298     /// An associated type with (possibly empty) bounds and optional concrete
2299     /// type.
2300     Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2301 }
2302
2303 // The bodies for items are stored "out of line", in a separate
2304 // hashmap in the `Crate`. Here we just record the hir-id of the item
2305 // so it can fetched later.
2306 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2307 pub struct ImplItemId {
2308     pub owner_id: OwnerId,
2309 }
2310
2311 impl ImplItemId {
2312     #[inline]
2313     pub fn hir_id(&self) -> HirId {
2314         // Items are always HIR owners.
2315         HirId::make_owner(self.owner_id.def_id)
2316     }
2317 }
2318
2319 /// Represents anything within an `impl` block.
2320 #[derive(Debug, HashStable_Generic)]
2321 pub struct ImplItem<'hir> {
2322     pub ident: Ident,
2323     pub owner_id: OwnerId,
2324     pub generics: &'hir Generics<'hir>,
2325     pub kind: ImplItemKind<'hir>,
2326     pub defaultness: Defaultness,
2327     pub span: Span,
2328     pub vis_span: Span,
2329 }
2330
2331 impl ImplItem<'_> {
2332     #[inline]
2333     pub fn hir_id(&self) -> HirId {
2334         // Items are always HIR owners.
2335         HirId::make_owner(self.owner_id.def_id)
2336     }
2337
2338     pub fn impl_item_id(&self) -> ImplItemId {
2339         ImplItemId { owner_id: self.owner_id }
2340     }
2341 }
2342
2343 /// Represents various kinds of content within an `impl`.
2344 #[derive(Debug, HashStable_Generic)]
2345 pub enum ImplItemKind<'hir> {
2346     /// An associated constant of the given type, set to the constant result
2347     /// of the expression.
2348     Const(&'hir Ty<'hir>, BodyId),
2349     /// An associated function implementation with the given signature and body.
2350     Fn(FnSig<'hir>, BodyId),
2351     /// An associated type.
2352     Type(&'hir Ty<'hir>),
2353 }
2354
2355 /// The name of the associated type for `Fn` return types.
2356 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2357
2358 /// Bind a type to an associated type (i.e., `A = Foo`).
2359 ///
2360 /// Bindings like `A: Debug` are represented as a special type `A =
2361 /// $::Debug` that is understood by the astconv code.
2362 ///
2363 /// FIXME(alexreg): why have a separate type for the binding case,
2364 /// wouldn't it be better to make the `ty` field an enum like the
2365 /// following?
2366 ///
2367 /// ```ignore (pseudo-rust)
2368 /// enum TypeBindingKind {
2369 ///    Equals(...),
2370 ///    Binding(...),
2371 /// }
2372 /// ```
2373 #[derive(Debug, HashStable_Generic)]
2374 pub struct TypeBinding<'hir> {
2375     pub hir_id: HirId,
2376     pub ident: Ident,
2377     pub gen_args: &'hir GenericArgs<'hir>,
2378     pub kind: TypeBindingKind<'hir>,
2379     pub span: Span,
2380 }
2381
2382 #[derive(Debug, HashStable_Generic)]
2383 pub enum Term<'hir> {
2384     Ty(&'hir Ty<'hir>),
2385     Const(AnonConst),
2386 }
2387
2388 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2389     fn from(ty: &'hir Ty<'hir>) -> Self {
2390         Term::Ty(ty)
2391     }
2392 }
2393
2394 impl<'hir> From<AnonConst> for Term<'hir> {
2395     fn from(c: AnonConst) -> Self {
2396         Term::Const(c)
2397     }
2398 }
2399
2400 // Represents the two kinds of type bindings.
2401 #[derive(Debug, HashStable_Generic)]
2402 pub enum TypeBindingKind<'hir> {
2403     /// E.g., `Foo<Bar: Send>`.
2404     Constraint { bounds: &'hir [GenericBound<'hir>] },
2405     /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2406     Equality { term: Term<'hir> },
2407 }
2408
2409 impl TypeBinding<'_> {
2410     pub fn ty(&self) -> &Ty<'_> {
2411         match self.kind {
2412             TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2413             _ => panic!("expected equality type binding for parenthesized generic args"),
2414         }
2415     }
2416     pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2417         match self.kind {
2418             TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2419             _ => None,
2420         }
2421     }
2422 }
2423
2424 #[derive(Debug, HashStable_Generic)]
2425 pub struct Ty<'hir> {
2426     pub hir_id: HirId,
2427     pub kind: TyKind<'hir>,
2428     pub span: Span,
2429 }
2430
2431 impl<'hir> Ty<'hir> {
2432     /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2433     pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2434         let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2435             return None;
2436         };
2437         let [segment] = &path.segments else {
2438             return None;
2439         };
2440         match path.res {
2441             Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2442                 Some((def_id, segment.ident))
2443             }
2444             _ => None,
2445         }
2446     }
2447
2448     pub fn peel_refs(&self) -> &Self {
2449         let mut final_ty = self;
2450         while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
2451             final_ty = ty;
2452         }
2453         final_ty
2454     }
2455
2456     pub fn find_self_aliases(&self) -> Vec<Span> {
2457         use crate::intravisit::Visitor;
2458         struct MyVisitor(Vec<Span>);
2459         impl<'v> Visitor<'v> for MyVisitor {
2460             fn visit_ty(&mut self, t: &'v Ty<'v>) {
2461                 if matches!(
2462                     &t.kind,
2463                     TyKind::Path(QPath::Resolved(
2464                         _,
2465                         Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2466                     ))
2467                 ) {
2468                     self.0.push(t.span);
2469                     return;
2470                 }
2471                 crate::intravisit::walk_ty(self, t);
2472             }
2473         }
2474
2475         let mut my_visitor = MyVisitor(vec![]);
2476         my_visitor.visit_ty(self);
2477         my_visitor.0
2478     }
2479 }
2480
2481 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2482 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2483 #[derive(HashStable_Generic)]
2484 pub enum PrimTy {
2485     Int(IntTy),
2486     Uint(UintTy),
2487     Float(FloatTy),
2488     Str,
2489     Bool,
2490     Char,
2491 }
2492
2493 impl PrimTy {
2494     /// All of the primitive types
2495     pub const ALL: [Self; 17] = [
2496         // any changes here should also be reflected in `PrimTy::from_name`
2497         Self::Int(IntTy::I8),
2498         Self::Int(IntTy::I16),
2499         Self::Int(IntTy::I32),
2500         Self::Int(IntTy::I64),
2501         Self::Int(IntTy::I128),
2502         Self::Int(IntTy::Isize),
2503         Self::Uint(UintTy::U8),
2504         Self::Uint(UintTy::U16),
2505         Self::Uint(UintTy::U32),
2506         Self::Uint(UintTy::U64),
2507         Self::Uint(UintTy::U128),
2508         Self::Uint(UintTy::Usize),
2509         Self::Float(FloatTy::F32),
2510         Self::Float(FloatTy::F64),
2511         Self::Bool,
2512         Self::Char,
2513         Self::Str,
2514     ];
2515
2516     /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2517     ///
2518     /// Used by clippy.
2519     pub fn name_str(self) -> &'static str {
2520         match self {
2521             PrimTy::Int(i) => i.name_str(),
2522             PrimTy::Uint(u) => u.name_str(),
2523             PrimTy::Float(f) => f.name_str(),
2524             PrimTy::Str => "str",
2525             PrimTy::Bool => "bool",
2526             PrimTy::Char => "char",
2527         }
2528     }
2529
2530     pub fn name(self) -> Symbol {
2531         match self {
2532             PrimTy::Int(i) => i.name(),
2533             PrimTy::Uint(u) => u.name(),
2534             PrimTy::Float(f) => f.name(),
2535             PrimTy::Str => sym::str,
2536             PrimTy::Bool => sym::bool,
2537             PrimTy::Char => sym::char,
2538         }
2539     }
2540
2541     /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2542     /// Returns `None` if no matching type is found.
2543     pub fn from_name(name: Symbol) -> Option<Self> {
2544         let ty = match name {
2545             // any changes here should also be reflected in `PrimTy::ALL`
2546             sym::i8 => Self::Int(IntTy::I8),
2547             sym::i16 => Self::Int(IntTy::I16),
2548             sym::i32 => Self::Int(IntTy::I32),
2549             sym::i64 => Self::Int(IntTy::I64),
2550             sym::i128 => Self::Int(IntTy::I128),
2551             sym::isize => Self::Int(IntTy::Isize),
2552             sym::u8 => Self::Uint(UintTy::U8),
2553             sym::u16 => Self::Uint(UintTy::U16),
2554             sym::u32 => Self::Uint(UintTy::U32),
2555             sym::u64 => Self::Uint(UintTy::U64),
2556             sym::u128 => Self::Uint(UintTy::U128),
2557             sym::usize => Self::Uint(UintTy::Usize),
2558             sym::f32 => Self::Float(FloatTy::F32),
2559             sym::f64 => Self::Float(FloatTy::F64),
2560             sym::bool => Self::Bool,
2561             sym::char => Self::Char,
2562             sym::str => Self::Str,
2563             _ => return None,
2564         };
2565         Some(ty)
2566     }
2567 }
2568
2569 #[derive(Debug, HashStable_Generic)]
2570 pub struct BareFnTy<'hir> {
2571     pub unsafety: Unsafety,
2572     pub abi: Abi,
2573     pub generic_params: &'hir [GenericParam<'hir>],
2574     pub decl: &'hir FnDecl<'hir>,
2575     pub param_names: &'hir [Ident],
2576 }
2577
2578 #[derive(Debug, HashStable_Generic)]
2579 pub struct OpaqueTy<'hir> {
2580     pub generics: &'hir Generics<'hir>,
2581     pub bounds: GenericBounds<'hir>,
2582     pub origin: OpaqueTyOrigin,
2583     pub in_trait: bool,
2584 }
2585
2586 /// From whence the opaque type came.
2587 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2588 pub enum OpaqueTyOrigin {
2589     /// `-> impl Trait`
2590     FnReturn(LocalDefId),
2591     /// `async fn`
2592     AsyncFn(LocalDefId),
2593     /// type aliases: `type Foo = impl Trait;`
2594     TyAlias,
2595 }
2596
2597 /// The various kinds of types recognized by the compiler.
2598 #[derive(Debug, HashStable_Generic)]
2599 pub enum TyKind<'hir> {
2600     /// A variable length slice (i.e., `[T]`).
2601     Slice(&'hir Ty<'hir>),
2602     /// A fixed length array (i.e., `[T; n]`).
2603     Array(&'hir Ty<'hir>, ArrayLen),
2604     /// A raw pointer (i.e., `*const T` or `*mut T`).
2605     Ptr(MutTy<'hir>),
2606     /// A reference (i.e., `&'a T` or `&'a mut T`).
2607     Ref(&'hir Lifetime, MutTy<'hir>),
2608     /// A bare function (e.g., `fn(usize) -> bool`).
2609     BareFn(&'hir BareFnTy<'hir>),
2610     /// The never type (`!`).
2611     Never,
2612     /// A tuple (`(A, B, C, D, ...)`).
2613     Tup(&'hir [Ty<'hir>]),
2614     /// A path to a type definition (`module::module::...::Type`), or an
2615     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2616     ///
2617     /// Type parameters may be stored in each `PathSegment`.
2618     Path(QPath<'hir>),
2619     /// An opaque type definition itself. This is only used for `impl Trait`.
2620     ///
2621     /// The generic argument list contains the lifetimes (and in the future
2622     /// possibly parameters) that are actually bound on the `impl Trait`.
2623     ///
2624     /// The last parameter specifies whether this opaque appears in a trait definition.
2625     OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2626     /// A trait object type `Bound1 + Bound2 + Bound3`
2627     /// where `Bound` is a trait or a lifetime.
2628     TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2629     /// Unused for now.
2630     Typeof(AnonConst),
2631     /// `TyKind::Infer` means the type should be inferred instead of it having been
2632     /// specified. This can appear anywhere in a type.
2633     Infer,
2634     /// Placeholder for a type that has failed to be defined.
2635     Err,
2636 }
2637
2638 #[derive(Debug, HashStable_Generic)]
2639 pub enum InlineAsmOperand<'hir> {
2640     In {
2641         reg: InlineAsmRegOrRegClass,
2642         expr: &'hir Expr<'hir>,
2643     },
2644     Out {
2645         reg: InlineAsmRegOrRegClass,
2646         late: bool,
2647         expr: Option<&'hir Expr<'hir>>,
2648     },
2649     InOut {
2650         reg: InlineAsmRegOrRegClass,
2651         late: bool,
2652         expr: &'hir Expr<'hir>,
2653     },
2654     SplitInOut {
2655         reg: InlineAsmRegOrRegClass,
2656         late: bool,
2657         in_expr: &'hir Expr<'hir>,
2658         out_expr: Option<&'hir Expr<'hir>>,
2659     },
2660     Const {
2661         anon_const: AnonConst,
2662     },
2663     SymFn {
2664         anon_const: AnonConst,
2665     },
2666     SymStatic {
2667         path: QPath<'hir>,
2668         def_id: DefId,
2669     },
2670 }
2671
2672 impl<'hir> InlineAsmOperand<'hir> {
2673     pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2674         match *self {
2675             Self::In { reg, .. }
2676             | Self::Out { reg, .. }
2677             | Self::InOut { reg, .. }
2678             | Self::SplitInOut { reg, .. } => Some(reg),
2679             Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2680         }
2681     }
2682
2683     pub fn is_clobber(&self) -> bool {
2684         matches!(
2685             self,
2686             InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2687         )
2688     }
2689 }
2690
2691 #[derive(Debug, HashStable_Generic)]
2692 pub struct InlineAsm<'hir> {
2693     pub template: &'hir [InlineAsmTemplatePiece],
2694     pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2695     pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2696     pub options: InlineAsmOptions,
2697     pub line_spans: &'hir [Span],
2698 }
2699
2700 /// Represents a parameter in a function header.
2701 #[derive(Debug, HashStable_Generic)]
2702 pub struct Param<'hir> {
2703     pub hir_id: HirId,
2704     pub pat: &'hir Pat<'hir>,
2705     pub ty_span: Span,
2706     pub span: Span,
2707 }
2708
2709 /// Represents the header (not the body) of a function declaration.
2710 #[derive(Debug, HashStable_Generic)]
2711 pub struct FnDecl<'hir> {
2712     /// The types of the function's parameters.
2713     ///
2714     /// Additional argument data is stored in the function's [body](Body::params).
2715     pub inputs: &'hir [Ty<'hir>],
2716     pub output: FnRetTy<'hir>,
2717     pub c_variadic: bool,
2718     /// Does the function have an implicit self?
2719     pub implicit_self: ImplicitSelfKind,
2720     /// Is lifetime elision allowed.
2721     pub lifetime_elision_allowed: bool,
2722 }
2723
2724 /// Represents what type of implicit self a function has, if any.
2725 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2726 pub enum ImplicitSelfKind {
2727     /// Represents a `fn x(self);`.
2728     Imm,
2729     /// Represents a `fn x(mut self);`.
2730     Mut,
2731     /// Represents a `fn x(&self);`.
2732     ImmRef,
2733     /// Represents a `fn x(&mut self);`.
2734     MutRef,
2735     /// Represents when a function does not have a self argument or
2736     /// when a function has a `self: X` argument.
2737     None,
2738 }
2739
2740 impl ImplicitSelfKind {
2741     /// Does this represent an implicit self?
2742     pub fn has_implicit_self(&self) -> bool {
2743         !matches!(*self, ImplicitSelfKind::None)
2744     }
2745 }
2746
2747 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2748 #[derive(HashStable_Generic)]
2749 pub enum IsAsync {
2750     Async,
2751     NotAsync,
2752 }
2753
2754 impl IsAsync {
2755     pub fn is_async(self) -> bool {
2756         self == IsAsync::Async
2757     }
2758 }
2759
2760 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2761 pub enum Defaultness {
2762     Default { has_value: bool },
2763     Final,
2764 }
2765
2766 impl Defaultness {
2767     pub fn has_value(&self) -> bool {
2768         match *self {
2769             Defaultness::Default { has_value } => has_value,
2770             Defaultness::Final => true,
2771         }
2772     }
2773
2774     pub fn is_final(&self) -> bool {
2775         *self == Defaultness::Final
2776     }
2777
2778     pub fn is_default(&self) -> bool {
2779         matches!(*self, Defaultness::Default { .. })
2780     }
2781 }
2782
2783 #[derive(Debug, HashStable_Generic)]
2784 pub enum FnRetTy<'hir> {
2785     /// Return type is not specified.
2786     ///
2787     /// Functions default to `()` and
2788     /// closures default to inference. Span points to where return
2789     /// type would be inserted.
2790     DefaultReturn(Span),
2791     /// Everything else.
2792     Return(&'hir Ty<'hir>),
2793 }
2794
2795 impl FnRetTy<'_> {
2796     #[inline]
2797     pub fn span(&self) -> Span {
2798         match *self {
2799             Self::DefaultReturn(span) => span,
2800             Self::Return(ref ty) => ty.span,
2801         }
2802     }
2803 }
2804
2805 /// Represents `for<...>` binder before a closure
2806 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2807 pub enum ClosureBinder {
2808     /// Binder is not specified.
2809     Default,
2810     /// Binder is specified.
2811     ///
2812     /// Span points to the whole `for<...>`.
2813     For { span: Span },
2814 }
2815
2816 #[derive(Encodable, Debug, HashStable_Generic)]
2817 pub struct Mod<'hir> {
2818     pub spans: ModSpans,
2819     pub item_ids: &'hir [ItemId],
2820 }
2821
2822 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2823 pub struct ModSpans {
2824     /// A span from the first token past `{` to the last token until `}`.
2825     /// For `mod foo;`, the inner span ranges from the first token
2826     /// to the last token in the external file.
2827     pub inner_span: Span,
2828     pub inject_use_span: Span,
2829 }
2830
2831 #[derive(Debug, HashStable_Generic)]
2832 pub struct EnumDef<'hir> {
2833     pub variants: &'hir [Variant<'hir>],
2834 }
2835
2836 #[derive(Debug, HashStable_Generic)]
2837 pub struct Variant<'hir> {
2838     /// Name of the variant.
2839     pub ident: Ident,
2840     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2841     pub hir_id: HirId,
2842     pub def_id: LocalDefId,
2843     /// Fields and constructor id of the variant.
2844     pub data: VariantData<'hir>,
2845     /// Explicit discriminant (e.g., `Foo = 1`).
2846     pub disr_expr: Option<AnonConst>,
2847     /// Span
2848     pub span: Span,
2849 }
2850
2851 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2852 pub enum UseKind {
2853     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2854     /// Also produced for each element of a list `use`, e.g.
2855     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2856     Single,
2857
2858     /// Glob import, e.g., `use foo::*`.
2859     Glob,
2860
2861     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2862     /// an additional `use foo::{}` for performing checks such as
2863     /// unstable feature gating. May be removed in the future.
2864     ListStem,
2865 }
2866
2867 /// References to traits in impls.
2868 ///
2869 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2870 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2871 /// trait being referred to but just a unique `HirId` that serves as a key
2872 /// within the resolution map.
2873 #[derive(Clone, Debug, HashStable_Generic)]
2874 pub struct TraitRef<'hir> {
2875     pub path: &'hir Path<'hir>,
2876     // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2877     #[stable_hasher(ignore)]
2878     pub hir_ref_id: HirId,
2879 }
2880
2881 impl TraitRef<'_> {
2882     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2883     pub fn trait_def_id(&self) -> Option<DefId> {
2884         match self.path.res {
2885             Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2886             Res::Err => None,
2887             _ => unreachable!(),
2888         }
2889     }
2890 }
2891
2892 #[derive(Clone, Debug, HashStable_Generic)]
2893 pub struct PolyTraitRef<'hir> {
2894     /// The `'a` in `for<'a> Foo<&'a T>`.
2895     pub bound_generic_params: &'hir [GenericParam<'hir>],
2896
2897     /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2898     pub trait_ref: TraitRef<'hir>,
2899
2900     pub span: Span,
2901 }
2902
2903 #[derive(Debug, HashStable_Generic)]
2904 pub struct FieldDef<'hir> {
2905     pub span: Span,
2906     pub vis_span: Span,
2907     pub ident: Ident,
2908     pub hir_id: HirId,
2909     pub def_id: LocalDefId,
2910     pub ty: &'hir Ty<'hir>,
2911 }
2912
2913 impl FieldDef<'_> {
2914     // Still necessary in couple of places
2915     pub fn is_positional(&self) -> bool {
2916         let first = self.ident.as_str().as_bytes()[0];
2917         (b'0'..=b'9').contains(&first)
2918     }
2919 }
2920
2921 /// Fields and constructor IDs of enum variants and structs.
2922 #[derive(Debug, HashStable_Generic)]
2923 pub enum VariantData<'hir> {
2924     /// A struct variant.
2925     ///
2926     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2927     Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2928     /// A tuple variant.
2929     ///
2930     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2931     Tuple(&'hir [FieldDef<'hir>], HirId, LocalDefId),
2932     /// A unit variant.
2933     ///
2934     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2935     Unit(HirId, LocalDefId),
2936 }
2937
2938 impl<'hir> VariantData<'hir> {
2939     /// Return the fields of this variant.
2940     pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2941         match *self {
2942             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2943             _ => &[],
2944         }
2945     }
2946
2947     pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
2948         match *self {
2949             VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
2950             VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
2951             VariantData::Struct(..) => None,
2952         }
2953     }
2954
2955     #[inline]
2956     pub fn ctor_kind(&self) -> Option<CtorKind> {
2957         self.ctor().map(|(kind, ..)| kind)
2958     }
2959
2960     /// Return the `HirId` of this variant's constructor, if it has one.
2961     #[inline]
2962     pub fn ctor_hir_id(&self) -> Option<HirId> {
2963         self.ctor().map(|(_, hir_id, _)| hir_id)
2964     }
2965
2966     /// Return the `LocalDefId` of this variant's constructor, if it has one.
2967     #[inline]
2968     pub fn ctor_def_id(&self) -> Option<LocalDefId> {
2969         self.ctor().map(|(.., def_id)| def_id)
2970     }
2971 }
2972
2973 // The bodies for items are stored "out of line", in a separate
2974 // hashmap in the `Crate`. Here we just record the hir-id of the item
2975 // so it can fetched later.
2976 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2977 pub struct ItemId {
2978     pub owner_id: OwnerId,
2979 }
2980
2981 impl ItemId {
2982     #[inline]
2983     pub fn hir_id(&self) -> HirId {
2984         // Items are always HIR owners.
2985         HirId::make_owner(self.owner_id.def_id)
2986     }
2987 }
2988
2989 /// An item
2990 ///
2991 /// The name might be a dummy name in case of anonymous items
2992 #[derive(Debug, HashStable_Generic)]
2993 pub struct Item<'hir> {
2994     pub ident: Ident,
2995     pub owner_id: OwnerId,
2996     pub kind: ItemKind<'hir>,
2997     pub span: Span,
2998     pub vis_span: Span,
2999 }
3000
3001 impl Item<'_> {
3002     #[inline]
3003     pub fn hir_id(&self) -> HirId {
3004         // Items are always HIR owners.
3005         HirId::make_owner(self.owner_id.def_id)
3006     }
3007
3008     pub fn item_id(&self) -> ItemId {
3009         ItemId { owner_id: self.owner_id }
3010     }
3011 }
3012
3013 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3014 #[derive(Encodable, Decodable, HashStable_Generic)]
3015 pub enum Unsafety {
3016     Unsafe,
3017     Normal,
3018 }
3019
3020 impl Unsafety {
3021     pub fn prefix_str(&self) -> &'static str {
3022         match self {
3023             Self::Unsafe => "unsafe ",
3024             Self::Normal => "",
3025         }
3026     }
3027 }
3028
3029 impl fmt::Display for Unsafety {
3030     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3031         f.write_str(match *self {
3032             Self::Unsafe => "unsafe",
3033             Self::Normal => "normal",
3034         })
3035     }
3036 }
3037
3038 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3039 #[derive(Encodable, Decodable, HashStable_Generic)]
3040 pub enum Constness {
3041     Const,
3042     NotConst,
3043 }
3044
3045 impl fmt::Display for Constness {
3046     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3047         f.write_str(match *self {
3048             Self::Const => "const",
3049             Self::NotConst => "non-const",
3050         })
3051     }
3052 }
3053
3054 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
3055 pub struct FnHeader {
3056     pub unsafety: Unsafety,
3057     pub constness: Constness,
3058     pub asyncness: IsAsync,
3059     pub abi: Abi,
3060 }
3061
3062 impl FnHeader {
3063     pub fn is_async(&self) -> bool {
3064         matches!(&self.asyncness, IsAsync::Async)
3065     }
3066
3067     pub fn is_const(&self) -> bool {
3068         matches!(&self.constness, Constness::Const)
3069     }
3070
3071     pub fn is_unsafe(&self) -> bool {
3072         matches!(&self.unsafety, Unsafety::Unsafe)
3073     }
3074 }
3075
3076 #[derive(Debug, HashStable_Generic)]
3077 pub enum ItemKind<'hir> {
3078     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3079     ///
3080     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3081     ExternCrate(Option<Symbol>),
3082
3083     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3084     ///
3085     /// or just
3086     ///
3087     /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3088     Use(&'hir UsePath<'hir>, UseKind),
3089
3090     /// A `static` item.
3091     Static(&'hir Ty<'hir>, Mutability, BodyId),
3092     /// A `const` item.
3093     Const(&'hir Ty<'hir>, BodyId),
3094     /// A function declaration.
3095     Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3096     /// A MBE macro definition (`macro_rules!` or `macro`).
3097     Macro(ast::MacroDef, MacroKind),
3098     /// A module.
3099     Mod(&'hir Mod<'hir>),
3100     /// An external module, e.g. `extern { .. }`.
3101     ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3102     /// Module-level inline assembly (from `global_asm!`).
3103     GlobalAsm(&'hir InlineAsm<'hir>),
3104     /// A type alias, e.g., `type Foo = Bar<u8>`.
3105     TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3106     /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3107     OpaqueTy(OpaqueTy<'hir>),
3108     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3109     Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3110     /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3111     Struct(VariantData<'hir>, &'hir Generics<'hir>),
3112     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3113     Union(VariantData<'hir>, &'hir Generics<'hir>),
3114     /// A trait definition.
3115     Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3116     /// A trait alias.
3117     TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3118
3119     /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3120     Impl(&'hir Impl<'hir>),
3121 }
3122
3123 #[derive(Debug, HashStable_Generic)]
3124 pub struct Impl<'hir> {
3125     pub unsafety: Unsafety,
3126     pub polarity: ImplPolarity,
3127     pub defaultness: Defaultness,
3128     // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3129     // decoding as `Span`s cannot be decoded when a `Session` is not available.
3130     pub defaultness_span: Option<Span>,
3131     pub constness: Constness,
3132     pub generics: &'hir Generics<'hir>,
3133
3134     /// The trait being implemented, if any.
3135     pub of_trait: Option<TraitRef<'hir>>,
3136
3137     pub self_ty: &'hir Ty<'hir>,
3138     pub items: &'hir [ImplItemRef],
3139 }
3140
3141 impl ItemKind<'_> {
3142     pub fn generics(&self) -> Option<&Generics<'_>> {
3143         Some(match *self {
3144             ItemKind::Fn(_, ref generics, _)
3145             | ItemKind::TyAlias(_, ref generics)
3146             | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3147             | ItemKind::Enum(_, ref generics)
3148             | ItemKind::Struct(_, ref generics)
3149             | ItemKind::Union(_, ref generics)
3150             | ItemKind::Trait(_, _, ref generics, _, _)
3151             | ItemKind::TraitAlias(ref generics, _)
3152             | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3153             _ => return None,
3154         })
3155     }
3156
3157     pub fn descr(&self) -> &'static str {
3158         match self {
3159             ItemKind::ExternCrate(..) => "extern crate",
3160             ItemKind::Use(..) => "`use` import",
3161             ItemKind::Static(..) => "static item",
3162             ItemKind::Const(..) => "constant item",
3163             ItemKind::Fn(..) => "function",
3164             ItemKind::Macro(..) => "macro",
3165             ItemKind::Mod(..) => "module",
3166             ItemKind::ForeignMod { .. } => "extern block",
3167             ItemKind::GlobalAsm(..) => "global asm item",
3168             ItemKind::TyAlias(..) => "type alias",
3169             ItemKind::OpaqueTy(..) => "opaque type",
3170             ItemKind::Enum(..) => "enum",
3171             ItemKind::Struct(..) => "struct",
3172             ItemKind::Union(..) => "union",
3173             ItemKind::Trait(..) => "trait",
3174             ItemKind::TraitAlias(..) => "trait alias",
3175             ItemKind::Impl(..) => "implementation",
3176         }
3177     }
3178 }
3179
3180 /// A reference from an trait to one of its associated items. This
3181 /// contains the item's id, naturally, but also the item's name and
3182 /// some other high-level details (like whether it is an associated
3183 /// type or method, and whether it is public). This allows other
3184 /// passes to find the impl they want without loading the ID (which
3185 /// means fewer edges in the incremental compilation graph).
3186 #[derive(Encodable, Debug, HashStable_Generic)]
3187 pub struct TraitItemRef {
3188     pub id: TraitItemId,
3189     pub ident: Ident,
3190     pub kind: AssocItemKind,
3191     pub span: Span,
3192 }
3193
3194 /// A reference from an impl to one of its associated items. This
3195 /// contains the item's ID, naturally, but also the item's name and
3196 /// some other high-level details (like whether it is an associated
3197 /// type or method, and whether it is public). This allows other
3198 /// passes to find the impl they want without loading the ID (which
3199 /// means fewer edges in the incremental compilation graph).
3200 #[derive(Debug, HashStable_Generic)]
3201 pub struct ImplItemRef {
3202     pub id: ImplItemId,
3203     pub ident: Ident,
3204     pub kind: AssocItemKind,
3205     pub span: Span,
3206     /// When we are in a trait impl, link to the trait-item's id.
3207     pub trait_item_def_id: Option<DefId>,
3208 }
3209
3210 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3211 pub enum AssocItemKind {
3212     Const,
3213     Fn { has_self: bool },
3214     Type,
3215 }
3216
3217 // The bodies for items are stored "out of line", in a separate
3218 // hashmap in the `Crate`. Here we just record the hir-id of the item
3219 // so it can fetched later.
3220 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3221 pub struct ForeignItemId {
3222     pub owner_id: OwnerId,
3223 }
3224
3225 impl ForeignItemId {
3226     #[inline]
3227     pub fn hir_id(&self) -> HirId {
3228         // Items are always HIR owners.
3229         HirId::make_owner(self.owner_id.def_id)
3230     }
3231 }
3232
3233 /// A reference from a foreign block to one of its items. This
3234 /// contains the item's ID, naturally, but also the item's name and
3235 /// some other high-level details (like whether it is an associated
3236 /// type or method, and whether it is public). This allows other
3237 /// passes to find the impl they want without loading the ID (which
3238 /// means fewer edges in the incremental compilation graph).
3239 #[derive(Debug, HashStable_Generic)]
3240 pub struct ForeignItemRef {
3241     pub id: ForeignItemId,
3242     pub ident: Ident,
3243     pub span: Span,
3244 }
3245
3246 #[derive(Debug, HashStable_Generic)]
3247 pub struct ForeignItem<'hir> {
3248     pub ident: Ident,
3249     pub kind: ForeignItemKind<'hir>,
3250     pub owner_id: OwnerId,
3251     pub span: Span,
3252     pub vis_span: Span,
3253 }
3254
3255 impl ForeignItem<'_> {
3256     #[inline]
3257     pub fn hir_id(&self) -> HirId {
3258         // Items are always HIR owners.
3259         HirId::make_owner(self.owner_id.def_id)
3260     }
3261
3262     pub fn foreign_item_id(&self) -> ForeignItemId {
3263         ForeignItemId { owner_id: self.owner_id }
3264     }
3265 }
3266
3267 /// An item within an `extern` block.
3268 #[derive(Debug, HashStable_Generic)]
3269 pub enum ForeignItemKind<'hir> {
3270     /// A foreign function.
3271     Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3272     /// A foreign static item (`static ext: u8`).
3273     Static(&'hir Ty<'hir>, Mutability),
3274     /// A foreign type.
3275     Type,
3276 }
3277
3278 /// A variable captured by a closure.
3279 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3280 pub struct Upvar {
3281     /// First span where it is accessed (there can be multiple).
3282     pub span: Span,
3283 }
3284
3285 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3286 // has length > 0 if the trait is found through an chain of imports, starting with the
3287 // import/use statement in the scope where the trait is used.
3288 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3289 pub struct TraitCandidate {
3290     pub def_id: DefId,
3291     pub import_ids: SmallVec<[LocalDefId; 1]>,
3292 }
3293
3294 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3295 pub enum OwnerNode<'hir> {
3296     Item(&'hir Item<'hir>),
3297     ForeignItem(&'hir ForeignItem<'hir>),
3298     TraitItem(&'hir TraitItem<'hir>),
3299     ImplItem(&'hir ImplItem<'hir>),
3300     Crate(&'hir Mod<'hir>),
3301 }
3302
3303 impl<'hir> OwnerNode<'hir> {
3304     pub fn ident(&self) -> Option<Ident> {
3305         match self {
3306             OwnerNode::Item(Item { ident, .. })
3307             | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3308             | OwnerNode::ImplItem(ImplItem { ident, .. })
3309             | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3310             OwnerNode::Crate(..) => None,
3311         }
3312     }
3313
3314     pub fn span(&self) -> Span {
3315         match self {
3316             OwnerNode::Item(Item { span, .. })
3317             | OwnerNode::ForeignItem(ForeignItem { span, .. })
3318             | OwnerNode::ImplItem(ImplItem { span, .. })
3319             | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3320             OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3321         }
3322     }
3323
3324     pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3325         match self {
3326             OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3327             | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3328             | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3329             OwnerNode::ForeignItem(ForeignItem {
3330                 kind: ForeignItemKind::Fn(fn_decl, _, _),
3331                 ..
3332             }) => Some(fn_decl),
3333             _ => None,
3334         }
3335     }
3336
3337     pub fn body_id(&self) -> Option<BodyId> {
3338         match self {
3339             OwnerNode::TraitItem(TraitItem {
3340                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3341                 ..
3342             })
3343             | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3344             | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3345             _ => None,
3346         }
3347     }
3348
3349     pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3350         Node::generics(self.into())
3351     }
3352
3353     pub fn def_id(self) -> OwnerId {
3354         match self {
3355             OwnerNode::Item(Item { owner_id, .. })
3356             | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3357             | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3358             | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3359             OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3360         }
3361     }
3362
3363     pub fn expect_item(self) -> &'hir Item<'hir> {
3364         match self {
3365             OwnerNode::Item(n) => n,
3366             _ => panic!(),
3367         }
3368     }
3369
3370     pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3371         match self {
3372             OwnerNode::ForeignItem(n) => n,
3373             _ => panic!(),
3374         }
3375     }
3376
3377     pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3378         match self {
3379             OwnerNode::ImplItem(n) => n,
3380             _ => panic!(),
3381         }
3382     }
3383
3384     pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3385         match self {
3386             OwnerNode::TraitItem(n) => n,
3387             _ => panic!(),
3388         }
3389     }
3390 }
3391
3392 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3393     fn into(self) -> OwnerNode<'hir> {
3394         OwnerNode::Item(self)
3395     }
3396 }
3397
3398 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3399     fn into(self) -> OwnerNode<'hir> {
3400         OwnerNode::ForeignItem(self)
3401     }
3402 }
3403
3404 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3405     fn into(self) -> OwnerNode<'hir> {
3406         OwnerNode::ImplItem(self)
3407     }
3408 }
3409
3410 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3411     fn into(self) -> OwnerNode<'hir> {
3412         OwnerNode::TraitItem(self)
3413     }
3414 }
3415
3416 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3417     fn into(self) -> Node<'hir> {
3418         match self {
3419             OwnerNode::Item(n) => Node::Item(n),
3420             OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3421             OwnerNode::ImplItem(n) => Node::ImplItem(n),
3422             OwnerNode::TraitItem(n) => Node::TraitItem(n),
3423             OwnerNode::Crate(n) => Node::Crate(n),
3424         }
3425     }
3426 }
3427
3428 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3429 pub enum Node<'hir> {
3430     Param(&'hir Param<'hir>),
3431     Item(&'hir Item<'hir>),
3432     ForeignItem(&'hir ForeignItem<'hir>),
3433     TraitItem(&'hir TraitItem<'hir>),
3434     ImplItem(&'hir ImplItem<'hir>),
3435     Variant(&'hir Variant<'hir>),
3436     Field(&'hir FieldDef<'hir>),
3437     AnonConst(&'hir AnonConst),
3438     Expr(&'hir Expr<'hir>),
3439     ExprField(&'hir ExprField<'hir>),
3440     Stmt(&'hir Stmt<'hir>),
3441     PathSegment(&'hir PathSegment<'hir>),
3442     Ty(&'hir Ty<'hir>),
3443     TypeBinding(&'hir TypeBinding<'hir>),
3444     TraitRef(&'hir TraitRef<'hir>),
3445     Pat(&'hir Pat<'hir>),
3446     PatField(&'hir PatField<'hir>),
3447     Arm(&'hir Arm<'hir>),
3448     Block(&'hir Block<'hir>),
3449     Local(&'hir Local<'hir>),
3450
3451     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3452     /// with synthesized constructors.
3453     Ctor(&'hir VariantData<'hir>),
3454
3455     Lifetime(&'hir Lifetime),
3456     GenericParam(&'hir GenericParam<'hir>),
3457
3458     Crate(&'hir Mod<'hir>),
3459
3460     Infer(&'hir InferArg),
3461 }
3462
3463 impl<'hir> Node<'hir> {
3464     /// Get the identifier of this `Node`, if applicable.
3465     ///
3466     /// # Edge cases
3467     ///
3468     /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3469     /// because `Ctor`s do not have identifiers themselves.
3470     /// Instead, call `.ident()` on the parent struct/variant, like so:
3471     ///
3472     /// ```ignore (illustrative)
3473     /// ctor
3474     ///     .ctor_hir_id()
3475     ///     .and_then(|ctor_id| tcx.hir().find_parent(ctor_id))
3476     ///     .and_then(|parent| parent.ident())
3477     /// ```
3478     pub fn ident(&self) -> Option<Ident> {
3479         match self {
3480             Node::TraitItem(TraitItem { ident, .. })
3481             | Node::ImplItem(ImplItem { ident, .. })
3482             | Node::ForeignItem(ForeignItem { ident, .. })
3483             | Node::Field(FieldDef { ident, .. })
3484             | Node::Variant(Variant { ident, .. })
3485             | Node::Item(Item { ident, .. })
3486             | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3487             Node::Lifetime(lt) => Some(lt.ident),
3488             Node::GenericParam(p) => Some(p.name.ident()),
3489             Node::TypeBinding(b) => Some(b.ident),
3490             Node::Param(..)
3491             | Node::AnonConst(..)
3492             | Node::Expr(..)
3493             | Node::Stmt(..)
3494             | Node::Block(..)
3495             | Node::Ctor(..)
3496             | Node::Pat(..)
3497             | Node::PatField(..)
3498             | Node::ExprField(..)
3499             | Node::Arm(..)
3500             | Node::Local(..)
3501             | Node::Crate(..)
3502             | Node::Ty(..)
3503             | Node::TraitRef(..)
3504             | Node::Infer(..) => None,
3505         }
3506     }
3507
3508     pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3509         match self {
3510             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3511             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3512             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3513             Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3514             | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3515                 Some(fn_decl)
3516             }
3517             _ => None,
3518         }
3519     }
3520
3521     pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3522         match self {
3523             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3524             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3525             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3526             _ => None,
3527         }
3528     }
3529
3530     pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
3531         match self {
3532             Node::Item(Item { kind: ItemKind::TyAlias(ty, ..), .. }) => Some(ty),
3533             _ => None,
3534         }
3535     }
3536
3537     pub fn body_id(&self) -> Option<BodyId> {
3538         match self {
3539             Node::TraitItem(TraitItem {
3540                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3541                 ..
3542             })
3543             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3544             | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3545             _ => None,
3546         }
3547     }
3548
3549     pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3550         match self {
3551             Node::ForeignItem(ForeignItem {
3552                 kind: ForeignItemKind::Fn(_, _, generics), ..
3553             })
3554             | Node::TraitItem(TraitItem { generics, .. })
3555             | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3556             Node::Item(item) => item.kind.generics(),
3557             _ => None,
3558         }
3559     }
3560
3561     pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3562         match self {
3563             Node::Item(i) => Some(OwnerNode::Item(i)),
3564             Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3565             Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3566             Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3567             Node::Crate(i) => Some(OwnerNode::Crate(i)),
3568             _ => None,
3569         }
3570     }
3571
3572     pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3573         match self {
3574             Node::Item(i) => match i.kind {
3575                 ItemKind::Fn(ref sig, ref generics, _) => {
3576                     Some(FnKind::ItemFn(i.ident, generics, sig.header))
3577                 }
3578                 _ => None,
3579             },
3580             Node::TraitItem(ti) => match ti.kind {
3581                 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3582                     Some(FnKind::Method(ti.ident, sig))
3583                 }
3584                 _ => None,
3585             },
3586             Node::ImplItem(ii) => match ii.kind {
3587                 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3588                 _ => None,
3589             },
3590             Node::Expr(e) => match e.kind {
3591                 ExprKind::Closure { .. } => Some(FnKind::Closure),
3592                 _ => None,
3593             },
3594             _ => None,
3595         }
3596     }
3597
3598     /// Get the fields for the tuple-constructor,
3599     /// if this node is a tuple constructor, otherwise None
3600     pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3601         if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None }
3602     }
3603 }
3604
3605 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3606 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3607 mod size_asserts {
3608     use super::*;
3609     // tidy-alphabetical-start
3610     static_assert_size!(Block<'_>, 48);
3611     static_assert_size!(Body<'_>, 32);
3612     static_assert_size!(Expr<'_>, 64);
3613     static_assert_size!(ExprKind<'_>, 48);
3614     static_assert_size!(FnDecl<'_>, 40);
3615     static_assert_size!(ForeignItem<'_>, 72);
3616     static_assert_size!(ForeignItemKind<'_>, 40);
3617     static_assert_size!(GenericArg<'_>, 32);
3618     static_assert_size!(GenericBound<'_>, 48);
3619     static_assert_size!(Generics<'_>, 56);
3620     static_assert_size!(Impl<'_>, 80);
3621     static_assert_size!(ImplItem<'_>, 80);
3622     static_assert_size!(ImplItemKind<'_>, 32);
3623     static_assert_size!(Item<'_>, 80);
3624     static_assert_size!(ItemKind<'_>, 48);
3625     static_assert_size!(Local<'_>, 64);
3626     static_assert_size!(Param<'_>, 32);
3627     static_assert_size!(Pat<'_>, 72);
3628     static_assert_size!(Path<'_>, 40);
3629     static_assert_size!(PathSegment<'_>, 48);
3630     static_assert_size!(PatKind<'_>, 48);
3631     static_assert_size!(QPath<'_>, 24);
3632     static_assert_size!(Res, 12);
3633     static_assert_size!(Stmt<'_>, 32);
3634     static_assert_size!(StmtKind<'_>, 16);
3635     static_assert_size!(TraitItem<'_>, 80);
3636     static_assert_size!(TraitItemKind<'_>, 40);
3637     static_assert_size!(Ty<'_>, 48);
3638     static_assert_size!(TyKind<'_>, 32);
3639     // tidy-alphabetical-end
3640 }
3641
3642 fn debug_fn(f: impl Fn(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Debug {
3643     struct DebugFn<F>(F);
3644     impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Debug for DebugFn<F> {
3645         fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3646             (self.0)(fmt)
3647         }
3648     }
3649     DebugFn(f)
3650 }