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