]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/mod.rs
Rollup merge of #46005 - GuillaumeGomez:short-unstable, r=nrc
[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_auto_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 #[derive(Copy, Clone, Debug)]
1032 pub enum BodyOwnerKind {
1033     /// Functions and methods.
1034     Fn,
1035
1036     /// Constants and associated constants.
1037     Const,
1038
1039     /// Initializer of a `static` item.
1040     Static(Mutability),
1041 }
1042
1043 /// An expression
1044 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1045 pub struct Expr {
1046     pub id: NodeId,
1047     pub span: Span,
1048     pub node: Expr_,
1049     pub attrs: ThinVec<Attribute>,
1050     pub hir_id: HirId,
1051 }
1052
1053 impl fmt::Debug for Expr {
1054     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1055         write!(f, "expr({}: {})", self.id,
1056                print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1057     }
1058 }
1059
1060 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1061 pub enum Expr_ {
1062     /// A `box x` expression.
1063     ExprBox(P<Expr>),
1064     /// An array (`[a, b, c, d]`)
1065     ExprArray(HirVec<Expr>),
1066     /// A function call
1067     ///
1068     /// The first field resolves to the function itself (usually an `ExprPath`),
1069     /// and the second field is the list of arguments.
1070     /// This also represents calling the constructor of
1071     /// tuple-like ADTs such as tuple structs and enum variants.
1072     ExprCall(P<Expr>, HirVec<Expr>),
1073     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1074     ///
1075     /// The `PathSegment`/`Span` represent the method name and its generic arguments
1076     /// (within the angle brackets).
1077     /// The first element of the vector of `Expr`s is the expression that evaluates
1078     /// to the object on which the method is being called on (the receiver),
1079     /// and the remaining elements are the rest of the arguments.
1080     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1081     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1082     ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1083     /// A tuple (`(a, b, c ,d)`)
1084     ExprTup(HirVec<Expr>),
1085     /// A binary operation (For example: `a + b`, `a * b`)
1086     ExprBinary(BinOp, P<Expr>, P<Expr>),
1087     /// A unary operation (For example: `!x`, `*x`)
1088     ExprUnary(UnOp, P<Expr>),
1089     /// A literal (For example: `1`, `"foo"`)
1090     ExprLit(P<Lit>),
1091     /// A cast (`foo as f64`)
1092     ExprCast(P<Expr>, P<Ty>),
1093     ExprType(P<Expr>, P<Ty>),
1094     /// An `if` block, with an optional else block
1095     ///
1096     /// `if expr { expr } else { expr }`
1097     ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1098     /// A while loop, with an optional label
1099     ///
1100     /// `'label: while expr { block }`
1101     ExprWhile(P<Expr>, P<Block>, Option<Spanned<Name>>),
1102     /// Conditionless loop (can be exited with break, continue, or return)
1103     ///
1104     /// `'label: loop { block }`
1105     ExprLoop(P<Block>, Option<Spanned<Name>>, LoopSource),
1106     /// A `match` block, with a source that indicates whether or not it is
1107     /// the result of a desugaring, and if so, which kind.
1108     ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1109     /// A closure (for example, `move |a, b, c| {a + b + c}`).
1110     ///
1111     /// The final span is the span of the argument block `|...|`
1112     ///
1113     /// This may also be a generator literal, indicated by the final boolean,
1114     /// in that case there is an GeneratorClause.
1115     ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, bool),
1116     /// A block (`{ ... }`)
1117     ExprBlock(P<Block>),
1118
1119     /// An assignment (`a = foo()`)
1120     ExprAssign(P<Expr>, P<Expr>),
1121     /// An assignment with an operator
1122     ///
1123     /// For example, `a += 1`.
1124     ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1125     /// Access of a named struct field (`obj.foo`)
1126     ExprField(P<Expr>, Spanned<Name>),
1127     /// Access of an unnamed field of a struct or tuple-struct
1128     ///
1129     /// For example, `foo.0`.
1130     ExprTupField(P<Expr>, Spanned<usize>),
1131     /// An indexing operation (`foo[2]`)
1132     ExprIndex(P<Expr>, P<Expr>),
1133
1134     /// Path to a definition, possibly containing lifetime or type parameters.
1135     ExprPath(QPath),
1136
1137     /// A referencing operation (`&a` or `&mut a`)
1138     ExprAddrOf(Mutability, P<Expr>),
1139     /// A `break`, with an optional label to break
1140     ExprBreak(Destination, Option<P<Expr>>),
1141     /// A `continue`, with an optional label
1142     ExprAgain(Destination),
1143     /// A `return`, with an optional value to be returned
1144     ExprRet(Option<P<Expr>>),
1145
1146     /// Inline assembly (from `asm!`), with its outputs and inputs.
1147     ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1148
1149     /// A struct or struct-like variant literal expression.
1150     ///
1151     /// For example, `Foo {x: 1, y: 2}`, or
1152     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1153     ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1154
1155     /// An array literal constructed from one repeated element.
1156     ///
1157     /// For example, `[1; 5]`. The first expression is the element
1158     /// to be repeated; the second is the number of times to repeat it.
1159     ExprRepeat(P<Expr>, BodyId),
1160
1161     /// A suspension point for generators. This is `yield <expr>` in Rust.
1162     ExprYield(P<Expr>),
1163 }
1164
1165 /// Optionally `Self`-qualified value/type path or associated extension.
1166 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1167 pub enum QPath {
1168     /// Path to a definition, optionally "fully-qualified" with a `Self`
1169     /// type, if the path points to an associated item in a trait.
1170     ///
1171     /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1172     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1173     /// even though they both have the same two-segment `Clone::clone` `Path`.
1174     Resolved(Option<P<Ty>>, P<Path>),
1175
1176     /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1177     /// Will be resolved by type-checking to an associated item.
1178     ///
1179     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1180     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1181     /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1182     TypeRelative(P<Ty>, P<PathSegment>)
1183 }
1184
1185 /// Hints at the original code for a let statement
1186 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1187 pub enum LocalSource {
1188     /// A `match _ { .. }`
1189     Normal,
1190     /// A desugared `for _ in _ { .. }` loop
1191     ForLoopDesugar,
1192 }
1193
1194 /// Hints at the original code for a `match _ { .. }`
1195 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1196 pub enum MatchSource {
1197     /// A `match _ { .. }`
1198     Normal,
1199     /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1200     IfLetDesugar {
1201         contains_else_clause: bool,
1202     },
1203     /// A `while let _ = _ { .. }` (which was desugared to a
1204     /// `loop { match _ { .. } }`)
1205     WhileLetDesugar,
1206     /// A desugared `for _ in _ { .. }` loop
1207     ForLoopDesugar,
1208     /// A desugared `?` operator
1209     TryDesugar,
1210 }
1211
1212 /// The loop type that yielded an ExprLoop
1213 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1214 pub enum LoopSource {
1215     /// A `loop { .. }` loop
1216     Loop,
1217     /// A `while let _ = _ { .. }` loop
1218     WhileLet,
1219     /// A `for _ in _ { .. }` loop
1220     ForLoop,
1221 }
1222
1223 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1224 pub enum LoopIdError {
1225     OutsideLoopScope,
1226     UnlabeledCfInWhileCondition,
1227     UnresolvedLabel,
1228 }
1229
1230 impl fmt::Display for LoopIdError {
1231     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1232         fmt::Display::fmt(match *self {
1233             LoopIdError::OutsideLoopScope => "not inside loop scope",
1234             LoopIdError::UnlabeledCfInWhileCondition =>
1235                 "unlabeled control flow (break or continue) in while condition",
1236             LoopIdError::UnresolvedLabel => "label not found",
1237         }, f)
1238     }
1239 }
1240
1241 // FIXME(cramertj) this should use `Result` once master compiles w/ a vesion of Rust where
1242 // `Result` implements `Encodable`/`Decodable`
1243 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1244 pub enum LoopIdResult {
1245     Ok(NodeId),
1246     Err(LoopIdError),
1247 }
1248 impl Into<Result<NodeId, LoopIdError>> for LoopIdResult {
1249     fn into(self) -> Result<NodeId, LoopIdError> {
1250         match self {
1251             LoopIdResult::Ok(ok) => Ok(ok),
1252             LoopIdResult::Err(err) => Err(err),
1253         }
1254     }
1255 }
1256 impl From<Result<NodeId, LoopIdError>> for LoopIdResult {
1257     fn from(res: Result<NodeId, LoopIdError>) -> Self {
1258         match res {
1259             Ok(ok) => LoopIdResult::Ok(ok),
1260             Err(err) => LoopIdResult::Err(err),
1261         }
1262     }
1263 }
1264
1265 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1266 pub enum ScopeTarget {
1267     Block(NodeId),
1268     Loop(LoopIdResult),
1269 }
1270
1271 impl ScopeTarget {
1272     pub fn opt_id(self) -> Option<NodeId> {
1273         match self {
1274             ScopeTarget::Block(node_id) |
1275             ScopeTarget::Loop(LoopIdResult::Ok(node_id)) => Some(node_id),
1276             ScopeTarget::Loop(LoopIdResult::Err(_)) => None,
1277         }
1278     }
1279 }
1280
1281 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1282 pub struct Destination {
1283     // This is `Some(_)` iff there is an explicit user-specified `label
1284     pub ident: Option<Spanned<Ident>>,
1285
1286     // These errors are caught and then reported during the diagnostics pass in
1287     // librustc_passes/loops.rs
1288     pub target_id: ScopeTarget,
1289 }
1290
1291 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1292 pub enum CaptureClause {
1293     CaptureByValue,
1294     CaptureByRef,
1295 }
1296
1297 // NB: If you change this, you'll probably want to change the corresponding
1298 // type structure in middle/ty.rs as well.
1299 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1300 pub struct MutTy {
1301     pub ty: P<Ty>,
1302     pub mutbl: Mutability,
1303 }
1304
1305 /// Represents a method's signature in a trait declaration or implementation.
1306 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1307 pub struct MethodSig {
1308     pub unsafety: Unsafety,
1309     pub constness: Constness,
1310     pub abi: Abi,
1311     pub decl: P<FnDecl>,
1312 }
1313
1314 // The bodies for items are stored "out of line", in a separate
1315 // hashmap in the `Crate`. Here we just record the node-id of the item
1316 // so it can fetched later.
1317 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1318 pub struct TraitItemId {
1319     pub node_id: NodeId,
1320 }
1321
1322 /// Represents an item declaration within a trait declaration,
1323 /// possibly including a default implementation. A trait item is
1324 /// either required (meaning it doesn't have an implementation, just a
1325 /// signature) or provided (meaning it has a default implementation).
1326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1327 pub struct TraitItem {
1328     pub id: NodeId,
1329     pub name: Name,
1330     pub hir_id: HirId,
1331     pub attrs: HirVec<Attribute>,
1332     pub generics: Generics,
1333     pub node: TraitItemKind,
1334     pub span: Span,
1335 }
1336
1337 /// A trait method's body (or just argument names).
1338 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1339 pub enum TraitMethod {
1340     /// No default body in the trait, just a signature.
1341     Required(HirVec<Spanned<Name>>),
1342
1343     /// Both signature and body are provided in the trait.
1344     Provided(BodyId),
1345 }
1346
1347 /// Represents a trait method or associated constant or type
1348 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1349 pub enum TraitItemKind {
1350     /// An associated constant with an optional value (otherwise `impl`s
1351     /// must contain a value)
1352     Const(P<Ty>, Option<BodyId>),
1353     /// A method with an optional body
1354     Method(MethodSig, TraitMethod),
1355     /// An associated type with (possibly empty) bounds and optional concrete
1356     /// type
1357     Type(TyParamBounds, Option<P<Ty>>),
1358 }
1359
1360 // The bodies for items are stored "out of line", in a separate
1361 // hashmap in the `Crate`. Here we just record the node-id of the item
1362 // so it can fetched later.
1363 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1364 pub struct ImplItemId {
1365     pub node_id: NodeId,
1366 }
1367
1368 /// Represents anything within an `impl` block
1369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1370 pub struct ImplItem {
1371     pub id: NodeId,
1372     pub name: Name,
1373     pub hir_id: HirId,
1374     pub vis: Visibility,
1375     pub defaultness: Defaultness,
1376     pub attrs: HirVec<Attribute>,
1377     pub generics: Generics,
1378     pub node: ImplItemKind,
1379     pub span: Span,
1380 }
1381
1382 /// Represents different contents within `impl`s
1383 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1384 pub enum ImplItemKind {
1385     /// An associated constant of the given type, set to the constant result
1386     /// of the expression
1387     Const(P<Ty>, BodyId),
1388     /// A method implementation with the given signature and body
1389     Method(MethodSig, BodyId),
1390     /// An associated type
1391     Type(P<Ty>),
1392 }
1393
1394 // Bind a type to an associated type: `A=Foo`.
1395 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1396 pub struct TypeBinding {
1397     pub id: NodeId,
1398     pub name: Name,
1399     pub ty: P<Ty>,
1400     pub span: Span,
1401 }
1402
1403
1404 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1405 pub struct Ty {
1406     pub id: NodeId,
1407     pub node: Ty_,
1408     pub span: Span,
1409     pub hir_id: HirId,
1410 }
1411
1412 impl fmt::Debug for Ty {
1413     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1414         write!(f, "type({})",
1415                print::to_string(print::NO_ANN, |s| s.print_type(self)))
1416     }
1417 }
1418
1419 /// Not represented directly in the AST, referred to by name through a ty_path.
1420 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1421 pub enum PrimTy {
1422     TyInt(IntTy),
1423     TyUint(UintTy),
1424     TyFloat(FloatTy),
1425     TyStr,
1426     TyBool,
1427     TyChar,
1428 }
1429
1430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1431 pub struct BareFnTy {
1432     pub unsafety: Unsafety,
1433     pub abi: Abi,
1434     pub lifetimes: HirVec<LifetimeDef>,
1435     pub decl: P<FnDecl>,
1436     pub arg_names: HirVec<Spanned<Name>>,
1437 }
1438
1439 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1440 /// The different kinds of types recognized by the compiler
1441 pub enum Ty_ {
1442     /// A variable length slice (`[T]`)
1443     TySlice(P<Ty>),
1444     /// A fixed length array (`[T; n]`)
1445     TyArray(P<Ty>, BodyId),
1446     /// A raw pointer (`*const T` or `*mut T`)
1447     TyPtr(MutTy),
1448     /// A reference (`&'a T` or `&'a mut T`)
1449     TyRptr(Lifetime, MutTy),
1450     /// A bare function (e.g. `fn(usize) -> bool`)
1451     TyBareFn(P<BareFnTy>),
1452     /// The never type (`!`)
1453     TyNever,
1454     /// A tuple (`(A, B, C, D,...)`)
1455     TyTup(HirVec<P<Ty>>),
1456     /// A path to a type definition (`module::module::...::Type`), or an
1457     /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1458     ///
1459     /// Type parameters may be stored in each `PathSegment`.
1460     TyPath(QPath),
1461     /// A trait object type `Bound1 + Bound2 + Bound3`
1462     /// where `Bound` is a trait or a lifetime.
1463     TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1464     /// An exsitentially quantified (there exists a type satisfying) `impl
1465     /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1466     TyImplTraitExistential(TyParamBounds),
1467     /// An universally quantified (for all types satisfying) `impl
1468     /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1469     TyImplTraitUniversal(DefId, TyParamBounds),
1470     /// Unused for now
1471     TyTypeof(BodyId),
1472     /// TyInfer means the type should be inferred instead of it having been
1473     /// specified. This can appear anywhere in a type.
1474     TyInfer,
1475     /// Placeholder for a type that has failed to be defined.
1476     TyErr,
1477 }
1478
1479 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1480 pub struct InlineAsmOutput {
1481     pub constraint: Symbol,
1482     pub is_rw: bool,
1483     pub is_indirect: bool,
1484 }
1485
1486 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1487 pub struct InlineAsm {
1488     pub asm: Symbol,
1489     pub asm_str_style: StrStyle,
1490     pub outputs: HirVec<InlineAsmOutput>,
1491     pub inputs: HirVec<Symbol>,
1492     pub clobbers: HirVec<Symbol>,
1493     pub volatile: bool,
1494     pub alignstack: bool,
1495     pub dialect: AsmDialect,
1496     pub ctxt: SyntaxContext,
1497 }
1498
1499 /// represents an argument in a function header
1500 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1501 pub struct Arg {
1502     pub pat: P<Pat>,
1503     pub id: NodeId,
1504     pub hir_id: HirId,
1505 }
1506
1507 /// Represents the header (not the body) of a function declaration
1508 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1509 pub struct FnDecl {
1510     pub inputs: HirVec<P<Ty>>,
1511     pub output: FunctionRetTy,
1512     pub variadic: bool,
1513     /// True if this function has an `self`, `&self` or `&mut self` receiver
1514     /// (but not a `self: Xxx` one).
1515     pub has_implicit_self: bool,
1516 }
1517
1518 /// Is the trait definition an auto trait?
1519 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1520 pub enum IsAuto {
1521     Yes,
1522     No
1523 }
1524
1525 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1526 pub enum Unsafety {
1527     Unsafe,
1528     Normal,
1529 }
1530
1531 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1532 pub enum Constness {
1533     Const,
1534     NotConst,
1535 }
1536
1537 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1538 pub enum Defaultness {
1539     Default { has_value: bool },
1540     Final,
1541 }
1542
1543 impl Defaultness {
1544     pub fn has_value(&self) -> bool {
1545         match *self {
1546             Defaultness::Default { has_value, .. } => has_value,
1547             Defaultness::Final => true,
1548         }
1549     }
1550
1551     pub fn is_final(&self) -> bool {
1552         *self == Defaultness::Final
1553     }
1554
1555     pub fn is_default(&self) -> bool {
1556         match *self {
1557             Defaultness::Default { .. } => true,
1558             _ => false,
1559         }
1560     }
1561 }
1562
1563 impl fmt::Display for Unsafety {
1564     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1565         fmt::Display::fmt(match *self {
1566                               Unsafety::Normal => "normal",
1567                               Unsafety::Unsafe => "unsafe",
1568                           },
1569                           f)
1570     }
1571 }
1572
1573 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1574 pub enum ImplPolarity {
1575     /// `impl Trait for Type`
1576     Positive,
1577     /// `impl !Trait for Type`
1578     Negative,
1579 }
1580
1581 impl fmt::Debug for ImplPolarity {
1582     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1583         match *self {
1584             ImplPolarity::Positive => "positive".fmt(f),
1585             ImplPolarity::Negative => "negative".fmt(f),
1586         }
1587     }
1588 }
1589
1590
1591 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1592 pub enum FunctionRetTy {
1593     /// Return type is not specified.
1594     ///
1595     /// Functions default to `()` and
1596     /// closures default to inference. Span points to where return
1597     /// type would be inserted.
1598     DefaultReturn(Span),
1599     /// Everything else
1600     Return(P<Ty>),
1601 }
1602
1603 impl FunctionRetTy {
1604     pub fn span(&self) -> Span {
1605         match *self {
1606             DefaultReturn(span) => span,
1607             Return(ref ty) => ty.span,
1608         }
1609     }
1610 }
1611
1612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1613 pub struct Mod {
1614     /// A span from the first token past `{` to the last token until `}`.
1615     /// For `mod foo;`, the inner span ranges from the first token
1616     /// to the last token in the external file.
1617     pub inner: Span,
1618     pub item_ids: HirVec<ItemId>,
1619 }
1620
1621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1622 pub struct ForeignMod {
1623     pub abi: Abi,
1624     pub items: HirVec<ForeignItem>,
1625 }
1626
1627 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1628 pub struct GlobalAsm {
1629     pub asm: Symbol,
1630     pub ctxt: SyntaxContext,
1631 }
1632
1633 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1634 pub struct EnumDef {
1635     pub variants: HirVec<Variant>,
1636 }
1637
1638 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1639 pub struct Variant_ {
1640     pub name: Name,
1641     pub attrs: HirVec<Attribute>,
1642     pub data: VariantData,
1643     /// Explicit discriminant, eg `Foo = 1`
1644     pub disr_expr: Option<BodyId>,
1645 }
1646
1647 pub type Variant = Spanned<Variant_>;
1648
1649 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1650 pub enum UseKind {
1651     /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1652     /// Also produced for each element of a list `use`, e.g.
1653     // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1654     Single,
1655
1656     /// Glob import, e.g. `use foo::*`.
1657     Glob,
1658
1659     /// Degenerate list import, e.g. `use foo::{a, b}` produces
1660     /// an additional `use foo::{}` for performing checks such as
1661     /// unstable feature gating. May be removed in the future.
1662     ListStem,
1663 }
1664
1665 /// TraitRef's appear in impls.
1666 ///
1667 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1668 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1669 /// trait being referred to but just a unique NodeId that serves as a key
1670 /// within the DefMap.
1671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1672 pub struct TraitRef {
1673     pub path: Path,
1674     pub ref_id: NodeId,
1675 }
1676
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 pub struct PolyTraitRef {
1679     /// The `'a` in `<'a> Foo<&'a T>`
1680     pub bound_lifetimes: HirVec<LifetimeDef>,
1681
1682     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1683     pub trait_ref: TraitRef,
1684
1685     pub span: Span,
1686 }
1687
1688 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1689 pub enum Visibility {
1690     Public,
1691     Crate,
1692     Restricted { path: P<Path>, id: NodeId },
1693     Inherited,
1694 }
1695
1696 impl Visibility {
1697     pub fn is_pub_restricted(&self) -> bool {
1698         use self::Visibility::*;
1699         match self {
1700             &Public |
1701             &Inherited => false,
1702             &Crate |
1703             &Restricted { .. } => true,
1704         }
1705     }
1706 }
1707
1708 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1709 pub struct StructField {
1710     pub span: Span,
1711     pub name: Name,
1712     pub vis: Visibility,
1713     pub id: NodeId,
1714     pub ty: P<Ty>,
1715     pub attrs: HirVec<Attribute>,
1716 }
1717
1718 impl StructField {
1719     // Still necessary in couple of places
1720     pub fn is_positional(&self) -> bool {
1721         let first = self.name.as_str().as_bytes()[0];
1722         first >= b'0' && first <= b'9'
1723     }
1724 }
1725
1726 /// Fields and Ids of enum variants and structs
1727 ///
1728 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1729 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1730 /// One shared Id can be successfully used for these two purposes.
1731 /// Id of the whole enum lives in `Item`.
1732 ///
1733 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1734 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1735 /// the variant itself" from enum variants.
1736 /// Id of the whole struct lives in `Item`.
1737 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1738 pub enum VariantData {
1739     Struct(HirVec<StructField>, NodeId),
1740     Tuple(HirVec<StructField>, NodeId),
1741     Unit(NodeId),
1742 }
1743
1744 impl VariantData {
1745     pub fn fields(&self) -> &[StructField] {
1746         match *self {
1747             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1748             _ => &[],
1749         }
1750     }
1751     pub fn id(&self) -> NodeId {
1752         match *self {
1753             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1754         }
1755     }
1756     pub fn is_struct(&self) -> bool {
1757         if let VariantData::Struct(..) = *self {
1758             true
1759         } else {
1760             false
1761         }
1762     }
1763     pub fn is_tuple(&self) -> bool {
1764         if let VariantData::Tuple(..) = *self {
1765             true
1766         } else {
1767             false
1768         }
1769     }
1770     pub fn is_unit(&self) -> bool {
1771         if let VariantData::Unit(..) = *self {
1772             true
1773         } else {
1774             false
1775         }
1776     }
1777 }
1778
1779 // The bodies for items are stored "out of line", in a separate
1780 // hashmap in the `Crate`. Here we just record the node-id of the item
1781 // so it can fetched later.
1782 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1783 pub struct ItemId {
1784     pub id: NodeId,
1785 }
1786
1787 /// An item
1788 ///
1789 /// The name might be a dummy name in case of anonymous items
1790 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1791 pub struct Item {
1792     pub name: Name,
1793     pub id: NodeId,
1794     pub hir_id: HirId,
1795     pub attrs: HirVec<Attribute>,
1796     pub node: Item_,
1797     pub vis: Visibility,
1798     pub span: Span,
1799 }
1800
1801 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1802 pub enum Item_ {
1803     /// An `extern crate` item, with optional original crate name,
1804     ///
1805     /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1806     ItemExternCrate(Option<Name>),
1807
1808     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
1809     ///
1810     /// or just
1811     ///
1812     /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
1813     ItemUse(P<Path>, UseKind),
1814
1815     /// A `static` item
1816     ItemStatic(P<Ty>, Mutability, BodyId),
1817     /// A `const` item
1818     ItemConst(P<Ty>, BodyId),
1819     /// A function declaration
1820     ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
1821     /// A module
1822     ItemMod(Mod),
1823     /// An external module
1824     ItemForeignMod(ForeignMod),
1825     /// Module-level inline assembly (from global_asm!)
1826     ItemGlobalAsm(P<GlobalAsm>),
1827     /// A type alias, e.g. `type Foo = Bar<u8>`
1828     ItemTy(P<Ty>, Generics),
1829     /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1830     ItemEnum(EnumDef, Generics),
1831     /// A struct definition, e.g. `struct Foo<A> {x: A}`
1832     ItemStruct(VariantData, Generics),
1833     /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
1834     ItemUnion(VariantData, Generics),
1835     /// Represents a Trait Declaration
1836     ItemTrait(IsAuto, Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
1837
1838     /// Auto trait implementations
1839     ///
1840     /// `impl Trait for .. {}`
1841     ItemAutoImpl(Unsafety, TraitRef),
1842     /// An implementation, eg `impl<A> Trait for Foo { .. }`
1843     ItemImpl(Unsafety,
1844              ImplPolarity,
1845              Defaultness,
1846              Generics,
1847              Option<TraitRef>, // (optional) trait this impl implements
1848              P<Ty>, // self
1849              HirVec<ImplItemRef>),
1850 }
1851
1852 impl Item_ {
1853     pub fn descriptive_variant(&self) -> &str {
1854         match *self {
1855             ItemExternCrate(..) => "extern crate",
1856             ItemUse(..) => "use",
1857             ItemStatic(..) => "static item",
1858             ItemConst(..) => "constant item",
1859             ItemFn(..) => "function",
1860             ItemMod(..) => "module",
1861             ItemForeignMod(..) => "foreign module",
1862             ItemGlobalAsm(..) => "global asm",
1863             ItemTy(..) => "type alias",
1864             ItemEnum(..) => "enum",
1865             ItemStruct(..) => "struct",
1866             ItemUnion(..) => "union",
1867             ItemTrait(..) => "trait",
1868             ItemImpl(..) |
1869             ItemAutoImpl(..) => "item",
1870         }
1871     }
1872
1873     pub fn adt_kind(&self) -> Option<AdtKind> {
1874         match *self {
1875             ItemStruct(..) => Some(AdtKind::Struct),
1876             ItemUnion(..) => Some(AdtKind::Union),
1877             ItemEnum(..) => Some(AdtKind::Enum),
1878             _ => None,
1879         }
1880     }
1881
1882     pub fn generics(&self) -> Option<&Generics> {
1883         Some(match *self {
1884             ItemFn(_, _, _, _, ref generics, _) |
1885             ItemTy(_, ref generics) |
1886             ItemEnum(_, ref generics) |
1887             ItemStruct(_, ref generics) |
1888             ItemUnion(_, ref generics) |
1889             ItemTrait(_, _, ref generics, _, _) |
1890             ItemImpl(_, _, _, ref generics, _, _, _)=> generics,
1891             _ => return None
1892         })
1893     }
1894 }
1895
1896 /// A reference from an trait to one of its associated items. This
1897 /// contains the item's id, naturally, but also the item's name and
1898 /// some other high-level details (like whether it is an associated
1899 /// type or method, and whether it is public). This allows other
1900 /// passes to find the impl they want without loading the id (which
1901 /// means fewer edges in the incremental compilation graph).
1902 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1903 pub struct TraitItemRef {
1904     pub id: TraitItemId,
1905     pub name: Name,
1906     pub kind: AssociatedItemKind,
1907     pub span: Span,
1908     pub defaultness: Defaultness,
1909 }
1910
1911 /// A reference from an impl to one of its associated items. This
1912 /// contains the item's id, naturally, but also the item's name and
1913 /// some other high-level details (like whether it is an associated
1914 /// type or method, and whether it is public). This allows other
1915 /// passes to find the impl they want without loading the id (which
1916 /// means fewer edges in the incremental compilation graph).
1917 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1918 pub struct ImplItemRef {
1919     pub id: ImplItemId,
1920     pub name: Name,
1921     pub kind: AssociatedItemKind,
1922     pub span: Span,
1923     pub vis: Visibility,
1924     pub defaultness: Defaultness,
1925 }
1926
1927 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1928 pub enum AssociatedItemKind {
1929     Const,
1930     Method { has_self: bool },
1931     Type,
1932 }
1933
1934 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1935 pub struct ForeignItem {
1936     pub name: Name,
1937     pub attrs: HirVec<Attribute>,
1938     pub node: ForeignItem_,
1939     pub id: NodeId,
1940     pub span: Span,
1941     pub vis: Visibility,
1942 }
1943
1944 /// An item within an `extern` block
1945 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1946 pub enum ForeignItem_ {
1947     /// A foreign function
1948     ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
1949     /// A foreign static item (`static ext: u8`), with optional mutability
1950     /// (the boolean is true when mutable)
1951     ForeignItemStatic(P<Ty>, bool),
1952     /// A foreign type
1953     ForeignItemType,
1954 }
1955
1956 impl ForeignItem_ {
1957     pub fn descriptive_variant(&self) -> &str {
1958         match *self {
1959             ForeignItemFn(..) => "foreign function",
1960             ForeignItemStatic(..) => "foreign static item",
1961             ForeignItemType => "foreign type",
1962         }
1963     }
1964 }
1965
1966 /// A free variable referred to in a function.
1967 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
1968 pub struct Freevar {
1969     /// The variable being accessed free.
1970     pub def: Def,
1971
1972     // First span where it is accessed (there can be multiple).
1973     pub span: Span
1974 }
1975
1976 impl Freevar {
1977     pub fn var_id(&self) -> NodeId {
1978         match self.def {
1979             Def::Local(id) | Def::Upvar(id, ..) => id,
1980             _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
1981         }
1982     }
1983 }
1984
1985 pub type FreevarMap = NodeMap<Vec<Freevar>>;
1986
1987 pub type CaptureModeMap = NodeMap<CaptureClause>;
1988
1989 #[derive(Clone, Debug)]
1990 pub struct TraitCandidate {
1991     pub def_id: DefId,
1992     pub import_id: Option<NodeId>,
1993 }
1994
1995 // Trait method resolution
1996 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
1997
1998 // Map from the NodeId of a glob import to a list of items which are actually
1999 // imported.
2000 pub type GlobMap = NodeMap<FxHashSet<Name>>;