]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
check: Reword the warning to be more prescriptive
[rust.git] / src / libsyntax / ast.rs
1 // Copyright 2012-2014 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 abstract syntax tree.
12
13 pub use self::AsmDialect::*;
14 pub use self::AttrStyle::*;
15 pub use self::BindingMode::*;
16 pub use self::BinOp_::*;
17 pub use self::BlockCheckMode::*;
18 pub use self::CaptureClause::*;
19 pub use self::Decl_::*;
20 pub use self::ExplicitSelf_::*;
21 pub use self::Expr_::*;
22 pub use self::FloatTy::*;
23 pub use self::FunctionRetTy::*;
24 pub use self::ForeignItem_::*;
25 pub use self::ImplItem_::*;
26 pub use self::InlinedItem::*;
27 pub use self::IntTy::*;
28 pub use self::Item_::*;
29 pub use self::KleeneOp::*;
30 pub use self::Lit_::*;
31 pub use self::LitIntType::*;
32 pub use self::LocalSource::*;
33 pub use self::Mac_::*;
34 pub use self::MacStmtStyle::*;
35 pub use self::MetaItem_::*;
36 pub use self::Mutability::*;
37 pub use self::Pat_::*;
38 pub use self::PathListItem_::*;
39 pub use self::PatWildKind::*;
40 pub use self::PrimTy::*;
41 pub use self::Sign::*;
42 pub use self::Stmt_::*;
43 pub use self::StrStyle::*;
44 pub use self::StructFieldKind::*;
45 pub use self::TokenTree::*;
46 pub use self::TraitItem_::*;
47 pub use self::Ty_::*;
48 pub use self::TyParamBound::*;
49 pub use self::UintTy::*;
50 pub use self::UnOp::*;
51 pub use self::UnsafeSource::*;
52 pub use self::VariantKind::*;
53 pub use self::ViewPath_::*;
54 pub use self::Visibility::*;
55 pub use self::PathParameters::*;
56
57 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
58 use abi::Abi;
59 use ast_util;
60 use ext::base;
61 use ext::tt::macro_parser;
62 use owned_slice::OwnedSlice;
63 use parse::token::{InternedString, str_to_ident};
64 use parse::token;
65 use parse::lexer;
66 use ptr::P;
67
68 use std::fmt;
69 use std::num::Int;
70 use std::rc::Rc;
71 use serialize::{Encodable, Decodable, Encoder, Decoder};
72
73 // FIXME #6993: in librustc, uses of "ident" should be replaced
74 // by just "Name".
75
76 /// An identifier contains a Name (index into the interner
77 /// table) and a SyntaxContext to track renaming and
78 /// macro expansion per Flatt et al., "Macros
79 /// That Work Together"
80 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
81 pub struct Ident {
82     pub name: Name,
83     pub ctxt: SyntaxContext
84 }
85
86 impl Ident {
87     /// Construct an identifier with the given name and an empty context:
88     pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
89
90     pub fn as_str<'a>(&'a self) -> &'a str {
91         self.name.as_str()
92     }
93
94     pub fn encode_with_hygiene(&self) -> String {
95         format!("\x00name_{},ctxt_{}\x00",
96                 self.name.usize(),
97                 self.ctxt)
98     }
99 }
100
101 impl fmt::Debug for Ident {
102     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
103         write!(f, "{}#{}", self.name, self.ctxt)
104     }
105 }
106
107 impl fmt::Display for Ident {
108     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109         fmt::Display::fmt(&self.name, f)
110     }
111 }
112
113 impl fmt::Debug for Name {
114     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115         let Name(nm) = *self;
116         write!(f, "{:?}({})", token::get_name(*self), nm)
117     }
118 }
119
120 impl fmt::Display for Name {
121     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
122         fmt::Display::fmt(&token::get_name(*self), f)
123     }
124 }
125
126 impl PartialEq for Ident {
127     fn eq(&self, other: &Ident) -> bool {
128         if self.ctxt == other.ctxt {
129             self.name == other.name
130         } else {
131             // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
132             // idents that have different contexts. You can't fix this without
133             // knowing whether the comparison should be hygienic or non-hygienic.
134             // if it should be non-hygienic (most things are), just compare the
135             // 'name' fields of the idents. Or, even better, replace the idents
136             // with Name's.
137             //
138             // On the other hand, if the comparison does need to be hygienic,
139             // one example and its non-hygienic counterpart would be:
140             //      syntax::parse::token::Token::mtwt_eq
141             //      syntax::ext::tt::macro_parser::token_name_eq
142             panic!("not allowed to compare these idents: {}, {}. \
143                    Probably related to issue \\#6993", self, other);
144         }
145     }
146     fn ne(&self, other: &Ident) -> bool {
147         ! self.eq(other)
148     }
149 }
150
151 /// A SyntaxContext represents a chain of macro-expandings
152 /// and renamings. Each macro expansion corresponds to
153 /// a fresh u32
154
155 // I'm representing this syntax context as an index into
156 // a table, in order to work around a compiler bug
157 // that's causing unreleased memory to cause core dumps
158 // and also perhaps to save some work in destructor checks.
159 // the special uint '0' will be used to indicate an empty
160 // syntax context.
161
162 // this uint is a reference to a table stored in thread-local
163 // storage.
164 pub type SyntaxContext = u32;
165 pub const EMPTY_CTXT : SyntaxContext = 0;
166 pub const ILLEGAL_CTXT : SyntaxContext = 1;
167
168 /// A name is a part of an identifier, representing a string or gensym. It's
169 /// the result of interning.
170 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
171            RustcEncodable, RustcDecodable, Clone, Copy)]
172 pub struct Name(pub u32);
173
174 impl Name {
175     pub fn as_str<'a>(&'a self) -> &'a str {
176         unsafe {
177             // FIXME #12938: can't use copy_lifetime since &str isn't a &T
178             ::std::mem::transmute::<&str,&str>(&token::get_name(*self))
179         }
180     }
181
182     pub fn usize(&self) -> usize {
183         let Name(nm) = *self;
184         nm as usize
185     }
186
187     pub fn ident(&self) -> Ident {
188         Ident { name: *self, ctxt: 0 }
189     }
190 }
191
192 /// A mark represents a unique id associated with a macro expansion
193 pub type Mrk = u32;
194
195 impl Encodable for Ident {
196     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
197         s.emit_str(&token::get_ident(*self))
198     }
199 }
200
201 impl Decodable for Ident {
202     fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
203         Ok(str_to_ident(&try!(d.read_str())[..]))
204     }
205 }
206
207 /// Function name (not all functions have names)
208 pub type FnIdent = Option<Ident>;
209
210 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,
211            Debug, Copy)]
212 pub struct Lifetime {
213     pub id: NodeId,
214     pub span: Span,
215     pub name: Name
216 }
217
218 /// A lifetime definition, eg `'a: 'b+'c+'d`
219 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
220 pub struct LifetimeDef {
221     pub lifetime: Lifetime,
222     pub bounds: Vec<Lifetime>
223 }
224
225 /// A "Path" is essentially Rust's notion of a name; for instance:
226 /// std::cmp::PartialEq  .  It's represented as a sequence of identifiers,
227 /// along with a bunch of supporting information.
228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
229 pub struct Path {
230     pub span: Span,
231     /// A `::foo` path, is relative to the crate root rather than current
232     /// module (like paths in an import).
233     pub global: bool,
234     /// The segments in the path: the things separated by `::`.
235     pub segments: Vec<PathSegment>,
236 }
237
238 /// A segment of a path: an identifier, an optional lifetime, and a set of
239 /// types.
240 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
241 pub struct PathSegment {
242     /// The identifier portion of this path segment.
243     pub identifier: Ident,
244
245     /// Type/lifetime parameters attached to this path. They come in
246     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
247     /// this is more than just simple syntactic sugar; the use of
248     /// parens affects the region binding rules, so we preserve the
249     /// distinction.
250     pub parameters: PathParameters,
251 }
252
253 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
254 pub enum PathParameters {
255     /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
256     AngleBracketedParameters(AngleBracketedParameterData),
257     /// The `(A,B)` and `C` in `Foo(A,B) -> C`
258     ParenthesizedParameters(ParenthesizedParameterData),
259 }
260
261 impl PathParameters {
262     pub fn none() -> PathParameters {
263         AngleBracketedParameters(AngleBracketedParameterData {
264             lifetimes: Vec::new(),
265             types: OwnedSlice::empty(),
266             bindings: OwnedSlice::empty(),
267         })
268     }
269
270     pub fn is_empty(&self) -> bool {
271         match *self {
272             AngleBracketedParameters(ref data) => data.is_empty(),
273
274             // Even if the user supplied no types, something like
275             // `X()` is equivalent to `X<(),()>`.
276             ParenthesizedParameters(..) => false,
277         }
278     }
279
280     pub fn has_lifetimes(&self) -> bool {
281         match *self {
282             AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
283             ParenthesizedParameters(_) => false,
284         }
285     }
286
287     pub fn has_types(&self) -> bool {
288         match *self {
289             AngleBracketedParameters(ref data) => !data.types.is_empty(),
290             ParenthesizedParameters(..) => true,
291         }
292     }
293
294     /// Returns the types that the user wrote. Note that these do not necessarily map to the type
295     /// parameters in the parenthesized case.
296     pub fn types(&self) -> Vec<&P<Ty>> {
297         match *self {
298             AngleBracketedParameters(ref data) => {
299                 data.types.iter().collect()
300             }
301             ParenthesizedParameters(ref data) => {
302                 data.inputs.iter()
303                     .chain(data.output.iter())
304                     .collect()
305             }
306         }
307     }
308
309     pub fn lifetimes(&self) -> Vec<&Lifetime> {
310         match *self {
311             AngleBracketedParameters(ref data) => {
312                 data.lifetimes.iter().collect()
313             }
314             ParenthesizedParameters(_) => {
315                 Vec::new()
316             }
317         }
318     }
319
320     pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
321         match *self {
322             AngleBracketedParameters(ref data) => {
323                 data.bindings.iter().collect()
324             }
325             ParenthesizedParameters(_) => {
326                 Vec::new()
327             }
328         }
329     }
330 }
331
332 /// A path like `Foo<'a, T>`
333 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
334 pub struct AngleBracketedParameterData {
335     /// The lifetime parameters for this path segment.
336     pub lifetimes: Vec<Lifetime>,
337     /// The type parameters for this path segment, if present.
338     pub types: OwnedSlice<P<Ty>>,
339     /// Bindings (equality constraints) on associated types, if present.
340     /// E.g., `Foo<A=Bar>`.
341     pub bindings: OwnedSlice<P<TypeBinding>>,
342 }
343
344 impl AngleBracketedParameterData {
345     fn is_empty(&self) -> bool {
346         self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
347     }
348 }
349
350 /// A path like `Foo(A,B) -> C`
351 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
352 pub struct ParenthesizedParameterData {
353     /// Overall span
354     pub span: Span,
355
356     /// `(A,B)`
357     pub inputs: Vec<P<Ty>>,
358
359     /// `C`
360     pub output: Option<P<Ty>>,
361 }
362
363 pub type CrateNum = u32;
364
365 pub type NodeId = u32;
366
367 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
368            RustcDecodable, Hash, Debug, Copy)]
369 pub struct DefId {
370     pub krate: CrateNum,
371     pub node: NodeId,
372 }
373
374 impl DefId {
375     /// Read the node id, asserting that this def-id is krate-local.
376     pub fn local_id(&self) -> NodeId {
377         assert_eq!(self.krate, LOCAL_CRATE);
378         self.node
379     }
380 }
381
382 /// Item definitions in the currently-compiled crate would have the CrateNum
383 /// LOCAL_CRATE in their DefId.
384 pub const LOCAL_CRATE: CrateNum = 0;
385 pub const CRATE_NODE_ID: NodeId = 0;
386
387 /// When parsing and doing expansions, we initially give all AST nodes this AST
388 /// node value. Then later, in the renumber pass, we renumber them to have
389 /// small, positive ids.
390 pub const DUMMY_NODE_ID: NodeId = -1;
391
392 /// The AST represents all type param bounds as types.
393 /// typeck::collect::compute_bounds matches these against
394 /// the "special" built-in traits (see middle::lang_items) and
395 /// detects Copy, Send and Sync.
396 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
397 pub enum TyParamBound {
398     TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
399     RegionTyParamBound(Lifetime)
400 }
401
402 /// A modifier on a bound, currently this is only used for `?Sized`, where the
403 /// modifier is `Maybe`. Negative bounds should also be handled here.
404 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
405 pub enum TraitBoundModifier {
406     None,
407     Maybe,
408 }
409
410 pub type TyParamBounds = OwnedSlice<TyParamBound>;
411
412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
413 pub struct TyParam {
414     pub ident: Ident,
415     pub id: NodeId,
416     pub bounds: TyParamBounds,
417     pub default: Option<P<Ty>>,
418     pub span: Span
419 }
420
421 /// Represents lifetimes and type parameters attached to a declaration
422 /// of a function, enum, trait, etc.
423 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
424 pub struct Generics {
425     pub lifetimes: Vec<LifetimeDef>,
426     pub ty_params: OwnedSlice<TyParam>,
427     pub where_clause: WhereClause,
428 }
429
430 impl Generics {
431     pub fn is_parameterized(&self) -> bool {
432         self.lifetimes.len() + self.ty_params.len() > 0
433     }
434     pub fn is_lt_parameterized(&self) -> bool {
435         self.lifetimes.len() > 0
436     }
437     pub fn is_type_parameterized(&self) -> bool {
438         self.ty_params.len() > 0
439     }
440 }
441
442 /// A `where` clause in a definition
443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
444 pub struct WhereClause {
445     pub id: NodeId,
446     pub predicates: Vec<WherePredicate>,
447 }
448
449 /// A single predicate in a `where` clause
450 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
451 pub enum WherePredicate {
452     /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
453     BoundPredicate(WhereBoundPredicate),
454     /// A lifetime predicate, e.g. `'a: 'b+'c`
455     RegionPredicate(WhereRegionPredicate),
456     /// An equality predicate (unsupported)
457     EqPredicate(WhereEqPredicate)
458 }
459
460 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
461 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
462 pub struct WhereBoundPredicate {
463     pub span: Span,
464     /// Any lifetimes from a `for` binding
465     pub bound_lifetimes: Vec<LifetimeDef>,
466     /// The type being bounded
467     pub bounded_ty: P<Ty>,
468     /// Trait and lifetime bounds (`Clone+Send+'static`)
469     pub bounds: OwnedSlice<TyParamBound>,
470 }
471
472 /// A lifetime predicate, e.g. `'a: 'b+'c`
473 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
474 pub struct WhereRegionPredicate {
475     pub span: Span,
476     pub lifetime: Lifetime,
477     pub bounds: Vec<Lifetime>,
478 }
479
480 /// An equality predicate (unsupported), e.g. `T=int`
481 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
482 pub struct WhereEqPredicate {
483     pub id: NodeId,
484     pub span: Span,
485     pub path: Path,
486     pub ty: P<Ty>,
487 }
488
489 /// The set of MetaItems that define the compilation environment of the crate,
490 /// used to drive conditional compilation
491 pub type CrateConfig = Vec<P<MetaItem>> ;
492
493 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
494 pub struct Crate {
495     pub module: Mod,
496     pub attrs: Vec<Attribute>,
497     pub config: CrateConfig,
498     pub span: Span,
499     pub exported_macros: Vec<MacroDef>,
500 }
501
502 pub type MetaItem = Spanned<MetaItem_>;
503
504 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
505 pub enum MetaItem_ {
506     MetaWord(InternedString),
507     MetaList(InternedString, Vec<P<MetaItem>>),
508     MetaNameValue(InternedString, Lit),
509 }
510
511 // can't be derived because the MetaList requires an unordered comparison
512 impl PartialEq for MetaItem_ {
513     fn eq(&self, other: &MetaItem_) -> bool {
514         match *self {
515             MetaWord(ref ns) => match *other {
516                 MetaWord(ref no) => (*ns) == (*no),
517                 _ => false
518             },
519             MetaNameValue(ref ns, ref vs) => match *other {
520                 MetaNameValue(ref no, ref vo) => {
521                     (*ns) == (*no) && vs.node == vo.node
522                 }
523                 _ => false
524             },
525             MetaList(ref ns, ref miss) => match *other {
526                 MetaList(ref no, ref miso) => {
527                     ns == no &&
528                         miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
529                 }
530                 _ => false
531             }
532         }
533     }
534 }
535
536 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
537 pub struct Block {
538     /// Statements in a block
539     pub stmts: Vec<P<Stmt>>,
540     /// An expression at the end of the block
541     /// without a semicolon, if any
542     pub expr: Option<P<Expr>>,
543     pub id: NodeId,
544     /// Distinguishes between `unsafe { ... }` and `{ ... }`
545     pub rules: BlockCheckMode,
546     pub span: Span,
547 }
548
549 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
550 pub struct Pat {
551     pub id: NodeId,
552     pub node: Pat_,
553     pub span: Span,
554 }
555
556 /// A single field in a struct pattern
557 ///
558 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
559 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
560 /// except is_shorthand is true
561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
562 pub struct FieldPat {
563     /// The identifier for the field
564     pub ident: Ident,
565     /// The pattern the field is destructured to
566     pub pat: P<Pat>,
567     pub is_shorthand: bool,
568 }
569
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
571 pub enum BindingMode {
572     BindByRef(Mutability),
573     BindByValue(Mutability),
574 }
575
576 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
577 pub enum PatWildKind {
578     /// Represents the wildcard pattern `_`
579     PatWildSingle,
580
581     /// Represents the wildcard pattern `..`
582     PatWildMulti,
583 }
584
585 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
586 pub enum Pat_ {
587     /// Represents a wildcard pattern (either `_` or `..`)
588     PatWild(PatWildKind),
589
590     /// A PatIdent may either be a new bound variable,
591     /// or a nullary enum (in which case the third field
592     /// is None).
593     ///
594     /// In the nullary enum case, the parser can't determine
595     /// which it is. The resolver determines this, and
596     /// records this pattern's NodeId in an auxiliary
597     /// set (of "PatIdents that refer to nullary enums")
598     PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
599
600     /// "None" means a * pattern where we don't bind the fields to names.
601     PatEnum(Path, Option<Vec<P<Pat>>>),
602
603     /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
604     /// The `bool` is `true` in the presence of a `..`
605     PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
606     /// A tuple pattern `(a, b)`
607     PatTup(Vec<P<Pat>>),
608     /// A `box` pattern
609     PatBox(P<Pat>),
610     /// A reference pattern, e.g. `&mut (a, b)`
611     PatRegion(P<Pat>, Mutability),
612     /// A literal
613     PatLit(P<Expr>),
614     /// A range pattern, e.g. `1...2`
615     PatRange(P<Expr>, P<Expr>),
616     /// [a, b, ..i, y, z] is represented as:
617     ///     PatVec(box [a, b], Some(i), box [y, z])
618     PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
619     /// A macro pattern; pre-expansion
620     PatMac(Mac),
621 }
622
623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
624 pub enum Mutability {
625     MutMutable,
626     MutImmutable,
627 }
628
629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
630 pub enum BinOp_ {
631     /// The `+` operator (addition)
632     BiAdd,
633     /// The `-` operator (subtraction)
634     BiSub,
635     /// The `*` operator (multiplication)
636     BiMul,
637     /// The `/` operator (division)
638     BiDiv,
639     /// The `%` operator (modulus)
640     BiRem,
641     /// The `&&` operator (logical and)
642     BiAnd,
643     /// The `||` operator (logical or)
644     BiOr,
645     /// The `^` operator (bitwise xor)
646     BiBitXor,
647     /// The `&` operator (bitwise and)
648     BiBitAnd,
649     /// The `|` operator (bitwise or)
650     BiBitOr,
651     /// The `<<` operator (shift left)
652     BiShl,
653     /// The `>>` operator (shift right)
654     BiShr,
655     /// The `==` operator (equality)
656     BiEq,
657     /// The `<` operator (less than)
658     BiLt,
659     /// The `<=` operator (less than or equal to)
660     BiLe,
661     /// The `!=` operator (not equal to)
662     BiNe,
663     /// The `>=` operator (greater than or equal to)
664     BiGe,
665     /// The `>` operator (greater than)
666     BiGt,
667 }
668
669 pub type BinOp = Spanned<BinOp_>;
670
671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
672 pub enum UnOp {
673     /// The `box` operator
674     UnUniq,
675     /// The `*` operator for dereferencing
676     UnDeref,
677     /// The `!` operator for logical inversion
678     UnNot,
679     /// The `-` operator for negation
680     UnNeg
681 }
682
683 /// A statement
684 pub type Stmt = Spanned<Stmt_>;
685
686 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
687 pub enum Stmt_ {
688     /// Could be an item or a local (let) binding:
689     StmtDecl(P<Decl>, NodeId),
690
691     /// Expr without trailing semi-colon (must have unit type):
692     StmtExpr(P<Expr>, NodeId),
693
694     /// Expr with trailing semi-colon (may have any type):
695     StmtSemi(P<Expr>, NodeId),
696
697     StmtMac(P<Mac>, MacStmtStyle),
698 }
699
700 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
701 pub enum MacStmtStyle {
702     /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
703     /// `foo!(...);`, `foo![...];`
704     MacStmtWithSemicolon,
705     /// The macro statement had braces; e.g. foo! { ... }
706     MacStmtWithBraces,
707     /// The macro statement had parentheses or brackets and no semicolon; e.g.
708     /// `foo!(...)`. All of these will end up being converted into macro
709     /// expressions.
710     MacStmtWithoutBraces,
711 }
712
713 /// Where a local declaration came from: either a true `let ... =
714 /// ...;`, or one desugared from the pattern of a for loop.
715 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
716 pub enum LocalSource {
717     LocalLet,
718     LocalFor,
719 }
720
721 // FIXME (pending discussion of #1697, #2178...): local should really be
722 // a refinement on pat.
723 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
724 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
725 pub struct Local {
726     pub pat: P<Pat>,
727     pub ty: Option<P<Ty>>,
728     /// Initializer expression to set the value, if any
729     pub init: Option<P<Expr>>,
730     pub id: NodeId,
731     pub span: Span,
732     pub source: LocalSource,
733 }
734
735 pub type Decl = Spanned<Decl_>;
736
737 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
738 pub enum Decl_ {
739     /// A local (let) binding:
740     DeclLocal(P<Local>),
741     /// An item binding:
742     DeclItem(P<Item>),
743 }
744
745 /// represents one arm of a 'match'
746 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
747 pub struct Arm {
748     pub attrs: Vec<Attribute>,
749     pub pats: Vec<P<Pat>>,
750     pub guard: Option<P<Expr>>,
751     pub body: P<Expr>,
752 }
753
754 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
755 pub struct Field {
756     pub ident: SpannedIdent,
757     pub expr: P<Expr>,
758     pub span: Span,
759 }
760
761 pub type SpannedIdent = Spanned<Ident>;
762
763 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
764 pub enum BlockCheckMode {
765     DefaultBlock,
766     UnsafeBlock(UnsafeSource),
767 }
768
769 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
770 pub enum UnsafeSource {
771     CompilerGenerated,
772     UserProvided,
773 }
774
775 /// An expression
776 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
777 pub struct Expr {
778     pub id: NodeId,
779     pub node: Expr_,
780     pub span: Span,
781 }
782
783 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
784 pub enum Expr_ {
785     /// First expr is the place; second expr is the value.
786     ExprBox(Option<P<Expr>>, P<Expr>),
787     /// An array (`[a, b, c, d]`)
788     ExprVec(Vec<P<Expr>>),
789     /// A function call
790     ///
791     /// The first field resolves to the function itself,
792     /// and the second field is the list of arguments
793     ExprCall(P<Expr>, Vec<P<Expr>>),
794     /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
795     ///
796     /// The `SpannedIdent` is the identifier for the method name.
797     /// The vector of `Ty`s are the ascripted type parameters for the method
798     /// (within the angle brackets).
799     ///
800     /// The first element of the vector of `Expr`s is the expression that evaluates
801     /// to the object on which the method is being called on (the receiver),
802     /// and the remaining elements are the rest of the arguments.
803     ///
804     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
805     /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
806     ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
807     /// A tuple (`(a, b, c ,d)`)
808     ExprTup(Vec<P<Expr>>),
809     /// A binary operation (For example: `a + b`, `a * b`)
810     ExprBinary(BinOp, P<Expr>, P<Expr>),
811     /// A unary operation (For example: `!x`, `*x`)
812     ExprUnary(UnOp, P<Expr>),
813     /// A literal (For example: `1u8`, `"foo"`)
814     ExprLit(P<Lit>),
815     /// A cast (`foo as f64`)
816     ExprCast(P<Expr>, P<Ty>),
817     /// An `if` block, with an optional else block
818     ///
819     /// `if expr { block } else { expr }`
820     ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
821     /// An `if let` expression with an optional else block
822     ///
823     /// `if let pat = expr { block } else { expr }`
824     ///
825     /// This is desugared to a `match` expression.
826     ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
827     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
828     /// A while loop, with an optional label
829     ///
830     /// `'label: while expr { block }`
831     ExprWhile(P<Expr>, P<Block>, Option<Ident>),
832     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
833     /// A while-let loop, with an optional label
834     ///
835     /// `'label: while let pat = expr { block }`
836     ///
837     /// This is desugared to a combination of `loop` and `match` expressions.
838     ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
839     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
840     /// A for loop, with an optional label
841     ///
842     /// `'label: for pat in expr { block }`
843     ///
844     /// This is desugared to a combination of `loop` and `match` expressions.
845     ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
846     /// Conditionless loop (can be exited with break, continue, or return)
847     ///
848     /// `'label: loop { block }`
849     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
850     ExprLoop(P<Block>, Option<Ident>),
851     /// A `match` block, with a source that indicates whether or not it is
852     /// the result of a desugaring, and if so, which kind.
853     ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
854     /// A closure (for example, `move |a, b, c| {a + b + c}`)
855     ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
856     /// A block (`{ ... }`)
857     ExprBlock(P<Block>),
858
859     /// An assignment (`a = foo()`)
860     ExprAssign(P<Expr>, P<Expr>),
861     /// An assignment with an operator
862     ///
863     /// For example, `a += 1`.
864     ExprAssignOp(BinOp, P<Expr>, P<Expr>),
865     /// Access of a named struct field (`obj.foo`)
866     ExprField(P<Expr>, SpannedIdent),
867     /// Access of an unnamed field of a struct or tuple-struct
868     ///
869     /// For example, `foo.0`.
870     ExprTupField(P<Expr>, Spanned<usize>),
871     /// An indexing operation (`foo[2]`)
872     ExprIndex(P<Expr>, P<Expr>),
873     /// A range (`1..2`, `1..`, or `..2`)
874     ExprRange(Option<P<Expr>>, Option<P<Expr>>),
875
876     /// Variable reference, possibly containing `::` and/or type
877     /// parameters, e.g. foo::bar::<baz>.
878     ///
879     /// Optionally "qualified",
880     /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
881     ExprPath(Option<QSelf>, Path),
882
883     /// A referencing operation (`&a` or `&mut a`)
884     ExprAddrOf(Mutability, P<Expr>),
885     /// A `break`, with an optional label to break
886     ExprBreak(Option<Ident>),
887     /// A `continue`, with an optional label
888     ExprAgain(Option<Ident>),
889     /// A `return`, with an optional value to be returned
890     ExprRet(Option<P<Expr>>),
891
892     /// Output of the `asm!()` macro
893     ExprInlineAsm(InlineAsm),
894
895     /// A macro invocation; pre-expansion
896     ExprMac(Mac),
897
898     /// A struct literal expression.
899     ///
900     /// For example, `Foo {x: 1, y: 2}`, or
901     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
902     ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
903
904     /// A vector literal constructed from one repeated element.
905     ///
906     /// For example, `[1u8; 5]`. The first expression is the element
907     /// to be repeated; the second is the number of times to repeat it.
908     ExprRepeat(P<Expr>, P<Expr>),
909
910     /// No-op: used solely so we can pretty-print faithfully
911     ExprParen(P<Expr>)
912 }
913
914 /// The explicit Self type in a "qualified path". The actual
915 /// path, including the trait and the associated item, is stored
916 /// separately. `position` represents the index of the associated
917 /// item qualified with this Self type.
918 ///
919 ///     <Vec<T> as a::b::Trait>::AssociatedItem
920 ///      ^~~~~     ~~~~~~~~~~~~~~^
921 ///      ty        position = 3
922 ///
923 ///     <Vec<T>>::AssociatedItem
924 ///      ^~~~~    ^
925 ///      ty       position = 0
926 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
927 pub struct QSelf {
928     pub ty: P<Ty>,
929     pub position: usize
930 }
931
932 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
933 pub enum MatchSource {
934     Normal,
935     IfLetDesugar { contains_else_clause: bool },
936     WhileLetDesugar,
937     ForLoopDesugar,
938 }
939
940 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
941 pub enum CaptureClause {
942     CaptureByValue,
943     CaptureByRef,
944 }
945
946 /// A delimited sequence of token trees
947 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
948 pub struct Delimited {
949     /// The type of delimiter
950     pub delim: token::DelimToken,
951     /// The span covering the opening delimiter
952     pub open_span: Span,
953     /// The delimited sequence of token trees
954     pub tts: Vec<TokenTree>,
955     /// The span covering the closing delimiter
956     pub close_span: Span,
957 }
958
959 impl Delimited {
960     /// Returns the opening delimiter as a token.
961     pub fn open_token(&self) -> token::Token {
962         token::OpenDelim(self.delim)
963     }
964
965     /// Returns the closing delimiter as a token.
966     pub fn close_token(&self) -> token::Token {
967         token::CloseDelim(self.delim)
968     }
969
970     /// Returns the opening delimiter as a token tree.
971     pub fn open_tt(&self) -> TokenTree {
972         TtToken(self.open_span, self.open_token())
973     }
974
975     /// Returns the closing delimiter as a token tree.
976     pub fn close_tt(&self) -> TokenTree {
977         TtToken(self.close_span, self.close_token())
978     }
979 }
980
981 /// A sequence of token treesee
982 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
983 pub struct SequenceRepetition {
984     /// The sequence of token trees
985     pub tts: Vec<TokenTree>,
986     /// The optional separator
987     pub separator: Option<token::Token>,
988     /// Whether the sequence can be repeated zero (*), or one or more times (+)
989     pub op: KleeneOp,
990     /// The number of `MatchNt`s that appear in the sequence (and subsequences)
991     pub num_captures: usize,
992 }
993
994 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
995 /// for token sequences.
996 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
997 pub enum KleeneOp {
998     ZeroOrMore,
999     OneOrMore,
1000 }
1001
1002 /// When the main rust parser encounters a syntax-extension invocation, it
1003 /// parses the arguments to the invocation as a token-tree. This is a very
1004 /// loose structure, such that all sorts of different AST-fragments can
1005 /// be passed to syntax extensions using a uniform type.
1006 ///
1007 /// If the syntax extension is an MBE macro, it will attempt to match its
1008 /// LHS token tree against the provided token tree, and if it finds a
1009 /// match, will transcribe the RHS token tree, splicing in any captured
1010 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1011 ///
1012 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1013 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1014 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1015 pub enum TokenTree {
1016     /// A single token
1017     TtToken(Span, token::Token),
1018     /// A delimited sequence of token trees
1019     TtDelimited(Span, Rc<Delimited>),
1020
1021     // This only makes sense in MBE macros.
1022
1023     /// A kleene-style repetition sequence with a span
1024     // FIXME(eddyb) #12938 Use DST.
1025     TtSequence(Span, Rc<SequenceRepetition>),
1026 }
1027
1028 impl TokenTree {
1029     pub fn len(&self) -> usize {
1030         match *self {
1031             TtToken(_, token::DocComment(_)) => 2,
1032             TtToken(_, token::SpecialVarNt(..)) => 2,
1033             TtToken(_, token::MatchNt(..)) => 3,
1034             TtDelimited(_, ref delimed) => {
1035                 delimed.tts.len() + 2
1036             }
1037             TtSequence(_, ref seq) => {
1038                 seq.tts.len()
1039             }
1040             TtToken(..) => 0
1041         }
1042     }
1043
1044     pub fn get_tt(&self, index: usize) -> TokenTree {
1045         match (self, index) {
1046             (&TtToken(sp, token::DocComment(_)), 0) => {
1047                 TtToken(sp, token::Pound)
1048             }
1049             (&TtToken(sp, token::DocComment(name)), 1) => {
1050                 TtDelimited(sp, Rc::new(Delimited {
1051                     delim: token::Bracket,
1052                     open_span: sp,
1053                     tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1054                                                        token::Plain)),
1055                               TtToken(sp, token::Eq),
1056                               TtToken(sp, token::Literal(token::Str_(name), None))],
1057                     close_span: sp,
1058                 }))
1059             }
1060             (&TtDelimited(_, ref delimed), _) => {
1061                 if index == 0 {
1062                     return delimed.open_tt();
1063                 }
1064                 if index == delimed.tts.len() + 1 {
1065                     return delimed.close_tt();
1066                 }
1067                 delimed.tts[index - 1].clone()
1068             }
1069             (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1070                 let v = [TtToken(sp, token::Dollar),
1071                          TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1072                                                   token::Plain))];
1073                 v[index].clone()
1074             }
1075             (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1076                 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1077                          TtToken(sp, token::Colon),
1078                          TtToken(sp, token::Ident(kind, kind_st))];
1079                 v[index].clone()
1080             }
1081             (&TtSequence(_, ref seq), _) => {
1082                 seq.tts[index].clone()
1083             }
1084             _ => panic!("Cannot expand a token tree")
1085         }
1086     }
1087
1088     /// Returns the `Span` corresponding to this token tree.
1089     pub fn get_span(&self) -> Span {
1090         match *self {
1091             TtToken(span, _)     => span,
1092             TtDelimited(span, _) => span,
1093             TtSequence(span, _)  => span,
1094         }
1095     }
1096
1097     /// Use this token tree as a matcher to parse given tts.
1098     pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1099                  -> macro_parser::NamedParseResult {
1100         // `None` is because we're not interpolating
1101         let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1102                                                          None,
1103                                                          None,
1104                                                          tts.iter().cloned().collect(),
1105                                                          true);
1106         macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1107     }
1108 }
1109
1110 pub type Mac = Spanned<Mac_>;
1111
1112 /// Represents a macro invocation. The Path indicates which macro
1113 /// is being invoked, and the vector of token-trees contains the source
1114 /// of the macro invocation.
1115 ///
1116 /// There's only one flavor, now, so this could presumably be simplified.
1117 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1118 pub enum Mac_ {
1119     // NB: the additional ident for a macro_rules-style macro is actually
1120     // stored in the enclosing item. Oog.
1121     MacInvocTT(Path, Vec<TokenTree>, SyntaxContext),   // new macro-invocation
1122 }
1123
1124 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1125 pub enum StrStyle {
1126     /// A regular string, like `"foo"`
1127     CookedStr,
1128     /// A raw string, like `r##"foo"##`
1129     ///
1130     /// The uint is the number of `#` symbols used
1131     RawStr(usize)
1132 }
1133
1134 /// A literal
1135 pub type Lit = Spanned<Lit_>;
1136
1137 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1138 pub enum Sign {
1139     Minus,
1140     Plus
1141 }
1142
1143 impl Sign {
1144     pub fn new<T:Int>(n: T) -> Sign {
1145         if n < Int::zero() {
1146             Minus
1147         } else {
1148             Plus
1149         }
1150     }
1151 }
1152
1153 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1154 pub enum LitIntType {
1155     SignedIntLit(IntTy, Sign),
1156     UnsignedIntLit(UintTy),
1157     UnsuffixedIntLit(Sign)
1158 }
1159
1160 impl LitIntType {
1161     pub fn suffix_len(&self) -> usize {
1162         match *self {
1163             UnsuffixedIntLit(_) => 0,
1164             SignedIntLit(s, _) => s.suffix_len(),
1165             UnsignedIntLit(u) => u.suffix_len()
1166         }
1167     }
1168 }
1169
1170 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1171 pub enum Lit_ {
1172     /// A string literal (`"foo"`)
1173     LitStr(InternedString, StrStyle),
1174     /// A byte string (`b"foo"`)
1175     LitBinary(Rc<Vec<u8>>),
1176     /// A byte char (`b'f'`)
1177     LitByte(u8),
1178     /// A character literal (`'a'`)
1179     LitChar(char),
1180     /// An integer literal (`1u8`)
1181     LitInt(u64, LitIntType),
1182     /// A float literal (`1f64` or `1E10f64`)
1183     LitFloat(InternedString, FloatTy),
1184     /// A float literal without a suffix (`1.0 or 1.0E10`)
1185     LitFloatUnsuffixed(InternedString),
1186     /// A boolean literal
1187     LitBool(bool),
1188 }
1189
1190 // NB: If you change this, you'll probably want to change the corresponding
1191 // type structure in middle/ty.rs as well.
1192 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1193 pub struct MutTy {
1194     pub ty: P<Ty>,
1195     pub mutbl: Mutability,
1196 }
1197
1198 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1199 pub struct TypeField {
1200     pub ident: Ident,
1201     pub mt: MutTy,
1202     pub span: Span,
1203 }
1204
1205 /// Represents a method's signature in a trait declaration,
1206 /// or in an implementation.
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1208 pub struct MethodSig {
1209     pub unsafety: Unsafety,
1210     pub abi: Abi,
1211     pub decl: P<FnDecl>,
1212     pub generics: Generics,
1213     pub explicit_self: ExplicitSelf,
1214 }
1215
1216 /// Represents a method declaration in a trait declaration, possibly including
1217 /// a default implementation A trait method is either required (meaning it
1218 /// doesn't have an implementation, just a signature) or provided (meaning it
1219 /// has a default implementation).
1220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1221 pub struct TraitItem {
1222     pub id: NodeId,
1223     pub ident: Ident,
1224     pub attrs: Vec<Attribute>,
1225     pub node: TraitItem_,
1226     pub span: Span,
1227 }
1228
1229 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1230 pub enum TraitItem_ {
1231     MethodTraitItem(MethodSig, Option<P<Block>>),
1232     TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1233 }
1234
1235 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1236 pub struct ImplItem {
1237     pub id: NodeId,
1238     pub ident: Ident,
1239     pub vis: Visibility,
1240     pub attrs: Vec<Attribute>,
1241     pub node: ImplItem_,
1242     pub span: Span,
1243 }
1244
1245 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1246 pub enum ImplItem_ {
1247     MethodImplItem(MethodSig, P<Block>),
1248     TypeImplItem(P<Ty>),
1249     MacImplItem(Mac),
1250 }
1251
1252 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1253 pub enum IntTy {
1254     TyIs(bool /* is this deprecated `int`? */),
1255     TyI8,
1256     TyI16,
1257     TyI32,
1258     TyI64,
1259 }
1260
1261 impl PartialEq for IntTy {
1262     fn eq(&self, other: &IntTy) -> bool {
1263         match (*self, *other) {
1264             // true/false need to compare the same, so this can't be derived
1265             (TyIs(_), TyIs(_)) |
1266             (TyI8, TyI8) |
1267             (TyI16, TyI16) |
1268             (TyI32, TyI32) |
1269             (TyI64, TyI64) => true,
1270             _ => false
1271         }
1272     }
1273 }
1274
1275 impl fmt::Debug for IntTy {
1276     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1277         fmt::Display::fmt(self, f)
1278     }
1279 }
1280
1281 impl fmt::Display for IntTy {
1282     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1283         write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1284     }
1285 }
1286
1287 impl IntTy {
1288     pub fn suffix_len(&self) -> usize {
1289         match *self {
1290             TyIs(true) /* i */ => 1,
1291             TyIs(false) /* is */ | TyI8 => 2,
1292             TyI16 | TyI32 | TyI64  => 3,
1293         }
1294     }
1295 }
1296
1297 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1298 pub enum UintTy {
1299     TyUs(bool /* is this deprecated uint? */),
1300     TyU8,
1301     TyU16,
1302     TyU32,
1303     TyU64,
1304 }
1305
1306 impl PartialEq for UintTy {
1307     fn eq(&self, other: &UintTy) -> bool {
1308         match (*self, *other) {
1309             // true/false need to compare the same, so this can't be derived
1310             (TyUs(_), TyUs(_)) |
1311             (TyU8, TyU8) |
1312             (TyU16, TyU16) |
1313             (TyU32, TyU32) |
1314             (TyU64, TyU64) => true,
1315             _ => false
1316         }
1317     }
1318 }
1319
1320 impl UintTy {
1321     pub fn suffix_len(&self) -> usize {
1322         match *self {
1323             TyUs(true) /* u */ => 1,
1324             TyUs(false) /* us */ | TyU8 => 2,
1325             TyU16 | TyU32 | TyU64  => 3,
1326         }
1327     }
1328 }
1329
1330 impl fmt::Debug for UintTy {
1331     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1332         fmt::Display::fmt(self, f)
1333     }
1334 }
1335
1336 impl fmt::Display for UintTy {
1337     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1338         write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1339     }
1340 }
1341
1342 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1343 pub enum FloatTy {
1344     TyF32,
1345     TyF64,
1346 }
1347
1348 impl fmt::Debug for FloatTy {
1349     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1350         fmt::Display::fmt(self, f)
1351     }
1352 }
1353
1354 impl fmt::Display for FloatTy {
1355     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1356         write!(f, "{}", ast_util::float_ty_to_string(*self))
1357     }
1358 }
1359
1360 impl FloatTy {
1361     pub fn suffix_len(&self) -> usize {
1362         match *self {
1363             TyF32 | TyF64 => 3, // add F128 handling here
1364         }
1365     }
1366 }
1367
1368 // Bind a type to an associated type: `A=Foo`.
1369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1370 pub struct TypeBinding {
1371     pub id: NodeId,
1372     pub ident: Ident,
1373     pub ty: P<Ty>,
1374     pub span: Span,
1375 }
1376
1377
1378 // NB PartialEq method appears below.
1379 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1380 pub struct Ty {
1381     pub id: NodeId,
1382     pub node: Ty_,
1383     pub span: Span,
1384 }
1385
1386 /// Not represented directly in the AST, referred to by name through a ty_path.
1387 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1388 pub enum PrimTy {
1389     TyInt(IntTy),
1390     TyUint(UintTy),
1391     TyFloat(FloatTy),
1392     TyStr,
1393     TyBool,
1394     TyChar
1395 }
1396
1397 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1398 pub struct BareFnTy {
1399     pub unsafety: Unsafety,
1400     pub abi: Abi,
1401     pub lifetimes: Vec<LifetimeDef>,
1402     pub decl: P<FnDecl>
1403 }
1404
1405 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1406 /// The different kinds of types recognized by the compiler
1407 pub enum Ty_ {
1408     TyVec(P<Ty>),
1409     /// A fixed length array (`[T; n]`)
1410     TyFixedLengthVec(P<Ty>, P<Expr>),
1411     /// A raw pointer (`*const T` or `*mut T`)
1412     TyPtr(MutTy),
1413     /// A reference (`&'a T` or `&'a mut T`)
1414     TyRptr(Option<Lifetime>, MutTy),
1415     /// A bare function (e.g. `fn(usize) -> bool`)
1416     TyBareFn(P<BareFnTy>),
1417     /// A tuple (`(A, B, C, D,...)`)
1418     TyTup(Vec<P<Ty>> ),
1419     /// A path (`module::module::...::Type`), optionally
1420     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1421     ///
1422     /// Type parameters are stored in the Path itself
1423     TyPath(Option<QSelf>, Path),
1424     /// Something like `A+B`. Note that `B` must always be a path.
1425     TyObjectSum(P<Ty>, TyParamBounds),
1426     /// A type like `for<'a> Foo<&'a Bar>`
1427     TyPolyTraitRef(TyParamBounds),
1428     /// No-op; kept solely so that we can pretty-print faithfully
1429     TyParen(P<Ty>),
1430     /// Unused for now
1431     TyTypeof(P<Expr>),
1432     /// TyInfer means the type should be inferred instead of it having been
1433     /// specified. This can appear anywhere in a type.
1434     TyInfer,
1435 }
1436
1437 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1438 pub enum AsmDialect {
1439     AsmAtt,
1440     AsmIntel
1441 }
1442
1443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1444 pub struct InlineAsm {
1445     pub asm: InternedString,
1446     pub asm_str_style: StrStyle,
1447     pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1448     pub inputs: Vec<(InternedString, P<Expr>)>,
1449     pub clobbers: Vec<InternedString>,
1450     pub volatile: bool,
1451     pub alignstack: bool,
1452     pub dialect: AsmDialect,
1453     pub expn_id: ExpnId,
1454 }
1455
1456 /// represents an argument in a function header
1457 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1458 pub struct Arg {
1459     pub ty: P<Ty>,
1460     pub pat: P<Pat>,
1461     pub id: NodeId,
1462 }
1463
1464 impl Arg {
1465     pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1466         let path = Spanned{span:span,node:self_ident};
1467         Arg {
1468             // HACK(eddyb) fake type for the self argument.
1469             ty: P(Ty {
1470                 id: DUMMY_NODE_ID,
1471                 node: TyInfer,
1472                 span: DUMMY_SP,
1473             }),
1474             pat: P(Pat {
1475                 id: DUMMY_NODE_ID,
1476                 node: PatIdent(BindByValue(mutability), path, None),
1477                 span: span
1478             }),
1479             id: DUMMY_NODE_ID
1480         }
1481     }
1482 }
1483
1484 /// Represents the header (not the body) of a function declaration
1485 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1486 pub struct FnDecl {
1487     pub inputs: Vec<Arg>,
1488     pub output: FunctionRetTy,
1489     pub variadic: bool
1490 }
1491
1492 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1493 pub enum Unsafety {
1494     Unsafe,
1495     Normal,
1496 }
1497
1498 impl fmt::Display for Unsafety {
1499     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1500         fmt::Display::fmt(match *self {
1501             Unsafety::Normal => "normal",
1502             Unsafety::Unsafe => "unsafe",
1503         }, f)
1504     }
1505 }
1506
1507 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1508 pub enum ImplPolarity {
1509     /// `impl Trait for Type`
1510     Positive,
1511     /// `impl !Trait for Type`
1512     Negative,
1513 }
1514
1515 impl fmt::Debug for ImplPolarity {
1516     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1517         match *self {
1518             ImplPolarity::Positive => "positive".fmt(f),
1519             ImplPolarity::Negative => "negative".fmt(f),
1520         }
1521     }
1522 }
1523
1524
1525 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1526 pub enum FunctionRetTy {
1527     /// Functions with return type `!`that always
1528     /// raise an error or exit (i.e. never return to the caller)
1529     NoReturn(Span),
1530     /// Return type is not specified.
1531     ///
1532     /// Functions default to `()` and
1533     /// closures default to inference. Span points to where return
1534     /// type would be inserted.
1535     DefaultReturn(Span),
1536     /// Everything else
1537     Return(P<Ty>),
1538 }
1539
1540 impl FunctionRetTy {
1541     pub fn span(&self) -> Span {
1542         match *self {
1543             NoReturn(span) => span,
1544             DefaultReturn(span) => span,
1545             Return(ref ty) => ty.span
1546         }
1547     }
1548 }
1549
1550 /// Represents the kind of 'self' associated with a method
1551 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1552 pub enum ExplicitSelf_ {
1553     /// No self
1554     SelfStatic,
1555     /// `self`
1556     SelfValue(Ident),
1557     /// `&'lt self`, `&'lt mut self`
1558     SelfRegion(Option<Lifetime>, Mutability, Ident),
1559     /// `self: TYPE`
1560     SelfExplicit(P<Ty>, Ident),
1561 }
1562
1563 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1564
1565 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1566 pub struct Mod {
1567     /// A span from the first token past `{` to the last token until `}`.
1568     /// For `mod foo;`, the inner span ranges from the first token
1569     /// to the last token in the external file.
1570     pub inner: Span,
1571     pub items: Vec<P<Item>>,
1572 }
1573
1574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1575 pub struct ForeignMod {
1576     pub abi: Abi,
1577     pub items: Vec<P<ForeignItem>>,
1578 }
1579
1580 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1581 pub struct VariantArg {
1582     pub ty: P<Ty>,
1583     pub id: NodeId,
1584 }
1585
1586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1587 pub enum VariantKind {
1588     /// Tuple variant, e.g. `Foo(A, B)`
1589     TupleVariantKind(Vec<VariantArg>),
1590     /// Struct variant, e.g. `Foo {x: A, y: B}`
1591     StructVariantKind(P<StructDef>),
1592 }
1593
1594 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1595 pub struct EnumDef {
1596     pub variants: Vec<P<Variant>>,
1597 }
1598
1599 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1600 pub struct Variant_ {
1601     pub name: Ident,
1602     pub attrs: Vec<Attribute>,
1603     pub kind: VariantKind,
1604     pub id: NodeId,
1605     /// Explicit discriminant, eg `Foo = 1`
1606     pub disr_expr: Option<P<Expr>>,
1607     pub vis: Visibility,
1608 }
1609
1610 pub type Variant = Spanned<Variant_>;
1611
1612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1613 pub enum PathListItem_ {
1614     PathListIdent { name: Ident, id: NodeId },
1615     PathListMod { id: NodeId }
1616 }
1617
1618 impl PathListItem_ {
1619     pub fn id(&self) -> NodeId {
1620         match *self {
1621             PathListIdent { id, .. } | PathListMod { id } => id
1622         }
1623     }
1624 }
1625
1626 pub type PathListItem = Spanned<PathListItem_>;
1627
1628 pub type ViewPath = Spanned<ViewPath_>;
1629
1630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1631 pub enum ViewPath_ {
1632
1633     /// `foo::bar::baz as quux`
1634     ///
1635     /// or just
1636     ///
1637     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1638     ViewPathSimple(Ident, Path),
1639
1640     /// `foo::bar::*`
1641     ViewPathGlob(Path),
1642
1643     /// `foo::bar::{a,b,c}`
1644     ViewPathList(Path, Vec<PathListItem>)
1645 }
1646
1647 /// Meta-data associated with an item
1648 pub type Attribute = Spanned<Attribute_>;
1649
1650 /// Distinguishes between Attributes that decorate items and Attributes that
1651 /// are contained as statements within items. These two cases need to be
1652 /// distinguished for pretty-printing.
1653 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1654 pub enum AttrStyle {
1655     AttrOuter,
1656     AttrInner,
1657 }
1658
1659 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1660 pub struct AttrId(pub usize);
1661
1662 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1663 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1664 pub struct Attribute_ {
1665     pub id: AttrId,
1666     pub style: AttrStyle,
1667     pub value: P<MetaItem>,
1668     pub is_sugared_doc: bool,
1669 }
1670
1671 /// TraitRef's appear in impls.
1672 ///
1673 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1674 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1675 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1676 /// same as the impl's node id).
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 pub struct TraitRef {
1679     pub path: Path,
1680     pub ref_id: NodeId,
1681 }
1682
1683 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1684 pub struct PolyTraitRef {
1685     /// The `'a` in `<'a> Foo<&'a T>`
1686     pub bound_lifetimes: Vec<LifetimeDef>,
1687
1688     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1689     pub trait_ref: TraitRef,
1690
1691     pub span: Span,
1692 }
1693
1694 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1695 pub enum Visibility {
1696     Public,
1697     Inherited,
1698 }
1699
1700 impl Visibility {
1701     pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1702         match self {
1703             &Inherited => parent_visibility,
1704             &Public => *self
1705         }
1706     }
1707 }
1708
1709 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1710 pub struct StructField_ {
1711     pub kind: StructFieldKind,
1712     pub id: NodeId,
1713     pub ty: P<Ty>,
1714     pub attrs: Vec<Attribute>,
1715 }
1716
1717 impl StructField_ {
1718     pub fn ident(&self) -> Option<Ident> {
1719         match self.kind {
1720             NamedField(ref ident, _) => Some(ident.clone()),
1721             UnnamedField(_) => None
1722         }
1723     }
1724 }
1725
1726 pub type StructField = Spanned<StructField_>;
1727
1728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1729 pub enum StructFieldKind {
1730     NamedField(Ident, Visibility),
1731     /// Element of a tuple-like struct
1732     UnnamedField(Visibility),
1733 }
1734
1735 impl StructFieldKind {
1736     pub fn is_unnamed(&self) -> bool {
1737         match *self {
1738             UnnamedField(..) => true,
1739             NamedField(..) => false,
1740         }
1741     }
1742 }
1743
1744 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1745 pub struct StructDef {
1746     /// Fields, not including ctor
1747     pub fields: Vec<StructField>,
1748     /// ID of the constructor. This is only used for tuple- or enum-like
1749     /// structs.
1750     pub ctor_id: Option<NodeId>,
1751 }
1752
1753 /*
1754   FIXME (#3300): Should allow items to be anonymous. Right now
1755   we just use dummy names for anon items.
1756  */
1757 /// An item
1758 ///
1759 /// The name might be a dummy name in case of anonymous items
1760 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1761 pub struct Item {
1762     pub ident: Ident,
1763     pub attrs: Vec<Attribute>,
1764     pub id: NodeId,
1765     pub node: Item_,
1766     pub vis: Visibility,
1767     pub span: Span,
1768 }
1769
1770 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1771 pub enum Item_ {
1772     /// An`extern crate` item, with optional original crate name,
1773     ///
1774     /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1775     ItemExternCrate(Option<Name>),
1776     /// A `use` or `pub use` item
1777     ItemUse(P<ViewPath>),
1778
1779     /// A `static` item
1780     ItemStatic(P<Ty>, Mutability, P<Expr>),
1781     /// A `const` item
1782     ItemConst(P<Ty>, P<Expr>),
1783     /// A function declaration
1784     ItemFn(P<FnDecl>, Unsafety, Abi, Generics, P<Block>),
1785     /// A module
1786     ItemMod(Mod),
1787     /// An external module
1788     ItemForeignMod(ForeignMod),
1789     /// A type alias, e.g. `type Foo = Bar<u8>`
1790     ItemTy(P<Ty>, Generics),
1791     /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1792     ItemEnum(EnumDef, Generics),
1793     /// A struct definition, e.g. `struct Foo<A> {x: A}`
1794     ItemStruct(P<StructDef>, Generics),
1795     /// Represents a Trait Declaration
1796     ItemTrait(Unsafety,
1797               Generics,
1798               TyParamBounds,
1799               Vec<P<TraitItem>>),
1800
1801     // Default trait implementations
1802     ///
1803     // `impl Trait for .. {}`
1804     ItemDefaultImpl(Unsafety, TraitRef),
1805     /// An implementation, eg `impl<A> Trait for Foo { .. }`
1806     ItemImpl(Unsafety,
1807              ImplPolarity,
1808              Generics,
1809              Option<TraitRef>, // (optional) trait this impl implements
1810              P<Ty>, // self
1811              Vec<P<ImplItem>>),
1812     /// A macro invocation (which includes macro definition)
1813     ItemMac(Mac),
1814 }
1815
1816 impl Item_ {
1817     pub fn descriptive_variant(&self) -> &str {
1818         match *self {
1819             ItemExternCrate(..) => "extern crate",
1820             ItemUse(..) => "use",
1821             ItemStatic(..) => "static item",
1822             ItemConst(..) => "constant item",
1823             ItemFn(..) => "function",
1824             ItemMod(..) => "module",
1825             ItemForeignMod(..) => "foreign module",
1826             ItemTy(..) => "type alias",
1827             ItemEnum(..) => "enum",
1828             ItemStruct(..) => "struct",
1829             ItemTrait(..) => "trait",
1830             ItemMac(..) |
1831             ItemImpl(..) |
1832             ItemDefaultImpl(..) => "item"
1833         }
1834     }
1835 }
1836
1837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1838 pub struct ForeignItem {
1839     pub ident: Ident,
1840     pub attrs: Vec<Attribute>,
1841     pub node: ForeignItem_,
1842     pub id: NodeId,
1843     pub span: Span,
1844     pub vis: Visibility,
1845 }
1846
1847 /// An item within an `extern` block
1848 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1849 pub enum ForeignItem_ {
1850     /// A foreign function
1851     ForeignItemFn(P<FnDecl>, Generics),
1852     /// A foreign static item (`static ext: u8`), with optional mutability
1853     /// (the boolean is true when mutable)
1854     ForeignItemStatic(P<Ty>, bool),
1855 }
1856
1857 impl ForeignItem_ {
1858     pub fn descriptive_variant(&self) -> &str {
1859         match *self {
1860             ForeignItemFn(..) => "foreign function",
1861             ForeignItemStatic(..) => "foreign static item"
1862         }
1863     }
1864 }
1865
1866 /// The data we save and restore about an inlined item or method.  This is not
1867 /// part of the AST that we parse from a file, but it becomes part of the tree
1868 /// that we trans.
1869 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1870 pub enum InlinedItem {
1871     IIItem(P<Item>),
1872     IITraitItem(DefId /* impl id */, P<TraitItem>),
1873     IIImplItem(DefId /* impl id */, P<ImplItem>),
1874     IIForeign(P<ForeignItem>),
1875 }
1876
1877 /// A macro definition, in this crate or imported from another.
1878 ///
1879 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1880 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1881 pub struct MacroDef {
1882     pub ident: Ident,
1883     pub attrs: Vec<Attribute>,
1884     pub id: NodeId,
1885     pub span: Span,
1886     pub imported_from: Option<Ident>,
1887     pub export: bool,
1888     pub use_locally: bool,
1889     pub allow_internal_unstable: bool,
1890     pub body: Vec<TokenTree>,
1891 }
1892
1893 #[cfg(test)]
1894 mod test {
1895     use serialize;
1896     use super::*;
1897
1898     // are ASTs encodable?
1899     #[test]
1900     fn check_asts_encodable() {
1901         fn assert_encodable<T: serialize::Encodable>() {}
1902         assert_encodable::<Crate>();
1903     }
1904 }