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