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