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