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