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