]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/mod.rs
introduce 'type AttrVec'
[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 {
746     pub module: Mod,
747     pub attrs: HirVec<Attribute>,
748     pub span: Span,
749     pub exported_macros: HirVec<MacroDef>,
750     // Attributes from non-exported macros, kept only for collecting the library feature list.
751     pub non_exported_macro_attrs: HirVec<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>,
760
761     pub trait_items: BTreeMap<TraitItemId, TraitItem>,
762     pub impl_items: BTreeMap<ImplItemId, ImplItem>,
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 {
778     pub fn item(&self, id: HirId) -> &Item {
779         &self.items[&id]
780     }
781
782     pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
783         &self.trait_items[&id]
784     }
785
786     pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
787         &self.impl_items[&id]
788     }
789
790     /// Visits all items in the crate in some deterministic (but
791     /// unspecified) order. If you just need to process every item,
792     /// but don't care about nesting, this method is the best choice.
793     ///
794     /// If you do care about nesting -- usually because your algorithm
795     /// follows lexical scoping rules -- then you want a different
796     /// approach. You should override `visit_nested_item` in your
797     /// visitor and then call `intravisit::walk_crate` instead.
798     pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
799         where V: itemlikevisit::ItemLikeVisitor<'hir>
800     {
801         for (_, item) in &self.items {
802             visitor.visit_item(item);
803         }
804
805         for (_, trait_item) in &self.trait_items {
806             visitor.visit_trait_item(trait_item);
807         }
808
809         for (_, impl_item) in &self.impl_items {
810             visitor.visit_impl_item(impl_item);
811         }
812     }
813
814     /// A parallel version of `visit_all_item_likes`.
815     pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
816         where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
817     {
818         parallel!({
819             par_for_each_in(&self.items, |(_, item)| {
820                 visitor.visit_item(item);
821             });
822         }, {
823             par_for_each_in(&self.trait_items, |(_, trait_item)| {
824                 visitor.visit_trait_item(trait_item);
825             });
826         }, {
827             par_for_each_in(&self.impl_items, |(_, impl_item)| {
828                 visitor.visit_impl_item(impl_item);
829             });
830         });
831     }
832
833     pub fn body(&self, id: BodyId) -> &Body {
834         &self.bodies[&id]
835     }
836 }
837
838 /// A macro definition, in this crate or imported from another.
839 ///
840 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
841 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
842 pub struct MacroDef {
843     pub name: Name,
844     pub vis: Visibility,
845     pub attrs: HirVec<Attribute>,
846     pub hir_id: HirId,
847     pub span: Span,
848     pub body: TokenStream,
849     pub legacy: bool,
850 }
851
852 /// A block of statements `{ .. }`, which may have a label (in this case the
853 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
854 /// the `rules` being anything but `DefaultBlock`.
855 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
856 pub struct Block {
857     /// Statements in a block.
858     pub stmts: HirVec<Stmt>,
859     /// An expression at the end of the block
860     /// without a semicolon, if any.
861     pub expr: Option<P<Expr>>,
862     #[stable_hasher(ignore)]
863     pub hir_id: HirId,
864     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
865     pub rules: BlockCheckMode,
866     pub span: Span,
867     /// If true, then there may exist `break 'a` values that aim to
868     /// break out of this block early.
869     /// Used by `'label: {}` blocks and by `try {}` blocks.
870     pub targeted_by_break: bool,
871 }
872
873 #[derive(RustcEncodable, RustcDecodable, HashStable)]
874 pub struct Pat {
875     #[stable_hasher(ignore)]
876     pub hir_id: HirId,
877     pub kind: PatKind,
878     pub span: Span,
879 }
880
881 impl fmt::Debug for Pat {
882     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883         write!(f, "pat({}: {})", self.hir_id,
884                print::to_string(print::NO_ANN, |s| s.print_pat(self)))
885     }
886 }
887
888 impl Pat {
889     // FIXME(#19596) this is a workaround, but there should be a better way
890     fn walk_short_(&self, it: &mut impl FnMut(&Pat) -> bool) -> bool {
891         if !it(self) {
892             return false;
893         }
894
895         use PatKind::*;
896         match &self.kind {
897             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
898             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
899             Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
900             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
901             Slice(before, slice, after) => {
902                 before.iter()
903                       .chain(slice.iter())
904                       .chain(after.iter())
905                       .all(|p| p.walk_short_(it))
906             }
907         }
908     }
909
910     /// Walk the pattern in left-to-right order,
911     /// short circuiting (with `.all(..)`) if `false` is returned.
912     ///
913     /// Note that when visiting e.g. `Tuple(ps)`,
914     /// if visiting `ps[0]` returns `false`,
915     /// then `ps[1]` will not be visited.
916     pub fn walk_short(&self, mut it: impl FnMut(&Pat) -> bool) -> bool {
917         self.walk_short_(&mut it)
918     }
919
920     // FIXME(#19596) this is a workaround, but there should be a better way
921     fn walk_(&self, it: &mut impl FnMut(&Pat) -> bool) {
922         if !it(self) {
923             return;
924         }
925
926         use PatKind::*;
927         match &self.kind {
928             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {},
929             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
930             Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
931             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
932             Slice(before, slice, after) => {
933                 before.iter()
934                       .chain(slice.iter())
935                       .chain(after.iter())
936                       .for_each(|p| p.walk_(it))
937             }
938         }
939     }
940
941     /// Walk the pattern in left-to-right order.
942     ///
943     /// If `it(pat)` returns `false`, the children are not visited.
944     pub fn walk(&self, mut it: impl FnMut(&Pat) -> bool) {
945         self.walk_(&mut it)
946     }
947 }
948
949 /// A single field in a struct pattern.
950 ///
951 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
952 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
953 /// except `is_shorthand` is true.
954 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
955 pub struct FieldPat {
956     #[stable_hasher(ignore)]
957     pub hir_id: HirId,
958     /// The identifier for the field.
959     #[stable_hasher(project(name))]
960     pub ident: Ident,
961     /// The pattern the field is destructured to.
962     pub pat: P<Pat>,
963     pub is_shorthand: bool,
964     pub span: Span,
965 }
966
967 /// Explicit binding annotations given in the HIR for a binding. Note
968 /// that this is not the final binding *mode* that we infer after type
969 /// inference.
970 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
971 pub enum BindingAnnotation {
972     /// No binding annotation given: this means that the final binding mode
973     /// will depend on whether we have skipped through a `&` reference
974     /// when matching. For example, the `x` in `Some(x)` will have binding
975     /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
976     /// ultimately be inferred to be by-reference.
977     ///
978     /// Note that implicit reference skipping is not implemented yet (#42640).
979     Unannotated,
980
981     /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
982     Mutable,
983
984     /// Annotated as `ref`, like `ref x`
985     Ref,
986
987     /// Annotated as `ref mut x`.
988     RefMut,
989 }
990
991 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
992 pub enum RangeEnd {
993     Included,
994     Excluded,
995 }
996
997 impl fmt::Display for RangeEnd {
998     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
999         f.write_str(match self {
1000             RangeEnd::Included => "..=",
1001             RangeEnd::Excluded => "..",
1002         })
1003     }
1004 }
1005
1006 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1007 pub enum PatKind {
1008     /// Represents a wildcard pattern (i.e., `_`).
1009     Wild,
1010
1011     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1012     /// The `HirId` is the canonical ID for the variable being bound,
1013     /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1014     /// which is the pattern ID of the first `x`.
1015     Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
1016
1017     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1018     /// The `bool` is `true` in the presence of a `..`.
1019     Struct(QPath, HirVec<FieldPat>, bool),
1020
1021     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1022     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1023     /// `0 <= position <= subpats.len()`
1024     TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
1025
1026     /// An or-pattern `A | B | C`.
1027     /// Invariant: `pats.len() >= 2`.
1028     Or(HirVec<P<Pat>>),
1029
1030     /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1031     Path(QPath),
1032
1033     /// A tuple pattern (e.g., `(a, b)`).
1034     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1035     /// `0 <= position <= subpats.len()`
1036     Tuple(HirVec<P<Pat>>, Option<usize>),
1037
1038     /// A `box` pattern.
1039     Box(P<Pat>),
1040
1041     /// A reference pattern (e.g., `&mut (a, b)`).
1042     Ref(P<Pat>, Mutability),
1043
1044     /// A literal.
1045     Lit(P<Expr>),
1046
1047     /// A range pattern (e.g., `1..=2` or `1..2`).
1048     Range(P<Expr>, P<Expr>, RangeEnd),
1049
1050     /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1051     ///
1052     /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1053     /// If `slice` exists, then `after` can be non-empty.
1054     ///
1055     /// The representation for e.g., `[a, b, .., c, d]` is:
1056     /// ```
1057     /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1058     /// ```
1059     Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1060 }
1061
1062 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1063 pub enum BinOpKind {
1064     /// The `+` operator (addition).
1065     Add,
1066     /// The `-` operator (subtraction).
1067     Sub,
1068     /// The `*` operator (multiplication).
1069     Mul,
1070     /// The `/` operator (division).
1071     Div,
1072     /// The `%` operator (modulus).
1073     Rem,
1074     /// The `&&` operator (logical and).
1075     And,
1076     /// The `||` operator (logical or).
1077     Or,
1078     /// The `^` operator (bitwise xor).
1079     BitXor,
1080     /// The `&` operator (bitwise and).
1081     BitAnd,
1082     /// The `|` operator (bitwise or).
1083     BitOr,
1084     /// The `<<` operator (shift left).
1085     Shl,
1086     /// The `>>` operator (shift right).
1087     Shr,
1088     /// The `==` operator (equality).
1089     Eq,
1090     /// The `<` operator (less than).
1091     Lt,
1092     /// The `<=` operator (less than or equal to).
1093     Le,
1094     /// The `!=` operator (not equal to).
1095     Ne,
1096     /// The `>=` operator (greater than or equal to).
1097     Ge,
1098     /// The `>` operator (greater than).
1099     Gt,
1100 }
1101
1102 impl BinOpKind {
1103     pub fn as_str(self) -> &'static str {
1104         match self {
1105             BinOpKind::Add => "+",
1106             BinOpKind::Sub => "-",
1107             BinOpKind::Mul => "*",
1108             BinOpKind::Div => "/",
1109             BinOpKind::Rem => "%",
1110             BinOpKind::And => "&&",
1111             BinOpKind::Or => "||",
1112             BinOpKind::BitXor => "^",
1113             BinOpKind::BitAnd => "&",
1114             BinOpKind::BitOr => "|",
1115             BinOpKind::Shl => "<<",
1116             BinOpKind::Shr => ">>",
1117             BinOpKind::Eq => "==",
1118             BinOpKind::Lt => "<",
1119             BinOpKind::Le => "<=",
1120             BinOpKind::Ne => "!=",
1121             BinOpKind::Ge => ">=",
1122             BinOpKind::Gt => ">",
1123         }
1124     }
1125
1126     pub fn is_lazy(self) -> bool {
1127         match self {
1128             BinOpKind::And | BinOpKind::Or => true,
1129             _ => false,
1130         }
1131     }
1132
1133     pub fn is_shift(self) -> bool {
1134         match self {
1135             BinOpKind::Shl | BinOpKind::Shr => true,
1136             _ => false,
1137         }
1138     }
1139
1140     pub fn is_comparison(self) -> bool {
1141         match self {
1142             BinOpKind::Eq |
1143             BinOpKind::Lt |
1144             BinOpKind::Le |
1145             BinOpKind::Ne |
1146             BinOpKind::Gt |
1147             BinOpKind::Ge => true,
1148             BinOpKind::And |
1149             BinOpKind::Or |
1150             BinOpKind::Add |
1151             BinOpKind::Sub |
1152             BinOpKind::Mul |
1153             BinOpKind::Div |
1154             BinOpKind::Rem |
1155             BinOpKind::BitXor |
1156             BinOpKind::BitAnd |
1157             BinOpKind::BitOr |
1158             BinOpKind::Shl |
1159             BinOpKind::Shr => false,
1160         }
1161     }
1162
1163     /// Returns `true` if the binary operator takes its arguments by value.
1164     pub fn is_by_value(self) -> bool {
1165         !self.is_comparison()
1166     }
1167 }
1168
1169 impl Into<ast::BinOpKind> for BinOpKind {
1170     fn into(self) -> ast::BinOpKind {
1171         match self {
1172             BinOpKind::Add => ast::BinOpKind::Add,
1173             BinOpKind::Sub => ast::BinOpKind::Sub,
1174             BinOpKind::Mul => ast::BinOpKind::Mul,
1175             BinOpKind::Div => ast::BinOpKind::Div,
1176             BinOpKind::Rem => ast::BinOpKind::Rem,
1177             BinOpKind::And => ast::BinOpKind::And,
1178             BinOpKind::Or => ast::BinOpKind::Or,
1179             BinOpKind::BitXor => ast::BinOpKind::BitXor,
1180             BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1181             BinOpKind::BitOr => ast::BinOpKind::BitOr,
1182             BinOpKind::Shl => ast::BinOpKind::Shl,
1183             BinOpKind::Shr => ast::BinOpKind::Shr,
1184             BinOpKind::Eq => ast::BinOpKind::Eq,
1185             BinOpKind::Lt => ast::BinOpKind::Lt,
1186             BinOpKind::Le => ast::BinOpKind::Le,
1187             BinOpKind::Ne => ast::BinOpKind::Ne,
1188             BinOpKind::Ge => ast::BinOpKind::Ge,
1189             BinOpKind::Gt => ast::BinOpKind::Gt,
1190         }
1191     }
1192 }
1193
1194 pub type BinOp = Spanned<BinOpKind>;
1195
1196 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1197 pub enum UnOp {
1198     /// The `*` operator (deferencing).
1199     UnDeref,
1200     /// The `!` operator (logical negation).
1201     UnNot,
1202     /// The `-` operator (negation).
1203     UnNeg,
1204 }
1205
1206 impl UnOp {
1207     pub fn as_str(self) -> &'static str {
1208         match self {
1209             UnDeref => "*",
1210             UnNot => "!",
1211             UnNeg => "-",
1212         }
1213     }
1214
1215     /// Returns `true` if the unary operator takes its argument by value.
1216     pub fn is_by_value(self) -> bool {
1217         match self {
1218             UnNeg | UnNot => true,
1219             _ => false,
1220         }
1221     }
1222 }
1223
1224 /// A statement.
1225 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1226 pub struct Stmt {
1227     pub hir_id: HirId,
1228     pub kind: StmtKind,
1229     pub span: Span,
1230 }
1231
1232 impl fmt::Debug for Stmt {
1233     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1234         write!(f, "stmt({}: {})", self.hir_id,
1235                print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1236     }
1237 }
1238
1239 /// The contents of a statement.
1240 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1241 pub enum StmtKind {
1242     /// A local (`let`) binding.
1243     Local(P<Local>),
1244
1245     /// An item binding.
1246     Item(ItemId),
1247
1248     /// An expression without a trailing semi-colon (must have unit type).
1249     Expr(P<Expr>),
1250
1251     /// An expression with a trailing semi-colon (may have any type).
1252     Semi(P<Expr>),
1253 }
1254
1255 impl StmtKind {
1256     pub fn attrs(&self) -> &[Attribute] {
1257         match *self {
1258             StmtKind::Local(ref l) => &l.attrs,
1259             StmtKind::Item(_) => &[],
1260             StmtKind::Expr(ref e) |
1261             StmtKind::Semi(ref e) => &e.attrs,
1262         }
1263     }
1264 }
1265
1266 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1267 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1268 pub struct Local {
1269     pub pat: P<Pat>,
1270     /// Type annotation, if any (otherwise the type will be inferred).
1271     pub ty: Option<P<Ty>>,
1272     /// Initializer expression to set the value, if any.
1273     pub init: Option<P<Expr>>,
1274     pub hir_id: HirId,
1275     pub span: Span,
1276     pub attrs: AttrVec,
1277     /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1278     /// desugaring. Otherwise will be `Normal`.
1279     pub source: LocalSource,
1280 }
1281
1282 /// Represents a single arm of a `match` expression, e.g.
1283 /// `<pat> (if <guard>) => <body>`.
1284 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1285 pub struct Arm {
1286     #[stable_hasher(ignore)]
1287     pub hir_id: HirId,
1288     pub span: Span,
1289     pub attrs: HirVec<Attribute>,
1290     /// If this pattern and the optional guard matches, then `body` is evaluated.
1291     pub pat: P<Pat>,
1292     /// Optional guard clause.
1293     pub guard: Option<Guard>,
1294     /// The expression the arm evaluates to if this arm matches.
1295     pub body: P<Expr>,
1296 }
1297
1298 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1299 pub enum Guard {
1300     If(P<Expr>),
1301 }
1302
1303 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1304 pub struct Field {
1305     #[stable_hasher(ignore)]
1306     pub hir_id: HirId,
1307     pub ident: Ident,
1308     pub expr: P<Expr>,
1309     pub span: Span,
1310     pub is_shorthand: bool,
1311 }
1312
1313 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1314 pub enum BlockCheckMode {
1315     DefaultBlock,
1316     UnsafeBlock(UnsafeSource),
1317     PushUnsafeBlock(UnsafeSource),
1318     PopUnsafeBlock(UnsafeSource),
1319 }
1320
1321 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1322 pub enum UnsafeSource {
1323     CompilerGenerated,
1324     UserProvided,
1325 }
1326
1327 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1328 pub struct BodyId {
1329     pub hir_id: HirId,
1330 }
1331
1332 /// The body of a function, closure, or constant value. In the case of
1333 /// a function, the body contains not only the function body itself
1334 /// (which is an expression), but also the argument patterns, since
1335 /// those are something that the caller doesn't really care about.
1336 ///
1337 /// # Examples
1338 ///
1339 /// ```
1340 /// fn foo((x, y): (u32, u32)) -> u32 {
1341 ///     x + y
1342 /// }
1343 /// ```
1344 ///
1345 /// Here, the `Body` associated with `foo()` would contain:
1346 ///
1347 /// - an `params` array containing the `(x, y)` pattern
1348 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1349 /// - `generator_kind` would be `None`
1350 ///
1351 /// All bodies have an **owner**, which can be accessed via the HIR
1352 /// map using `body_owner_def_id()`.
1353 #[derive(RustcEncodable, RustcDecodable, Debug)]
1354 pub struct Body {
1355     pub params: HirVec<Param>,
1356     pub value: Expr,
1357     pub generator_kind: Option<GeneratorKind>,
1358 }
1359
1360 impl Body {
1361     pub fn id(&self) -> BodyId {
1362         BodyId {
1363             hir_id: self.value.hir_id,
1364         }
1365     }
1366
1367     pub fn generator_kind(&self) -> Option<GeneratorKind> {
1368         self.generator_kind
1369     }
1370 }
1371
1372 /// The type of source expression that caused this generator to be created.
1373 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1374 pub enum GeneratorKind {
1375     /// An explicit `async` block or the body of an async function.
1376     Async(AsyncGeneratorKind),
1377
1378     /// A generator literal created via a `yield` inside a closure.
1379     Gen,
1380 }
1381
1382 impl fmt::Display for GeneratorKind {
1383     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1384         match self {
1385             GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1386             GeneratorKind::Gen => f.write_str("generator"),
1387         }
1388     }
1389 }
1390
1391 /// In the case of a generator created as part of an async construct,
1392 /// which kind of async construct caused it to be created?
1393 ///
1394 /// This helps error messages but is also used to drive coercions in
1395 /// type-checking (see #60424).
1396 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1397 pub enum AsyncGeneratorKind {
1398     /// An explicit `async` block written by the user.
1399     Block,
1400
1401     /// An explicit `async` block written by the user.
1402     Closure,
1403
1404     /// The `async` block generated as the body of an async function.
1405     Fn,
1406 }
1407
1408 impl fmt::Display for AsyncGeneratorKind {
1409     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1410         f.write_str(match self {
1411             AsyncGeneratorKind::Block => "`async` block",
1412             AsyncGeneratorKind::Closure => "`async` closure body",
1413             AsyncGeneratorKind::Fn => "`async fn` body",
1414         })
1415     }
1416 }
1417
1418 #[derive(Copy, Clone, Debug)]
1419 pub enum BodyOwnerKind {
1420     /// Functions and methods.
1421     Fn,
1422
1423     /// Closures
1424     Closure,
1425
1426     /// Constants and associated constants.
1427     Const,
1428
1429     /// Initializer of a `static` item.
1430     Static(Mutability),
1431 }
1432
1433 impl BodyOwnerKind {
1434     pub fn is_fn_or_closure(self) -> bool {
1435         match self {
1436             BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1437             BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1438         }
1439     }
1440 }
1441
1442 /// A literal.
1443 pub type Lit = Spanned<LitKind>;
1444
1445 /// A constant (expression) that's not an item or associated item,
1446 /// but needs its own `DefId` for type-checking, const-eval, etc.
1447 /// These are usually found nested inside types (e.g., array lengths)
1448 /// or expressions (e.g., repeat counts), and also used to define
1449 /// explicit discriminant values for enum variants.
1450 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1451 pub struct AnonConst {
1452     pub hir_id: HirId,
1453     pub body: BodyId,
1454 }
1455
1456 /// An expression.
1457 #[derive(RustcEncodable, RustcDecodable)]
1458 pub struct Expr {
1459     pub hir_id: HirId,
1460     pub kind: ExprKind,
1461     pub attrs: AttrVec,
1462     pub span: Span,
1463 }
1464
1465 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1466 #[cfg(target_arch = "x86_64")]
1467 static_assert_size!(Expr, 64);
1468
1469 impl Expr {
1470     pub fn precedence(&self) -> ExprPrecedence {
1471         match self.kind {
1472             ExprKind::Box(_) => ExprPrecedence::Box,
1473             ExprKind::Array(_) => ExprPrecedence::Array,
1474             ExprKind::Call(..) => ExprPrecedence::Call,
1475             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1476             ExprKind::Tup(_) => ExprPrecedence::Tup,
1477             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1478             ExprKind::Unary(..) => ExprPrecedence::Unary,
1479             ExprKind::Lit(_) => ExprPrecedence::Lit,
1480             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1481             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1482             ExprKind::Loop(..) => ExprPrecedence::Loop,
1483             ExprKind::Match(..) => ExprPrecedence::Match,
1484             ExprKind::Closure(..) => ExprPrecedence::Closure,
1485             ExprKind::Block(..) => ExprPrecedence::Block,
1486             ExprKind::Assign(..) => ExprPrecedence::Assign,
1487             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1488             ExprKind::Field(..) => ExprPrecedence::Field,
1489             ExprKind::Index(..) => ExprPrecedence::Index,
1490             ExprKind::Path(..) => ExprPrecedence::Path,
1491             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1492             ExprKind::Break(..) => ExprPrecedence::Break,
1493             ExprKind::Continue(..) => ExprPrecedence::Continue,
1494             ExprKind::Ret(..) => ExprPrecedence::Ret,
1495             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1496             ExprKind::Struct(..) => ExprPrecedence::Struct,
1497             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1498             ExprKind::Yield(..) => ExprPrecedence::Yield,
1499             ExprKind::Err => ExprPrecedence::Err,
1500         }
1501     }
1502
1503     // Whether this looks like a place expr, without checking for deref
1504     // adjustments.
1505     // This will return `true` in some potentially surprising cases such as
1506     // `CONSTANT.field`.
1507     pub fn is_syntactic_place_expr(&self) -> bool {
1508         self.is_place_expr(|_| true)
1509     }
1510
1511     // Whether this is a place expression.
1512     // `allow_projections_from` should return `true` if indexing a field or
1513     // index expression based on the given expression should be considered a
1514     // place expression.
1515     pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1516         match self.kind {
1517             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1518                 match path.res {
1519                     Res::Local(..)
1520                     | Res::Def(DefKind::Static, _)
1521                     | Res::Err => true,
1522                     _ => false,
1523                 }
1524             }
1525
1526             // Type ascription inherits its place expression kind from its
1527             // operand. See:
1528             // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1529             ExprKind::Type(ref e, _) => {
1530                 e.is_place_expr(allow_projections_from)
1531             }
1532
1533             ExprKind::Unary(UnDeref, _) => true,
1534
1535             ExprKind::Field(ref base, _) |
1536             ExprKind::Index(ref base, _) => {
1537                 allow_projections_from(base)
1538                     || base.is_place_expr(allow_projections_from)
1539             }
1540
1541             // Partially qualified paths in expressions can only legally
1542             // refer to associated items which are always rvalues.
1543             ExprKind::Path(QPath::TypeRelative(..)) |
1544
1545             ExprKind::Call(..) |
1546             ExprKind::MethodCall(..) |
1547             ExprKind::Struct(..) |
1548             ExprKind::Tup(..) |
1549             ExprKind::Match(..) |
1550             ExprKind::Closure(..) |
1551             ExprKind::Block(..) |
1552             ExprKind::Repeat(..) |
1553             ExprKind::Array(..) |
1554             ExprKind::Break(..) |
1555             ExprKind::Continue(..) |
1556             ExprKind::Ret(..) |
1557             ExprKind::Loop(..) |
1558             ExprKind::Assign(..) |
1559             ExprKind::InlineAsm(..) |
1560             ExprKind::AssignOp(..) |
1561             ExprKind::Lit(_) |
1562             ExprKind::Unary(..) |
1563             ExprKind::Box(..) |
1564             ExprKind::AddrOf(..) |
1565             ExprKind::Binary(..) |
1566             ExprKind::Yield(..) |
1567             ExprKind::Cast(..) |
1568             ExprKind::DropTemps(..) |
1569             ExprKind::Err => {
1570                 false
1571             }
1572         }
1573     }
1574
1575     /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1576     /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1577     /// silent, only signaling the ownership system. By doing this, suggestions that check the
1578     /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1579     /// beyond remembering to call this function before doing analysis on it.
1580     pub fn peel_drop_temps(&self) -> &Self {
1581         let mut expr = self;
1582         while let ExprKind::DropTemps(inner) = &expr.kind {
1583             expr = inner;
1584         }
1585         expr
1586     }
1587 }
1588
1589 impl fmt::Debug for Expr {
1590     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1591         write!(f, "expr({}: {})", self.hir_id,
1592                print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1593     }
1594 }
1595
1596 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1597 pub enum ExprKind {
1598     /// A `box x` expression.
1599     Box(P<Expr>),
1600     /// An array (e.g., `[a, b, c, d]`).
1601     Array(HirVec<Expr>),
1602     /// A function call.
1603     ///
1604     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1605     /// and the second field is the list of arguments.
1606     /// This also represents calling the constructor of
1607     /// tuple-like ADTs such as tuple structs and enum variants.
1608     Call(P<Expr>, HirVec<Expr>),
1609     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1610     ///
1611     /// The `PathSegment`/`Span` represent the method name and its generic arguments
1612     /// (within the angle brackets).
1613     /// The first element of the vector of `Expr`s is the expression that evaluates
1614     /// to the object on which the method is being called on (the receiver),
1615     /// and the remaining elements are the rest of the arguments.
1616     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1617     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1618     ///
1619     /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1620     /// the `hir_id` of the `MethodCall` node itself.
1621     ///
1622     /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1623     MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1624     /// A tuple (e.g., `(a, b, c, d)`).
1625     Tup(HirVec<Expr>),
1626     /// A binary operation (e.g., `a + b`, `a * b`).
1627     Binary(BinOp, P<Expr>, P<Expr>),
1628     /// A unary operation (e.g., `!x`, `*x`).
1629     Unary(UnOp, P<Expr>),
1630     /// A literal (e.g., `1`, `"foo"`).
1631     Lit(Lit),
1632     /// A cast (e.g., `foo as f64`).
1633     Cast(P<Expr>, P<Ty>),
1634     /// A type reference (e.g., `Foo`).
1635     Type(P<Expr>, P<Ty>),
1636     /// Wraps the expression in a terminating scope.
1637     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1638     ///
1639     /// This construct only exists to tweak the drop order in HIR lowering.
1640     /// An example of that is the desugaring of `for` loops.
1641     DropTemps(P<Expr>),
1642     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1643     ///
1644     /// I.e., `'label: loop { <block> }`.
1645     Loop(P<Block>, Option<Label>, LoopSource),
1646     /// A `match` block, with a source that indicates whether or not it is
1647     /// the result of a desugaring, and if so, which kind.
1648     Match(P<Expr>, HirVec<Arm>, MatchSource),
1649     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1650     ///
1651     /// The `Span` is the argument block `|...|`.
1652     ///
1653     /// This may also be a generator literal or an `async block` as indicated by the
1654     /// `Option<Movability>`.
1655     Closure(CaptureBy, P<FnDecl>, BodyId, Span, Option<Movability>),
1656     /// A block (e.g., `'label: { ... }`).
1657     Block(P<Block>, Option<Label>),
1658
1659     /// An assignment (e.g., `a = foo()`).
1660     Assign(P<Expr>, P<Expr>),
1661     /// An assignment with an operator.
1662     ///
1663     /// E.g., `a += 1`.
1664     AssignOp(BinOp, P<Expr>, P<Expr>),
1665     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1666     Field(P<Expr>, Ident),
1667     /// An indexing operation (`foo[2]`).
1668     Index(P<Expr>, P<Expr>),
1669
1670     /// Path to a definition, possibly containing lifetime or type parameters.
1671     Path(QPath),
1672
1673     /// A referencing operation (i.e., `&a`, `&mut a`, `&raw const a`, or `&raw mut a`).
1674     AddrOf(BorrowKind, Mutability, P<Expr>),
1675     /// A `break`, with an optional label to break.
1676     Break(Destination, Option<P<Expr>>),
1677     /// A `continue`, with an optional label.
1678     Continue(Destination),
1679     /// A `return`, with an optional value to be returned.
1680     Ret(Option<P<Expr>>),
1681
1682     /// Inline assembly (from `asm!`), with its outputs and inputs.
1683     InlineAsm(P<InlineAsm>),
1684
1685     /// A struct or struct-like variant literal expression.
1686     ///
1687     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1688     /// where `base` is the `Option<Expr>`.
1689     Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1690
1691     /// An array literal constructed from one repeated element.
1692     ///
1693     /// E.g., `[1; 5]`. The first expression is the element
1694     /// to be repeated; the second is the number of times to repeat it.
1695     Repeat(P<Expr>, AnonConst),
1696
1697     /// A suspension point for generators (i.e., `yield <expr>`).
1698     Yield(P<Expr>, YieldSource),
1699
1700     /// A placeholder for an expression that wasn't syntactically well formed in some way.
1701     Err,
1702 }
1703
1704 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1705 ///
1706 /// To resolve the path to a `DefId`, call [`qpath_res`].
1707 ///
1708 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1709 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1710 pub enum QPath {
1711     /// Path to a definition, optionally "fully-qualified" with a `Self`
1712     /// type, if the path points to an associated item in a trait.
1713     ///
1714     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1715     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1716     /// even though they both have the same two-segment `Clone::clone` `Path`.
1717     Resolved(Option<P<Ty>>, P<Path>),
1718
1719     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1720     /// Will be resolved by type-checking to an associated item.
1721     ///
1722     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1723     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1724     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1725     TypeRelative(P<Ty>, P<PathSegment>)
1726 }
1727
1728 /// Hints at the original code for a let statement.
1729 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1730 pub enum LocalSource {
1731     /// A `match _ { .. }`.
1732     Normal,
1733     /// A desugared `for _ in _ { .. }` loop.
1734     ForLoopDesugar,
1735     /// When lowering async functions, we create locals within the `async move` so that
1736     /// all parameters are dropped after the future is polled.
1737     ///
1738     /// ```ignore (pseudo-Rust)
1739     /// async fn foo(<pattern> @ x: Type) {
1740     ///     async move {
1741     ///         let <pattern> = x;
1742     ///     }
1743     /// }
1744     /// ```
1745     AsyncFn,
1746     /// A desugared `<expr>.await`.
1747     AwaitDesugar,
1748 }
1749
1750 /// Hints at the original code for a `match _ { .. }`.
1751 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1752 pub enum MatchSource {
1753     /// A `match _ { .. }`.
1754     Normal,
1755     /// An `if _ { .. }` (optionally with `else { .. }`).
1756     IfDesugar {
1757         contains_else_clause: bool,
1758     },
1759     /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1760     IfLetDesugar {
1761         contains_else_clause: bool,
1762     },
1763     /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1764     WhileDesugar,
1765     /// A `while let _ = _ { .. }` (which was desugared to a
1766     /// `loop { match _ { .. } }`).
1767     WhileLetDesugar,
1768     /// A desugared `for _ in _ { .. }` loop.
1769     ForLoopDesugar,
1770     /// A desugared `?` operator.
1771     TryDesugar,
1772     /// A desugared `<expr>.await`.
1773     AwaitDesugar,
1774 }
1775
1776 impl MatchSource {
1777     pub fn name(self) -> &'static str {
1778         use MatchSource::*;
1779         match self {
1780             Normal => "match",
1781             IfDesugar { .. } | IfLetDesugar { .. } => "if",
1782             WhileDesugar | WhileLetDesugar => "while",
1783             ForLoopDesugar => "for",
1784             TryDesugar => "?",
1785             AwaitDesugar => ".await",
1786         }
1787     }
1788 }
1789
1790 /// The loop type that yielded an `ExprKind::Loop`.
1791 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1792 pub enum LoopSource {
1793     /// A `loop { .. }` loop.
1794     Loop,
1795     /// A `while _ { .. }` loop.
1796     While,
1797     /// A `while let _ = _ { .. }` loop.
1798     WhileLet,
1799     /// A `for _ in _ { .. }` loop.
1800     ForLoop,
1801 }
1802
1803 impl LoopSource {
1804     pub fn name(self) -> &'static str {
1805         match self {
1806             LoopSource::Loop => "loop",
1807             LoopSource::While | LoopSource::WhileLet => "while",
1808             LoopSource::ForLoop => "for",
1809         }
1810     }
1811 }
1812
1813 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1814 pub enum LoopIdError {
1815     OutsideLoopScope,
1816     UnlabeledCfInWhileCondition,
1817     UnresolvedLabel,
1818 }
1819
1820 impl fmt::Display for LoopIdError {
1821     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1822         f.write_str(match self {
1823             LoopIdError::OutsideLoopScope => "not inside loop scope",
1824             LoopIdError::UnlabeledCfInWhileCondition =>
1825                 "unlabeled control flow (break or continue) in while condition",
1826             LoopIdError::UnresolvedLabel => "label not found",
1827         })
1828     }
1829 }
1830
1831 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1832 pub struct Destination {
1833     // This is `Some(_)` iff there is an explicit user-specified `label
1834     pub label: Option<Label>,
1835
1836     // These errors are caught and then reported during the diagnostics pass in
1837     // librustc_passes/loops.rs
1838     pub target_id: Result<HirId, LoopIdError>,
1839 }
1840
1841 /// The yield kind that caused an `ExprKind::Yield`.
1842 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1843 pub enum YieldSource {
1844     /// An `<expr>.await`.
1845     Await,
1846     /// A plain `yield`.
1847     Yield,
1848 }
1849
1850 impl fmt::Display for YieldSource {
1851     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1852         f.write_str(match self {
1853             YieldSource::Await => "`await`",
1854             YieldSource::Yield => "`yield`",
1855         })
1856     }
1857 }
1858
1859 // N.B., if you change this, you'll probably want to change the corresponding
1860 // type structure in middle/ty.rs as well.
1861 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1862 pub struct MutTy {
1863     pub ty: P<Ty>,
1864     pub mutbl: Mutability,
1865 }
1866
1867 /// Represents a function's signature in a trait declaration,
1868 /// trait implementation, or a free function.
1869 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1870 pub struct FnSig {
1871     pub header: FnHeader,
1872     pub decl: P<FnDecl>,
1873 }
1874
1875 // The bodies for items are stored "out of line", in a separate
1876 // hashmap in the `Crate`. Here we just record the node-id of the item
1877 // so it can fetched later.
1878 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1879 pub struct TraitItemId {
1880     pub hir_id: HirId,
1881 }
1882
1883 /// Represents an item declaration within a trait declaration,
1884 /// possibly including a default implementation. A trait item is
1885 /// either required (meaning it doesn't have an implementation, just a
1886 /// signature) or provided (meaning it has a default implementation).
1887 #[derive(RustcEncodable, RustcDecodable, Debug)]
1888 pub struct TraitItem {
1889     pub ident: Ident,
1890     pub hir_id: HirId,
1891     pub attrs: HirVec<Attribute>,
1892     pub generics: Generics,
1893     pub kind: TraitItemKind,
1894     pub span: Span,
1895 }
1896
1897 /// Represents a trait method's body (or just argument names).
1898 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1899 pub enum TraitMethod {
1900     /// No default body in the trait, just a signature.
1901     Required(HirVec<Ident>),
1902
1903     /// Both signature and body are provided in the trait.
1904     Provided(BodyId),
1905 }
1906
1907 /// Represents a trait method or associated constant or type
1908 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1909 pub enum TraitItemKind {
1910     /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1911     Const(P<Ty>, Option<BodyId>),
1912     /// A method with an optional body.
1913     Method(FnSig, TraitMethod),
1914     /// An associated type with (possibly empty) bounds and optional concrete
1915     /// type.
1916     Type(GenericBounds, Option<P<Ty>>),
1917 }
1918
1919 // The bodies for items are stored "out of line", in a separate
1920 // hashmap in the `Crate`. Here we just record the node-id of the item
1921 // so it can fetched later.
1922 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1923 pub struct ImplItemId {
1924     pub hir_id: HirId,
1925 }
1926
1927 /// Represents anything within an `impl` block.
1928 #[derive(RustcEncodable, RustcDecodable, Debug)]
1929 pub struct ImplItem {
1930     pub ident: Ident,
1931     pub hir_id: HirId,
1932     pub vis: Visibility,
1933     pub defaultness: Defaultness,
1934     pub attrs: HirVec<Attribute>,
1935     pub generics: Generics,
1936     pub kind: ImplItemKind,
1937     pub span: Span,
1938 }
1939
1940 /// Represents various kinds of content within an `impl`.
1941 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1942 pub enum ImplItemKind {
1943     /// An associated constant of the given type, set to the constant result
1944     /// of the expression.
1945     Const(P<Ty>, BodyId),
1946     /// A method implementation with the given signature and body.
1947     Method(FnSig, BodyId),
1948     /// An associated type.
1949     TyAlias(P<Ty>),
1950     /// An associated `type = impl Trait`.
1951     OpaqueTy(GenericBounds),
1952 }
1953
1954 /// Bind a type to an associated type (i.e., `A = Foo`).
1955 ///
1956 /// Bindings like `A: Debug` are represented as a special type `A =
1957 /// $::Debug` that is understood by the astconv code.
1958 ///
1959 /// FIXME(alexreg): why have a separate type for the binding case,
1960 /// wouldn't it be better to make the `ty` field an enum like the
1961 /// following?
1962 ///
1963 /// ```
1964 /// enum TypeBindingKind {
1965 ///    Equals(...),
1966 ///    Binding(...),
1967 /// }
1968 /// ```
1969 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1970 pub struct TypeBinding {
1971     pub hir_id: HirId,
1972     #[stable_hasher(project(name))]
1973     pub ident: Ident,
1974     pub kind: TypeBindingKind,
1975     pub span: Span,
1976 }
1977
1978 // Represents the two kinds of type bindings.
1979 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1980 pub enum TypeBindingKind {
1981     /// E.g., `Foo<Bar: Send>`.
1982     Constraint {
1983         bounds: HirVec<GenericBound>,
1984     },
1985     /// E.g., `Foo<Bar = ()>`.
1986     Equality {
1987         ty: P<Ty>,
1988     },
1989 }
1990
1991 impl TypeBinding {
1992     pub fn ty(&self) -> &Ty {
1993         match self.kind {
1994             TypeBindingKind::Equality { ref ty } => ty,
1995             _ => bug!("expected equality type binding for parenthesized generic args"),
1996         }
1997     }
1998 }
1999
2000 #[derive(RustcEncodable, RustcDecodable)]
2001 pub struct Ty {
2002     pub hir_id: HirId,
2003     pub kind: TyKind,
2004     pub span: Span,
2005 }
2006
2007 impl fmt::Debug for Ty {
2008     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2009         write!(f, "type({})",
2010                print::to_string(print::NO_ANN, |s| s.print_type(self)))
2011     }
2012 }
2013
2014 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2015 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2016 pub enum PrimTy {
2017     Int(IntTy),
2018     Uint(UintTy),
2019     Float(FloatTy),
2020     Str,
2021     Bool,
2022     Char,
2023 }
2024
2025 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2026 pub struct BareFnTy {
2027     pub unsafety: Unsafety,
2028     pub abi: Abi,
2029     pub generic_params: HirVec<GenericParam>,
2030     pub decl: P<FnDecl>,
2031     pub param_names: HirVec<Ident>,
2032 }
2033
2034 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2035 pub struct OpaqueTy {
2036     pub generics: Generics,
2037     pub bounds: GenericBounds,
2038     pub impl_trait_fn: Option<DefId>,
2039     pub origin: OpaqueTyOrigin,
2040 }
2041
2042 /// From whence the opaque type came.
2043 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2044 pub enum OpaqueTyOrigin {
2045     /// `type Foo = impl Trait;`
2046     TypeAlias,
2047     /// `-> impl Trait`
2048     FnReturn,
2049     /// `async fn`
2050     AsyncFn,
2051 }
2052
2053 /// The various kinds of types recognized by the compiler.
2054 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2055 pub enum TyKind {
2056     /// A variable length slice (i.e., `[T]`).
2057     Slice(P<Ty>),
2058     /// A fixed length array (i.e., `[T; n]`).
2059     Array(P<Ty>, AnonConst),
2060     /// A raw pointer (i.e., `*const T` or `*mut T`).
2061     Ptr(MutTy),
2062     /// A reference (i.e., `&'a T` or `&'a mut T`).
2063     Rptr(Lifetime, MutTy),
2064     /// A bare function (e.g., `fn(usize) -> bool`).
2065     BareFn(P<BareFnTy>),
2066     /// The never type (`!`).
2067     Never,
2068     /// A tuple (`(A, B, C, D, ...)`).
2069     Tup(HirVec<Ty>),
2070     /// A path to a type definition (`module::module::...::Type`), or an
2071     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2072     ///
2073     /// Type parameters may be stored in each `PathSegment`.
2074     Path(QPath),
2075     /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2076     /// item that `impl Trait` in return position desugars to.
2077     ///
2078     /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2079     /// that are actually bound on the `impl Trait`.
2080     Def(ItemId, HirVec<GenericArg>),
2081     /// A trait object type `Bound1 + Bound2 + Bound3`
2082     /// where `Bound` is a trait or a lifetime.
2083     TraitObject(HirVec<PolyTraitRef>, Lifetime),
2084     /// Unused for now.
2085     Typeof(AnonConst),
2086     /// `TyKind::Infer` means the type should be inferred instead of it having been
2087     /// specified. This can appear anywhere in a type.
2088     Infer,
2089     /// Placeholder for a type that has failed to be defined.
2090     Err,
2091 }
2092
2093 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2094 pub struct InlineAsmOutput {
2095     pub constraint: Symbol,
2096     pub is_rw: bool,
2097     pub is_indirect: bool,
2098     pub span: Span,
2099 }
2100
2101 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2102 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2103 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2104 pub struct InlineAsmInner {
2105     pub asm: Symbol,
2106     pub asm_str_style: StrStyle,
2107     pub outputs: Vec<InlineAsmOutput>,
2108     pub inputs: Vec<Symbol>,
2109     pub clobbers: Vec<Symbol>,
2110     pub volatile: bool,
2111     pub alignstack: bool,
2112     pub dialect: AsmDialect,
2113 }
2114
2115 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2116 pub struct InlineAsm {
2117     pub inner: InlineAsmInner,
2118     pub outputs_exprs: HirVec<Expr>,
2119     pub inputs_exprs: HirVec<Expr>,
2120 }
2121
2122 /// Represents a parameter in a function header.
2123 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2124 pub struct Param {
2125     pub attrs: HirVec<Attribute>,
2126     pub hir_id: HirId,
2127     pub pat: P<Pat>,
2128     pub span: Span,
2129 }
2130
2131 /// Represents the header (not the body) of a function declaration.
2132 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2133 pub struct FnDecl {
2134     /// The types of the function's parameters.
2135     ///
2136     /// Additional argument data is stored in the function's [body](Body::parameters).
2137     pub inputs: HirVec<Ty>,
2138     pub output: FunctionRetTy,
2139     pub c_variadic: bool,
2140     /// Does the function have an implicit self?
2141     pub implicit_self: ImplicitSelfKind,
2142 }
2143
2144 /// Represents what type of implicit self a function has, if any.
2145 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2146 pub enum ImplicitSelfKind {
2147     /// Represents a `fn x(self);`.
2148     Imm,
2149     /// Represents a `fn x(mut self);`.
2150     Mut,
2151     /// Represents a `fn x(&self);`.
2152     ImmRef,
2153     /// Represents a `fn x(&mut self);`.
2154     MutRef,
2155     /// Represents when a function does not have a self argument or
2156     /// when a function has a `self: X` argument.
2157     None
2158 }
2159
2160 impl ImplicitSelfKind {
2161     /// Does this represent an implicit self?
2162     pub fn has_implicit_self(&self) -> bool {
2163         match *self {
2164             ImplicitSelfKind::None => false,
2165             _ => true,
2166         }
2167     }
2168 }
2169
2170 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2171          Ord, RustcEncodable, RustcDecodable, Debug)]
2172 pub enum IsAsync {
2173     Async,
2174     NotAsync,
2175 }
2176
2177 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2178 pub enum Defaultness {
2179     Default { has_value: bool },
2180     Final,
2181 }
2182
2183 impl Defaultness {
2184     pub fn has_value(&self) -> bool {
2185         match *self {
2186             Defaultness::Default { has_value, .. } => has_value,
2187             Defaultness::Final => true,
2188         }
2189     }
2190
2191     pub fn is_final(&self) -> bool {
2192         *self == Defaultness::Final
2193     }
2194
2195     pub fn is_default(&self) -> bool {
2196         match *self {
2197             Defaultness::Default { .. } => true,
2198             _ => false,
2199         }
2200     }
2201 }
2202
2203 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2204 pub enum FunctionRetTy {
2205     /// Return type is not specified.
2206     ///
2207     /// Functions default to `()` and
2208     /// closures default to inference. Span points to where return
2209     /// type would be inserted.
2210     DefaultReturn(Span),
2211     /// Everything else.
2212     Return(P<Ty>),
2213 }
2214
2215 impl fmt::Display for FunctionRetTy {
2216     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2217         match self {
2218             Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2219             DefaultReturn(_) => "()".fmt(f),
2220         }
2221     }
2222 }
2223
2224 impl FunctionRetTy {
2225     pub fn span(&self) -> Span {
2226         match *self {
2227             DefaultReturn(span) => span,
2228             Return(ref ty) => ty.span,
2229         }
2230     }
2231 }
2232
2233 #[derive(RustcEncodable, RustcDecodable, Debug)]
2234 pub struct Mod {
2235     /// A span from the first token past `{` to the last token until `}`.
2236     /// For `mod foo;`, the inner span ranges from the first token
2237     /// to the last token in the external file.
2238     pub inner: Span,
2239     pub item_ids: HirVec<ItemId>,
2240 }
2241
2242 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2243 pub struct ForeignMod {
2244     pub abi: Abi,
2245     pub items: HirVec<ForeignItem>,
2246 }
2247
2248 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2249 pub struct GlobalAsm {
2250     pub asm: Symbol,
2251 }
2252
2253 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2254 pub struct EnumDef {
2255     pub variants: HirVec<Variant>,
2256 }
2257
2258 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2259 pub struct Variant {
2260     /// Name of the variant.
2261     #[stable_hasher(project(name))]
2262     pub ident: Ident,
2263     /// Attributes of the variant.
2264     pub attrs: HirVec<Attribute>,
2265     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2266     pub id: HirId,
2267     /// Fields and constructor id of the variant.
2268     pub data: VariantData,
2269     /// Explicit discriminant (e.g., `Foo = 1`).
2270     pub disr_expr: Option<AnonConst>,
2271     /// Span
2272     pub span: Span
2273 }
2274
2275 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2276 pub enum UseKind {
2277     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2278     /// Also produced for each element of a list `use`, e.g.
2279     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2280     Single,
2281
2282     /// Glob import, e.g., `use foo::*`.
2283     Glob,
2284
2285     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2286     /// an additional `use foo::{}` for performing checks such as
2287     /// unstable feature gating. May be removed in the future.
2288     ListStem,
2289 }
2290
2291 /// References to traits in impls.
2292 ///
2293 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2294 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2295 /// trait being referred to but just a unique `HirId` that serves as a key
2296 /// within the resolution map.
2297 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2298 pub struct TraitRef {
2299     pub path: P<Path>,
2300     // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2301     #[stable_hasher(ignore)]
2302     pub hir_ref_id: HirId,
2303 }
2304
2305 impl TraitRef {
2306     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2307     pub fn trait_def_id(&self) -> DefId {
2308         match self.path.res {
2309             Res::Def(DefKind::Trait, did) => did,
2310             Res::Def(DefKind::TraitAlias, did) => did,
2311             Res::Err => {
2312                 FatalError.raise();
2313             }
2314             _ => unreachable!(),
2315         }
2316     }
2317 }
2318
2319 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2320 pub struct PolyTraitRef {
2321     /// The `'a` in `<'a> Foo<&'a T>`.
2322     pub bound_generic_params: HirVec<GenericParam>,
2323
2324     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2325     pub trait_ref: TraitRef,
2326
2327     pub span: Span,
2328 }
2329
2330 pub type Visibility = Spanned<VisibilityKind>;
2331
2332 #[derive(RustcEncodable, RustcDecodable, Debug)]
2333 pub enum VisibilityKind {
2334     Public,
2335     Crate(CrateSugar),
2336     Restricted { path: P<Path>, hir_id: HirId },
2337     Inherited,
2338 }
2339
2340 impl VisibilityKind {
2341     pub fn is_pub(&self) -> bool {
2342         match *self {
2343             VisibilityKind::Public => true,
2344             _ => false
2345         }
2346     }
2347
2348     pub fn is_pub_restricted(&self) -> bool {
2349         match *self {
2350             VisibilityKind::Public |
2351             VisibilityKind::Inherited => false,
2352             VisibilityKind::Crate(..) |
2353             VisibilityKind::Restricted { .. } => true,
2354         }
2355     }
2356
2357     pub fn descr(&self) -> &'static str {
2358         match *self {
2359             VisibilityKind::Public => "public",
2360             VisibilityKind::Inherited => "private",
2361             VisibilityKind::Crate(..) => "crate-visible",
2362             VisibilityKind::Restricted { .. } => "restricted",
2363         }
2364     }
2365 }
2366
2367 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2368 pub struct StructField {
2369     pub span: Span,
2370     #[stable_hasher(project(name))]
2371     pub ident: Ident,
2372     pub vis: Visibility,
2373     pub hir_id: HirId,
2374     pub ty: P<Ty>,
2375     pub attrs: HirVec<Attribute>,
2376 }
2377
2378 impl StructField {
2379     // Still necessary in couple of places
2380     pub fn is_positional(&self) -> bool {
2381         let first = self.ident.as_str().as_bytes()[0];
2382         first >= b'0' && first <= b'9'
2383     }
2384 }
2385
2386 /// Fields and constructor IDs of enum variants and structs.
2387 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2388 pub enum VariantData {
2389     /// A struct variant.
2390     ///
2391     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2392     Struct(HirVec<StructField>, /* recovered */ bool),
2393     /// A tuple variant.
2394     ///
2395     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2396     Tuple(HirVec<StructField>, HirId),
2397     /// A unit variant.
2398     ///
2399     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2400     Unit(HirId),
2401 }
2402
2403 impl VariantData {
2404     /// Return the fields of this variant.
2405     pub fn fields(&self) -> &[StructField] {
2406         match *self {
2407             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2408             _ => &[],
2409         }
2410     }
2411
2412     /// Return the `HirId` of this variant's constructor, if it has one.
2413     pub fn ctor_hir_id(&self) -> Option<HirId> {
2414         match *self {
2415             VariantData::Struct(_, _) => None,
2416             VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2417         }
2418     }
2419 }
2420
2421 // The bodies for items are stored "out of line", in a separate
2422 // hashmap in the `Crate`. Here we just record the node-id of the item
2423 // so it can fetched later.
2424 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2425 pub struct ItemId {
2426     pub id: HirId,
2427 }
2428
2429 /// An item
2430 ///
2431 /// The name might be a dummy name in case of anonymous items
2432 #[derive(RustcEncodable, RustcDecodable, Debug)]
2433 pub struct Item {
2434     pub ident: Ident,
2435     pub hir_id: HirId,
2436     pub attrs: HirVec<Attribute>,
2437     pub kind: ItemKind,
2438     pub vis: Visibility,
2439     pub span: Span,
2440 }
2441
2442 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2443 pub struct FnHeader {
2444     pub unsafety: Unsafety,
2445     pub constness: Constness,
2446     pub asyncness: IsAsync,
2447     pub abi: Abi,
2448 }
2449
2450 impl FnHeader {
2451     pub fn is_const(&self) -> bool {
2452         match &self.constness {
2453             Constness::Const => true,
2454             _ => false,
2455         }
2456     }
2457 }
2458
2459 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2460 pub enum ItemKind {
2461     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2462     ///
2463     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2464     ExternCrate(Option<Name>),
2465
2466     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2467     ///
2468     /// or just
2469     ///
2470     /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2471     Use(P<Path>, UseKind),
2472
2473     /// A `static` item.
2474     Static(P<Ty>, Mutability, BodyId),
2475     /// A `const` item.
2476     Const(P<Ty>, BodyId),
2477     /// A function declaration.
2478     Fn(FnSig, Generics, BodyId),
2479     /// A module.
2480     Mod(Mod),
2481     /// An external module, e.g. `extern { .. }`.
2482     ForeignMod(ForeignMod),
2483     /// Module-level inline assembly (from `global_asm!`).
2484     GlobalAsm(P<GlobalAsm>),
2485     /// A type alias, e.g., `type Foo = Bar<u8>`.
2486     TyAlias(P<Ty>, Generics),
2487     /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2488     OpaqueTy(OpaqueTy),
2489     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2490     Enum(EnumDef, Generics),
2491     /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2492     Struct(VariantData, Generics),
2493     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2494     Union(VariantData, Generics),
2495     /// A trait definition.
2496     Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2497     /// A trait alias.
2498     TraitAlias(Generics, GenericBounds),
2499
2500     /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2501     Impl(Unsafety,
2502          ImplPolarity,
2503          Defaultness,
2504          Generics,
2505          Option<TraitRef>, // (optional) trait this impl implements
2506          P<Ty>, // self
2507          HirVec<ImplItemRef>),
2508 }
2509
2510 impl ItemKind {
2511     pub fn descriptive_variant(&self) -> &str {
2512         match *self {
2513             ItemKind::ExternCrate(..) => "extern crate",
2514             ItemKind::Use(..) => "use",
2515             ItemKind::Static(..) => "static item",
2516             ItemKind::Const(..) => "constant item",
2517             ItemKind::Fn(..) => "function",
2518             ItemKind::Mod(..) => "module",
2519             ItemKind::ForeignMod(..) => "foreign module",
2520             ItemKind::GlobalAsm(..) => "global asm",
2521             ItemKind::TyAlias(..) => "type alias",
2522             ItemKind::OpaqueTy(..) => "opaque type",
2523             ItemKind::Enum(..) => "enum",
2524             ItemKind::Struct(..) => "struct",
2525             ItemKind::Union(..) => "union",
2526             ItemKind::Trait(..) => "trait",
2527             ItemKind::TraitAlias(..) => "trait alias",
2528             ItemKind::Impl(..) => "impl",
2529         }
2530     }
2531
2532     pub fn adt_kind(&self) -> Option<AdtKind> {
2533         match *self {
2534             ItemKind::Struct(..) => Some(AdtKind::Struct),
2535             ItemKind::Union(..) => Some(AdtKind::Union),
2536             ItemKind::Enum(..) => Some(AdtKind::Enum),
2537             _ => None,
2538         }
2539     }
2540
2541     pub fn generics(&self) -> Option<&Generics> {
2542         Some(match *self {
2543             ItemKind::Fn(_, ref generics, _) |
2544             ItemKind::TyAlias(_, ref generics) |
2545             ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) |
2546             ItemKind::Enum(_, ref generics) |
2547             ItemKind::Struct(_, ref generics) |
2548             ItemKind::Union(_, ref generics) |
2549             ItemKind::Trait(_, _, ref generics, _, _) |
2550             ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2551             _ => return None
2552         })
2553     }
2554 }
2555
2556 /// A reference from an trait to one of its associated items. This
2557 /// contains the item's id, naturally, but also the item's name and
2558 /// some other high-level details (like whether it is an associated
2559 /// type or method, and whether it is public). This allows other
2560 /// passes to find the impl they want without loading the ID (which
2561 /// means fewer edges in the incremental compilation graph).
2562 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2563 pub struct TraitItemRef {
2564     pub id: TraitItemId,
2565     #[stable_hasher(project(name))]
2566     pub ident: Ident,
2567     pub kind: AssocItemKind,
2568     pub span: Span,
2569     pub defaultness: Defaultness,
2570 }
2571
2572 /// A reference from an impl to one of its associated items. This
2573 /// contains the item's ID, naturally, but also the item's name and
2574 /// some other high-level details (like whether it is an associated
2575 /// type or method, and whether it is public). This allows other
2576 /// passes to find the impl they want without loading the ID (which
2577 /// means fewer edges in the incremental compilation graph).
2578 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2579 pub struct ImplItemRef {
2580     pub id: ImplItemId,
2581     #[stable_hasher(project(name))]
2582     pub ident: Ident,
2583     pub kind: AssocItemKind,
2584     pub span: Span,
2585     pub vis: Visibility,
2586     pub defaultness: Defaultness,
2587 }
2588
2589 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2590 pub enum AssocItemKind {
2591     Const,
2592     Method { has_self: bool },
2593     Type,
2594     OpaqueTy,
2595 }
2596
2597 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2598 pub struct ForeignItem {
2599     #[stable_hasher(project(name))]
2600     pub ident: Ident,
2601     pub attrs: HirVec<Attribute>,
2602     pub kind: ForeignItemKind,
2603     pub hir_id: HirId,
2604     pub span: Span,
2605     pub vis: Visibility,
2606 }
2607
2608 /// An item within an `extern` block.
2609 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2610 pub enum ForeignItemKind {
2611     /// A foreign function.
2612     Fn(P<FnDecl>, HirVec<Ident>, Generics),
2613     /// A foreign static item (`static ext: u8`).
2614     Static(P<Ty>, Mutability),
2615     /// A foreign type.
2616     Type,
2617 }
2618
2619 impl ForeignItemKind {
2620     pub fn descriptive_variant(&self) -> &str {
2621         match *self {
2622             ForeignItemKind::Fn(..) => "foreign function",
2623             ForeignItemKind::Static(..) => "foreign static item",
2624             ForeignItemKind::Type => "foreign type",
2625         }
2626     }
2627 }
2628
2629 /// A variable captured by a closure.
2630 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2631 pub struct Upvar {
2632     // First span where it is accessed (there can be multiple).
2633     pub span: Span
2634 }
2635
2636 pub type CaptureModeMap = NodeMap<CaptureBy>;
2637
2638  // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2639  // has length > 0 if the trait is found through an chain of imports, starting with the
2640  // import/use statement in the scope where the trait is used.
2641 #[derive(Clone, Debug)]
2642 pub struct TraitCandidate {
2643     pub def_id: DefId,
2644     pub import_ids: SmallVec<[NodeId; 1]>,
2645 }
2646
2647 // Trait method resolution
2648 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2649
2650 // Map from the NodeId of a glob import to a list of items which are actually
2651 // imported.
2652 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2653
2654 pub fn provide(providers: &mut Providers<'_>) {
2655     check_attr::provide(providers);
2656     map::provide(providers);
2657     upvars::provide(providers);
2658 }
2659
2660 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2661 pub struct CodegenFnAttrs {
2662     pub flags: CodegenFnAttrFlags,
2663     /// Parsed representation of the `#[inline]` attribute
2664     pub inline: InlineAttr,
2665     /// Parsed representation of the `#[optimize]` attribute
2666     pub optimize: OptimizeAttr,
2667     /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2668     /// function should be exported under
2669     pub export_name: Option<Symbol>,
2670     /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2671     /// imported function should be imported as. Note that `export_name`
2672     /// probably isn't set when this is set, this is for foreign items while
2673     /// `#[export_name]` is for Rust-defined functions.
2674     pub link_name: Option<Symbol>,
2675     /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2676     /// imported function has in the dynamic library. Note that this must not
2677     /// be set when `link_name` is set. This is for foreign items with the
2678     /// "raw-dylib" kind.
2679     pub link_ordinal: Option<usize>,
2680     /// The `#[target_feature(enable = "...")]` attribute and the enabled
2681     /// features (only enabled features are supported right now).
2682     pub target_features: Vec<Symbol>,
2683     /// The `#[linkage = "..."]` attribute and the value we found.
2684     pub linkage: Option<Linkage>,
2685     /// The `#[link_section = "..."]` attribute, or what executable section this
2686     /// should be placed in.
2687     pub link_section: Option<Symbol>,
2688 }
2689
2690 bitflags! {
2691     #[derive(RustcEncodable, RustcDecodable, HashStable)]
2692     pub struct CodegenFnAttrFlags: u32 {
2693         /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2694         /// the hot path.
2695         const COLD                      = 1 << 0;
2696         /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2697         /// function is never null.
2698         const ALLOCATOR                 = 1 << 1;
2699         /// `#[unwind]`: an indicator that this function may unwind despite what
2700         /// its ABI signature may otherwise imply.
2701         const UNWIND                    = 1 << 2;
2702         /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2703         /// function will never unwind. Probably obsolete by recent changes with
2704         /// #[unwind], but hasn't been removed/migrated yet
2705         const RUSTC_ALLOCATOR_NOUNWIND  = 1 << 3;
2706         /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2707         /// should be generated.
2708         const NAKED                     = 1 << 4;
2709         /// `#[no_mangle]`: an indicator that the function's name should be the same
2710         /// as its symbol.
2711         const NO_MANGLE                 = 1 << 5;
2712         /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2713         /// "weird symbol" for the standard library in that it has slightly
2714         /// different linkage, visibility, and reachability rules.
2715         const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2716         /// `#[no_debug]`: an indicator that no debugging information should be
2717         /// generated for this function by LLVM.
2718         const NO_DEBUG                  = 1 << 7;
2719         /// `#[thread_local]`: indicates a static is actually a thread local
2720         /// piece of memory
2721         const THREAD_LOCAL              = 1 << 8;
2722         /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2723         /// linker can!).
2724         const USED                      = 1 << 9;
2725         /// `#[ffi_returns_twice]`, indicates that an extern function can return
2726         /// multiple times
2727         const FFI_RETURNS_TWICE         = 1 << 10;
2728         /// `#[track_caller]`: allow access to the caller location
2729         const TRACK_CALLER              = 1 << 11;
2730     }
2731 }
2732
2733 impl CodegenFnAttrs {
2734     pub fn new() -> CodegenFnAttrs {
2735         CodegenFnAttrs {
2736             flags: CodegenFnAttrFlags::empty(),
2737             inline: InlineAttr::None,
2738             optimize: OptimizeAttr::None,
2739             export_name: None,
2740             link_name: None,
2741             link_ordinal: None,
2742             target_features: vec![],
2743             linkage: None,
2744             link_section: None,
2745         }
2746     }
2747
2748     /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2749     pub fn requests_inline(&self) -> bool {
2750         match self.inline {
2751             InlineAttr::Hint | InlineAttr::Always => true,
2752             InlineAttr::None | InlineAttr::Never => false,
2753         }
2754     }
2755
2756     /// Returns `true` if it looks like this symbol needs to be exported, for example:
2757     ///
2758     /// * `#[no_mangle]` is present
2759     /// * `#[export_name(...)]` is present
2760     /// * `#[linkage]` is present
2761     pub fn contains_extern_indicator(&self) -> bool {
2762         self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2763             self.export_name.is_some() ||
2764             match self.linkage {
2765                 // These are private, so make sure we don't try to consider
2766                 // them external.
2767                 None |
2768                 Some(Linkage::Internal) |
2769                 Some(Linkage::Private) => false,
2770                 Some(_) => true,
2771             }
2772     }
2773 }
2774
2775 #[derive(Copy, Clone, Debug)]
2776 pub enum Node<'hir> {
2777     Param(&'hir Param),
2778     Item(&'hir Item),
2779     ForeignItem(&'hir ForeignItem),
2780     TraitItem(&'hir TraitItem),
2781     ImplItem(&'hir ImplItem),
2782     Variant(&'hir Variant),
2783     Field(&'hir StructField),
2784     AnonConst(&'hir AnonConst),
2785     Expr(&'hir Expr),
2786     Stmt(&'hir Stmt),
2787     PathSegment(&'hir PathSegment),
2788     Ty(&'hir Ty),
2789     TraitRef(&'hir TraitRef),
2790     Binding(&'hir Pat),
2791     Pat(&'hir Pat),
2792     Arm(&'hir Arm),
2793     Block(&'hir Block),
2794     Local(&'hir Local),
2795     MacroDef(&'hir MacroDef),
2796
2797     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2798     /// with synthesized constructors.
2799     Ctor(&'hir VariantData),
2800
2801     Lifetime(&'hir Lifetime),
2802     GenericParam(&'hir GenericParam),
2803     Visibility(&'hir Visibility),
2804
2805     Crate,
2806 }
2807
2808 impl Node<'_> {
2809     pub fn ident(&self) -> Option<Ident> {
2810         match self {
2811             Node::TraitItem(TraitItem { ident, .. }) |
2812             Node::ImplItem(ImplItem { ident, .. }) |
2813             Node::ForeignItem(ForeignItem { ident, .. }) |
2814             Node::Item(Item { ident, .. }) => Some(*ident),
2815             _ => None,
2816         }
2817     }
2818 }