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