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