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