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