]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Rename ExprKind::Vec to Array in HIR and HAIR.
[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::TyParamBound::*;
14 pub use self::UnsafeSource::*;
15 pub use self::ViewPath_::*;
16 pub use self::PathParameters::*;
17 pub use symbol::Symbol as Name;
18 pub use util::ThinVec;
19
20 use syntax_pos::{mk_sp, Span, DUMMY_SP, ExpnId};
21 use codemap::{respan, Spanned};
22 use abi::Abi;
23 use ext::hygiene::SyntaxContext;
24 use print::pprust;
25 use ptr::P;
26 use symbol::{Symbol, keywords};
27 use tokenstream::{TokenTree};
28
29 use std::collections::HashSet;
30 use std::fmt;
31 use std::rc::Rc;
32 use std::u32;
33
34 use serialize::{self, Encodable, Decodable, Encoder, Decoder};
35
36 use rustc_i128::{u128, i128};
37
38 /// An identifier contains a Name (index into the interner
39 /// table) and a SyntaxContext to track renaming and
40 /// macro expansion per Flatt et al., "Macros That Work Together"
41 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
42 pub struct Ident {
43     pub name: Symbol,
44     pub ctxt: SyntaxContext
45 }
46
47 impl Ident {
48     pub const fn with_empty_ctxt(name: Name) -> Ident {
49         Ident { name: name, ctxt: SyntaxContext::empty() }
50     }
51
52     /// Maps a string to an identifier with an empty syntax context.
53     pub fn from_str(s: &str) -> Ident {
54         Ident::with_empty_ctxt(Symbol::intern(s))
55     }
56
57     pub fn unhygienize(&self) -> Ident {
58         Ident { name: self.name, ctxt: SyntaxContext::empty() }
59     }
60 }
61
62 impl fmt::Debug for Ident {
63     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64         write!(f, "{}{:?}", self.name, self.ctxt)
65     }
66 }
67
68 impl fmt::Display for Ident {
69     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70         fmt::Display::fmt(&self.name, f)
71     }
72 }
73
74 impl Encodable for Ident {
75     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
76         self.name.encode(s)
77     }
78 }
79
80 impl Decodable for Ident {
81     fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
82         Ok(Ident::with_empty_ctxt(Name::decode(d)?))
83     }
84 }
85
86 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
87 pub struct Lifetime {
88     pub id: NodeId,
89     pub span: Span,
90     pub name: Name
91 }
92
93 impl fmt::Debug for Lifetime {
94     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95         write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
96     }
97 }
98
99 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
100 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
101 pub struct LifetimeDef {
102     pub attrs: ThinVec<Attribute>,
103     pub lifetime: Lifetime,
104     pub bounds: Vec<Lifetime>
105 }
106
107 /// A "Path" is essentially Rust's notion of a name.
108 ///
109 /// It's represented as a sequence of identifiers,
110 /// along with a bunch of supporting information.
111 ///
112 /// E.g. `std::cmp::PartialEq`
113 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
114 pub struct Path {
115     pub span: Span,
116     /// The segments in the path: the things separated by `::`.
117     /// Global paths begin with `keywords::CrateRoot`.
118     pub segments: Vec<PathSegment>,
119 }
120
121 impl fmt::Debug for Path {
122     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123         write!(f, "path({})", pprust::path_to_string(self))
124     }
125 }
126
127 impl fmt::Display for Path {
128     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129         write!(f, "{}", pprust::path_to_string(self))
130     }
131 }
132
133 impl Path {
134     // convert a span and an identifier to the corresponding
135     // 1-segment path
136     pub fn from_ident(s: Span, identifier: Ident) -> Path {
137         Path {
138             span: s,
139             segments: vec![identifier.into()],
140         }
141     }
142
143     pub fn default_to_global(mut self) -> Path {
144         let name = self.segments[0].identifier.name;
145         if !self.is_global() && name != "$crate" &&
146            name != keywords::SelfValue.name() && name != keywords::Super.name() {
147             self.segments.insert(0, PathSegment::crate_root());
148         }
149         self
150     }
151
152     pub fn is_global(&self) -> bool {
153         !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
154     }
155 }
156
157 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
158 ///
159 /// E.g. `std`, `String` or `Box<T>`
160 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
161 pub struct PathSegment {
162     /// The identifier portion of this path segment.
163     pub identifier: Ident,
164
165     /// Type/lifetime parameters attached to this path. They come in
166     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
167     /// this is more than just simple syntactic sugar; the use of
168     /// parens affects the region binding rules, so we preserve the
169     /// distinction.
170     /// The `Option<P<..>>` wrapper is purely a size optimization;
171     /// `None` is used to represent both `Path` and `Path<>`.
172     pub parameters: Option<P<PathParameters>>,
173 }
174
175 impl From<Ident> for PathSegment {
176     fn from(id: Ident) -> Self {
177         PathSegment { identifier: id, parameters: None }
178     }
179 }
180
181 impl PathSegment {
182     pub fn crate_root() -> Self {
183         PathSegment {
184             identifier: keywords::CrateRoot.ident(),
185             parameters: None,
186         }
187     }
188 }
189
190 /// Parameters of a path segment.
191 ///
192 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
193 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
194 pub enum PathParameters {
195     /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
196     AngleBracketed(AngleBracketedParameterData),
197     /// The `(A,B)` and `C` in `Foo(A,B) -> C`
198     Parenthesized(ParenthesizedParameterData),
199 }
200
201 /// A path like `Foo<'a, T>`
202 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
203 pub struct AngleBracketedParameterData {
204     /// The lifetime parameters for this path segment.
205     pub lifetimes: Vec<Lifetime>,
206     /// The type parameters for this path segment, if present.
207     pub types: P<[P<Ty>]>,
208     /// Bindings (equality constraints) on associated types, if present.
209     ///
210     /// E.g., `Foo<A=Bar>`.
211     pub bindings: P<[TypeBinding]>,
212 }
213
214 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
215     fn into(self) -> Option<P<PathParameters>> {
216         let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
217         if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
218     }
219 }
220
221 /// A path like `Foo(A,B) -> C`
222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
223 pub struct ParenthesizedParameterData {
224     /// Overall span
225     pub span: Span,
226
227     /// `(A,B)`
228     pub inputs: Vec<P<Ty>>,
229
230     /// `C`
231     pub output: Option<P<Ty>>,
232 }
233
234 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
235 pub struct NodeId(u32);
236
237 impl NodeId {
238     pub fn new(x: usize) -> NodeId {
239         assert!(x < (u32::MAX as usize));
240         NodeId(x as u32)
241     }
242
243     pub fn from_u32(x: u32) -> NodeId {
244         NodeId(x)
245     }
246
247     pub fn as_usize(&self) -> usize {
248         self.0 as usize
249     }
250
251     pub fn as_u32(&self) -> u32 {
252         self.0
253     }
254 }
255
256 impl fmt::Display for NodeId {
257     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
258         fmt::Display::fmt(&self.0, f)
259     }
260 }
261
262 impl serialize::UseSpecializedEncodable for NodeId {
263     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
264         s.emit_u32(self.0)
265     }
266 }
267
268 impl serialize::UseSpecializedDecodable for NodeId {
269     fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
270         d.read_u32().map(NodeId)
271     }
272 }
273
274 /// Node id used to represent the root of the crate.
275 pub const CRATE_NODE_ID: NodeId = NodeId(0);
276
277 /// When parsing and doing expansions, we initially give all AST nodes this AST
278 /// node value. Then later, in the renumber pass, we renumber them to have
279 /// small, positive ids.
280 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
281
282 /// The AST represents all type param bounds as types.
283 /// typeck::collect::compute_bounds matches these against
284 /// the "special" built-in traits (see middle::lang_items) and
285 /// detects Copy, Send and Sync.
286 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
287 pub enum TyParamBound {
288     TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
289     RegionTyParamBound(Lifetime)
290 }
291
292 /// A modifier on a bound, currently this is only used for `?Sized`, where the
293 /// modifier is `Maybe`. Negative bounds should also be handled here.
294 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
295 pub enum TraitBoundModifier {
296     None,
297     Maybe,
298 }
299
300 pub type TyParamBounds = P<[TyParamBound]>;
301
302 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
303 pub struct TyParam {
304     pub attrs: ThinVec<Attribute>,
305     pub ident: Ident,
306     pub id: NodeId,
307     pub bounds: TyParamBounds,
308     pub default: Option<P<Ty>>,
309     pub span: Span,
310 }
311
312 /// Represents lifetimes and type parameters attached to a declaration
313 /// of a function, enum, trait, etc.
314 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
315 pub struct Generics {
316     pub lifetimes: Vec<LifetimeDef>,
317     pub ty_params: P<[TyParam]>,
318     pub where_clause: WhereClause,
319     pub span: Span,
320 }
321
322 impl Generics {
323     pub fn is_lt_parameterized(&self) -> bool {
324         !self.lifetimes.is_empty()
325     }
326     pub fn is_type_parameterized(&self) -> bool {
327         !self.ty_params.is_empty()
328     }
329     pub fn is_parameterized(&self) -> bool {
330         self.is_lt_parameterized() || self.is_type_parameterized()
331     }
332     pub fn span_for_name(&self, name: &str) -> Option<Span> {
333         for t in &self.ty_params {
334             if t.ident.name == name {
335                 return Some(t.span);
336             }
337         }
338         None
339     }
340 }
341
342 impl Default for Generics {
343     /// Creates an instance of `Generics`.
344     fn default() ->  Generics {
345         Generics {
346             lifetimes: Vec::new(),
347             ty_params: P::new(),
348             where_clause: WhereClause {
349                 id: DUMMY_NODE_ID,
350                 predicates: Vec::new(),
351             },
352             span: DUMMY_SP,
353         }
354     }
355 }
356
357 /// A `where` clause in a definition
358 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
359 pub struct WhereClause {
360     pub id: NodeId,
361     pub predicates: Vec<WherePredicate>,
362 }
363
364 /// A single predicate in a `where` clause
365 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
366 pub enum WherePredicate {
367     /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
368     BoundPredicate(WhereBoundPredicate),
369     /// A lifetime predicate, e.g. `'a: 'b+'c`
370     RegionPredicate(WhereRegionPredicate),
371     /// An equality predicate (unsupported)
372     EqPredicate(WhereEqPredicate),
373 }
374
375 /// A type bound.
376 ///
377 /// E.g. `for<'c> Foo: Send+Clone+'c`
378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
379 pub struct WhereBoundPredicate {
380     pub span: Span,
381     /// Any lifetimes from a `for` binding
382     pub bound_lifetimes: Vec<LifetimeDef>,
383     /// The type being bounded
384     pub bounded_ty: P<Ty>,
385     /// Trait and lifetime bounds (`Clone+Send+'static`)
386     pub bounds: TyParamBounds,
387 }
388
389 /// A lifetime predicate.
390 ///
391 /// E.g. `'a: 'b+'c`
392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
393 pub struct WhereRegionPredicate {
394     pub span: Span,
395     pub lifetime: Lifetime,
396     pub bounds: Vec<Lifetime>,
397 }
398
399 /// An equality predicate (unsupported).
400 ///
401 /// E.g. `T=int`
402 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
403 pub struct WhereEqPredicate {
404     pub id: NodeId,
405     pub span: Span,
406     pub path: Path,
407     pub ty: P<Ty>,
408 }
409
410 /// The set of MetaItems that define the compilation environment of the crate,
411 /// used to drive conditional compilation
412 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
413
414 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
415 pub struct Crate {
416     pub module: Mod,
417     pub attrs: Vec<Attribute>,
418     pub span: Span,
419     pub exported_macros: Vec<MacroDef>,
420 }
421
422 /// A spanned compile-time attribute list item.
423 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
424
425 /// Possible values inside of compile-time attribute lists.
426 ///
427 /// E.g. the '..' in `#[name(..)]`.
428 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
429 pub enum NestedMetaItemKind {
430     /// A full MetaItem, for recursive meta items.
431     MetaItem(MetaItem),
432     /// A literal.
433     ///
434     /// E.g. "foo", 64, true
435     Literal(Lit),
436 }
437
438 /// A spanned compile-time attribute item.
439 ///
440 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
441 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
442 pub struct MetaItem {
443     pub name: Name,
444     pub node: MetaItemKind,
445     pub span: Span,
446 }
447
448 /// A compile-time attribute item.
449 ///
450 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
451 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
452 pub enum MetaItemKind {
453     /// Word meta item.
454     ///
455     /// E.g. `test` as in `#[test]`
456     Word,
457     /// List meta item.
458     ///
459     /// E.g. `derive(..)` as in `#[derive(..)]`
460     List(Vec<NestedMetaItem>),
461     /// Name value meta item.
462     ///
463     /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
464     NameValue(Lit)
465 }
466
467 /// A Block (`{ .. }`).
468 ///
469 /// E.g. `{ .. }` as in `fn foo() { .. }`
470 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
471 pub struct Block {
472     /// Statements in a block
473     pub stmts: Vec<Stmt>,
474     pub id: NodeId,
475     /// Distinguishes between `unsafe { ... }` and `{ ... }`
476     pub rules: BlockCheckMode,
477     pub span: Span,
478 }
479
480 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
481 pub struct Pat {
482     pub id: NodeId,
483     pub node: PatKind,
484     pub span: Span,
485 }
486
487 impl fmt::Debug for Pat {
488     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489         write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
490     }
491 }
492
493 impl Pat {
494     pub fn walk<F>(&self, it: &mut F) -> bool
495         where F: FnMut(&Pat) -> bool
496     {
497         if !it(self) {
498             return false;
499         }
500
501         match self.node {
502             PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
503             PatKind::Struct(_, ref fields, _) => {
504                 fields.iter().all(|field| field.node.pat.walk(it))
505             }
506             PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
507                 s.iter().all(|p| p.walk(it))
508             }
509             PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
510                 s.walk(it)
511             }
512             PatKind::Slice(ref before, ref slice, ref after) => {
513                 before.iter().all(|p| p.walk(it)) &&
514                 slice.iter().all(|p| p.walk(it)) &&
515                 after.iter().all(|p| p.walk(it))
516             }
517             PatKind::Wild |
518             PatKind::Lit(_) |
519             PatKind::Range(..) |
520             PatKind::Ident(..) |
521             PatKind::Path(..) |
522             PatKind::Mac(_) => {
523                 true
524             }
525         }
526     }
527 }
528
529 /// A single field in a struct pattern
530 ///
531 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
532 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
533 /// except is_shorthand is true
534 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
535 pub struct FieldPat {
536     /// The identifier for the field
537     pub ident: Ident,
538     /// The pattern the field is destructured to
539     pub pat: P<Pat>,
540     pub is_shorthand: bool,
541     pub attrs: ThinVec<Attribute>,
542 }
543
544 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
545 pub enum BindingMode {
546     ByRef(Mutability),
547     ByValue(Mutability),
548 }
549
550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
551 pub enum PatKind {
552     /// Represents a wildcard pattern (`_`)
553     Wild,
554
555     /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
556     /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
557     /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
558     /// during name resolution.
559     Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
560
561     /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
562     /// The `bool` is `true` in the presence of a `..`.
563     Struct(Path, Vec<Spanned<FieldPat>>, bool),
564
565     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
566     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
567     /// 0 <= position <= subpats.len()
568     TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
569
570     /// A possibly qualified path pattern.
571     /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
572     /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
573     /// only legally refer to associated constants.
574     Path(Option<QSelf>, Path),
575
576     /// A tuple pattern `(a, b)`.
577     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
578     /// 0 <= position <= subpats.len()
579     Tuple(Vec<P<Pat>>, Option<usize>),
580     /// A `box` pattern
581     Box(P<Pat>),
582     /// A reference pattern, e.g. `&mut (a, b)`
583     Ref(P<Pat>, Mutability),
584     /// A literal
585     Lit(P<Expr>),
586     /// A range pattern, e.g. `1...2`
587     Range(P<Expr>, P<Expr>),
588     /// `[a, b, ..i, y, z]` is represented as:
589     ///     `PatKind::Slice(box [a, b], Some(i), box [y, z])`
590     Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
591     /// A macro pattern; pre-expansion
592     Mac(Mac),
593 }
594
595 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
596 pub enum Mutability {
597     Mutable,
598     Immutable,
599 }
600
601 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
602 pub enum BinOpKind {
603     /// The `+` operator (addition)
604     Add,
605     /// The `-` operator (subtraction)
606     Sub,
607     /// The `*` operator (multiplication)
608     Mul,
609     /// The `/` operator (division)
610     Div,
611     /// The `%` operator (modulus)
612     Rem,
613     /// The `&&` operator (logical and)
614     And,
615     /// The `||` operator (logical or)
616     Or,
617     /// The `^` operator (bitwise xor)
618     BitXor,
619     /// The `&` operator (bitwise and)
620     BitAnd,
621     /// The `|` operator (bitwise or)
622     BitOr,
623     /// The `<<` operator (shift left)
624     Shl,
625     /// The `>>` operator (shift right)
626     Shr,
627     /// The `==` operator (equality)
628     Eq,
629     /// The `<` operator (less than)
630     Lt,
631     /// The `<=` operator (less than or equal to)
632     Le,
633     /// The `!=` operator (not equal to)
634     Ne,
635     /// The `>=` operator (greater than or equal to)
636     Ge,
637     /// The `>` operator (greater than)
638     Gt,
639 }
640
641 impl BinOpKind {
642     pub fn to_string(&self) -> &'static str {
643         use self::BinOpKind::*;
644         match *self {
645             Add => "+",
646             Sub => "-",
647             Mul => "*",
648             Div => "/",
649             Rem => "%",
650             And => "&&",
651             Or => "||",
652             BitXor => "^",
653             BitAnd => "&",
654             BitOr => "|",
655             Shl => "<<",
656             Shr => ">>",
657             Eq => "==",
658             Lt => "<",
659             Le => "<=",
660             Ne => "!=",
661             Ge => ">=",
662             Gt => ">",
663         }
664     }
665     pub fn lazy(&self) -> bool {
666         match *self {
667             BinOpKind::And | BinOpKind::Or => true,
668             _ => false
669         }
670     }
671
672     pub fn is_shift(&self) -> bool {
673         match *self {
674             BinOpKind::Shl | BinOpKind::Shr => true,
675             _ => false
676         }
677     }
678     pub fn is_comparison(&self) -> bool {
679         use self::BinOpKind::*;
680         match *self {
681             Eq | Lt | Le | Ne | Gt | Ge =>
682             true,
683             And | Or | Add | Sub | Mul | Div | Rem |
684             BitXor | BitAnd | BitOr | Shl | Shr =>
685             false,
686         }
687     }
688     /// Returns `true` if the binary operator takes its arguments by value
689     pub fn is_by_value(&self) -> bool {
690         !self.is_comparison()
691     }
692 }
693
694 pub type BinOp = Spanned<BinOpKind>;
695
696 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
697 pub enum UnOp {
698     /// The `*` operator for dereferencing
699     Deref,
700     /// The `!` operator for logical inversion
701     Not,
702     /// The `-` operator for negation
703     Neg,
704 }
705
706 impl UnOp {
707     /// Returns `true` if the unary operator takes its argument by value
708     pub fn is_by_value(u: UnOp) -> bool {
709         match u {
710             UnOp::Neg | UnOp::Not => true,
711             _ => false,
712         }
713     }
714
715     pub fn to_string(op: UnOp) -> &'static str {
716         match op {
717             UnOp::Deref => "*",
718             UnOp::Not => "!",
719             UnOp::Neg => "-",
720         }
721     }
722 }
723
724 /// A statement
725 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
726 pub struct Stmt {
727     pub id: NodeId,
728     pub node: StmtKind,
729     pub span: Span,
730 }
731
732 impl Stmt {
733     pub fn add_trailing_semicolon(mut self) -> Self {
734         self.node = match self.node {
735             StmtKind::Expr(expr) => StmtKind::Semi(expr),
736             StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
737                 (mac, MacStmtStyle::Semicolon, attrs)
738             })),
739             node @ _ => node,
740         };
741         self
742     }
743 }
744
745 impl fmt::Debug for Stmt {
746     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
747         write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
748     }
749 }
750
751
752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
753 pub enum StmtKind {
754     /// A local (let) binding.
755     Local(P<Local>),
756
757     /// An item definition.
758     Item(P<Item>),
759
760     /// Expr without trailing semi-colon.
761     Expr(P<Expr>),
762
763     Semi(P<Expr>),
764
765     Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
766 }
767
768 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
769 pub enum MacStmtStyle {
770     /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
771     /// `foo!(...);`, `foo![...];`
772     Semicolon,
773     /// The macro statement had braces; e.g. foo! { ... }
774     Braces,
775     /// The macro statement had parentheses or brackets and no semicolon; e.g.
776     /// `foo!(...)`. All of these will end up being converted into macro
777     /// expressions.
778     NoBraces,
779 }
780
781 // FIXME (pending discussion of #1697, #2178...): local should really be
782 // a refinement on pat.
783 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
785 pub struct Local {
786     pub pat: P<Pat>,
787     pub ty: Option<P<Ty>>,
788     /// Initializer expression to set the value, if any
789     pub init: Option<P<Expr>>,
790     pub id: NodeId,
791     pub span: Span,
792     pub attrs: ThinVec<Attribute>,
793 }
794
795 /// An arm of a 'match'.
796 ///
797 /// E.g. `0...10 => { println!("match!") }` as in
798 ///
799 /// ```rust,ignore
800 /// match n {
801 ///     0...10 => { println!("match!") },
802 ///     // ..
803 /// }
804 /// ```
805 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
806 pub struct Arm {
807     pub attrs: Vec<Attribute>,
808     pub pats: Vec<P<Pat>>,
809     pub guard: Option<P<Expr>>,
810     pub body: P<Expr>,
811 }
812
813 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
814 pub struct Field {
815     pub ident: SpannedIdent,
816     pub expr: P<Expr>,
817     pub span: Span,
818     pub is_shorthand: bool,
819     pub attrs: ThinVec<Attribute>,
820 }
821
822 pub type SpannedIdent = Spanned<Ident>;
823
824 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
825 pub enum BlockCheckMode {
826     Default,
827     Unsafe(UnsafeSource),
828 }
829
830 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
831 pub enum UnsafeSource {
832     CompilerGenerated,
833     UserProvided,
834 }
835
836 /// An expression
837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
838 pub struct Expr {
839     pub id: NodeId,
840     pub node: ExprKind,
841     pub span: Span,
842     pub attrs: ThinVec<Attribute>
843 }
844
845 impl fmt::Debug for Expr {
846     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
847         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
848     }
849 }
850
851 /// Limit types of a range (inclusive or exclusive)
852 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
853 pub enum RangeLimits {
854     /// Inclusive at the beginning, exclusive at the end
855     HalfOpen,
856     /// Inclusive at the beginning and end
857     Closed,
858 }
859
860 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
861 pub enum ExprKind {
862     /// A `box x` expression.
863     Box(P<Expr>),
864     /// First expr is the place; second expr is the value.
865     InPlace(P<Expr>, P<Expr>),
866     /// An array (`[a, b, c, d]`)
867     Array(Vec<P<Expr>>),
868     /// A function call
869     ///
870     /// The first field resolves to the function itself,
871     /// and the second field is the list of arguments
872     Call(P<Expr>, Vec<P<Expr>>),
873     /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
874     ///
875     /// The `SpannedIdent` is the identifier for the method name.
876     /// The vector of `Ty`s are the ascripted type parameters for the method
877     /// (within the angle brackets).
878     ///
879     /// The first element of the vector of `Expr`s is the expression that evaluates
880     /// to the object on which the method is being called on (the receiver),
881     /// and the remaining elements are the rest of the arguments.
882     ///
883     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
884     /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
885     MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
886     /// A tuple (`(a, b, c ,d)`)
887     Tup(Vec<P<Expr>>),
888     /// A binary operation (For example: `a + b`, `a * b`)
889     Binary(BinOp, P<Expr>, P<Expr>),
890     /// A unary operation (For example: `!x`, `*x`)
891     Unary(UnOp, P<Expr>),
892     /// A literal (For example: `1`, `"foo"`)
893     Lit(P<Lit>),
894     /// A cast (`foo as f64`)
895     Cast(P<Expr>, P<Ty>),
896     Type(P<Expr>, P<Ty>),
897     /// An `if` block, with an optional else block
898     ///
899     /// `if expr { block } else { expr }`
900     If(P<Expr>, P<Block>, Option<P<Expr>>),
901     /// An `if let` expression with an optional else block
902     ///
903     /// `if let pat = expr { block } else { expr }`
904     ///
905     /// This is desugared to a `match` expression.
906     IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
907     /// A while loop, with an optional label
908     ///
909     /// `'label: while expr { block }`
910     While(P<Expr>, P<Block>, Option<SpannedIdent>),
911     /// A while-let loop, with an optional label
912     ///
913     /// `'label: while let pat = expr { block }`
914     ///
915     /// This is desugared to a combination of `loop` and `match` expressions.
916     WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
917     /// A for loop, with an optional label
918     ///
919     /// `'label: for pat in expr { block }`
920     ///
921     /// This is desugared to a combination of `loop` and `match` expressions.
922     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
923     /// Conditionless loop (can be exited with break, continue, or return)
924     ///
925     /// `'label: loop { block }`
926     Loop(P<Block>, Option<SpannedIdent>),
927     /// A `match` block.
928     Match(P<Expr>, Vec<Arm>),
929     /// A closure (for example, `move |a, b, c| a + b + c`)
930     ///
931     /// The final span is the span of the argument block `|...|`
932     Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
933     /// A block (`{ ... }`)
934     Block(P<Block>),
935
936     /// An assignment (`a = foo()`)
937     Assign(P<Expr>, P<Expr>),
938     /// An assignment with an operator
939     ///
940     /// For example, `a += 1`.
941     AssignOp(BinOp, P<Expr>, P<Expr>),
942     /// Access of a named struct field (`obj.foo`)
943     Field(P<Expr>, SpannedIdent),
944     /// Access of an unnamed field of a struct or tuple-struct
945     ///
946     /// For example, `foo.0`.
947     TupField(P<Expr>, Spanned<usize>),
948     /// An indexing operation (`foo[2]`)
949     Index(P<Expr>, P<Expr>),
950     /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
951     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
952
953     /// Variable reference, possibly containing `::` and/or type
954     /// parameters, e.g. foo::bar::<baz>.
955     ///
956     /// Optionally "qualified",
957     /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
958     Path(Option<QSelf>, Path),
959
960     /// A referencing operation (`&a` or `&mut a`)
961     AddrOf(Mutability, P<Expr>),
962     /// A `break`, with an optional label to break, and an optional expression
963     Break(Option<SpannedIdent>, Option<P<Expr>>),
964     /// A `continue`, with an optional label
965     Continue(Option<SpannedIdent>),
966     /// A `return`, with an optional value to be returned
967     Ret(Option<P<Expr>>),
968
969     /// Output of the `asm!()` macro
970     InlineAsm(P<InlineAsm>),
971
972     /// A macro invocation; pre-expansion
973     Mac(Mac),
974
975     /// A struct literal expression.
976     ///
977     /// For example, `Foo {x: 1, y: 2}`, or
978     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
979     Struct(Path, Vec<Field>, Option<P<Expr>>),
980
981     /// An array literal constructed from one repeated element.
982     ///
983     /// For example, `[1; 5]`. The first expression is the element
984     /// to be repeated; the second is the number of times to repeat it.
985     Repeat(P<Expr>, P<Expr>),
986
987     /// No-op: used solely so we can pretty-print faithfully
988     Paren(P<Expr>),
989
990     /// `expr?`
991     Try(P<Expr>),
992 }
993
994 /// The explicit Self type in a "qualified path". The actual
995 /// path, including the trait and the associated item, is stored
996 /// separately. `position` represents the index of the associated
997 /// item qualified with this Self type.
998 ///
999 /// ```rust,ignore
1000 /// <Vec<T> as a::b::Trait>::AssociatedItem
1001 ///  ^~~~~     ~~~~~~~~~~~~~~^
1002 ///  ty        position = 3
1003 ///
1004 /// <Vec<T>>::AssociatedItem
1005 ///  ^~~~~    ^
1006 ///  ty       position = 0
1007 /// ```
1008 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1009 pub struct QSelf {
1010     pub ty: P<Ty>,
1011     pub position: usize
1012 }
1013
1014 /// A capture clause
1015 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1016 pub enum CaptureBy {
1017     Value,
1018     Ref,
1019 }
1020
1021 pub type Mac = Spanned<Mac_>;
1022
1023 /// Represents a macro invocation. The Path indicates which macro
1024 /// is being invoked, and the vector of token-trees contains the source
1025 /// of the macro invocation.
1026 ///
1027 /// NB: the additional ident for a macro_rules-style macro is actually
1028 /// stored in the enclosing item. Oog.
1029 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1030 pub struct Mac_ {
1031     pub path: Path,
1032     pub tts: Vec<TokenTree>,
1033 }
1034
1035 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1036 pub enum StrStyle {
1037     /// A regular string, like `"foo"`
1038     Cooked,
1039     /// A raw string, like `r##"foo"##`
1040     ///
1041     /// The uint is the number of `#` symbols used
1042     Raw(usize)
1043 }
1044
1045 /// A literal
1046 pub type Lit = Spanned<LitKind>;
1047
1048 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1049 pub enum LitIntType {
1050     Signed(IntTy),
1051     Unsigned(UintTy),
1052     Unsuffixed,
1053 }
1054
1055 /// Literal kind.
1056 ///
1057 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1058 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1059 pub enum LitKind {
1060     /// A string literal (`"foo"`)
1061     Str(Symbol, StrStyle),
1062     /// A byte string (`b"foo"`)
1063     ByteStr(Rc<Vec<u8>>),
1064     /// A byte char (`b'f'`)
1065     Byte(u8),
1066     /// A character literal (`'a'`)
1067     Char(char),
1068     /// An integer literal (`1`)
1069     Int(u128, LitIntType),
1070     /// A float literal (`1f64` or `1E10f64`)
1071     Float(Symbol, FloatTy),
1072     /// A float literal without a suffix (`1.0 or 1.0E10`)
1073     FloatUnsuffixed(Symbol),
1074     /// A boolean literal
1075     Bool(bool),
1076 }
1077
1078 impl LitKind {
1079     /// Returns true if this literal is a string and false otherwise.
1080     pub fn is_str(&self) -> bool {
1081         match *self {
1082             LitKind::Str(..) => true,
1083             _ => false,
1084         }
1085     }
1086
1087     /// Returns true if this literal has no suffix. Note: this will return true
1088     /// for literals with prefixes such as raw strings and byte strings.
1089     pub fn is_unsuffixed(&self) -> bool {
1090         match *self {
1091             // unsuffixed variants
1092             LitKind::Str(..) => true,
1093             LitKind::ByteStr(..) => true,
1094             LitKind::Byte(..) => true,
1095             LitKind::Char(..) => true,
1096             LitKind::Int(_, LitIntType::Unsuffixed) => true,
1097             LitKind::FloatUnsuffixed(..) => true,
1098             LitKind::Bool(..) => true,
1099             // suffixed variants
1100             LitKind::Int(_, LitIntType::Signed(..)) => false,
1101             LitKind::Int(_, LitIntType::Unsigned(..)) => false,
1102             LitKind::Float(..) => false,
1103         }
1104     }
1105
1106     /// Returns true if this literal has a suffix.
1107     pub fn is_suffixed(&self) -> bool {
1108         !self.is_unsuffixed()
1109     }
1110 }
1111
1112 // NB: If you change this, you'll probably want to change the corresponding
1113 // type structure in middle/ty.rs as well.
1114 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1115 pub struct MutTy {
1116     pub ty: P<Ty>,
1117     pub mutbl: Mutability,
1118 }
1119
1120 /// Represents a method's signature in a trait declaration,
1121 /// or in an implementation.
1122 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1123 pub struct MethodSig {
1124     pub unsafety: Unsafety,
1125     pub constness: Spanned<Constness>,
1126     pub abi: Abi,
1127     pub decl: P<FnDecl>,
1128     pub generics: Generics,
1129 }
1130
1131 /// Represents an item declaration within a trait declaration,
1132 /// possibly including a default implementation. A trait item is
1133 /// either required (meaning it doesn't have an implementation, just a
1134 /// signature) or provided (meaning it has a default implementation).
1135 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1136 pub struct TraitItem {
1137     pub id: NodeId,
1138     pub ident: Ident,
1139     pub attrs: Vec<Attribute>,
1140     pub node: TraitItemKind,
1141     pub span: Span,
1142 }
1143
1144 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1145 pub enum TraitItemKind {
1146     Const(P<Ty>, Option<P<Expr>>),
1147     Method(MethodSig, Option<P<Block>>),
1148     Type(TyParamBounds, Option<P<Ty>>),
1149     Macro(Mac),
1150 }
1151
1152 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1153 pub struct ImplItem {
1154     pub id: NodeId,
1155     pub ident: Ident,
1156     pub vis: Visibility,
1157     pub defaultness: Defaultness,
1158     pub attrs: Vec<Attribute>,
1159     pub node: ImplItemKind,
1160     pub span: Span,
1161 }
1162
1163 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1164 pub enum ImplItemKind {
1165     Const(P<Ty>, P<Expr>),
1166     Method(MethodSig, P<Block>),
1167     Type(P<Ty>),
1168     Macro(Mac),
1169 }
1170
1171 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1172 pub enum IntTy {
1173     Is,
1174     I8,
1175     I16,
1176     I32,
1177     I64,
1178     I128,
1179 }
1180
1181 impl fmt::Debug for IntTy {
1182     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1183         fmt::Display::fmt(self, f)
1184     }
1185 }
1186
1187 impl fmt::Display for IntTy {
1188     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1189         write!(f, "{}", self.ty_to_string())
1190     }
1191 }
1192
1193 impl IntTy {
1194     pub fn ty_to_string(&self) -> &'static str {
1195         match *self {
1196             IntTy::Is => "isize",
1197             IntTy::I8 => "i8",
1198             IntTy::I16 => "i16",
1199             IntTy::I32 => "i32",
1200             IntTy::I64 => "i64",
1201             IntTy::I128 => "i128",
1202         }
1203     }
1204
1205     pub fn val_to_string(&self, val: i128) -> String {
1206         // cast to a u128 so we can correctly print INT128_MIN. All integral types
1207         // are parsed as u128, so we wouldn't want to print an extra negative
1208         // sign.
1209         format!("{}{}", val as u128, self.ty_to_string())
1210     }
1211
1212     pub fn bit_width(&self) -> Option<usize> {
1213         Some(match *self {
1214             IntTy::Is => return None,
1215             IntTy::I8 => 8,
1216             IntTy::I16 => 16,
1217             IntTy::I32 => 32,
1218             IntTy::I64 => 64,
1219             IntTy::I128 => 128,
1220         })
1221     }
1222 }
1223
1224 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1225 pub enum UintTy {
1226     Us,
1227     U8,
1228     U16,
1229     U32,
1230     U64,
1231     U128,
1232 }
1233
1234 impl UintTy {
1235     pub fn ty_to_string(&self) -> &'static str {
1236         match *self {
1237             UintTy::Us => "usize",
1238             UintTy::U8 => "u8",
1239             UintTy::U16 => "u16",
1240             UintTy::U32 => "u32",
1241             UintTy::U64 => "u64",
1242             UintTy::U128 => "u128",
1243         }
1244     }
1245
1246     pub fn val_to_string(&self, val: u128) -> String {
1247         format!("{}{}", val, self.ty_to_string())
1248     }
1249
1250     pub fn bit_width(&self) -> Option<usize> {
1251         Some(match *self {
1252             UintTy::Us => return None,
1253             UintTy::U8 => 8,
1254             UintTy::U16 => 16,
1255             UintTy::U32 => 32,
1256             UintTy::U64 => 64,
1257             UintTy::U128 => 128,
1258         })
1259     }
1260 }
1261
1262 impl fmt::Debug for UintTy {
1263     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1264         fmt::Display::fmt(self, f)
1265     }
1266 }
1267
1268 impl fmt::Display for UintTy {
1269     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1270         write!(f, "{}", self.ty_to_string())
1271     }
1272 }
1273
1274 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1275 pub enum FloatTy {
1276     F32,
1277     F64,
1278 }
1279
1280 impl fmt::Debug for FloatTy {
1281     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1282         fmt::Display::fmt(self, f)
1283     }
1284 }
1285
1286 impl fmt::Display for FloatTy {
1287     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1288         write!(f, "{}", self.ty_to_string())
1289     }
1290 }
1291
1292 impl FloatTy {
1293     pub fn ty_to_string(&self) -> &'static str {
1294         match *self {
1295             FloatTy::F32 => "f32",
1296             FloatTy::F64 => "f64",
1297         }
1298     }
1299
1300     pub fn bit_width(&self) -> usize {
1301         match *self {
1302             FloatTy::F32 => 32,
1303             FloatTy::F64 => 64,
1304         }
1305     }
1306 }
1307
1308 // Bind a type to an associated type: `A=Foo`.
1309 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1310 pub struct TypeBinding {
1311     pub id: NodeId,
1312     pub ident: Ident,
1313     pub ty: P<Ty>,
1314     pub span: Span,
1315 }
1316
1317 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1318 pub struct Ty {
1319     pub id: NodeId,
1320     pub node: TyKind,
1321     pub span: Span,
1322 }
1323
1324 impl fmt::Debug for Ty {
1325     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1326         write!(f, "type({})", pprust::ty_to_string(self))
1327     }
1328 }
1329
1330 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1331 pub struct BareFnTy {
1332     pub unsafety: Unsafety,
1333     pub abi: Abi,
1334     pub lifetimes: Vec<LifetimeDef>,
1335     pub decl: P<FnDecl>
1336 }
1337
1338 /// The different kinds of types recognized by the compiler
1339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1340 pub enum TyKind {
1341     /// A variable-length slice (`[T]`)
1342     Slice(P<Ty>),
1343     /// A fixed length array (`[T; n]`)
1344     Array(P<Ty>, P<Expr>),
1345     /// A raw pointer (`*const T` or `*mut T`)
1346     Ptr(MutTy),
1347     /// A reference (`&'a T` or `&'a mut T`)
1348     Rptr(Option<Lifetime>, MutTy),
1349     /// A bare function (e.g. `fn(usize) -> bool`)
1350     BareFn(P<BareFnTy>),
1351     /// The never type (`!`)
1352     Never,
1353     /// A tuple (`(A, B, C, D,...)`)
1354     Tup(Vec<P<Ty>> ),
1355     /// A path (`module::module::...::Type`), optionally
1356     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1357     ///
1358     /// Type parameters are stored in the Path itself
1359     Path(Option<QSelf>, Path),
1360     /// Something like `A+B`. Note that `B` must always be a path.
1361     ObjectSum(P<Ty>, TyParamBounds),
1362     /// A type like `for<'a> Foo<&'a Bar>`
1363     PolyTraitRef(TyParamBounds),
1364     /// An `impl TraitA+TraitB` type.
1365     ImplTrait(TyParamBounds),
1366     /// No-op; kept solely so that we can pretty-print faithfully
1367     Paren(P<Ty>),
1368     /// Unused for now
1369     Typeof(P<Expr>),
1370     /// TyKind::Infer means the type should be inferred instead of it having been
1371     /// specified. This can appear anywhere in a type.
1372     Infer,
1373     /// Inferred type of a `self` or `&self` argument in a method.
1374     ImplicitSelf,
1375     // A macro in the type position.
1376     Mac(Mac),
1377 }
1378
1379 /// Inline assembly dialect.
1380 ///
1381 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1382 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1383 pub enum AsmDialect {
1384     Att,
1385     Intel,
1386 }
1387
1388 /// Inline assembly.
1389 ///
1390 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1392 pub struct InlineAsmOutput {
1393     pub constraint: Symbol,
1394     pub expr: P<Expr>,
1395     pub is_rw: bool,
1396     pub is_indirect: bool,
1397 }
1398
1399 /// Inline assembly.
1400 ///
1401 /// E.g. `asm!("NOP");`
1402 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1403 pub struct InlineAsm {
1404     pub asm: Symbol,
1405     pub asm_str_style: StrStyle,
1406     pub outputs: Vec<InlineAsmOutput>,
1407     pub inputs: Vec<(Symbol, P<Expr>)>,
1408     pub clobbers: Vec<Symbol>,
1409     pub volatile: bool,
1410     pub alignstack: bool,
1411     pub dialect: AsmDialect,
1412     pub expn_id: ExpnId,
1413 }
1414
1415 /// An argument in a function header.
1416 ///
1417 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1418 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1419 pub struct Arg {
1420     pub ty: P<Ty>,
1421     pub pat: P<Pat>,
1422     pub id: NodeId,
1423 }
1424
1425 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1426 ///
1427 /// E.g. `&mut self` as in `fn foo(&mut self)`
1428 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1429 pub enum SelfKind {
1430     /// `self`, `mut self`
1431     Value(Mutability),
1432     /// `&'lt self`, `&'lt mut self`
1433     Region(Option<Lifetime>, Mutability),
1434     /// `self: TYPE`, `mut self: TYPE`
1435     Explicit(P<Ty>, Mutability),
1436 }
1437
1438 pub type ExplicitSelf = Spanned<SelfKind>;
1439
1440 impl Arg {
1441     pub fn to_self(&self) -> Option<ExplicitSelf> {
1442         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1443             if ident.node.name == keywords::SelfValue.name() {
1444                 return match self.ty.node {
1445                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1446                     TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1447                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1448                     }
1449                     _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1450                                      SelfKind::Explicit(self.ty.clone(), mutbl))),
1451                 }
1452             }
1453         }
1454         None
1455     }
1456
1457     pub fn is_self(&self) -> bool {
1458         if let PatKind::Ident(_, ident, _) = self.pat.node {
1459             ident.node.name == keywords::SelfValue.name()
1460         } else {
1461             false
1462         }
1463     }
1464
1465     pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1466         let span = mk_sp(eself.span.lo, eself_ident.span.hi);
1467         let infer_ty = P(Ty {
1468             id: DUMMY_NODE_ID,
1469             node: TyKind::ImplicitSelf,
1470             span: span,
1471         });
1472         let arg = |mutbl, ty| Arg {
1473             pat: P(Pat {
1474                 id: DUMMY_NODE_ID,
1475                 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1476                 span: span,
1477             }),
1478             ty: ty,
1479             id: DUMMY_NODE_ID,
1480         };
1481         match eself.node {
1482             SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1483             SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1484             SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1485                 id: DUMMY_NODE_ID,
1486                 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1487                 span: span,
1488             })),
1489         }
1490     }
1491 }
1492
1493 /// Header (not the body) of a function declaration.
1494 ///
1495 /// E.g. `fn foo(bar: baz)`
1496 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1497 pub struct FnDecl {
1498     pub inputs: Vec<Arg>,
1499     pub output: FunctionRetTy,
1500     pub variadic: bool
1501 }
1502
1503 impl FnDecl {
1504     pub fn get_self(&self) -> Option<ExplicitSelf> {
1505         self.inputs.get(0).and_then(Arg::to_self)
1506     }
1507     pub fn has_self(&self) -> bool {
1508         self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1509     }
1510 }
1511
1512 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1513 pub enum Unsafety {
1514     Unsafe,
1515     Normal,
1516 }
1517
1518 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1519 pub enum Constness {
1520     Const,
1521     NotConst,
1522 }
1523
1524 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1525 pub enum Defaultness {
1526     Default,
1527     Final,
1528 }
1529
1530 impl fmt::Display for Unsafety {
1531     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1532         fmt::Display::fmt(match *self {
1533             Unsafety::Normal => "normal",
1534             Unsafety::Unsafe => "unsafe",
1535         }, f)
1536     }
1537 }
1538
1539 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1540 pub enum ImplPolarity {
1541     /// `impl Trait for Type`
1542     Positive,
1543     /// `impl !Trait for Type`
1544     Negative,
1545 }
1546
1547 impl fmt::Debug for ImplPolarity {
1548     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1549         match *self {
1550             ImplPolarity::Positive => "positive".fmt(f),
1551             ImplPolarity::Negative => "negative".fmt(f),
1552         }
1553     }
1554 }
1555
1556
1557 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1558 pub enum FunctionRetTy {
1559     /// Return type is not specified.
1560     ///
1561     /// Functions default to `()` and
1562     /// closures default to inference. Span points to where return
1563     /// type would be inserted.
1564     Default(Span),
1565     /// Everything else
1566     Ty(P<Ty>),
1567 }
1568
1569 impl FunctionRetTy {
1570     pub fn span(&self) -> Span {
1571         match *self {
1572             FunctionRetTy::Default(span) => span,
1573             FunctionRetTy::Ty(ref ty) => ty.span,
1574         }
1575     }
1576 }
1577
1578 /// Module declaration.
1579 ///
1580 /// E.g. `mod foo;` or `mod foo { .. }`
1581 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1582 pub struct Mod {
1583     /// A span from the first token past `{` to the last token until `}`.
1584     /// For `mod foo;`, the inner span ranges from the first token
1585     /// to the last token in the external file.
1586     pub inner: Span,
1587     pub items: Vec<P<Item>>,
1588 }
1589
1590 /// Foreign module declaration.
1591 ///
1592 /// E.g. `extern { .. }` or `extern C { .. }`
1593 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1594 pub struct ForeignMod {
1595     pub abi: Abi,
1596     pub items: Vec<ForeignItem>,
1597 }
1598
1599 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1600 pub struct EnumDef {
1601     pub variants: Vec<Variant>,
1602 }
1603
1604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1605 pub struct Variant_ {
1606     pub name: Ident,
1607     pub attrs: Vec<Attribute>,
1608     pub data: VariantData,
1609     /// Explicit discriminant, e.g. `Foo = 1`
1610     pub disr_expr: Option<P<Expr>>,
1611 }
1612
1613 pub type Variant = Spanned<Variant_>;
1614
1615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1616 pub struct PathListItem_ {
1617     pub name: Ident,
1618     /// renamed in list, e.g. `use foo::{bar as baz};`
1619     pub rename: Option<Ident>,
1620     pub id: NodeId,
1621 }
1622
1623 pub type PathListItem = Spanned<PathListItem_>;
1624
1625 pub type ViewPath = Spanned<ViewPath_>;
1626
1627 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1628 pub enum ViewPath_ {
1629
1630     /// `foo::bar::baz as quux`
1631     ///
1632     /// or just
1633     ///
1634     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1635     ViewPathSimple(Ident, Path),
1636
1637     /// `foo::bar::*`
1638     ViewPathGlob(Path),
1639
1640     /// `foo::bar::{a,b,c}`
1641     ViewPathList(Path, Vec<PathListItem>)
1642 }
1643
1644 impl ViewPath_ {
1645     pub fn path(&self) -> &Path {
1646         match *self {
1647             ViewPathSimple(_, ref path) |
1648             ViewPathGlob (ref path) |
1649             ViewPathList(ref path, _) => path
1650         }
1651     }
1652 }
1653
1654
1655 /// Distinguishes between Attributes that decorate items and Attributes that
1656 /// are contained as statements within items. These two cases need to be
1657 /// distinguished for pretty-printing.
1658 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1659 pub enum AttrStyle {
1660     Outer,
1661     Inner,
1662 }
1663
1664 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1665 pub struct AttrId(pub usize);
1666
1667 /// Meta-data associated with an item
1668 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1669 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1670 pub struct Attribute {
1671     pub id: AttrId,
1672     pub style: AttrStyle,
1673     pub value: MetaItem,
1674     pub is_sugared_doc: bool,
1675     pub span: Span,
1676 }
1677
1678 /// TraitRef's appear in impls.
1679 ///
1680 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1681 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1682 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1683 /// same as the impl's node id).
1684 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1685 pub struct TraitRef {
1686     pub path: Path,
1687     pub ref_id: NodeId,
1688 }
1689
1690 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1691 pub struct PolyTraitRef {
1692     /// The `'a` in `<'a> Foo<&'a T>`
1693     pub bound_lifetimes: Vec<LifetimeDef>,
1694
1695     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1696     pub trait_ref: TraitRef,
1697
1698     pub span: Span,
1699 }
1700
1701 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1702 pub enum Visibility {
1703     Public,
1704     Crate(Span),
1705     Restricted { path: P<Path>, id: NodeId },
1706     Inherited,
1707 }
1708
1709 /// Field of a struct.
1710 ///
1711 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1712 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1713 pub struct StructField {
1714     pub span: Span,
1715     pub ident: Option<Ident>,
1716     pub vis: Visibility,
1717     pub id: NodeId,
1718     pub ty: P<Ty>,
1719     pub attrs: Vec<Attribute>,
1720 }
1721
1722 /// Fields and Ids of enum variants and structs
1723 ///
1724 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1725 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1726 /// One shared Id can be successfully used for these two purposes.
1727 /// Id of the whole enum lives in `Item`.
1728 ///
1729 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1730 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1731 /// the variant itself" from enum variants.
1732 /// Id of the whole struct lives in `Item`.
1733 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1734 pub enum VariantData {
1735     /// Struct variant.
1736     ///
1737     /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1738     Struct(Vec<StructField>, NodeId),
1739     /// Tuple variant.
1740     ///
1741     /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1742     Tuple(Vec<StructField>, NodeId),
1743     /// Unit variant.
1744     ///
1745     /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1746     Unit(NodeId),
1747 }
1748
1749 impl VariantData {
1750     pub fn fields(&self) -> &[StructField] {
1751         match *self {
1752             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1753             _ => &[],
1754         }
1755     }
1756     pub fn id(&self) -> NodeId {
1757         match *self {
1758             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1759         }
1760     }
1761     pub fn is_struct(&self) -> bool {
1762         if let VariantData::Struct(..) = *self { true } else { false }
1763     }
1764     pub fn is_tuple(&self) -> bool {
1765         if let VariantData::Tuple(..) = *self { true } else { false }
1766     }
1767     pub fn is_unit(&self) -> bool {
1768         if let VariantData::Unit(..) = *self { true } else { false }
1769     }
1770 }
1771
1772 /// An item
1773 ///
1774 /// The name might be a dummy name in case of anonymous items
1775 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1776 pub struct Item {
1777     pub ident: Ident,
1778     pub attrs: Vec<Attribute>,
1779     pub id: NodeId,
1780     pub node: ItemKind,
1781     pub vis: Visibility,
1782     pub span: Span,
1783 }
1784
1785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1786 pub enum ItemKind {
1787     /// An`extern crate` item, with optional original crate name.
1788     ///
1789     /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1790     ExternCrate(Option<Name>),
1791     /// A use declaration (`use` or `pub use`) item.
1792     ///
1793     /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1794     Use(P<ViewPath>),
1795     /// A static item (`static` or `pub static`).
1796     ///
1797     /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1798     Static(P<Ty>, Mutability, P<Expr>),
1799     /// A constant item (`const` or `pub const`).
1800     ///
1801     /// E.g. `const FOO: i32 = 42;`
1802     Const(P<Ty>, P<Expr>),
1803     /// A function declaration (`fn` or `pub fn`).
1804     ///
1805     /// E.g. `fn foo(bar: usize) -> usize { .. }`
1806     Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1807     /// A module declaration (`mod` or `pub mod`).
1808     ///
1809     /// E.g. `mod foo;` or `mod foo { .. }`
1810     Mod(Mod),
1811     /// An external module (`extern` or `pub extern`).
1812     ///
1813     /// E.g. `extern {}` or `extern "C" {}`
1814     ForeignMod(ForeignMod),
1815     /// A type alias (`type` or `pub type`).
1816     ///
1817     /// E.g. `type Foo = Bar<u8>;`
1818     Ty(P<Ty>, Generics),
1819     /// An enum definition (`enum` or `pub enum`).
1820     ///
1821     /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1822     Enum(EnumDef, Generics),
1823     /// A struct definition (`struct` or `pub struct`).
1824     ///
1825     /// E.g. `struct Foo<A> { x: A }`
1826     Struct(VariantData, Generics),
1827     /// A union definition (`union` or `pub union`).
1828     ///
1829     /// E.g. `union Foo<A, B> { x: A, y: B }`
1830     Union(VariantData, Generics),
1831     /// A Trait declaration (`trait` or `pub trait`).
1832     ///
1833     /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1834     Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1835     // Default trait implementation.
1836     ///
1837     /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1838     DefaultImpl(Unsafety, TraitRef),
1839     /// An implementation.
1840     ///
1841     /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1842     Impl(Unsafety,
1843              ImplPolarity,
1844              Generics,
1845              Option<TraitRef>, // (optional) trait this impl implements
1846              P<Ty>, // self
1847              Vec<ImplItem>),
1848     /// A macro invocation (which includes macro definition).
1849     ///
1850     /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1851     Mac(Mac),
1852 }
1853
1854 impl ItemKind {
1855     pub fn descriptive_variant(&self) -> &str {
1856         match *self {
1857             ItemKind::ExternCrate(..) => "extern crate",
1858             ItemKind::Use(..) => "use",
1859             ItemKind::Static(..) => "static item",
1860             ItemKind::Const(..) => "constant item",
1861             ItemKind::Fn(..) => "function",
1862             ItemKind::Mod(..) => "module",
1863             ItemKind::ForeignMod(..) => "foreign module",
1864             ItemKind::Ty(..) => "type alias",
1865             ItemKind::Enum(..) => "enum",
1866             ItemKind::Struct(..) => "struct",
1867             ItemKind::Union(..) => "union",
1868             ItemKind::Trait(..) => "trait",
1869             ItemKind::Mac(..) |
1870             ItemKind::Impl(..) |
1871             ItemKind::DefaultImpl(..) => "item"
1872         }
1873     }
1874 }
1875
1876 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1877 pub struct ForeignItem {
1878     pub ident: Ident,
1879     pub attrs: Vec<Attribute>,
1880     pub node: ForeignItemKind,
1881     pub id: NodeId,
1882     pub span: Span,
1883     pub vis: Visibility,
1884 }
1885
1886 /// An item within an `extern` block
1887 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1888 pub enum ForeignItemKind {
1889     /// A foreign function
1890     Fn(P<FnDecl>, Generics),
1891     /// A foreign static item (`static ext: u8`), with optional mutability
1892     /// (the boolean is true when mutable)
1893     Static(P<Ty>, bool),
1894 }
1895
1896 impl ForeignItemKind {
1897     pub fn descriptive_variant(&self) -> &str {
1898         match *self {
1899             ForeignItemKind::Fn(..) => "foreign function",
1900             ForeignItemKind::Static(..) => "foreign static item"
1901         }
1902     }
1903 }
1904
1905 /// A macro definition, in this crate or imported from another.
1906 ///
1907 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1908 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1909 pub struct MacroDef {
1910     pub ident: Ident,
1911     pub attrs: Vec<Attribute>,
1912     pub id: NodeId,
1913     pub span: Span,
1914     pub body: Vec<TokenTree>,
1915 }
1916
1917 #[cfg(test)]
1918 mod tests {
1919     use serialize;
1920     use super::*;
1921
1922     // are ASTs encodable?
1923     #[test]
1924     fn check_asts_encodable() {
1925         fn assert_encodable<T: serialize::Encodable>() {}
1926         assert_encodable::<Crate>();
1927     }
1928 }