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