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