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