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