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