]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/hir.rs
Rollup merge of #30136 - fhahn:remove-int-from-doc-examples, r=steveklabnik
[rust.git] / src / librustc_front / hir.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::BindingMode::*;
14 pub use self::BinOp_::*;
15 pub use self::BlockCheckMode::*;
16 pub use self::CaptureClause::*;
17 pub use self::Decl_::*;
18 pub use self::ExplicitSelf_::*;
19 pub use self::Expr_::*;
20 pub use self::FunctionRetTy::*;
21 pub use self::ForeignItem_::*;
22 pub use self::Item_::*;
23 pub use self::Mutability::*;
24 pub use self::Pat_::*;
25 pub use self::PathListItem_::*;
26 pub use self::PrimTy::*;
27 pub use self::Stmt_::*;
28 pub use self::StructFieldKind::*;
29 pub use self::TraitItem_::*;
30 pub use self::Ty_::*;
31 pub use self::TyParamBound::*;
32 pub use self::UnOp::*;
33 pub use self::UnsafeSource::*;
34 pub use self::ViewPath_::*;
35 pub use self::Visibility::*;
36 pub use self::PathParameters::*;
37
38 use intravisit::Visitor;
39 use std::collections::BTreeMap;
40 use syntax::codemap::{self, Span, Spanned, DUMMY_SP, ExpnId};
41 use syntax::abi::Abi;
42 use syntax::ast::{Name, Ident, NodeId, DUMMY_NODE_ID, TokenTree, AsmDialect};
43 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, CrateConfig};
44 use syntax::owned_slice::OwnedSlice;
45 use syntax::parse::token::InternedString;
46 use syntax::ptr::P;
47
48 use print::pprust;
49 use util;
50
51 use std::fmt;
52 use serialize::{Encodable, Encoder, Decoder};
53
54 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
55 pub struct Lifetime {
56     pub id: NodeId,
57     pub span: Span,
58     pub name: Name,
59 }
60
61 impl fmt::Debug for Lifetime {
62     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63         write!(f,
64                "lifetime({}: {})",
65                self.id,
66                pprust::lifetime_to_string(self))
67     }
68 }
69
70 /// A lifetime definition, eg `'a: 'b+'c+'d`
71 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
72 pub struct LifetimeDef {
73     pub lifetime: Lifetime,
74     pub bounds: Vec<Lifetime>,
75 }
76
77 /// A "Path" is essentially Rust's notion of a name; for instance:
78 /// std::cmp::PartialEq  .  It's represented as a sequence of identifiers,
79 /// along with a bunch of supporting information.
80 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
81 pub struct Path {
82     pub span: Span,
83     /// A `::foo` path, is relative to the crate root rather than current
84     /// module (like paths in an import).
85     pub global: bool,
86     /// The segments in the path: the things separated by `::`.
87     pub segments: Vec<PathSegment>,
88 }
89
90 impl fmt::Debug for Path {
91     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92         write!(f, "path({})", pprust::path_to_string(self))
93     }
94 }
95
96 impl fmt::Display for Path {
97     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98         write!(f, "{}", pprust::path_to_string(self))
99     }
100 }
101
102 /// A segment of a path: an identifier, an optional lifetime, and a set of
103 /// types.
104 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
105 pub struct PathSegment {
106     /// The identifier portion of this path segment.
107     pub identifier: Ident,
108
109     /// Type/lifetime parameters attached to this path. They come in
110     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
111     /// this is more than just simple syntactic sugar; the use of
112     /// parens affects the region binding rules, so we preserve the
113     /// distinction.
114     pub parameters: PathParameters,
115 }
116
117 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
118 pub enum PathParameters {
119     /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
120     AngleBracketedParameters(AngleBracketedParameterData),
121     /// The `(A,B)` and `C` in `Foo(A,B) -> C`
122     ParenthesizedParameters(ParenthesizedParameterData),
123 }
124
125 impl PathParameters {
126     pub fn none() -> PathParameters {
127         AngleBracketedParameters(AngleBracketedParameterData {
128             lifetimes: Vec::new(),
129             types: OwnedSlice::empty(),
130             bindings: OwnedSlice::empty(),
131         })
132     }
133
134     pub fn is_empty(&self) -> bool {
135         match *self {
136             AngleBracketedParameters(ref data) => data.is_empty(),
137
138             // Even if the user supplied no types, something like
139             // `X()` is equivalent to `X<(),()>`.
140             ParenthesizedParameters(..) => false,
141         }
142     }
143
144     pub fn has_lifetimes(&self) -> bool {
145         match *self {
146             AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
147             ParenthesizedParameters(_) => false,
148         }
149     }
150
151     pub fn has_types(&self) -> bool {
152         match *self {
153             AngleBracketedParameters(ref data) => !data.types.is_empty(),
154             ParenthesizedParameters(..) => true,
155         }
156     }
157
158     /// Returns the types that the user wrote. Note that these do not necessarily map to the type
159     /// parameters in the parenthesized case.
160     pub fn types(&self) -> Vec<&P<Ty>> {
161         match *self {
162             AngleBracketedParameters(ref data) => {
163                 data.types.iter().collect()
164             }
165             ParenthesizedParameters(ref data) => {
166                 data.inputs
167                     .iter()
168                     .chain(data.output.iter())
169                     .collect()
170             }
171         }
172     }
173
174     pub fn lifetimes(&self) -> Vec<&Lifetime> {
175         match *self {
176             AngleBracketedParameters(ref data) => {
177                 data.lifetimes.iter().collect()
178             }
179             ParenthesizedParameters(_) => {
180                 Vec::new()
181             }
182         }
183     }
184
185     pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
186         match *self {
187             AngleBracketedParameters(ref data) => {
188                 data.bindings.iter().collect()
189             }
190             ParenthesizedParameters(_) => {
191                 Vec::new()
192             }
193         }
194     }
195 }
196
197 /// A path like `Foo<'a, T>`
198 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
199 pub struct AngleBracketedParameterData {
200     /// The lifetime parameters for this path segment.
201     pub lifetimes: Vec<Lifetime>,
202     /// The type parameters for this path segment, if present.
203     pub types: OwnedSlice<P<Ty>>,
204     /// Bindings (equality constraints) on associated types, if present.
205     /// E.g., `Foo<A=Bar>`.
206     pub bindings: OwnedSlice<P<TypeBinding>>,
207 }
208
209 impl AngleBracketedParameterData {
210     fn is_empty(&self) -> bool {
211         self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
212     }
213 }
214
215 /// A path like `Foo(A,B) -> C`
216 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
217 pub struct ParenthesizedParameterData {
218     /// Overall span
219     pub span: Span,
220
221     /// `(A,B)`
222     pub inputs: Vec<P<Ty>>,
223
224     /// `C`
225     pub output: Option<P<Ty>>,
226 }
227
228 /// The AST represents all type param bounds as types.
229 /// typeck::collect::compute_bounds matches these against
230 /// the "special" built-in traits (see middle::lang_items) and
231 /// detects Copy, Send and Sync.
232 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
233 pub enum TyParamBound {
234     TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
235     RegionTyParamBound(Lifetime),
236 }
237
238 /// A modifier on a bound, currently this is only used for `?Sized`, where the
239 /// modifier is `Maybe`. Negative bounds should also be handled here.
240 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
241 pub enum TraitBoundModifier {
242     None,
243     Maybe,
244 }
245
246 pub type TyParamBounds = OwnedSlice<TyParamBound>;
247
248 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
249 pub struct TyParam {
250     pub name: Name,
251     pub id: NodeId,
252     pub bounds: TyParamBounds,
253     pub default: Option<P<Ty>>,
254     pub span: Span,
255 }
256
257 /// Represents lifetimes and type parameters attached to a declaration
258 /// of a function, enum, trait, etc.
259 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
260 pub struct Generics {
261     pub lifetimes: Vec<LifetimeDef>,
262     pub ty_params: OwnedSlice<TyParam>,
263     pub where_clause: WhereClause,
264 }
265
266 impl Generics {
267     pub fn is_lt_parameterized(&self) -> bool {
268         !self.lifetimes.is_empty()
269     }
270     pub fn is_type_parameterized(&self) -> bool {
271         !self.ty_params.is_empty()
272     }
273     pub fn is_parameterized(&self) -> bool {
274         self.is_lt_parameterized() || self.is_type_parameterized()
275     }
276 }
277
278 /// A `where` clause in a definition
279 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
280 pub struct WhereClause {
281     pub id: NodeId,
282     pub predicates: Vec<WherePredicate>,
283 }
284
285 /// A single predicate in a `where` clause
286 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
287 pub enum WherePredicate {
288     /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
289     BoundPredicate(WhereBoundPredicate),
290     /// A lifetime predicate, e.g. `'a: 'b+'c`
291     RegionPredicate(WhereRegionPredicate),
292     /// An equality predicate (unsupported)
293     EqPredicate(WhereEqPredicate),
294 }
295
296 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
297 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
298 pub struct WhereBoundPredicate {
299     pub span: Span,
300     /// Any lifetimes from a `for` binding
301     pub bound_lifetimes: Vec<LifetimeDef>,
302     /// The type being bounded
303     pub bounded_ty: P<Ty>,
304     /// Trait and lifetime bounds (`Clone+Send+'static`)
305     pub bounds: OwnedSlice<TyParamBound>,
306 }
307
308 /// A lifetime predicate, e.g. `'a: 'b+'c`
309 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
310 pub struct WhereRegionPredicate {
311     pub span: Span,
312     pub lifetime: Lifetime,
313     pub bounds: Vec<Lifetime>,
314 }
315
316 /// An equality predicate (unsupported), e.g. `T=int`
317 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
318 pub struct WhereEqPredicate {
319     pub id: NodeId,
320     pub span: Span,
321     pub path: Path,
322     pub ty: P<Ty>,
323 }
324
325 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
326 pub struct Crate {
327     pub module: Mod,
328     pub attrs: Vec<Attribute>,
329     pub config: CrateConfig,
330     pub span: Span,
331     pub exported_macros: Vec<MacroDef>,
332
333     // NB: We use a BTreeMap here so that `visit_all_items` iterates
334     // over the ids in increasing order. In principle it should not
335     // matter what order we visit things in, but in *practice* it
336     // does, because it can affect the order in which errors are
337     // detected, which in turn can make compile-fail tests yield
338     // slightly different results.
339     pub items: BTreeMap<NodeId, Item>,
340 }
341
342 impl Crate {
343     pub fn item(&self, id: NodeId) -> &Item {
344         &self.items[&id]
345     }
346
347     /// Visits all items in the crate in some determinstic (but
348     /// unspecified) order. If you just need to process every item,
349     /// but don't care about nesting, this method is the best choice.
350     ///
351     /// If you do care about nesting -- usually because your algorithm
352     /// follows lexical scoping rules -- then you want a different
353     /// approach. You should override `visit_nested_item` in your
354     /// visitor and then call `intravisit::walk_crate` instead.
355     pub fn visit_all_items<'hir, V:Visitor<'hir>>(&'hir self, visitor: &mut V) {
356         for (_, item) in &self.items {
357             visitor.visit_item(item);
358         }
359     }
360 }
361
362 /// A macro definition, in this crate or imported from another.
363 ///
364 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
365 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
366 pub struct MacroDef {
367     pub name: Name,
368     pub attrs: Vec<Attribute>,
369     pub id: NodeId,
370     pub span: Span,
371     pub imported_from: Option<Name>,
372     pub export: bool,
373     pub use_locally: bool,
374     pub allow_internal_unstable: bool,
375     pub body: Vec<TokenTree>,
376 }
377
378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
379 pub struct Block {
380     /// Statements in a block
381     pub stmts: Vec<P<Stmt>>,
382     /// An expression at the end of the block
383     /// without a semicolon, if any
384     pub expr: Option<P<Expr>>,
385     pub id: NodeId,
386     /// Distinguishes between `unsafe { ... }` and `{ ... }`
387     pub rules: BlockCheckMode,
388     pub span: Span,
389 }
390
391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
392 pub struct Pat {
393     pub id: NodeId,
394     pub node: Pat_,
395     pub span: Span,
396 }
397
398 impl fmt::Debug for Pat {
399     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
400         write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
401     }
402 }
403
404 /// A single field in a struct pattern
405 ///
406 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
407 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
408 /// except is_shorthand is true
409 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
410 pub struct FieldPat {
411     /// The identifier for the field
412     pub name: Name,
413     /// The pattern the field is destructured to
414     pub pat: P<Pat>,
415     pub is_shorthand: bool,
416 }
417
418 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
419 pub enum BindingMode {
420     BindByRef(Mutability),
421     BindByValue(Mutability),
422 }
423
424 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
425 pub enum Pat_ {
426     /// Represents a wildcard pattern (`_`)
427     PatWild,
428
429     /// A PatIdent may either be a new bound variable,
430     /// or a nullary enum (in which case the third field
431     /// is None).
432     ///
433     /// In the nullary enum case, the parser can't determine
434     /// which it is. The resolver determines this, and
435     /// records this pattern's NodeId in an auxiliary
436     /// set (of "PatIdents that refer to nullary enums")
437     PatIdent(BindingMode, Spanned<Ident>, Option<P<Pat>>),
438
439     /// "None" means a `Variant(..)` pattern where we don't bind the fields to names.
440     PatEnum(Path, Option<Vec<P<Pat>>>),
441
442     /// An associated const named using the qualified path `<T>::CONST` or
443     /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
444     /// referred to as simply `T::CONST`, in which case they will end up as
445     /// PatEnum, and the resolver will have to sort that out.
446     PatQPath(QSelf, Path),
447
448     /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
449     /// The `bool` is `true` in the presence of a `..`
450     PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
451     /// A tuple pattern `(a, b)`
452     PatTup(Vec<P<Pat>>),
453     /// A `box` pattern
454     PatBox(P<Pat>),
455     /// A reference pattern, e.g. `&mut (a, b)`
456     PatRegion(P<Pat>, Mutability),
457     /// A literal
458     PatLit(P<Expr>),
459     /// A range pattern, e.g. `1...2`
460     PatRange(P<Expr>, P<Expr>),
461     /// `[a, b, ..i, y, z]` is represented as:
462     ///     `PatVec(box [a, b], Some(i), box [y, z])`
463     PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
464 }
465
466 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
467 pub enum Mutability {
468     MutMutable,
469     MutImmutable,
470 }
471
472 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
473 pub enum BinOp_ {
474     /// The `+` operator (addition)
475     BiAdd,
476     /// The `-` operator (subtraction)
477     BiSub,
478     /// The `*` operator (multiplication)
479     BiMul,
480     /// The `/` operator (division)
481     BiDiv,
482     /// The `%` operator (modulus)
483     BiRem,
484     /// The `&&` operator (logical and)
485     BiAnd,
486     /// The `||` operator (logical or)
487     BiOr,
488     /// The `^` operator (bitwise xor)
489     BiBitXor,
490     /// The `&` operator (bitwise and)
491     BiBitAnd,
492     /// The `|` operator (bitwise or)
493     BiBitOr,
494     /// The `<<` operator (shift left)
495     BiShl,
496     /// The `>>` operator (shift right)
497     BiShr,
498     /// The `==` operator (equality)
499     BiEq,
500     /// The `<` operator (less than)
501     BiLt,
502     /// The `<=` operator (less than or equal to)
503     BiLe,
504     /// The `!=` operator (not equal to)
505     BiNe,
506     /// The `>=` operator (greater than or equal to)
507     BiGe,
508     /// The `>` operator (greater than)
509     BiGt,
510 }
511
512 pub type BinOp = Spanned<BinOp_>;
513
514 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
515 pub enum UnOp {
516     /// The `*` operator for dereferencing
517     UnDeref,
518     /// The `!` operator for logical inversion
519     UnNot,
520     /// The `-` operator for negation
521     UnNeg,
522 }
523
524 /// A statement
525 pub type Stmt = Spanned<Stmt_>;
526
527 impl fmt::Debug for Stmt_ {
528     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
529         // Sadness.
530         let spanned = codemap::dummy_spanned(self.clone());
531         write!(f,
532                "stmt({}: {})",
533                util::stmt_id(&spanned),
534                pprust::stmt_to_string(&spanned))
535     }
536 }
537
538 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
539 pub enum Stmt_ {
540     /// Could be an item or a local (let) binding:
541     StmtDecl(P<Decl>, NodeId),
542
543     /// Expr without trailing semi-colon (must have unit type):
544     StmtExpr(P<Expr>, NodeId),
545
546     /// Expr with trailing semi-colon (may have any type):
547     StmtSemi(P<Expr>, NodeId),
548 }
549
550 // FIXME (pending discussion of #1697, #2178...): local should really be
551 // a refinement on pat.
552 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
553 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
554 pub struct Local {
555     pub pat: P<Pat>,
556     pub ty: Option<P<Ty>>,
557     /// Initializer expression to set the value, if any
558     pub init: Option<P<Expr>>,
559     pub id: NodeId,
560     pub span: Span,
561 }
562
563 pub type Decl = Spanned<Decl_>;
564
565 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
566 pub enum Decl_ {
567     /// A local (let) binding:
568     DeclLocal(P<Local>),
569     /// An item binding:
570     DeclItem(ItemId),
571 }
572
573 /// represents one arm of a 'match'
574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
575 pub struct Arm {
576     pub attrs: Vec<Attribute>,
577     pub pats: Vec<P<Pat>>,
578     pub guard: Option<P<Expr>>,
579     pub body: P<Expr>,
580 }
581
582 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
583 pub struct Field {
584     pub name: Spanned<Name>,
585     pub expr: P<Expr>,
586     pub span: Span,
587 }
588
589 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
590 pub enum BlockCheckMode {
591     DefaultBlock,
592     UnsafeBlock(UnsafeSource),
593     PushUnsafeBlock(UnsafeSource),
594     PopUnsafeBlock(UnsafeSource),
595     // Within this block (but outside a PopUnstableBlock), we suspend checking of stability.
596     PushUnstableBlock,
597     PopUnstableBlock,
598 }
599
600 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
601 pub enum UnsafeSource {
602     CompilerGenerated,
603     UserProvided,
604 }
605
606 /// An expression
607 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
608 pub struct Expr {
609     pub id: NodeId,
610     pub node: Expr_,
611     pub span: Span,
612 }
613
614 impl fmt::Debug for Expr {
615     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
616         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
617     }
618 }
619
620 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
621 pub enum Expr_ {
622     /// A `box x` expression.
623     ExprBox(P<Expr>),
624     /// An array (`[a, b, c, d]`)
625     ExprVec(Vec<P<Expr>>),
626     /// A function call
627     ///
628     /// The first field resolves to the function itself,
629     /// and the second field is the list of arguments
630     ExprCall(P<Expr>, Vec<P<Expr>>),
631     /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
632     ///
633     /// The `Spanned<Name>` is the identifier for the method name.
634     /// The vector of `Ty`s are the ascripted type parameters for the method
635     /// (within the angle brackets).
636     ///
637     /// The first element of the vector of `Expr`s is the expression that evaluates
638     /// to the object on which the method is being called on (the receiver),
639     /// and the remaining elements are the rest of the arguments.
640     ///
641     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
642     /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
643     ExprMethodCall(Spanned<Name>, Vec<P<Ty>>, Vec<P<Expr>>),
644     /// A tuple (`(a, b, c ,d)`)
645     ExprTup(Vec<P<Expr>>),
646     /// A binary operation (For example: `a + b`, `a * b`)
647     ExprBinary(BinOp, P<Expr>, P<Expr>),
648     /// A unary operation (For example: `!x`, `*x`)
649     ExprUnary(UnOp, P<Expr>),
650     /// A literal (For example: `1u8`, `"foo"`)
651     ExprLit(P<Lit>),
652     /// A cast (`foo as f64`)
653     ExprCast(P<Expr>, P<Ty>),
654     /// An `if` block, with an optional else block
655     ///
656     /// `if expr { block } else { expr }`
657     ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
658     /// A while loop, with an optional label
659     ///
660     /// `'label: while expr { block }`
661     ExprWhile(P<Expr>, P<Block>, Option<Ident>),
662     /// Conditionless loop (can be exited with break, continue, or return)
663     ///
664     /// `'label: loop { block }`
665     ExprLoop(P<Block>, Option<Ident>),
666     /// A `match` block, with a source that indicates whether or not it is
667     /// the result of a desugaring, and if so, which kind.
668     ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
669     /// A closure (for example, `move |a, b, c| {a + b + c}`)
670     ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
671     /// A block (`{ ... }`)
672     ExprBlock(P<Block>),
673
674     /// An assignment (`a = foo()`)
675     ExprAssign(P<Expr>, P<Expr>),
676     /// An assignment with an operator
677     ///
678     /// For example, `a += 1`.
679     ExprAssignOp(BinOp, P<Expr>, P<Expr>),
680     /// Access of a named struct field (`obj.foo`)
681     ExprField(P<Expr>, Spanned<Name>),
682     /// Access of an unnamed field of a struct or tuple-struct
683     ///
684     /// For example, `foo.0`.
685     ExprTupField(P<Expr>, Spanned<usize>),
686     /// An indexing operation (`foo[2]`)
687     ExprIndex(P<Expr>, P<Expr>),
688     /// A range (`1..2`, `1..`, or `..2`)
689     ExprRange(Option<P<Expr>>, Option<P<Expr>>),
690
691     /// Variable reference, possibly containing `::` and/or type
692     /// parameters, e.g. foo::bar::<baz>.
693     ///
694     /// Optionally "qualified",
695     /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
696     ExprPath(Option<QSelf>, Path),
697
698     /// A referencing operation (`&a` or `&mut a`)
699     ExprAddrOf(Mutability, P<Expr>),
700     /// A `break`, with an optional label to break
701     ExprBreak(Option<Spanned<Ident>>),
702     /// A `continue`, with an optional label
703     ExprAgain(Option<Spanned<Ident>>),
704     /// A `return`, with an optional value to be returned
705     ExprRet(Option<P<Expr>>),
706
707     /// Output of the `asm!()` macro
708     ExprInlineAsm(InlineAsm),
709
710     /// A struct literal expression.
711     ///
712     /// For example, `Foo {x: 1, y: 2}`, or
713     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
714     ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
715
716     /// A vector literal constructed from one repeated element.
717     ///
718     /// For example, `[1u8; 5]`. The first expression is the element
719     /// to be repeated; the second is the number of times to repeat it.
720     ExprRepeat(P<Expr>, P<Expr>),
721 }
722
723 /// The explicit Self type in a "qualified path". The actual
724 /// path, including the trait and the associated item, is stored
725 /// separately. `position` represents the index of the associated
726 /// item qualified with this Self type.
727 ///
728 ///     <Vec<T> as a::b::Trait>::AssociatedItem
729 ///      ^~~~~     ~~~~~~~~~~~~~~^
730 ///      ty        position = 3
731 ///
732 ///     <Vec<T>>::AssociatedItem
733 ///      ^~~~~    ^
734 ///      ty       position = 0
735 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
736 pub struct QSelf {
737     pub ty: P<Ty>,
738     pub position: usize,
739 }
740
741 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
742 pub enum MatchSource {
743     Normal,
744     IfLetDesugar {
745         contains_else_clause: bool,
746     },
747     WhileLetDesugar,
748     ForLoopDesugar,
749 }
750
751 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
752 pub enum CaptureClause {
753     CaptureByValue,
754     CaptureByRef,
755 }
756
757 // NB: If you change this, you'll probably want to change the corresponding
758 // type structure in middle/ty.rs as well.
759 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
760 pub struct MutTy {
761     pub ty: P<Ty>,
762     pub mutbl: Mutability,
763 }
764
765 /// Represents a method's signature in a trait declaration,
766 /// or in an implementation.
767 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
768 pub struct MethodSig {
769     pub unsafety: Unsafety,
770     pub constness: Constness,
771     pub abi: Abi,
772     pub decl: P<FnDecl>,
773     pub generics: Generics,
774     pub explicit_self: ExplicitSelf,
775 }
776
777 /// Represents a method declaration in a trait declaration, possibly including
778 /// a default implementation A trait method is either required (meaning it
779 /// doesn't have an implementation, just a signature) or provided (meaning it
780 /// has a default implementation).
781 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
782 pub struct TraitItem {
783     pub id: NodeId,
784     pub name: Name,
785     pub attrs: Vec<Attribute>,
786     pub node: TraitItem_,
787     pub span: Span,
788 }
789
790 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
791 pub enum TraitItem_ {
792     ConstTraitItem(P<Ty>, Option<P<Expr>>),
793     MethodTraitItem(MethodSig, Option<P<Block>>),
794     TypeTraitItem(TyParamBounds, Option<P<Ty>>),
795 }
796
797 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
798 pub struct ImplItem {
799     pub id: NodeId,
800     pub name: Name,
801     pub vis: Visibility,
802     pub attrs: Vec<Attribute>,
803     pub node: ImplItemKind,
804     pub span: Span,
805 }
806
807 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
808 pub enum ImplItemKind {
809     Const(P<Ty>, P<Expr>),
810     Method(MethodSig, P<Block>),
811     Type(P<Ty>),
812 }
813
814 // Bind a type to an associated type: `A=Foo`.
815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
816 pub struct TypeBinding {
817     pub id: NodeId,
818     pub name: Name,
819     pub ty: P<Ty>,
820     pub span: Span,
821 }
822
823
824 // NB PartialEq method appears below.
825 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
826 pub struct Ty {
827     pub id: NodeId,
828     pub node: Ty_,
829     pub span: Span,
830 }
831
832 impl fmt::Debug for Ty {
833     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
834         write!(f, "type({})", pprust::ty_to_string(self))
835     }
836 }
837
838 /// Not represented directly in the AST, referred to by name through a ty_path.
839 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
840 pub enum PrimTy {
841     TyInt(IntTy),
842     TyUint(UintTy),
843     TyFloat(FloatTy),
844     TyStr,
845     TyBool,
846     TyChar,
847 }
848
849 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
850 pub struct BareFnTy {
851     pub unsafety: Unsafety,
852     pub abi: Abi,
853     pub lifetimes: Vec<LifetimeDef>,
854     pub decl: P<FnDecl>,
855 }
856
857 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
858 /// The different kinds of types recognized by the compiler
859 pub enum Ty_ {
860     TyVec(P<Ty>),
861     /// A fixed length array (`[T; n]`)
862     TyFixedLengthVec(P<Ty>, P<Expr>),
863     /// A raw pointer (`*const T` or `*mut T`)
864     TyPtr(MutTy),
865     /// A reference (`&'a T` or `&'a mut T`)
866     TyRptr(Option<Lifetime>, MutTy),
867     /// A bare function (e.g. `fn(usize) -> bool`)
868     TyBareFn(P<BareFnTy>),
869     /// A tuple (`(A, B, C, D,...)`)
870     TyTup(Vec<P<Ty>>),
871     /// A path (`module::module::...::Type`), optionally
872     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
873     ///
874     /// Type parameters are stored in the Path itself
875     TyPath(Option<QSelf>, Path),
876     /// Something like `A+B`. Note that `B` must always be a path.
877     TyObjectSum(P<Ty>, TyParamBounds),
878     /// A type like `for<'a> Foo<&'a Bar>`
879     TyPolyTraitRef(TyParamBounds),
880     /// Unused for now
881     TyTypeof(P<Expr>),
882     /// TyInfer means the type should be inferred instead of it having been
883     /// specified. This can appear anywhere in a type.
884     TyInfer,
885 }
886
887 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
888 pub struct InlineAsm {
889     pub asm: InternedString,
890     pub asm_str_style: StrStyle,
891     pub outputs: Vec<(InternedString, P<Expr>, bool)>,
892     pub inputs: Vec<(InternedString, P<Expr>)>,
893     pub clobbers: Vec<InternedString>,
894     pub volatile: bool,
895     pub alignstack: bool,
896     pub dialect: AsmDialect,
897     pub expn_id: ExpnId,
898 }
899
900 /// represents an argument in a function header
901 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
902 pub struct Arg {
903     pub ty: P<Ty>,
904     pub pat: P<Pat>,
905     pub id: NodeId,
906 }
907
908 impl Arg {
909     pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
910         let path = Spanned {
911             span: span,
912             node: self_ident,
913         };
914         Arg {
915             // HACK(eddyb) fake type for the self argument.
916             ty: P(Ty {
917                 id: DUMMY_NODE_ID,
918                 node: TyInfer,
919                 span: DUMMY_SP,
920             }),
921             pat: P(Pat {
922                 id: DUMMY_NODE_ID,
923                 node: PatIdent(BindByValue(mutability), path, None),
924                 span: span,
925             }),
926             id: DUMMY_NODE_ID,
927         }
928     }
929 }
930
931 /// Represents the header (not the body) of a function declaration
932 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
933 pub struct FnDecl {
934     pub inputs: Vec<Arg>,
935     pub output: FunctionRetTy,
936     pub variadic: bool,
937 }
938
939 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
940 pub enum Unsafety {
941     Unsafe,
942     Normal,
943 }
944
945 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
946 pub enum Constness {
947     Const,
948     NotConst,
949 }
950
951 impl fmt::Display for Unsafety {
952     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
953         fmt::Display::fmt(match *self {
954                               Unsafety::Normal => "normal",
955                               Unsafety::Unsafe => "unsafe",
956                           },
957                           f)
958     }
959 }
960
961 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
962 pub enum ImplPolarity {
963     /// `impl Trait for Type`
964     Positive,
965     /// `impl !Trait for Type`
966     Negative,
967 }
968
969 impl fmt::Debug for ImplPolarity {
970     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
971         match *self {
972             ImplPolarity::Positive => "positive".fmt(f),
973             ImplPolarity::Negative => "negative".fmt(f),
974         }
975     }
976 }
977
978
979 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
980 pub enum FunctionRetTy {
981     /// Functions with return type `!`that always
982     /// raise an error or exit (i.e. never return to the caller)
983     NoReturn(Span),
984     /// Return type is not specified.
985     ///
986     /// Functions default to `()` and
987     /// closures default to inference. Span points to where return
988     /// type would be inserted.
989     DefaultReturn(Span),
990     /// Everything else
991     Return(P<Ty>),
992 }
993
994 impl FunctionRetTy {
995     pub fn span(&self) -> Span {
996         match *self {
997             NoReturn(span) => span,
998             DefaultReturn(span) => span,
999             Return(ref ty) => ty.span,
1000         }
1001     }
1002 }
1003
1004 /// Represents the kind of 'self' associated with a method
1005 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1006 pub enum ExplicitSelf_ {
1007     /// No self
1008     SelfStatic,
1009     /// `self`
1010     SelfValue(Name),
1011     /// `&'lt self`, `&'lt mut self`
1012     SelfRegion(Option<Lifetime>, Mutability, Name),
1013     /// `self: TYPE`
1014     SelfExplicit(P<Ty>, Name),
1015 }
1016
1017 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1018
1019 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1020 pub struct Mod {
1021     /// A span from the first token past `{` to the last token until `}`.
1022     /// For `mod foo;`, the inner span ranges from the first token
1023     /// to the last token in the external file.
1024     pub inner: Span,
1025     pub item_ids: Vec<ItemId>,
1026 }
1027
1028 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1029 pub struct ForeignMod {
1030     pub abi: Abi,
1031     pub items: Vec<P<ForeignItem>>,
1032 }
1033
1034 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1035 pub struct EnumDef {
1036     pub variants: Vec<P<Variant>>,
1037 }
1038
1039 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1040 pub struct Variant_ {
1041     pub name: Name,
1042     pub attrs: Vec<Attribute>,
1043     pub data: VariantData,
1044     /// Explicit discriminant, eg `Foo = 1`
1045     pub disr_expr: Option<P<Expr>>,
1046 }
1047
1048 pub type Variant = Spanned<Variant_>;
1049
1050 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1051 pub enum PathListItem_ {
1052     PathListIdent {
1053         name: Name,
1054         /// renamed in list, eg `use foo::{bar as baz};`
1055         rename: Option<Name>,
1056         id: NodeId,
1057     },
1058     PathListMod {
1059         /// renamed in list, eg `use foo::{self as baz};`
1060         rename: Option<Name>,
1061         id: NodeId,
1062     },
1063 }
1064
1065 impl PathListItem_ {
1066     pub fn id(&self) -> NodeId {
1067         match *self {
1068             PathListIdent { id, .. } | PathListMod { id, .. } => id,
1069         }
1070     }
1071
1072     pub fn name(&self) -> Option<Name> {
1073         match *self {
1074             PathListIdent { name, .. } => Some(name),
1075             PathListMod { .. } => None,
1076         }
1077     }
1078
1079     pub fn rename(&self) -> Option<Name> {
1080         match *self {
1081             PathListIdent { rename, .. } | PathListMod { rename, .. } => rename,
1082         }
1083     }
1084 }
1085
1086 pub type PathListItem = Spanned<PathListItem_>;
1087
1088 pub type ViewPath = Spanned<ViewPath_>;
1089
1090 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1091 pub enum ViewPath_ {
1092     /// `foo::bar::baz as quux`
1093     ///
1094     /// or just
1095     ///
1096     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1097     ViewPathSimple(Name, Path),
1098
1099     /// `foo::bar::*`
1100     ViewPathGlob(Path),
1101
1102     /// `foo::bar::{a,b,c}`
1103     ViewPathList(Path, Vec<PathListItem>),
1104 }
1105
1106 /// TraitRef's appear in impls.
1107 ///
1108 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1109 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1110 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1111 /// same as the impl's node id).
1112 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1113 pub struct TraitRef {
1114     pub path: Path,
1115     pub ref_id: NodeId,
1116 }
1117
1118 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1119 pub struct PolyTraitRef {
1120     /// The `'a` in `<'a> Foo<&'a T>`
1121     pub bound_lifetimes: Vec<LifetimeDef>,
1122
1123     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1124     pub trait_ref: TraitRef,
1125
1126     pub span: Span,
1127 }
1128
1129 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1130 pub enum Visibility {
1131     Public,
1132     Inherited,
1133 }
1134
1135 impl Visibility {
1136     pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1137         match self {
1138             &Inherited => parent_visibility,
1139             &Public => *self,
1140         }
1141     }
1142 }
1143
1144 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1145 pub struct StructField_ {
1146     pub kind: StructFieldKind,
1147     pub id: NodeId,
1148     pub ty: P<Ty>,
1149     pub attrs: Vec<Attribute>,
1150 }
1151
1152 impl StructField_ {
1153     pub fn name(&self) -> Option<Name> {
1154         match self.kind {
1155             NamedField(name, _) => Some(name),
1156             UnnamedField(_) => None,
1157         }
1158     }
1159 }
1160
1161 pub type StructField = Spanned<StructField_>;
1162
1163 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1164 pub enum StructFieldKind {
1165     NamedField(Name, Visibility),
1166     /// Element of a tuple-like struct
1167     UnnamedField(Visibility),
1168 }
1169
1170 impl StructFieldKind {
1171     pub fn is_unnamed(&self) -> bool {
1172         match *self {
1173             UnnamedField(..) => true,
1174             NamedField(..) => false,
1175         }
1176     }
1177
1178     pub fn visibility(&self) -> Visibility {
1179         match *self {
1180             NamedField(_, vis) | UnnamedField(vis) => vis,
1181         }
1182     }
1183 }
1184
1185 /// Fields and Ids of enum variants and structs
1186 ///
1187 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1188 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1189 /// One shared Id can be successfully used for these two purposes.
1190 /// Id of the whole enum lives in `Item`.
1191 ///
1192 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1193 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1194 /// the variant itself" from enum variants.
1195 /// Id of the whole struct lives in `Item`.
1196 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1197 pub enum VariantData {
1198     Struct(Vec<StructField>, NodeId),
1199     Tuple(Vec<StructField>, NodeId),
1200     Unit(NodeId),
1201 }
1202
1203 impl VariantData {
1204     pub fn fields(&self) -> &[StructField] {
1205         match *self {
1206             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1207             _ => &[],
1208         }
1209     }
1210     pub fn id(&self) -> NodeId {
1211         match *self {
1212             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1213         }
1214     }
1215     pub fn is_struct(&self) -> bool {
1216         if let VariantData::Struct(..) = *self {
1217             true
1218         } else {
1219             false
1220         }
1221     }
1222     pub fn is_tuple(&self) -> bool {
1223         if let VariantData::Tuple(..) = *self {
1224             true
1225         } else {
1226             false
1227         }
1228     }
1229     pub fn is_unit(&self) -> bool {
1230         if let VariantData::Unit(..) = *self {
1231             true
1232         } else {
1233             false
1234         }
1235     }
1236 }
1237
1238 // The bodies for items are stored "out of line", in a separate
1239 // hashmap in the `Crate`. Here we just record the node-id of the item
1240 // so it can fetched later.
1241 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1242 pub struct ItemId {
1243     pub id: NodeId,
1244 }
1245
1246 //  FIXME (#3300): Should allow items to be anonymous. Right now
1247 //  we just use dummy names for anon items.
1248 /// An item
1249 ///
1250 /// The name might be a dummy name in case of anonymous items
1251 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1252 pub struct Item {
1253     pub name: Name,
1254     pub attrs: Vec<Attribute>,
1255     pub id: NodeId,
1256     pub node: Item_,
1257     pub vis: Visibility,
1258     pub span: Span,
1259 }
1260
1261 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1262 pub enum Item_ {
1263     /// An`extern crate` item, with optional original crate name,
1264     ///
1265     /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1266     ItemExternCrate(Option<Name>),
1267     /// A `use` or `pub use` item
1268     ItemUse(P<ViewPath>),
1269
1270     /// A `static` item
1271     ItemStatic(P<Ty>, Mutability, P<Expr>),
1272     /// A `const` item
1273     ItemConst(P<Ty>, P<Expr>),
1274     /// A function declaration
1275     ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1276     /// A module
1277     ItemMod(Mod),
1278     /// An external module
1279     ItemForeignMod(ForeignMod),
1280     /// A type alias, e.g. `type Foo = Bar<u8>`
1281     ItemTy(P<Ty>, Generics),
1282     /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1283     ItemEnum(EnumDef, Generics),
1284     /// A struct definition, e.g. `struct Foo<A> {x: A}`
1285     ItemStruct(VariantData, Generics),
1286     /// Represents a Trait Declaration
1287     ItemTrait(Unsafety, Generics, TyParamBounds, Vec<P<TraitItem>>),
1288
1289     // Default trait implementations
1290     ///
1291     /// `impl Trait for .. {}`
1292     ItemDefaultImpl(Unsafety, TraitRef),
1293     /// An implementation, eg `impl<A> Trait for Foo { .. }`
1294     ItemImpl(Unsafety,
1295              ImplPolarity,
1296              Generics,
1297              Option<TraitRef>, // (optional) trait this impl implements
1298              P<Ty>, // self
1299              Vec<P<ImplItem>>),
1300 }
1301
1302 impl Item_ {
1303     pub fn descriptive_variant(&self) -> &str {
1304         match *self {
1305             ItemExternCrate(..) => "extern crate",
1306             ItemUse(..) => "use",
1307             ItemStatic(..) => "static item",
1308             ItemConst(..) => "constant item",
1309             ItemFn(..) => "function",
1310             ItemMod(..) => "module",
1311             ItemForeignMod(..) => "foreign module",
1312             ItemTy(..) => "type alias",
1313             ItemEnum(..) => "enum",
1314             ItemStruct(..) => "struct",
1315             ItemTrait(..) => "trait",
1316             ItemImpl(..) |
1317             ItemDefaultImpl(..) => "item",
1318         }
1319     }
1320 }
1321
1322 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1323 pub struct ForeignItem {
1324     pub name: Name,
1325     pub attrs: Vec<Attribute>,
1326     pub node: ForeignItem_,
1327     pub id: NodeId,
1328     pub span: Span,
1329     pub vis: Visibility,
1330 }
1331
1332 /// An item within an `extern` block
1333 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1334 pub enum ForeignItem_ {
1335     /// A foreign function
1336     ForeignItemFn(P<FnDecl>, Generics),
1337     /// A foreign static item (`static ext: u8`), with optional mutability
1338     /// (the boolean is true when mutable)
1339     ForeignItemStatic(P<Ty>, bool),
1340 }
1341
1342 impl ForeignItem_ {
1343     pub fn descriptive_variant(&self) -> &str {
1344         match *self {
1345             ForeignItemFn(..) => "foreign function",
1346             ForeignItemStatic(..) => "foreign static item",
1347         }
1348     }
1349 }