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