]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/hir.rs
Rollup merge of #103236 - tspiteri:redoc-int-adc-sbb, r=m-ou-se
[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 capture_clause: CaptureBy,
942     pub bound_generic_params: &'hir [GenericParam<'hir>],
943     pub fn_decl: &'hir FnDecl<'hir>,
944     pub body: BodyId,
945     /// The span of the declaration block: 'move |...| -> ...'
946     pub fn_decl_span: Span,
947     /// The span of the argument block `|...|`
948     pub fn_arg_span: Option<Span>,
949     pub movability: Option<Movability>,
950 }
951
952 /// A block of statements `{ .. }`, which may have a label (in this case the
953 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
954 /// the `rules` being anything but `DefaultBlock`.
955 #[derive(Debug, HashStable_Generic)]
956 pub struct Block<'hir> {
957     /// Statements in a block.
958     pub stmts: &'hir [Stmt<'hir>],
959     /// An expression at the end of the block
960     /// without a semicolon, if any.
961     pub expr: Option<&'hir Expr<'hir>>,
962     #[stable_hasher(ignore)]
963     pub hir_id: HirId,
964     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
965     pub rules: BlockCheckMode,
966     pub span: Span,
967     /// If true, then there may exist `break 'a` values that aim to
968     /// break out of this block early.
969     /// Used by `'label: {}` blocks and by `try {}` blocks.
970     pub targeted_by_break: bool,
971 }
972
973 impl<'hir> Block<'hir> {
974     pub fn innermost_block(&self) -> &Block<'hir> {
975         let mut block = self;
976         while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
977             block = inner_block;
978         }
979         block
980     }
981 }
982
983 #[derive(Debug, HashStable_Generic)]
984 pub struct Pat<'hir> {
985     #[stable_hasher(ignore)]
986     pub hir_id: HirId,
987     pub kind: PatKind<'hir>,
988     pub span: Span,
989     /// Whether to use default binding modes.
990     /// At present, this is false only for destructuring assignment.
991     pub default_binding_modes: bool,
992 }
993
994 impl<'hir> Pat<'hir> {
995     // FIXME(#19596) this is a workaround, but there should be a better way
996     fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
997         if !it(self) {
998             return false;
999         }
1000
1001         use PatKind::*;
1002         match self.kind {
1003             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
1004             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
1005             Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1006             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1007             Slice(before, slice, after) => {
1008                 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1009             }
1010         }
1011     }
1012
1013     /// Walk the pattern in left-to-right order,
1014     /// short circuiting (with `.all(..)`) if `false` is returned.
1015     ///
1016     /// Note that when visiting e.g. `Tuple(ps)`,
1017     /// if visiting `ps[0]` returns `false`,
1018     /// then `ps[1]` will not be visited.
1019     pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1020         self.walk_short_(&mut it)
1021     }
1022
1023     // FIXME(#19596) this is a workaround, but there should be a better way
1024     fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1025         if !it(self) {
1026             return;
1027         }
1028
1029         use PatKind::*;
1030         match self.kind {
1031             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1032             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1033             Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1034             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1035             Slice(before, slice, after) => {
1036                 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1037             }
1038         }
1039     }
1040
1041     /// Walk the pattern in left-to-right order.
1042     ///
1043     /// If `it(pat)` returns `false`, the children are not visited.
1044     pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1045         self.walk_(&mut it)
1046     }
1047
1048     /// Walk the pattern in left-to-right order.
1049     ///
1050     /// If you always want to recurse, prefer this method over `walk`.
1051     pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1052         self.walk(|p| {
1053             it(p);
1054             true
1055         })
1056     }
1057 }
1058
1059 /// A single field in a struct pattern.
1060 ///
1061 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1062 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1063 /// except `is_shorthand` is true.
1064 #[derive(Debug, HashStable_Generic)]
1065 pub struct PatField<'hir> {
1066     #[stable_hasher(ignore)]
1067     pub hir_id: HirId,
1068     /// The identifier for the field.
1069     pub ident: Ident,
1070     /// The pattern the field is destructured to.
1071     pub pat: &'hir Pat<'hir>,
1072     pub is_shorthand: bool,
1073     pub span: Span,
1074 }
1075
1076 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1077 pub enum RangeEnd {
1078     Included,
1079     Excluded,
1080 }
1081
1082 impl fmt::Display for RangeEnd {
1083     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1084         f.write_str(match self {
1085             RangeEnd::Included => "..=",
1086             RangeEnd::Excluded => "..",
1087         })
1088     }
1089 }
1090
1091 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1092 // this type only takes up 4 bytes, at the cost of being restricted to a
1093 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1094 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1095 pub struct DotDotPos(u32);
1096
1097 impl DotDotPos {
1098     /// Panics if n >= u32::MAX.
1099     pub fn new(n: Option<usize>) -> Self {
1100         match n {
1101             Some(n) => {
1102                 assert!(n < u32::MAX as usize);
1103                 Self(n as u32)
1104             }
1105             None => Self(u32::MAX),
1106         }
1107     }
1108
1109     pub fn as_opt_usize(&self) -> Option<usize> {
1110         if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1111     }
1112 }
1113
1114 impl fmt::Debug for DotDotPos {
1115     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116         self.as_opt_usize().fmt(f)
1117     }
1118 }
1119
1120 #[derive(Debug, HashStable_Generic)]
1121 pub enum PatKind<'hir> {
1122     /// Represents a wildcard pattern (i.e., `_`).
1123     Wild,
1124
1125     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1126     /// The `HirId` is the canonical ID for the variable being bound,
1127     /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1128     /// which is the pattern ID of the first `x`.
1129     Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1130
1131     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1132     /// The `bool` is `true` in the presence of a `..`.
1133     Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1134
1135     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1136     /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1137     /// `0 <= position <= subpats.len()`
1138     TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1139
1140     /// An or-pattern `A | B | C`.
1141     /// Invariant: `pats.len() >= 2`.
1142     Or(&'hir [Pat<'hir>]),
1143
1144     /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1145     Path(QPath<'hir>),
1146
1147     /// A tuple pattern (e.g., `(a, b)`).
1148     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1149     /// `0 <= position <= subpats.len()`
1150     Tuple(&'hir [Pat<'hir>], DotDotPos),
1151
1152     /// A `box` pattern.
1153     Box(&'hir Pat<'hir>),
1154
1155     /// A reference pattern (e.g., `&mut (a, b)`).
1156     Ref(&'hir Pat<'hir>, Mutability),
1157
1158     /// A literal.
1159     Lit(&'hir Expr<'hir>),
1160
1161     /// A range pattern (e.g., `1..=2` or `1..2`).
1162     Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1163
1164     /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1165     ///
1166     /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1167     /// If `slice` exists, then `after` can be non-empty.
1168     ///
1169     /// The representation for e.g., `[a, b, .., c, d]` is:
1170     /// ```ignore (illustrative)
1171     /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1172     /// ```
1173     Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1174 }
1175
1176 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1177 pub enum BinOpKind {
1178     /// The `+` operator (addition).
1179     Add,
1180     /// The `-` operator (subtraction).
1181     Sub,
1182     /// The `*` operator (multiplication).
1183     Mul,
1184     /// The `/` operator (division).
1185     Div,
1186     /// The `%` operator (modulus).
1187     Rem,
1188     /// The `&&` operator (logical and).
1189     And,
1190     /// The `||` operator (logical or).
1191     Or,
1192     /// The `^` operator (bitwise xor).
1193     BitXor,
1194     /// The `&` operator (bitwise and).
1195     BitAnd,
1196     /// The `|` operator (bitwise or).
1197     BitOr,
1198     /// The `<<` operator (shift left).
1199     Shl,
1200     /// The `>>` operator (shift right).
1201     Shr,
1202     /// The `==` operator (equality).
1203     Eq,
1204     /// The `<` operator (less than).
1205     Lt,
1206     /// The `<=` operator (less than or equal to).
1207     Le,
1208     /// The `!=` operator (not equal to).
1209     Ne,
1210     /// The `>=` operator (greater than or equal to).
1211     Ge,
1212     /// The `>` operator (greater than).
1213     Gt,
1214 }
1215
1216 impl BinOpKind {
1217     pub fn as_str(self) -> &'static str {
1218         match self {
1219             BinOpKind::Add => "+",
1220             BinOpKind::Sub => "-",
1221             BinOpKind::Mul => "*",
1222             BinOpKind::Div => "/",
1223             BinOpKind::Rem => "%",
1224             BinOpKind::And => "&&",
1225             BinOpKind::Or => "||",
1226             BinOpKind::BitXor => "^",
1227             BinOpKind::BitAnd => "&",
1228             BinOpKind::BitOr => "|",
1229             BinOpKind::Shl => "<<",
1230             BinOpKind::Shr => ">>",
1231             BinOpKind::Eq => "==",
1232             BinOpKind::Lt => "<",
1233             BinOpKind::Le => "<=",
1234             BinOpKind::Ne => "!=",
1235             BinOpKind::Ge => ">=",
1236             BinOpKind::Gt => ">",
1237         }
1238     }
1239
1240     pub fn is_lazy(self) -> bool {
1241         matches!(self, BinOpKind::And | BinOpKind::Or)
1242     }
1243
1244     pub fn is_shift(self) -> bool {
1245         matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1246     }
1247
1248     pub fn is_comparison(self) -> bool {
1249         match self {
1250             BinOpKind::Eq
1251             | BinOpKind::Lt
1252             | BinOpKind::Le
1253             | BinOpKind::Ne
1254             | BinOpKind::Gt
1255             | BinOpKind::Ge => true,
1256             BinOpKind::And
1257             | BinOpKind::Or
1258             | BinOpKind::Add
1259             | BinOpKind::Sub
1260             | BinOpKind::Mul
1261             | BinOpKind::Div
1262             | BinOpKind::Rem
1263             | BinOpKind::BitXor
1264             | BinOpKind::BitAnd
1265             | BinOpKind::BitOr
1266             | BinOpKind::Shl
1267             | BinOpKind::Shr => false,
1268         }
1269     }
1270
1271     /// Returns `true` if the binary operator takes its arguments by value.
1272     pub fn is_by_value(self) -> bool {
1273         !self.is_comparison()
1274     }
1275 }
1276
1277 impl Into<ast::BinOpKind> for BinOpKind {
1278     fn into(self) -> ast::BinOpKind {
1279         match self {
1280             BinOpKind::Add => ast::BinOpKind::Add,
1281             BinOpKind::Sub => ast::BinOpKind::Sub,
1282             BinOpKind::Mul => ast::BinOpKind::Mul,
1283             BinOpKind::Div => ast::BinOpKind::Div,
1284             BinOpKind::Rem => ast::BinOpKind::Rem,
1285             BinOpKind::And => ast::BinOpKind::And,
1286             BinOpKind::Or => ast::BinOpKind::Or,
1287             BinOpKind::BitXor => ast::BinOpKind::BitXor,
1288             BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1289             BinOpKind::BitOr => ast::BinOpKind::BitOr,
1290             BinOpKind::Shl => ast::BinOpKind::Shl,
1291             BinOpKind::Shr => ast::BinOpKind::Shr,
1292             BinOpKind::Eq => ast::BinOpKind::Eq,
1293             BinOpKind::Lt => ast::BinOpKind::Lt,
1294             BinOpKind::Le => ast::BinOpKind::Le,
1295             BinOpKind::Ne => ast::BinOpKind::Ne,
1296             BinOpKind::Ge => ast::BinOpKind::Ge,
1297             BinOpKind::Gt => ast::BinOpKind::Gt,
1298         }
1299     }
1300 }
1301
1302 pub type BinOp = Spanned<BinOpKind>;
1303
1304 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1305 pub enum UnOp {
1306     /// The `*` operator (dereferencing).
1307     Deref,
1308     /// The `!` operator (logical negation).
1309     Not,
1310     /// The `-` operator (negation).
1311     Neg,
1312 }
1313
1314 impl UnOp {
1315     pub fn as_str(self) -> &'static str {
1316         match self {
1317             Self::Deref => "*",
1318             Self::Not => "!",
1319             Self::Neg => "-",
1320         }
1321     }
1322
1323     /// Returns `true` if the unary operator takes its argument by value.
1324     pub fn is_by_value(self) -> bool {
1325         matches!(self, Self::Neg | Self::Not)
1326     }
1327 }
1328
1329 /// A statement.
1330 #[derive(Debug, HashStable_Generic)]
1331 pub struct Stmt<'hir> {
1332     pub hir_id: HirId,
1333     pub kind: StmtKind<'hir>,
1334     pub span: Span,
1335 }
1336
1337 /// The contents of a statement.
1338 #[derive(Debug, HashStable_Generic)]
1339 pub enum StmtKind<'hir> {
1340     /// A local (`let`) binding.
1341     Local(&'hir Local<'hir>),
1342
1343     /// An item binding.
1344     Item(ItemId),
1345
1346     /// An expression without a trailing semi-colon (must have unit type).
1347     Expr(&'hir Expr<'hir>),
1348
1349     /// An expression with a trailing semi-colon (may have any type).
1350     Semi(&'hir Expr<'hir>),
1351 }
1352
1353 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1354 #[derive(Debug, HashStable_Generic)]
1355 pub struct Local<'hir> {
1356     pub pat: &'hir Pat<'hir>,
1357     /// Type annotation, if any (otherwise the type will be inferred).
1358     pub ty: Option<&'hir Ty<'hir>>,
1359     /// Initializer expression to set the value, if any.
1360     pub init: Option<&'hir Expr<'hir>>,
1361     /// Else block for a `let...else` binding.
1362     pub els: Option<&'hir Block<'hir>>,
1363     pub hir_id: HirId,
1364     pub span: Span,
1365     /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1366     /// desugaring. Otherwise will be `Normal`.
1367     pub source: LocalSource,
1368 }
1369
1370 /// Represents a single arm of a `match` expression, e.g.
1371 /// `<pat> (if <guard>) => <body>`.
1372 #[derive(Debug, HashStable_Generic)]
1373 pub struct Arm<'hir> {
1374     #[stable_hasher(ignore)]
1375     pub hir_id: HirId,
1376     pub span: Span,
1377     /// If this pattern and the optional guard matches, then `body` is evaluated.
1378     pub pat: &'hir Pat<'hir>,
1379     /// Optional guard clause.
1380     pub guard: Option<Guard<'hir>>,
1381     /// The expression the arm evaluates to if this arm matches.
1382     pub body: &'hir Expr<'hir>,
1383 }
1384
1385 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1386 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1387 ///
1388 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1389 /// desugaring to if-let. Only let-else supports the type annotation at present.
1390 #[derive(Debug, HashStable_Generic)]
1391 pub struct Let<'hir> {
1392     pub hir_id: HirId,
1393     pub span: Span,
1394     pub pat: &'hir Pat<'hir>,
1395     pub ty: Option<&'hir Ty<'hir>>,
1396     pub init: &'hir Expr<'hir>,
1397 }
1398
1399 #[derive(Debug, HashStable_Generic)]
1400 pub enum Guard<'hir> {
1401     If(&'hir Expr<'hir>),
1402     IfLet(&'hir Let<'hir>),
1403 }
1404
1405 impl<'hir> Guard<'hir> {
1406     /// Returns the body of the guard
1407     ///
1408     /// In other words, returns the e in either of the following:
1409     ///
1410     /// - `if e`
1411     /// - `if let x = e`
1412     pub fn body(&self) -> &'hir Expr<'hir> {
1413         match self {
1414             Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1415         }
1416     }
1417 }
1418
1419 #[derive(Debug, HashStable_Generic)]
1420 pub struct ExprField<'hir> {
1421     #[stable_hasher(ignore)]
1422     pub hir_id: HirId,
1423     pub ident: Ident,
1424     pub expr: &'hir Expr<'hir>,
1425     pub span: Span,
1426     pub is_shorthand: bool,
1427 }
1428
1429 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1430 pub enum BlockCheckMode {
1431     DefaultBlock,
1432     UnsafeBlock(UnsafeSource),
1433 }
1434
1435 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1436 pub enum UnsafeSource {
1437     CompilerGenerated,
1438     UserProvided,
1439 }
1440
1441 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1442 pub struct BodyId {
1443     pub hir_id: HirId,
1444 }
1445
1446 /// The body of a function, closure, or constant value. In the case of
1447 /// a function, the body contains not only the function body itself
1448 /// (which is an expression), but also the argument patterns, since
1449 /// those are something that the caller doesn't really care about.
1450 ///
1451 /// # Examples
1452 ///
1453 /// ```
1454 /// fn foo((x, y): (u32, u32)) -> u32 {
1455 ///     x + y
1456 /// }
1457 /// ```
1458 ///
1459 /// Here, the `Body` associated with `foo()` would contain:
1460 ///
1461 /// - an `params` array containing the `(x, y)` pattern
1462 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1463 /// - `generator_kind` would be `None`
1464 ///
1465 /// All bodies have an **owner**, which can be accessed via the HIR
1466 /// map using `body_owner_def_id()`.
1467 #[derive(Debug, HashStable_Generic)]
1468 pub struct Body<'hir> {
1469     pub params: &'hir [Param<'hir>],
1470     pub value: &'hir Expr<'hir>,
1471     pub generator_kind: Option<GeneratorKind>,
1472 }
1473
1474 impl<'hir> Body<'hir> {
1475     pub fn id(&self) -> BodyId {
1476         BodyId { hir_id: self.value.hir_id }
1477     }
1478
1479     pub fn generator_kind(&self) -> Option<GeneratorKind> {
1480         self.generator_kind
1481     }
1482 }
1483
1484 /// The type of source expression that caused this generator to be created.
1485 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1486 #[derive(HashStable_Generic, Encodable, Decodable)]
1487 pub enum GeneratorKind {
1488     /// An explicit `async` block or the body of an async function.
1489     Async(AsyncGeneratorKind),
1490
1491     /// A generator literal created via a `yield` inside a closure.
1492     Gen,
1493 }
1494
1495 impl fmt::Display for GeneratorKind {
1496     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1497         match self {
1498             GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1499             GeneratorKind::Gen => f.write_str("generator"),
1500         }
1501     }
1502 }
1503
1504 impl GeneratorKind {
1505     pub fn descr(&self) -> &'static str {
1506         match self {
1507             GeneratorKind::Async(ask) => ask.descr(),
1508             GeneratorKind::Gen => "generator",
1509         }
1510     }
1511 }
1512
1513 /// In the case of a generator created as part of an async construct,
1514 /// which kind of async construct caused it to be created?
1515 ///
1516 /// This helps error messages but is also used to drive coercions in
1517 /// type-checking (see #60424).
1518 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1519 #[derive(HashStable_Generic, Encodable, Decodable)]
1520 pub enum AsyncGeneratorKind {
1521     /// An explicit `async` block written by the user.
1522     Block,
1523
1524     /// An explicit `async` closure written by the user.
1525     Closure,
1526
1527     /// The `async` block generated as the body of an async function.
1528     Fn,
1529 }
1530
1531 impl fmt::Display for AsyncGeneratorKind {
1532     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533         f.write_str(match self {
1534             AsyncGeneratorKind::Block => "async block",
1535             AsyncGeneratorKind::Closure => "async closure body",
1536             AsyncGeneratorKind::Fn => "async fn body",
1537         })
1538     }
1539 }
1540
1541 impl AsyncGeneratorKind {
1542     pub fn descr(&self) -> &'static str {
1543         match self {
1544             AsyncGeneratorKind::Block => "`async` block",
1545             AsyncGeneratorKind::Closure => "`async` closure body",
1546             AsyncGeneratorKind::Fn => "`async fn` body",
1547         }
1548     }
1549 }
1550
1551 #[derive(Copy, Clone, Debug)]
1552 pub enum BodyOwnerKind {
1553     /// Functions and methods.
1554     Fn,
1555
1556     /// Closures
1557     Closure,
1558
1559     /// Constants and associated constants.
1560     Const,
1561
1562     /// Initializer of a `static` item.
1563     Static(Mutability),
1564 }
1565
1566 impl BodyOwnerKind {
1567     pub fn is_fn_or_closure(self) -> bool {
1568         match self {
1569             BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1570             BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1571         }
1572     }
1573 }
1574
1575 /// The kind of an item that requires const-checking.
1576 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1577 pub enum ConstContext {
1578     /// A `const fn`.
1579     ConstFn,
1580
1581     /// A `static` or `static mut`.
1582     Static(Mutability),
1583
1584     /// A `const`, associated `const`, or other const context.
1585     ///
1586     /// Other contexts include:
1587     /// - Array length expressions
1588     /// - Enum discriminants
1589     /// - Const generics
1590     ///
1591     /// For the most part, other contexts are treated just like a regular `const`, so they are
1592     /// lumped into the same category.
1593     Const,
1594 }
1595
1596 impl ConstContext {
1597     /// A description of this const context that can appear between backticks in an error message.
1598     ///
1599     /// E.g. `const` or `static mut`.
1600     pub fn keyword_name(self) -> &'static str {
1601         match self {
1602             Self::Const => "const",
1603             Self::Static(Mutability::Not) => "static",
1604             Self::Static(Mutability::Mut) => "static mut",
1605             Self::ConstFn => "const fn",
1606         }
1607     }
1608 }
1609
1610 /// A colloquial, trivially pluralizable description of this const context for use in error
1611 /// messages.
1612 impl fmt::Display for ConstContext {
1613     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1614         match *self {
1615             Self::Const => write!(f, "constant"),
1616             Self::Static(_) => write!(f, "static"),
1617             Self::ConstFn => write!(f, "constant function"),
1618         }
1619     }
1620 }
1621
1622 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1623 // due to a cyclical dependency between hir that crate.
1624
1625 /// A literal.
1626 pub type Lit = Spanned<LitKind>;
1627
1628 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1629 pub enum ArrayLen {
1630     Infer(HirId, Span),
1631     Body(AnonConst),
1632 }
1633
1634 impl ArrayLen {
1635     pub fn hir_id(&self) -> HirId {
1636         match self {
1637             &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, .. }) => hir_id,
1638         }
1639     }
1640 }
1641
1642 /// A constant (expression) that's not an item or associated item,
1643 /// but needs its own `DefId` for type-checking, const-eval, etc.
1644 /// These are usually found nested inside types (e.g., array lengths)
1645 /// or expressions (e.g., repeat counts), and also used to define
1646 /// explicit discriminant values for enum variants.
1647 ///
1648 /// You can check if this anon const is a default in a const param
1649 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)`
1650 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1651 pub struct AnonConst {
1652     pub hir_id: HirId,
1653     pub def_id: LocalDefId,
1654     pub body: BodyId,
1655 }
1656
1657 /// An expression.
1658 #[derive(Debug, HashStable_Generic)]
1659 pub struct Expr<'hir> {
1660     pub hir_id: HirId,
1661     pub kind: ExprKind<'hir>,
1662     pub span: Span,
1663 }
1664
1665 impl Expr<'_> {
1666     pub fn precedence(&self) -> ExprPrecedence {
1667         match self.kind {
1668             ExprKind::Box(_) => ExprPrecedence::Box,
1669             ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1670             ExprKind::Array(_) => ExprPrecedence::Array,
1671             ExprKind::Call(..) => ExprPrecedence::Call,
1672             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1673             ExprKind::Tup(_) => ExprPrecedence::Tup,
1674             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1675             ExprKind::Unary(..) => ExprPrecedence::Unary,
1676             ExprKind::Lit(_) => ExprPrecedence::Lit,
1677             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1678             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1679             ExprKind::If(..) => ExprPrecedence::If,
1680             ExprKind::Let(..) => ExprPrecedence::Let,
1681             ExprKind::Loop(..) => ExprPrecedence::Loop,
1682             ExprKind::Match(..) => ExprPrecedence::Match,
1683             ExprKind::Closure { .. } => ExprPrecedence::Closure,
1684             ExprKind::Block(..) => ExprPrecedence::Block,
1685             ExprKind::Assign(..) => ExprPrecedence::Assign,
1686             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1687             ExprKind::Field(..) => ExprPrecedence::Field,
1688             ExprKind::Index(..) => ExprPrecedence::Index,
1689             ExprKind::Path(..) => ExprPrecedence::Path,
1690             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1691             ExprKind::Break(..) => ExprPrecedence::Break,
1692             ExprKind::Continue(..) => ExprPrecedence::Continue,
1693             ExprKind::Ret(..) => ExprPrecedence::Ret,
1694             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1695             ExprKind::Struct(..) => ExprPrecedence::Struct,
1696             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1697             ExprKind::Yield(..) => ExprPrecedence::Yield,
1698             ExprKind::Err => ExprPrecedence::Err,
1699         }
1700     }
1701
1702     /// Whether this looks like a place expr, without checking for deref
1703     /// adjustments.
1704     /// This will return `true` in some potentially surprising cases such as
1705     /// `CONSTANT.field`.
1706     pub fn is_syntactic_place_expr(&self) -> bool {
1707         self.is_place_expr(|_| true)
1708     }
1709
1710     /// Whether this is a place expression.
1711     ///
1712     /// `allow_projections_from` should return `true` if indexing a field or index expression based
1713     /// on the given expression should be considered a place expression.
1714     pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1715         match self.kind {
1716             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1717                 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1718             }
1719
1720             // Type ascription inherits its place expression kind from its
1721             // operand. See:
1722             // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1723             ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1724
1725             ExprKind::Unary(UnOp::Deref, _) => true,
1726
1727             ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1728                 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1729             }
1730
1731             // Lang item paths cannot currently be local variables or statics.
1732             ExprKind::Path(QPath::LangItem(..)) => false,
1733
1734             // Partially qualified paths in expressions can only legally
1735             // refer to associated items which are always rvalues.
1736             ExprKind::Path(QPath::TypeRelative(..))
1737             | ExprKind::Call(..)
1738             | ExprKind::MethodCall(..)
1739             | ExprKind::Struct(..)
1740             | ExprKind::Tup(..)
1741             | ExprKind::If(..)
1742             | ExprKind::Match(..)
1743             | ExprKind::Closure { .. }
1744             | ExprKind::Block(..)
1745             | ExprKind::Repeat(..)
1746             | ExprKind::Array(..)
1747             | ExprKind::Break(..)
1748             | ExprKind::Continue(..)
1749             | ExprKind::Ret(..)
1750             | ExprKind::Let(..)
1751             | ExprKind::Loop(..)
1752             | ExprKind::Assign(..)
1753             | ExprKind::InlineAsm(..)
1754             | ExprKind::AssignOp(..)
1755             | ExprKind::Lit(_)
1756             | ExprKind::ConstBlock(..)
1757             | ExprKind::Unary(..)
1758             | ExprKind::Box(..)
1759             | ExprKind::AddrOf(..)
1760             | ExprKind::Binary(..)
1761             | ExprKind::Yield(..)
1762             | ExprKind::Cast(..)
1763             | ExprKind::DropTemps(..)
1764             | ExprKind::Err => false,
1765         }
1766     }
1767
1768     /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1769     /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1770     /// silent, only signaling the ownership system. By doing this, suggestions that check the
1771     /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1772     /// beyond remembering to call this function before doing analysis on it.
1773     pub fn peel_drop_temps(&self) -> &Self {
1774         let mut expr = self;
1775         while let ExprKind::DropTemps(inner) = &expr.kind {
1776             expr = inner;
1777         }
1778         expr
1779     }
1780
1781     pub fn peel_blocks(&self) -> &Self {
1782         let mut expr = self;
1783         while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1784             expr = inner;
1785         }
1786         expr
1787     }
1788
1789     pub fn can_have_side_effects(&self) -> bool {
1790         match self.peel_drop_temps().kind {
1791             ExprKind::Path(_) | ExprKind::Lit(_) => false,
1792             ExprKind::Type(base, _)
1793             | ExprKind::Unary(_, base)
1794             | ExprKind::Field(base, _)
1795             | ExprKind::Index(base, _)
1796             | ExprKind::AddrOf(.., base)
1797             | ExprKind::Cast(base, _) => {
1798                 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1799                 // method exclusively for diagnostics and there's a *cultural* pressure against
1800                 // them being used only for its side-effects.
1801                 base.can_have_side_effects()
1802             }
1803             ExprKind::Struct(_, fields, init) => fields
1804                 .iter()
1805                 .map(|field| field.expr)
1806                 .chain(init.into_iter())
1807                 .all(|e| e.can_have_side_effects()),
1808
1809             ExprKind::Array(args)
1810             | ExprKind::Tup(args)
1811             | ExprKind::Call(
1812                 Expr {
1813                     kind:
1814                         ExprKind::Path(QPath::Resolved(
1815                             None,
1816                             Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1817                         )),
1818                     ..
1819                 },
1820                 args,
1821             ) => args.iter().all(|arg| arg.can_have_side_effects()),
1822             ExprKind::If(..)
1823             | ExprKind::Match(..)
1824             | ExprKind::MethodCall(..)
1825             | ExprKind::Call(..)
1826             | ExprKind::Closure { .. }
1827             | ExprKind::Block(..)
1828             | ExprKind::Repeat(..)
1829             | ExprKind::Break(..)
1830             | ExprKind::Continue(..)
1831             | ExprKind::Ret(..)
1832             | ExprKind::Let(..)
1833             | ExprKind::Loop(..)
1834             | ExprKind::Assign(..)
1835             | ExprKind::InlineAsm(..)
1836             | ExprKind::AssignOp(..)
1837             | ExprKind::ConstBlock(..)
1838             | ExprKind::Box(..)
1839             | ExprKind::Binary(..)
1840             | ExprKind::Yield(..)
1841             | ExprKind::DropTemps(..)
1842             | ExprKind::Err => true,
1843         }
1844     }
1845
1846     /// To a first-order approximation, is this a pattern?
1847     pub fn is_approximately_pattern(&self) -> bool {
1848         match &self.kind {
1849             ExprKind::Box(_)
1850             | ExprKind::Array(_)
1851             | ExprKind::Call(..)
1852             | ExprKind::Tup(_)
1853             | ExprKind::Lit(_)
1854             | ExprKind::Path(_)
1855             | ExprKind::Struct(..) => true,
1856             _ => false,
1857         }
1858     }
1859
1860     pub fn method_ident(&self) -> Option<Ident> {
1861         match self.kind {
1862             ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1863             ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1864             _ => None,
1865         }
1866     }
1867 }
1868
1869 /// Checks if the specified expression is a built-in range literal.
1870 /// (See: `LoweringContext::lower_expr()`).
1871 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1872     match expr.kind {
1873         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1874         ExprKind::Struct(ref qpath, _, _) => matches!(
1875             **qpath,
1876             QPath::LangItem(
1877                 LangItem::Range
1878                     | LangItem::RangeTo
1879                     | LangItem::RangeFrom
1880                     | LangItem::RangeFull
1881                     | LangItem::RangeToInclusive,
1882                 ..
1883             )
1884         ),
1885
1886         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1887         ExprKind::Call(ref func, _) => {
1888             matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1889         }
1890
1891         _ => false,
1892     }
1893 }
1894
1895 #[derive(Debug, HashStable_Generic)]
1896 pub enum ExprKind<'hir> {
1897     /// A `box x` expression.
1898     Box(&'hir Expr<'hir>),
1899     /// Allow anonymous constants from an inline `const` block
1900     ConstBlock(AnonConst),
1901     /// An array (e.g., `[a, b, c, d]`).
1902     Array(&'hir [Expr<'hir>]),
1903     /// A function call.
1904     ///
1905     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1906     /// and the second field is the list of arguments.
1907     /// This also represents calling the constructor of
1908     /// tuple-like ADTs such as tuple structs and enum variants.
1909     Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1910     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1911     ///
1912     /// The `PathSegment` represents the method name and its generic arguments
1913     /// (within the angle brackets).
1914     /// The `&Expr` is the expression that evaluates
1915     /// to the object on which the method is being called on (the receiver),
1916     /// and the `&[Expr]` is the rest of the arguments.
1917     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1918     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1919     /// The final `Span` represents the span of the function and arguments
1920     /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1921     ///
1922     /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1923     /// the `hir_id` of the `MethodCall` node itself.
1924     ///
1925     /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1926     MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1927     /// A tuple (e.g., `(a, b, c, d)`).
1928     Tup(&'hir [Expr<'hir>]),
1929     /// A binary operation (e.g., `a + b`, `a * b`).
1930     Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1931     /// A unary operation (e.g., `!x`, `*x`).
1932     Unary(UnOp, &'hir Expr<'hir>),
1933     /// A literal (e.g., `1`, `"foo"`).
1934     Lit(Lit),
1935     /// A cast (e.g., `foo as f64`).
1936     Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1937     /// A type reference (e.g., `Foo`).
1938     Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1939     /// Wraps the expression in a terminating scope.
1940     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1941     ///
1942     /// This construct only exists to tweak the drop order in HIR lowering.
1943     /// An example of that is the desugaring of `for` loops.
1944     DropTemps(&'hir Expr<'hir>),
1945     /// A `let $pat = $expr` expression.
1946     ///
1947     /// These are not `Local` and only occur as expressions.
1948     /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1949     Let(&'hir Let<'hir>),
1950     /// An `if` block, with an optional else block.
1951     ///
1952     /// I.e., `if <expr> { <expr> } else { <expr> }`.
1953     If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1954     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1955     ///
1956     /// I.e., `'label: loop { <block> }`.
1957     ///
1958     /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1959     Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1960     /// A `match` block, with a source that indicates whether or not it is
1961     /// the result of a desugaring, and if so, which kind.
1962     Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1963     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1964     ///
1965     /// The `Span` is the argument block `|...|`.
1966     ///
1967     /// This may also be a generator literal or an `async block` as indicated by the
1968     /// `Option<Movability>`.
1969     Closure(&'hir Closure<'hir>),
1970     /// A block (e.g., `'label: { ... }`).
1971     Block(&'hir Block<'hir>, Option<Label>),
1972
1973     /// An assignment (e.g., `a = foo()`).
1974     Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1975     /// An assignment with an operator.
1976     ///
1977     /// E.g., `a += 1`.
1978     AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1979     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1980     Field(&'hir Expr<'hir>, Ident),
1981     /// An indexing operation (`foo[2]`).
1982     Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1983
1984     /// Path to a definition, possibly containing lifetime or type parameters.
1985     Path(QPath<'hir>),
1986
1987     /// A referencing operation (i.e., `&a` or `&mut a`).
1988     AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1989     /// A `break`, with an optional label to break.
1990     Break(Destination, Option<&'hir Expr<'hir>>),
1991     /// A `continue`, with an optional label.
1992     Continue(Destination),
1993     /// A `return`, with an optional value to be returned.
1994     Ret(Option<&'hir Expr<'hir>>),
1995
1996     /// Inline assembly (from `asm!`), with its outputs and inputs.
1997     InlineAsm(&'hir InlineAsm<'hir>),
1998
1999     /// A struct or struct-like variant literal expression.
2000     ///
2001     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2002     /// where `base` is the `Option<Expr>`.
2003     Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
2004
2005     /// An array literal constructed from one repeated element.
2006     ///
2007     /// E.g., `[1; 5]`. The first expression is the element
2008     /// to be repeated; the second is the number of times to repeat it.
2009     Repeat(&'hir Expr<'hir>, ArrayLen),
2010
2011     /// A suspension point for generators (i.e., `yield <expr>`).
2012     Yield(&'hir Expr<'hir>, YieldSource),
2013
2014     /// A placeholder for an expression that wasn't syntactically well formed in some way.
2015     Err,
2016 }
2017
2018 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2019 ///
2020 /// To resolve the path to a `DefId`, call [`qpath_res`].
2021 ///
2022 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2023 #[derive(Debug, HashStable_Generic)]
2024 pub enum QPath<'hir> {
2025     /// Path to a definition, optionally "fully-qualified" with a `Self`
2026     /// type, if the path points to an associated item in a trait.
2027     ///
2028     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2029     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2030     /// even though they both have the same two-segment `Clone::clone` `Path`.
2031     Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2032
2033     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2034     /// Will be resolved by type-checking to an associated item.
2035     ///
2036     /// UFCS source paths can desugar into this, with `Vec::new` turning into
2037     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2038     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2039     TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2040
2041     /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2042     LangItem(LangItem, Span, Option<HirId>),
2043 }
2044
2045 impl<'hir> QPath<'hir> {
2046     /// Returns the span of this `QPath`.
2047     pub fn span(&self) -> Span {
2048         match *self {
2049             QPath::Resolved(_, path) => path.span,
2050             QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2051             QPath::LangItem(_, span, _) => span,
2052         }
2053     }
2054
2055     /// Returns the span of the qself of this `QPath`. For example, `()` in
2056     /// `<() as Trait>::method`.
2057     pub fn qself_span(&self) -> Span {
2058         match *self {
2059             QPath::Resolved(_, path) => path.span,
2060             QPath::TypeRelative(qself, _) => qself.span,
2061             QPath::LangItem(_, span, _) => span,
2062         }
2063     }
2064
2065     /// Returns the span of the last segment of this `QPath`. For example, `method` in
2066     /// `<() as Trait>::method`.
2067     pub fn last_segment_span(&self) -> Span {
2068         match *self {
2069             QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2070             QPath::TypeRelative(_, segment) => segment.ident.span,
2071             QPath::LangItem(_, span, _) => span,
2072         }
2073     }
2074 }
2075
2076 /// Hints at the original code for a let statement.
2077 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2078 pub enum LocalSource {
2079     /// A `match _ { .. }`.
2080     Normal,
2081     /// When lowering async functions, we create locals within the `async move` so that
2082     /// all parameters are dropped after the future is polled.
2083     ///
2084     /// ```ignore (pseudo-Rust)
2085     /// async fn foo(<pattern> @ x: Type) {
2086     ///     async move {
2087     ///         let <pattern> = x;
2088     ///     }
2089     /// }
2090     /// ```
2091     AsyncFn,
2092     /// A desugared `<expr>.await`.
2093     AwaitDesugar,
2094     /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2095     /// The span is that of the `=` sign.
2096     AssignDesugar(Span),
2097 }
2098
2099 /// Hints at the original code for a `match _ { .. }`.
2100 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2101 #[derive(HashStable_Generic)]
2102 pub enum MatchSource {
2103     /// A `match _ { .. }`.
2104     Normal,
2105     /// A desugared `for _ in _ { .. }` loop.
2106     ForLoopDesugar,
2107     /// A desugared `?` operator.
2108     TryDesugar,
2109     /// A desugared `<expr>.await`.
2110     AwaitDesugar,
2111 }
2112
2113 impl MatchSource {
2114     #[inline]
2115     pub const fn name(self) -> &'static str {
2116         use MatchSource::*;
2117         match self {
2118             Normal => "match",
2119             ForLoopDesugar => "for",
2120             TryDesugar => "?",
2121             AwaitDesugar => ".await",
2122         }
2123     }
2124 }
2125
2126 /// The loop type that yielded an `ExprKind::Loop`.
2127 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2128 pub enum LoopSource {
2129     /// A `loop { .. }` loop.
2130     Loop,
2131     /// A `while _ { .. }` loop.
2132     While,
2133     /// A `for _ in _ { .. }` loop.
2134     ForLoop,
2135 }
2136
2137 impl LoopSource {
2138     pub fn name(self) -> &'static str {
2139         match self {
2140             LoopSource::Loop => "loop",
2141             LoopSource::While => "while",
2142             LoopSource::ForLoop => "for",
2143         }
2144     }
2145 }
2146
2147 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2148 pub enum LoopIdError {
2149     OutsideLoopScope,
2150     UnlabeledCfInWhileCondition,
2151     UnresolvedLabel,
2152 }
2153
2154 impl fmt::Display for LoopIdError {
2155     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2156         f.write_str(match self {
2157             LoopIdError::OutsideLoopScope => "not inside loop scope",
2158             LoopIdError::UnlabeledCfInWhileCondition => {
2159                 "unlabeled control flow (break or continue) in while condition"
2160             }
2161             LoopIdError::UnresolvedLabel => "label not found",
2162         })
2163     }
2164 }
2165
2166 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2167 pub struct Destination {
2168     /// This is `Some(_)` iff there is an explicit user-specified 'label
2169     pub label: Option<Label>,
2170
2171     /// These errors are caught and then reported during the diagnostics pass in
2172     /// `librustc_passes/loops.rs`
2173     pub target_id: Result<HirId, LoopIdError>,
2174 }
2175
2176 /// The yield kind that caused an `ExprKind::Yield`.
2177 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2178 pub enum YieldSource {
2179     /// An `<expr>.await`.
2180     Await { expr: Option<HirId> },
2181     /// A plain `yield`.
2182     Yield,
2183 }
2184
2185 impl YieldSource {
2186     pub fn is_await(&self) -> bool {
2187         matches!(self, YieldSource::Await { .. })
2188     }
2189 }
2190
2191 impl fmt::Display for YieldSource {
2192     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2193         f.write_str(match self {
2194             YieldSource::Await { .. } => "`await`",
2195             YieldSource::Yield => "`yield`",
2196         })
2197     }
2198 }
2199
2200 impl From<GeneratorKind> for YieldSource {
2201     fn from(kind: GeneratorKind) -> Self {
2202         match kind {
2203             // Guess based on the kind of the current generator.
2204             GeneratorKind::Gen => Self::Yield,
2205             GeneratorKind::Async(_) => Self::Await { expr: None },
2206         }
2207     }
2208 }
2209
2210 // N.B., if you change this, you'll probably want to change the corresponding
2211 // type structure in middle/ty.rs as well.
2212 #[derive(Debug, HashStable_Generic)]
2213 pub struct MutTy<'hir> {
2214     pub ty: &'hir Ty<'hir>,
2215     pub mutbl: Mutability,
2216 }
2217
2218 /// Represents a function's signature in a trait declaration,
2219 /// trait implementation, or a free function.
2220 #[derive(Debug, HashStable_Generic)]
2221 pub struct FnSig<'hir> {
2222     pub header: FnHeader,
2223     pub decl: &'hir FnDecl<'hir>,
2224     pub span: Span,
2225 }
2226
2227 // The bodies for items are stored "out of line", in a separate
2228 // hashmap in the `Crate`. Here we just record the hir-id of the item
2229 // so it can fetched later.
2230 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2231 pub struct TraitItemId {
2232     pub owner_id: OwnerId,
2233 }
2234
2235 impl TraitItemId {
2236     #[inline]
2237     pub fn hir_id(&self) -> HirId {
2238         // Items are always HIR owners.
2239         HirId::make_owner(self.owner_id.def_id)
2240     }
2241 }
2242
2243 /// Represents an item declaration within a trait declaration,
2244 /// possibly including a default implementation. A trait item is
2245 /// either required (meaning it doesn't have an implementation, just a
2246 /// signature) or provided (meaning it has a default implementation).
2247 #[derive(Debug, HashStable_Generic)]
2248 pub struct TraitItem<'hir> {
2249     pub ident: Ident,
2250     pub owner_id: OwnerId,
2251     pub generics: &'hir Generics<'hir>,
2252     pub kind: TraitItemKind<'hir>,
2253     pub span: Span,
2254     pub defaultness: Defaultness,
2255 }
2256
2257 impl TraitItem<'_> {
2258     #[inline]
2259     pub fn hir_id(&self) -> HirId {
2260         // Items are always HIR owners.
2261         HirId::make_owner(self.owner_id.def_id)
2262     }
2263
2264     pub fn trait_item_id(&self) -> TraitItemId {
2265         TraitItemId { owner_id: self.owner_id }
2266     }
2267 }
2268
2269 /// Represents a trait method's body (or just argument names).
2270 #[derive(Encodable, Debug, HashStable_Generic)]
2271 pub enum TraitFn<'hir> {
2272     /// No default body in the trait, just a signature.
2273     Required(&'hir [Ident]),
2274
2275     /// Both signature and body are provided in the trait.
2276     Provided(BodyId),
2277 }
2278
2279 /// Represents a trait method or associated constant or type
2280 #[derive(Debug, HashStable_Generic)]
2281 pub enum TraitItemKind<'hir> {
2282     /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2283     Const(&'hir Ty<'hir>, Option<BodyId>),
2284     /// An associated function with an optional body.
2285     Fn(FnSig<'hir>, TraitFn<'hir>),
2286     /// An associated type with (possibly empty) bounds and optional concrete
2287     /// type.
2288     Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2289 }
2290
2291 // The bodies for items are stored "out of line", in a separate
2292 // hashmap in the `Crate`. Here we just record the hir-id of the item
2293 // so it can fetched later.
2294 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2295 pub struct ImplItemId {
2296     pub owner_id: OwnerId,
2297 }
2298
2299 impl ImplItemId {
2300     #[inline]
2301     pub fn hir_id(&self) -> HirId {
2302         // Items are always HIR owners.
2303         HirId::make_owner(self.owner_id.def_id)
2304     }
2305 }
2306
2307 /// Represents anything within an `impl` block.
2308 #[derive(Debug, HashStable_Generic)]
2309 pub struct ImplItem<'hir> {
2310     pub ident: Ident,
2311     pub owner_id: OwnerId,
2312     pub generics: &'hir Generics<'hir>,
2313     pub kind: ImplItemKind<'hir>,
2314     pub defaultness: Defaultness,
2315     pub span: Span,
2316     pub vis_span: Span,
2317 }
2318
2319 impl ImplItem<'_> {
2320     #[inline]
2321     pub fn hir_id(&self) -> HirId {
2322         // Items are always HIR owners.
2323         HirId::make_owner(self.owner_id.def_id)
2324     }
2325
2326     pub fn impl_item_id(&self) -> ImplItemId {
2327         ImplItemId { owner_id: self.owner_id }
2328     }
2329 }
2330
2331 /// Represents various kinds of content within an `impl`.
2332 #[derive(Debug, HashStable_Generic)]
2333 pub enum ImplItemKind<'hir> {
2334     /// An associated constant of the given type, set to the constant result
2335     /// of the expression.
2336     Const(&'hir Ty<'hir>, BodyId),
2337     /// An associated function implementation with the given signature and body.
2338     Fn(FnSig<'hir>, BodyId),
2339     /// An associated type.
2340     Type(&'hir Ty<'hir>),
2341 }
2342
2343 /// The name of the associated type for `Fn` return types.
2344 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2345
2346 /// Bind a type to an associated type (i.e., `A = Foo`).
2347 ///
2348 /// Bindings like `A: Debug` are represented as a special type `A =
2349 /// $::Debug` that is understood by the astconv code.
2350 ///
2351 /// FIXME(alexreg): why have a separate type for the binding case,
2352 /// wouldn't it be better to make the `ty` field an enum like the
2353 /// following?
2354 ///
2355 /// ```ignore (pseudo-rust)
2356 /// enum TypeBindingKind {
2357 ///    Equals(...),
2358 ///    Binding(...),
2359 /// }
2360 /// ```
2361 #[derive(Debug, HashStable_Generic)]
2362 pub struct TypeBinding<'hir> {
2363     pub hir_id: HirId,
2364     pub ident: Ident,
2365     pub gen_args: &'hir GenericArgs<'hir>,
2366     pub kind: TypeBindingKind<'hir>,
2367     pub span: Span,
2368 }
2369
2370 #[derive(Debug, HashStable_Generic)]
2371 pub enum Term<'hir> {
2372     Ty(&'hir Ty<'hir>),
2373     Const(AnonConst),
2374 }
2375
2376 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2377     fn from(ty: &'hir Ty<'hir>) -> Self {
2378         Term::Ty(ty)
2379     }
2380 }
2381
2382 impl<'hir> From<AnonConst> for Term<'hir> {
2383     fn from(c: AnonConst) -> Self {
2384         Term::Const(c)
2385     }
2386 }
2387
2388 // Represents the two kinds of type bindings.
2389 #[derive(Debug, HashStable_Generic)]
2390 pub enum TypeBindingKind<'hir> {
2391     /// E.g., `Foo<Bar: Send>`.
2392     Constraint { bounds: &'hir [GenericBound<'hir>] },
2393     /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2394     Equality { term: Term<'hir> },
2395 }
2396
2397 impl TypeBinding<'_> {
2398     pub fn ty(&self) -> &Ty<'_> {
2399         match self.kind {
2400             TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2401             _ => panic!("expected equality type binding for parenthesized generic args"),
2402         }
2403     }
2404     pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2405         match self.kind {
2406             TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2407             _ => None,
2408         }
2409     }
2410 }
2411
2412 #[derive(Debug, HashStable_Generic)]
2413 pub struct Ty<'hir> {
2414     pub hir_id: HirId,
2415     pub kind: TyKind<'hir>,
2416     pub span: Span,
2417 }
2418
2419 impl<'hir> Ty<'hir> {
2420     /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2421     pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2422         let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2423             return None;
2424         };
2425         let [segment] = &path.segments else {
2426             return None;
2427         };
2428         match path.res {
2429             Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2430                 Some((def_id, segment.ident))
2431             }
2432             _ => None,
2433         }
2434     }
2435
2436     pub fn peel_refs(&self) -> &Self {
2437         let mut final_ty = self;
2438         while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
2439             final_ty = ty;
2440         }
2441         final_ty
2442     }
2443
2444     pub fn find_self_aliases(&self) -> Vec<Span> {
2445         use crate::intravisit::Visitor;
2446         struct MyVisitor(Vec<Span>);
2447         impl<'v> Visitor<'v> for MyVisitor {
2448             fn visit_ty(&mut self, t: &'v Ty<'v>) {
2449                 if matches!(
2450                     &t.kind,
2451                     TyKind::Path(QPath::Resolved(
2452                         _,
2453                         Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2454                     ))
2455                 ) {
2456                     self.0.push(t.span);
2457                     return;
2458                 }
2459                 crate::intravisit::walk_ty(self, t);
2460             }
2461         }
2462
2463         let mut my_visitor = MyVisitor(vec![]);
2464         my_visitor.visit_ty(self);
2465         my_visitor.0
2466     }
2467 }
2468
2469 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2470 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2471 #[derive(HashStable_Generic)]
2472 pub enum PrimTy {
2473     Int(IntTy),
2474     Uint(UintTy),
2475     Float(FloatTy),
2476     Str,
2477     Bool,
2478     Char,
2479 }
2480
2481 impl PrimTy {
2482     /// All of the primitive types
2483     pub const ALL: [Self; 17] = [
2484         // any changes here should also be reflected in `PrimTy::from_name`
2485         Self::Int(IntTy::I8),
2486         Self::Int(IntTy::I16),
2487         Self::Int(IntTy::I32),
2488         Self::Int(IntTy::I64),
2489         Self::Int(IntTy::I128),
2490         Self::Int(IntTy::Isize),
2491         Self::Uint(UintTy::U8),
2492         Self::Uint(UintTy::U16),
2493         Self::Uint(UintTy::U32),
2494         Self::Uint(UintTy::U64),
2495         Self::Uint(UintTy::U128),
2496         Self::Uint(UintTy::Usize),
2497         Self::Float(FloatTy::F32),
2498         Self::Float(FloatTy::F64),
2499         Self::Bool,
2500         Self::Char,
2501         Self::Str,
2502     ];
2503
2504     /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2505     ///
2506     /// Used by clippy.
2507     pub fn name_str(self) -> &'static str {
2508         match self {
2509             PrimTy::Int(i) => i.name_str(),
2510             PrimTy::Uint(u) => u.name_str(),
2511             PrimTy::Float(f) => f.name_str(),
2512             PrimTy::Str => "str",
2513             PrimTy::Bool => "bool",
2514             PrimTy::Char => "char",
2515         }
2516     }
2517
2518     pub fn name(self) -> Symbol {
2519         match self {
2520             PrimTy::Int(i) => i.name(),
2521             PrimTy::Uint(u) => u.name(),
2522             PrimTy::Float(f) => f.name(),
2523             PrimTy::Str => sym::str,
2524             PrimTy::Bool => sym::bool,
2525             PrimTy::Char => sym::char,
2526         }
2527     }
2528
2529     /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2530     /// Returns `None` if no matching type is found.
2531     pub fn from_name(name: Symbol) -> Option<Self> {
2532         let ty = match name {
2533             // any changes here should also be reflected in `PrimTy::ALL`
2534             sym::i8 => Self::Int(IntTy::I8),
2535             sym::i16 => Self::Int(IntTy::I16),
2536             sym::i32 => Self::Int(IntTy::I32),
2537             sym::i64 => Self::Int(IntTy::I64),
2538             sym::i128 => Self::Int(IntTy::I128),
2539             sym::isize => Self::Int(IntTy::Isize),
2540             sym::u8 => Self::Uint(UintTy::U8),
2541             sym::u16 => Self::Uint(UintTy::U16),
2542             sym::u32 => Self::Uint(UintTy::U32),
2543             sym::u64 => Self::Uint(UintTy::U64),
2544             sym::u128 => Self::Uint(UintTy::U128),
2545             sym::usize => Self::Uint(UintTy::Usize),
2546             sym::f32 => Self::Float(FloatTy::F32),
2547             sym::f64 => Self::Float(FloatTy::F64),
2548             sym::bool => Self::Bool,
2549             sym::char => Self::Char,
2550             sym::str => Self::Str,
2551             _ => return None,
2552         };
2553         Some(ty)
2554     }
2555 }
2556
2557 #[derive(Debug, HashStable_Generic)]
2558 pub struct BareFnTy<'hir> {
2559     pub unsafety: Unsafety,
2560     pub abi: Abi,
2561     pub generic_params: &'hir [GenericParam<'hir>],
2562     pub decl: &'hir FnDecl<'hir>,
2563     pub param_names: &'hir [Ident],
2564 }
2565
2566 #[derive(Debug, HashStable_Generic)]
2567 pub struct OpaqueTy<'hir> {
2568     pub generics: &'hir Generics<'hir>,
2569     pub bounds: GenericBounds<'hir>,
2570     pub origin: OpaqueTyOrigin,
2571     pub in_trait: bool,
2572 }
2573
2574 /// From whence the opaque type came.
2575 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2576 pub enum OpaqueTyOrigin {
2577     /// `-> impl Trait`
2578     FnReturn(LocalDefId),
2579     /// `async fn`
2580     AsyncFn(LocalDefId),
2581     /// type aliases: `type Foo = impl Trait;`
2582     TyAlias,
2583 }
2584
2585 /// The various kinds of types recognized by the compiler.
2586 #[derive(Debug, HashStable_Generic)]
2587 pub enum TyKind<'hir> {
2588     /// A variable length slice (i.e., `[T]`).
2589     Slice(&'hir Ty<'hir>),
2590     /// A fixed length array (i.e., `[T; n]`).
2591     Array(&'hir Ty<'hir>, ArrayLen),
2592     /// A raw pointer (i.e., `*const T` or `*mut T`).
2593     Ptr(MutTy<'hir>),
2594     /// A reference (i.e., `&'a T` or `&'a mut T`).
2595     Ref(&'hir Lifetime, MutTy<'hir>),
2596     /// A bare function (e.g., `fn(usize) -> bool`).
2597     BareFn(&'hir BareFnTy<'hir>),
2598     /// The never type (`!`).
2599     Never,
2600     /// A tuple (`(A, B, C, D, ...)`).
2601     Tup(&'hir [Ty<'hir>]),
2602     /// A path to a type definition (`module::module::...::Type`), or an
2603     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2604     ///
2605     /// Type parameters may be stored in each `PathSegment`.
2606     Path(QPath<'hir>),
2607     /// An opaque type definition itself. This is only used for `impl Trait`.
2608     ///
2609     /// The generic argument list contains the lifetimes (and in the future
2610     /// possibly parameters) that are actually bound on the `impl Trait`.
2611     ///
2612     /// The last parameter specifies whether this opaque appears in a trait definition.
2613     OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2614     /// A trait object type `Bound1 + Bound2 + Bound3`
2615     /// where `Bound` is a trait or a lifetime.
2616     TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2617     /// Unused for now.
2618     Typeof(AnonConst),
2619     /// `TyKind::Infer` means the type should be inferred instead of it having been
2620     /// specified. This can appear anywhere in a type.
2621     Infer,
2622     /// Placeholder for a type that has failed to be defined.
2623     Err,
2624 }
2625
2626 #[derive(Debug, HashStable_Generic)]
2627 pub enum InlineAsmOperand<'hir> {
2628     In {
2629         reg: InlineAsmRegOrRegClass,
2630         expr: &'hir Expr<'hir>,
2631     },
2632     Out {
2633         reg: InlineAsmRegOrRegClass,
2634         late: bool,
2635         expr: Option<&'hir Expr<'hir>>,
2636     },
2637     InOut {
2638         reg: InlineAsmRegOrRegClass,
2639         late: bool,
2640         expr: &'hir Expr<'hir>,
2641     },
2642     SplitInOut {
2643         reg: InlineAsmRegOrRegClass,
2644         late: bool,
2645         in_expr: &'hir Expr<'hir>,
2646         out_expr: Option<&'hir Expr<'hir>>,
2647     },
2648     Const {
2649         anon_const: AnonConst,
2650     },
2651     SymFn {
2652         anon_const: AnonConst,
2653     },
2654     SymStatic {
2655         path: QPath<'hir>,
2656         def_id: DefId,
2657     },
2658 }
2659
2660 impl<'hir> InlineAsmOperand<'hir> {
2661     pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2662         match *self {
2663             Self::In { reg, .. }
2664             | Self::Out { reg, .. }
2665             | Self::InOut { reg, .. }
2666             | Self::SplitInOut { reg, .. } => Some(reg),
2667             Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2668         }
2669     }
2670
2671     pub fn is_clobber(&self) -> bool {
2672         matches!(
2673             self,
2674             InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2675         )
2676     }
2677 }
2678
2679 #[derive(Debug, HashStable_Generic)]
2680 pub struct InlineAsm<'hir> {
2681     pub template: &'hir [InlineAsmTemplatePiece],
2682     pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2683     pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2684     pub options: InlineAsmOptions,
2685     pub line_spans: &'hir [Span],
2686 }
2687
2688 /// Represents a parameter in a function header.
2689 #[derive(Debug, HashStable_Generic)]
2690 pub struct Param<'hir> {
2691     pub hir_id: HirId,
2692     pub pat: &'hir Pat<'hir>,
2693     pub ty_span: Span,
2694     pub span: Span,
2695 }
2696
2697 /// Represents the header (not the body) of a function declaration.
2698 #[derive(Debug, HashStable_Generic)]
2699 pub struct FnDecl<'hir> {
2700     /// The types of the function's parameters.
2701     ///
2702     /// Additional argument data is stored in the function's [body](Body::params).
2703     pub inputs: &'hir [Ty<'hir>],
2704     pub output: FnRetTy<'hir>,
2705     pub c_variadic: bool,
2706     /// Does the function have an implicit self?
2707     pub implicit_self: ImplicitSelfKind,
2708     /// Is lifetime elision allowed.
2709     pub lifetime_elision_allowed: bool,
2710 }
2711
2712 /// Represents what type of implicit self a function has, if any.
2713 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2714 pub enum ImplicitSelfKind {
2715     /// Represents a `fn x(self);`.
2716     Imm,
2717     /// Represents a `fn x(mut self);`.
2718     Mut,
2719     /// Represents a `fn x(&self);`.
2720     ImmRef,
2721     /// Represents a `fn x(&mut self);`.
2722     MutRef,
2723     /// Represents when a function does not have a self argument or
2724     /// when a function has a `self: X` argument.
2725     None,
2726 }
2727
2728 impl ImplicitSelfKind {
2729     /// Does this represent an implicit self?
2730     pub fn has_implicit_self(&self) -> bool {
2731         !matches!(*self, ImplicitSelfKind::None)
2732     }
2733 }
2734
2735 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2736 #[derive(HashStable_Generic)]
2737 pub enum IsAsync {
2738     Async,
2739     NotAsync,
2740 }
2741
2742 impl IsAsync {
2743     pub fn is_async(self) -> bool {
2744         self == IsAsync::Async
2745     }
2746 }
2747
2748 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2749 pub enum Defaultness {
2750     Default { has_value: bool },
2751     Final,
2752 }
2753
2754 impl Defaultness {
2755     pub fn has_value(&self) -> bool {
2756         match *self {
2757             Defaultness::Default { has_value } => has_value,
2758             Defaultness::Final => true,
2759         }
2760     }
2761
2762     pub fn is_final(&self) -> bool {
2763         *self == Defaultness::Final
2764     }
2765
2766     pub fn is_default(&self) -> bool {
2767         matches!(*self, Defaultness::Default { .. })
2768     }
2769 }
2770
2771 #[derive(Debug, HashStable_Generic)]
2772 pub enum FnRetTy<'hir> {
2773     /// Return type is not specified.
2774     ///
2775     /// Functions default to `()` and
2776     /// closures default to inference. Span points to where return
2777     /// type would be inserted.
2778     DefaultReturn(Span),
2779     /// Everything else.
2780     Return(&'hir Ty<'hir>),
2781 }
2782
2783 impl FnRetTy<'_> {
2784     #[inline]
2785     pub fn span(&self) -> Span {
2786         match *self {
2787             Self::DefaultReturn(span) => span,
2788             Self::Return(ref ty) => ty.span,
2789         }
2790     }
2791 }
2792
2793 /// Represents `for<...>` binder before a closure
2794 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2795 pub enum ClosureBinder {
2796     /// Binder is not specified.
2797     Default,
2798     /// Binder is specified.
2799     ///
2800     /// Span points to the whole `for<...>`.
2801     For { span: Span },
2802 }
2803
2804 #[derive(Encodable, Debug, HashStable_Generic)]
2805 pub struct Mod<'hir> {
2806     pub spans: ModSpans,
2807     pub item_ids: &'hir [ItemId],
2808 }
2809
2810 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2811 pub struct ModSpans {
2812     /// A span from the first token past `{` to the last token until `}`.
2813     /// For `mod foo;`, the inner span ranges from the first token
2814     /// to the last token in the external file.
2815     pub inner_span: Span,
2816     pub inject_use_span: Span,
2817 }
2818
2819 #[derive(Debug, HashStable_Generic)]
2820 pub struct EnumDef<'hir> {
2821     pub variants: &'hir [Variant<'hir>],
2822 }
2823
2824 #[derive(Debug, HashStable_Generic)]
2825 pub struct Variant<'hir> {
2826     /// Name of the variant.
2827     pub ident: Ident,
2828     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2829     pub hir_id: HirId,
2830     pub def_id: LocalDefId,
2831     /// Fields and constructor id of the variant.
2832     pub data: VariantData<'hir>,
2833     /// Explicit discriminant (e.g., `Foo = 1`).
2834     pub disr_expr: Option<AnonConst>,
2835     /// Span
2836     pub span: Span,
2837 }
2838
2839 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2840 pub enum UseKind {
2841     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2842     /// Also produced for each element of a list `use`, e.g.
2843     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2844     Single,
2845
2846     /// Glob import, e.g., `use foo::*`.
2847     Glob,
2848
2849     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2850     /// an additional `use foo::{}` for performing checks such as
2851     /// unstable feature gating. May be removed in the future.
2852     ListStem,
2853 }
2854
2855 /// References to traits in impls.
2856 ///
2857 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2858 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2859 /// trait being referred to but just a unique `HirId` that serves as a key
2860 /// within the resolution map.
2861 #[derive(Clone, Debug, HashStable_Generic)]
2862 pub struct TraitRef<'hir> {
2863     pub path: &'hir Path<'hir>,
2864     // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2865     #[stable_hasher(ignore)]
2866     pub hir_ref_id: HirId,
2867 }
2868
2869 impl TraitRef<'_> {
2870     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2871     pub fn trait_def_id(&self) -> Option<DefId> {
2872         match self.path.res {
2873             Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2874             Res::Err => None,
2875             _ => unreachable!(),
2876         }
2877     }
2878 }
2879
2880 #[derive(Clone, Debug, HashStable_Generic)]
2881 pub struct PolyTraitRef<'hir> {
2882     /// The `'a` in `for<'a> Foo<&'a T>`.
2883     pub bound_generic_params: &'hir [GenericParam<'hir>],
2884
2885     /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2886     pub trait_ref: TraitRef<'hir>,
2887
2888     pub span: Span,
2889 }
2890
2891 #[derive(Debug, HashStable_Generic)]
2892 pub struct FieldDef<'hir> {
2893     pub span: Span,
2894     pub vis_span: Span,
2895     pub ident: Ident,
2896     pub hir_id: HirId,
2897     pub def_id: LocalDefId,
2898     pub ty: &'hir Ty<'hir>,
2899 }
2900
2901 impl FieldDef<'_> {
2902     // Still necessary in couple of places
2903     pub fn is_positional(&self) -> bool {
2904         let first = self.ident.as_str().as_bytes()[0];
2905         (b'0'..=b'9').contains(&first)
2906     }
2907 }
2908
2909 /// Fields and constructor IDs of enum variants and structs.
2910 #[derive(Debug, HashStable_Generic)]
2911 pub enum VariantData<'hir> {
2912     /// A struct variant.
2913     ///
2914     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2915     Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2916     /// A tuple variant.
2917     ///
2918     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2919     Tuple(&'hir [FieldDef<'hir>], HirId, LocalDefId),
2920     /// A unit variant.
2921     ///
2922     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2923     Unit(HirId, LocalDefId),
2924 }
2925
2926 impl<'hir> VariantData<'hir> {
2927     /// Return the fields of this variant.
2928     pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2929         match *self {
2930             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2931             _ => &[],
2932         }
2933     }
2934
2935     pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
2936         match *self {
2937             VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
2938             VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
2939             VariantData::Struct(..) => None,
2940         }
2941     }
2942
2943     #[inline]
2944     pub fn ctor_kind(&self) -> Option<CtorKind> {
2945         self.ctor().map(|(kind, ..)| kind)
2946     }
2947
2948     /// Return the `HirId` of this variant's constructor, if it has one.
2949     #[inline]
2950     pub fn ctor_hir_id(&self) -> Option<HirId> {
2951         self.ctor().map(|(_, hir_id, _)| hir_id)
2952     }
2953
2954     /// Return the `LocalDefId` of this variant's constructor, if it has one.
2955     #[inline]
2956     pub fn ctor_def_id(&self) -> Option<LocalDefId> {
2957         self.ctor().map(|(.., def_id)| def_id)
2958     }
2959 }
2960
2961 // The bodies for items are stored "out of line", in a separate
2962 // hashmap in the `Crate`. Here we just record the hir-id of the item
2963 // so it can fetched later.
2964 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2965 pub struct ItemId {
2966     pub owner_id: OwnerId,
2967 }
2968
2969 impl ItemId {
2970     #[inline]
2971     pub fn hir_id(&self) -> HirId {
2972         // Items are always HIR owners.
2973         HirId::make_owner(self.owner_id.def_id)
2974     }
2975 }
2976
2977 /// An item
2978 ///
2979 /// The name might be a dummy name in case of anonymous items
2980 #[derive(Debug, HashStable_Generic)]
2981 pub struct Item<'hir> {
2982     pub ident: Ident,
2983     pub owner_id: OwnerId,
2984     pub kind: ItemKind<'hir>,
2985     pub span: Span,
2986     pub vis_span: Span,
2987 }
2988
2989 impl Item<'_> {
2990     #[inline]
2991     pub fn hir_id(&self) -> HirId {
2992         // Items are always HIR owners.
2993         HirId::make_owner(self.owner_id.def_id)
2994     }
2995
2996     pub fn item_id(&self) -> ItemId {
2997         ItemId { owner_id: self.owner_id }
2998     }
2999 }
3000
3001 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3002 #[derive(Encodable, Decodable, HashStable_Generic)]
3003 pub enum Unsafety {
3004     Unsafe,
3005     Normal,
3006 }
3007
3008 impl Unsafety {
3009     pub fn prefix_str(&self) -> &'static str {
3010         match self {
3011             Self::Unsafe => "unsafe ",
3012             Self::Normal => "",
3013         }
3014     }
3015 }
3016
3017 impl fmt::Display for Unsafety {
3018     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3019         f.write_str(match *self {
3020             Self::Unsafe => "unsafe",
3021             Self::Normal => "normal",
3022         })
3023     }
3024 }
3025
3026 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3027 #[derive(Encodable, Decodable, HashStable_Generic)]
3028 pub enum Constness {
3029     Const,
3030     NotConst,
3031 }
3032
3033 impl fmt::Display for Constness {
3034     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3035         f.write_str(match *self {
3036             Self::Const => "const",
3037             Self::NotConst => "non-const",
3038         })
3039     }
3040 }
3041
3042 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
3043 pub struct FnHeader {
3044     pub unsafety: Unsafety,
3045     pub constness: Constness,
3046     pub asyncness: IsAsync,
3047     pub abi: Abi,
3048 }
3049
3050 impl FnHeader {
3051     pub fn is_async(&self) -> bool {
3052         matches!(&self.asyncness, IsAsync::Async)
3053     }
3054
3055     pub fn is_const(&self) -> bool {
3056         matches!(&self.constness, Constness::Const)
3057     }
3058
3059     pub fn is_unsafe(&self) -> bool {
3060         matches!(&self.unsafety, Unsafety::Unsafe)
3061     }
3062 }
3063
3064 #[derive(Debug, HashStable_Generic)]
3065 pub enum ItemKind<'hir> {
3066     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3067     ///
3068     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3069     ExternCrate(Option<Symbol>),
3070
3071     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3072     ///
3073     /// or just
3074     ///
3075     /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3076     Use(&'hir UsePath<'hir>, UseKind),
3077
3078     /// A `static` item.
3079     Static(&'hir Ty<'hir>, Mutability, BodyId),
3080     /// A `const` item.
3081     Const(&'hir Ty<'hir>, BodyId),
3082     /// A function declaration.
3083     Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3084     /// A MBE macro definition (`macro_rules!` or `macro`).
3085     Macro(ast::MacroDef, MacroKind),
3086     /// A module.
3087     Mod(&'hir Mod<'hir>),
3088     /// An external module, e.g. `extern { .. }`.
3089     ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3090     /// Module-level inline assembly (from `global_asm!`).
3091     GlobalAsm(&'hir InlineAsm<'hir>),
3092     /// A type alias, e.g., `type Foo = Bar<u8>`.
3093     TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3094     /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3095     OpaqueTy(OpaqueTy<'hir>),
3096     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3097     Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3098     /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3099     Struct(VariantData<'hir>, &'hir Generics<'hir>),
3100     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3101     Union(VariantData<'hir>, &'hir Generics<'hir>),
3102     /// A trait definition.
3103     Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3104     /// A trait alias.
3105     TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3106
3107     /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3108     Impl(&'hir Impl<'hir>),
3109 }
3110
3111 #[derive(Debug, HashStable_Generic)]
3112 pub struct Impl<'hir> {
3113     pub unsafety: Unsafety,
3114     pub polarity: ImplPolarity,
3115     pub defaultness: Defaultness,
3116     // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3117     // decoding as `Span`s cannot be decoded when a `Session` is not available.
3118     pub defaultness_span: Option<Span>,
3119     pub constness: Constness,
3120     pub generics: &'hir Generics<'hir>,
3121
3122     /// The trait being implemented, if any.
3123     pub of_trait: Option<TraitRef<'hir>>,
3124
3125     pub self_ty: &'hir Ty<'hir>,
3126     pub items: &'hir [ImplItemRef],
3127 }
3128
3129 impl ItemKind<'_> {
3130     pub fn generics(&self) -> Option<&Generics<'_>> {
3131         Some(match *self {
3132             ItemKind::Fn(_, ref generics, _)
3133             | ItemKind::TyAlias(_, ref generics)
3134             | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3135             | ItemKind::Enum(_, ref generics)
3136             | ItemKind::Struct(_, ref generics)
3137             | ItemKind::Union(_, ref generics)
3138             | ItemKind::Trait(_, _, ref generics, _, _)
3139             | ItemKind::TraitAlias(ref generics, _)
3140             | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3141             _ => return None,
3142         })
3143     }
3144
3145     pub fn descr(&self) -> &'static str {
3146         match self {
3147             ItemKind::ExternCrate(..) => "extern crate",
3148             ItemKind::Use(..) => "`use` import",
3149             ItemKind::Static(..) => "static item",
3150             ItemKind::Const(..) => "constant item",
3151             ItemKind::Fn(..) => "function",
3152             ItemKind::Macro(..) => "macro",
3153             ItemKind::Mod(..) => "module",
3154             ItemKind::ForeignMod { .. } => "extern block",
3155             ItemKind::GlobalAsm(..) => "global asm item",
3156             ItemKind::TyAlias(..) => "type alias",
3157             ItemKind::OpaqueTy(..) => "opaque type",
3158             ItemKind::Enum(..) => "enum",
3159             ItemKind::Struct(..) => "struct",
3160             ItemKind::Union(..) => "union",
3161             ItemKind::Trait(..) => "trait",
3162             ItemKind::TraitAlias(..) => "trait alias",
3163             ItemKind::Impl(..) => "implementation",
3164         }
3165     }
3166 }
3167
3168 /// A reference from an trait to one of its associated items. This
3169 /// contains the item's id, naturally, but also the item's name and
3170 /// some other high-level details (like whether it is an associated
3171 /// type or method, and whether it is public). This allows other
3172 /// passes to find the impl they want without loading the ID (which
3173 /// means fewer edges in the incremental compilation graph).
3174 #[derive(Encodable, Debug, HashStable_Generic)]
3175 pub struct TraitItemRef {
3176     pub id: TraitItemId,
3177     pub ident: Ident,
3178     pub kind: AssocItemKind,
3179     pub span: Span,
3180 }
3181
3182 /// A reference from an impl to one of its associated items. This
3183 /// contains the item's ID, naturally, but also the item's name and
3184 /// some other high-level details (like whether it is an associated
3185 /// type or method, and whether it is public). This allows other
3186 /// passes to find the impl they want without loading the ID (which
3187 /// means fewer edges in the incremental compilation graph).
3188 #[derive(Debug, HashStable_Generic)]
3189 pub struct ImplItemRef {
3190     pub id: ImplItemId,
3191     pub ident: Ident,
3192     pub kind: AssocItemKind,
3193     pub span: Span,
3194     /// When we are in a trait impl, link to the trait-item's id.
3195     pub trait_item_def_id: Option<DefId>,
3196 }
3197
3198 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3199 pub enum AssocItemKind {
3200     Const,
3201     Fn { has_self: bool },
3202     Type,
3203 }
3204
3205 // The bodies for items are stored "out of line", in a separate
3206 // hashmap in the `Crate`. Here we just record the hir-id of the item
3207 // so it can fetched later.
3208 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3209 pub struct ForeignItemId {
3210     pub owner_id: OwnerId,
3211 }
3212
3213 impl ForeignItemId {
3214     #[inline]
3215     pub fn hir_id(&self) -> HirId {
3216         // Items are always HIR owners.
3217         HirId::make_owner(self.owner_id.def_id)
3218     }
3219 }
3220
3221 /// A reference from a foreign block to one of its items. This
3222 /// contains the item's ID, naturally, but also the item's name and
3223 /// some other high-level details (like whether it is an associated
3224 /// type or method, and whether it is public). This allows other
3225 /// passes to find the impl they want without loading the ID (which
3226 /// means fewer edges in the incremental compilation graph).
3227 #[derive(Debug, HashStable_Generic)]
3228 pub struct ForeignItemRef {
3229     pub id: ForeignItemId,
3230     pub ident: Ident,
3231     pub span: Span,
3232 }
3233
3234 #[derive(Debug, HashStable_Generic)]
3235 pub struct ForeignItem<'hir> {
3236     pub ident: Ident,
3237     pub kind: ForeignItemKind<'hir>,
3238     pub owner_id: OwnerId,
3239     pub span: Span,
3240     pub vis_span: Span,
3241 }
3242
3243 impl ForeignItem<'_> {
3244     #[inline]
3245     pub fn hir_id(&self) -> HirId {
3246         // Items are always HIR owners.
3247         HirId::make_owner(self.owner_id.def_id)
3248     }
3249
3250     pub fn foreign_item_id(&self) -> ForeignItemId {
3251         ForeignItemId { owner_id: self.owner_id }
3252     }
3253 }
3254
3255 /// An item within an `extern` block.
3256 #[derive(Debug, HashStable_Generic)]
3257 pub enum ForeignItemKind<'hir> {
3258     /// A foreign function.
3259     Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3260     /// A foreign static item (`static ext: u8`).
3261     Static(&'hir Ty<'hir>, Mutability),
3262     /// A foreign type.
3263     Type,
3264 }
3265
3266 /// A variable captured by a closure.
3267 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3268 pub struct Upvar {
3269     /// First span where it is accessed (there can be multiple).
3270     pub span: Span,
3271 }
3272
3273 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3274 // has length > 0 if the trait is found through an chain of imports, starting with the
3275 // import/use statement in the scope where the trait is used.
3276 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3277 pub struct TraitCandidate {
3278     pub def_id: DefId,
3279     pub import_ids: SmallVec<[LocalDefId; 1]>,
3280 }
3281
3282 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3283 pub enum OwnerNode<'hir> {
3284     Item(&'hir Item<'hir>),
3285     ForeignItem(&'hir ForeignItem<'hir>),
3286     TraitItem(&'hir TraitItem<'hir>),
3287     ImplItem(&'hir ImplItem<'hir>),
3288     Crate(&'hir Mod<'hir>),
3289 }
3290
3291 impl<'hir> OwnerNode<'hir> {
3292     pub fn ident(&self) -> Option<Ident> {
3293         match self {
3294             OwnerNode::Item(Item { ident, .. })
3295             | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3296             | OwnerNode::ImplItem(ImplItem { ident, .. })
3297             | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3298             OwnerNode::Crate(..) => None,
3299         }
3300     }
3301
3302     pub fn span(&self) -> Span {
3303         match self {
3304             OwnerNode::Item(Item { span, .. })
3305             | OwnerNode::ForeignItem(ForeignItem { span, .. })
3306             | OwnerNode::ImplItem(ImplItem { span, .. })
3307             | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3308             OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3309         }
3310     }
3311
3312     pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3313         match self {
3314             OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3315             | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3316             | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3317             OwnerNode::ForeignItem(ForeignItem {
3318                 kind: ForeignItemKind::Fn(fn_decl, _, _),
3319                 ..
3320             }) => Some(fn_decl),
3321             _ => None,
3322         }
3323     }
3324
3325     pub fn body_id(&self) -> Option<BodyId> {
3326         match self {
3327             OwnerNode::TraitItem(TraitItem {
3328                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3329                 ..
3330             })
3331             | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3332             | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3333             _ => None,
3334         }
3335     }
3336
3337     pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3338         Node::generics(self.into())
3339     }
3340
3341     pub fn def_id(self) -> OwnerId {
3342         match self {
3343             OwnerNode::Item(Item { owner_id, .. })
3344             | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3345             | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3346             | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3347             OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3348         }
3349     }
3350
3351     pub fn expect_item(self) -> &'hir Item<'hir> {
3352         match self {
3353             OwnerNode::Item(n) => n,
3354             _ => panic!(),
3355         }
3356     }
3357
3358     pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3359         match self {
3360             OwnerNode::ForeignItem(n) => n,
3361             _ => panic!(),
3362         }
3363     }
3364
3365     pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3366         match self {
3367             OwnerNode::ImplItem(n) => n,
3368             _ => panic!(),
3369         }
3370     }
3371
3372     pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3373         match self {
3374             OwnerNode::TraitItem(n) => n,
3375             _ => panic!(),
3376         }
3377     }
3378 }
3379
3380 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3381     fn into(self) -> OwnerNode<'hir> {
3382         OwnerNode::Item(self)
3383     }
3384 }
3385
3386 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3387     fn into(self) -> OwnerNode<'hir> {
3388         OwnerNode::ForeignItem(self)
3389     }
3390 }
3391
3392 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3393     fn into(self) -> OwnerNode<'hir> {
3394         OwnerNode::ImplItem(self)
3395     }
3396 }
3397
3398 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3399     fn into(self) -> OwnerNode<'hir> {
3400         OwnerNode::TraitItem(self)
3401     }
3402 }
3403
3404 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3405     fn into(self) -> Node<'hir> {
3406         match self {
3407             OwnerNode::Item(n) => Node::Item(n),
3408             OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3409             OwnerNode::ImplItem(n) => Node::ImplItem(n),
3410             OwnerNode::TraitItem(n) => Node::TraitItem(n),
3411             OwnerNode::Crate(n) => Node::Crate(n),
3412         }
3413     }
3414 }
3415
3416 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3417 pub enum Node<'hir> {
3418     Param(&'hir Param<'hir>),
3419     Item(&'hir Item<'hir>),
3420     ForeignItem(&'hir ForeignItem<'hir>),
3421     TraitItem(&'hir TraitItem<'hir>),
3422     ImplItem(&'hir ImplItem<'hir>),
3423     Variant(&'hir Variant<'hir>),
3424     Field(&'hir FieldDef<'hir>),
3425     AnonConst(&'hir AnonConst),
3426     Expr(&'hir Expr<'hir>),
3427     ExprField(&'hir ExprField<'hir>),
3428     Stmt(&'hir Stmt<'hir>),
3429     PathSegment(&'hir PathSegment<'hir>),
3430     Ty(&'hir Ty<'hir>),
3431     TypeBinding(&'hir TypeBinding<'hir>),
3432     TraitRef(&'hir TraitRef<'hir>),
3433     Pat(&'hir Pat<'hir>),
3434     PatField(&'hir PatField<'hir>),
3435     Arm(&'hir Arm<'hir>),
3436     Block(&'hir Block<'hir>),
3437     Local(&'hir Local<'hir>),
3438
3439     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3440     /// with synthesized constructors.
3441     Ctor(&'hir VariantData<'hir>),
3442
3443     Lifetime(&'hir Lifetime),
3444     GenericParam(&'hir GenericParam<'hir>),
3445
3446     Crate(&'hir Mod<'hir>),
3447
3448     Infer(&'hir InferArg),
3449 }
3450
3451 impl<'hir> Node<'hir> {
3452     /// Get the identifier of this `Node`, if applicable.
3453     ///
3454     /// # Edge cases
3455     ///
3456     /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3457     /// because `Ctor`s do not have identifiers themselves.
3458     /// Instead, call `.ident()` on the parent struct/variant, like so:
3459     ///
3460     /// ```ignore (illustrative)
3461     /// ctor
3462     ///     .ctor_hir_id()
3463     ///     .and_then(|ctor_id| tcx.hir().find_parent(ctor_id))
3464     ///     .and_then(|parent| parent.ident())
3465     /// ```
3466     pub fn ident(&self) -> Option<Ident> {
3467         match self {
3468             Node::TraitItem(TraitItem { ident, .. })
3469             | Node::ImplItem(ImplItem { ident, .. })
3470             | Node::ForeignItem(ForeignItem { ident, .. })
3471             | Node::Field(FieldDef { ident, .. })
3472             | Node::Variant(Variant { ident, .. })
3473             | Node::Item(Item { ident, .. })
3474             | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3475             Node::Lifetime(lt) => Some(lt.ident),
3476             Node::GenericParam(p) => Some(p.name.ident()),
3477             Node::TypeBinding(b) => Some(b.ident),
3478             Node::Param(..)
3479             | Node::AnonConst(..)
3480             | Node::Expr(..)
3481             | Node::Stmt(..)
3482             | Node::Block(..)
3483             | Node::Ctor(..)
3484             | Node::Pat(..)
3485             | Node::PatField(..)
3486             | Node::ExprField(..)
3487             | Node::Arm(..)
3488             | Node::Local(..)
3489             | Node::Crate(..)
3490             | Node::Ty(..)
3491             | Node::TraitRef(..)
3492             | Node::Infer(..) => None,
3493         }
3494     }
3495
3496     pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3497         match self {
3498             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3499             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3500             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3501             Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3502             | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3503                 Some(fn_decl)
3504             }
3505             _ => None,
3506         }
3507     }
3508
3509     pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3510         match self {
3511             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3512             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3513             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3514             _ => None,
3515         }
3516     }
3517
3518     pub fn body_id(&self) -> Option<BodyId> {
3519         match self {
3520             Node::TraitItem(TraitItem {
3521                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3522                 ..
3523             })
3524             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3525             | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3526             _ => None,
3527         }
3528     }
3529
3530     pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3531         match self {
3532             Node::ForeignItem(ForeignItem {
3533                 kind: ForeignItemKind::Fn(_, _, generics), ..
3534             })
3535             | Node::TraitItem(TraitItem { generics, .. })
3536             | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3537             Node::Item(item) => item.kind.generics(),
3538             _ => None,
3539         }
3540     }
3541
3542     pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3543         match self {
3544             Node::Item(i) => Some(OwnerNode::Item(i)),
3545             Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3546             Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3547             Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3548             Node::Crate(i) => Some(OwnerNode::Crate(i)),
3549             _ => None,
3550         }
3551     }
3552
3553     pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3554         match self {
3555             Node::Item(i) => match i.kind {
3556                 ItemKind::Fn(ref sig, ref generics, _) => {
3557                     Some(FnKind::ItemFn(i.ident, generics, sig.header))
3558                 }
3559                 _ => None,
3560             },
3561             Node::TraitItem(ti) => match ti.kind {
3562                 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3563                     Some(FnKind::Method(ti.ident, sig))
3564                 }
3565                 _ => None,
3566             },
3567             Node::ImplItem(ii) => match ii.kind {
3568                 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3569                 _ => None,
3570             },
3571             Node::Expr(e) => match e.kind {
3572                 ExprKind::Closure { .. } => Some(FnKind::Closure),
3573                 _ => None,
3574             },
3575             _ => None,
3576         }
3577     }
3578
3579     /// Get the fields for the tuple-constructor,
3580     /// if this node is a tuple constructor, otherwise None
3581     pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3582         if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None }
3583     }
3584 }
3585
3586 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3587 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3588 mod size_asserts {
3589     use super::*;
3590     // tidy-alphabetical-start
3591     static_assert_size!(Block<'_>, 48);
3592     static_assert_size!(Body<'_>, 32);
3593     static_assert_size!(Expr<'_>, 64);
3594     static_assert_size!(ExprKind<'_>, 48);
3595     static_assert_size!(FnDecl<'_>, 40);
3596     static_assert_size!(ForeignItem<'_>, 72);
3597     static_assert_size!(ForeignItemKind<'_>, 40);
3598     static_assert_size!(GenericArg<'_>, 32);
3599     static_assert_size!(GenericBound<'_>, 48);
3600     static_assert_size!(Generics<'_>, 56);
3601     static_assert_size!(Impl<'_>, 80);
3602     static_assert_size!(ImplItem<'_>, 80);
3603     static_assert_size!(ImplItemKind<'_>, 32);
3604     static_assert_size!(Item<'_>, 80);
3605     static_assert_size!(ItemKind<'_>, 48);
3606     static_assert_size!(Local<'_>, 64);
3607     static_assert_size!(Param<'_>, 32);
3608     static_assert_size!(Pat<'_>, 72);
3609     static_assert_size!(Path<'_>, 40);
3610     static_assert_size!(PathSegment<'_>, 48);
3611     static_assert_size!(PatKind<'_>, 48);
3612     static_assert_size!(QPath<'_>, 24);
3613     static_assert_size!(Res, 12);
3614     static_assert_size!(Stmt<'_>, 32);
3615     static_assert_size!(StmtKind<'_>, 16);
3616     static_assert_size!(TraitItem<'_>, 80);
3617     static_assert_size!(TraitItemKind<'_>, 40);
3618     static_assert_size!(Ty<'_>, 48);
3619     static_assert_size!(TyKind<'_>, 32);
3620     // tidy-alphabetical-end
3621 }
3622
3623 fn debug_fn(f: impl Fn(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Debug {
3624     struct DebugFn<F>(F);
3625     impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Debug for DebugFn<F> {
3626         fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3627             (self.0)(fmt)
3628         }
3629     }
3630     DebugFn(f)
3631 }