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