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