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