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