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