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