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