]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Auto merge of #44853 - alexcrichton:debug-codegen-units, r=michaelwoerister
[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(RangeSyntax),
542     Excluded,
543 }
544
545 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
546 pub enum RangeSyntax {
547     DotDotDot,
548     DotDotEq,
549 }
550
551 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
552 pub enum PatKind {
553     /// Represents a wildcard pattern (`_`)
554     Wild,
555
556     /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
557     /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
558     /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
559     /// during name resolution.
560     Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
561
562     /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
563     /// The `bool` is `true` in the presence of a `..`.
564     Struct(Path, Vec<Spanned<FieldPat>>, bool),
565
566     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
567     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
568     /// 0 <= position <= subpats.len()
569     TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
570
571     /// A possibly qualified path pattern.
572     /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
573     /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
574     /// only legally refer to associated constants.
575     Path(Option<QSelf>, Path),
576
577     /// A tuple pattern `(a, b)`.
578     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
579     /// 0 <= position <= subpats.len()
580     Tuple(Vec<P<Pat>>, Option<usize>),
581     /// A `box` pattern
582     Box(P<Pat>),
583     /// A reference pattern, e.g. `&mut (a, b)`
584     Ref(P<Pat>, Mutability),
585     /// A literal
586     Lit(P<Expr>),
587     /// A range pattern, e.g. `1...2`, `1..=2` or `1..2`
588     Range(P<Expr>, P<Expr>, RangeEnd),
589     /// `[a, b, ..i, y, z]` is represented as:
590     ///     `PatKind::Slice(box [a, b], Some(i), box [y, z])`
591     Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
592     /// A macro pattern; pre-expansion
593     Mac(Mac),
594 }
595
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
597 pub enum Mutability {
598     Mutable,
599     Immutable,
600 }
601
602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
603 pub enum BinOpKind {
604     /// The `+` operator (addition)
605     Add,
606     /// The `-` operator (subtraction)
607     Sub,
608     /// The `*` operator (multiplication)
609     Mul,
610     /// The `/` operator (division)
611     Div,
612     /// The `%` operator (modulus)
613     Rem,
614     /// The `&&` operator (logical and)
615     And,
616     /// The `||` operator (logical or)
617     Or,
618     /// The `^` operator (bitwise xor)
619     BitXor,
620     /// The `&` operator (bitwise and)
621     BitAnd,
622     /// The `|` operator (bitwise or)
623     BitOr,
624     /// The `<<` operator (shift left)
625     Shl,
626     /// The `>>` operator (shift right)
627     Shr,
628     /// The `==` operator (equality)
629     Eq,
630     /// The `<` operator (less than)
631     Lt,
632     /// The `<=` operator (less than or equal to)
633     Le,
634     /// The `!=` operator (not equal to)
635     Ne,
636     /// The `>=` operator (greater than or equal to)
637     Ge,
638     /// The `>` operator (greater than)
639     Gt,
640 }
641
642 impl BinOpKind {
643     pub fn to_string(&self) -> &'static str {
644         use self::BinOpKind::*;
645         match *self {
646             Add => "+",
647             Sub => "-",
648             Mul => "*",
649             Div => "/",
650             Rem => "%",
651             And => "&&",
652             Or => "||",
653             BitXor => "^",
654             BitAnd => "&",
655             BitOr => "|",
656             Shl => "<<",
657             Shr => ">>",
658             Eq => "==",
659             Lt => "<",
660             Le => "<=",
661             Ne => "!=",
662             Ge => ">=",
663             Gt => ">",
664         }
665     }
666     pub fn lazy(&self) -> bool {
667         match *self {
668             BinOpKind::And | BinOpKind::Or => true,
669             _ => false
670         }
671     }
672
673     pub fn is_shift(&self) -> bool {
674         match *self {
675             BinOpKind::Shl | BinOpKind::Shr => true,
676             _ => false
677         }
678     }
679     pub fn is_comparison(&self) -> bool {
680         use self::BinOpKind::*;
681         match *self {
682             Eq | Lt | Le | Ne | Gt | Ge =>
683             true,
684             And | Or | Add | Sub | Mul | Div | Rem |
685             BitXor | BitAnd | BitOr | Shl | Shr =>
686             false,
687         }
688     }
689     /// Returns `true` if the binary operator takes its arguments by value
690     pub fn is_by_value(&self) -> bool {
691         !self.is_comparison()
692     }
693 }
694
695 pub type BinOp = Spanned<BinOpKind>;
696
697 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
698 pub enum UnOp {
699     /// The `*` operator for dereferencing
700     Deref,
701     /// The `!` operator for logical inversion
702     Not,
703     /// The `-` operator for negation
704     Neg,
705 }
706
707 impl UnOp {
708     /// Returns `true` if the unary operator takes its argument by value
709     pub fn is_by_value(u: UnOp) -> bool {
710         match u {
711             UnOp::Neg | UnOp::Not => true,
712             _ => false,
713         }
714     }
715
716     pub fn to_string(op: UnOp) -> &'static str {
717         match op {
718             UnOp::Deref => "*",
719             UnOp::Not => "!",
720             UnOp::Neg => "-",
721         }
722     }
723 }
724
725 /// A statement
726 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
727 pub struct Stmt {
728     pub id: NodeId,
729     pub node: StmtKind,
730     pub span: Span,
731 }
732
733 impl Stmt {
734     pub fn add_trailing_semicolon(mut self) -> Self {
735         self.node = match self.node {
736             StmtKind::Expr(expr) => StmtKind::Semi(expr),
737             StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
738                 (mac, MacStmtStyle::Semicolon, attrs)
739             })),
740             node => node,
741         };
742         self
743     }
744
745     pub fn is_item(&self) -> bool {
746         match self.node {
747             StmtKind::Local(_) => true,
748             _ => false,
749         }
750     }
751 }
752
753 impl fmt::Debug for Stmt {
754     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
755         write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
756     }
757 }
758
759
760 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
761 pub enum StmtKind {
762     /// A local (let) binding.
763     Local(P<Local>),
764
765     /// An item definition.
766     Item(P<Item>),
767
768     /// Expr without trailing semi-colon.
769     Expr(P<Expr>),
770     /// Expr with a trailing semi-colon.
771     Semi(P<Expr>),
772     /// Macro.
773     Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
774 }
775
776 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
777 pub enum MacStmtStyle {
778     /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
779     /// `foo!(...);`, `foo![...];`
780     Semicolon,
781     /// The macro statement had braces; e.g. foo! { ... }
782     Braces,
783     /// The macro statement had parentheses or brackets and no semicolon; e.g.
784     /// `foo!(...)`. All of these will end up being converted into macro
785     /// expressions.
786     NoBraces,
787 }
788
789 // FIXME (pending discussion of #1697, #2178...): local should really be
790 // a refinement on pat.
791 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
792 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
793 pub struct Local {
794     pub pat: P<Pat>,
795     pub ty: Option<P<Ty>>,
796     /// Initializer expression to set the value, if any
797     pub init: Option<P<Expr>>,
798     pub id: NodeId,
799     pub span: Span,
800     pub attrs: ThinVec<Attribute>,
801 }
802
803 /// An arm of a 'match'.
804 ///
805 /// E.g. `0...10 => { println!("match!") }` as in
806 ///
807 /// ```
808 /// match 123 {
809 ///     0...10 => { println!("match!") },
810 ///     _ => { println!("no match!") },
811 /// }
812 /// ```
813 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
814 pub struct Arm {
815     pub attrs: Vec<Attribute>,
816     pub pats: Vec<P<Pat>>,
817     pub guard: Option<P<Expr>>,
818     pub body: P<Expr>,
819     pub beginning_vert: Option<Span>, // For RFC 1925 feature gate
820 }
821
822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
823 pub struct Field {
824     pub ident: SpannedIdent,
825     pub expr: P<Expr>,
826     pub span: Span,
827     pub is_shorthand: bool,
828     pub attrs: ThinVec<Attribute>,
829 }
830
831 pub type SpannedIdent = Spanned<Ident>;
832
833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
834 pub enum BlockCheckMode {
835     Default,
836     Unsafe(UnsafeSource),
837 }
838
839 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
840 pub enum UnsafeSource {
841     CompilerGenerated,
842     UserProvided,
843 }
844
845 /// An expression
846 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
847 pub struct Expr {
848     pub id: NodeId,
849     pub node: ExprKind,
850     pub span: Span,
851     pub attrs: ThinVec<Attribute>
852 }
853
854 impl Expr {
855     /// Wether this expression would be valid somewhere that expects a value, for example, an `if`
856     /// condition.
857     pub fn returns(&self) -> bool {
858         if let ExprKind::Block(ref block) = self.node {
859             match block.stmts.last().map(|last_stmt| &last_stmt.node) {
860                 // implicit return
861                 Some(&StmtKind::Expr(_)) => true,
862                 Some(&StmtKind::Semi(ref expr)) => {
863                     if let ExprKind::Ret(_) = expr.node {
864                         // last statement is explicit return
865                         true
866                     } else {
867                         false
868                     }
869                 }
870                 // This is a block that doesn't end in either an implicit or explicit return
871                 _ => false,
872             }
873         } else {
874             // This is not a block, it is a value
875             true
876         }
877     }
878 }
879
880 impl fmt::Debug for Expr {
881     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
883     }
884 }
885
886 /// Limit types of a range (inclusive or exclusive)
887 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
888 pub enum RangeLimits {
889     /// Inclusive at the beginning, exclusive at the end
890     HalfOpen,
891     /// Inclusive at the beginning and end
892     Closed,
893 }
894
895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
896 pub enum ExprKind {
897     /// A `box x` expression.
898     Box(P<Expr>),
899     /// First expr is the place; second expr is the value.
900     InPlace(P<Expr>, P<Expr>),
901     /// An array (`[a, b, c, d]`)
902     Array(Vec<P<Expr>>),
903     /// A function call
904     ///
905     /// The first field resolves to the function itself,
906     /// and the second field is the list of arguments
907     Call(P<Expr>, Vec<P<Expr>>),
908     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
909     ///
910     /// The `PathSegment` represents the method name and its generic arguments
911     /// (within the angle brackets).
912     /// The first element of the vector of `Expr`s is the expression that evaluates
913     /// to the object on which the method is being called on (the receiver),
914     /// and the remaining elements are the rest of the arguments.
915     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
916     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
917     MethodCall(PathSegment, Vec<P<Expr>>),
918     /// A tuple (`(a, b, c ,d)`)
919     Tup(Vec<P<Expr>>),
920     /// A binary operation (For example: `a + b`, `a * b`)
921     Binary(BinOp, P<Expr>, P<Expr>),
922     /// A unary operation (For example: `!x`, `*x`)
923     Unary(UnOp, P<Expr>),
924     /// A literal (For example: `1`, `"foo"`)
925     Lit(P<Lit>),
926     /// A cast (`foo as f64`)
927     Cast(P<Expr>, P<Ty>),
928     Type(P<Expr>, P<Ty>),
929     /// An `if` block, with an optional else block
930     ///
931     /// `if expr { block } else { expr }`
932     If(P<Expr>, P<Block>, Option<P<Expr>>),
933     /// An `if let` expression with an optional else block
934     ///
935     /// `if let pat = expr { block } else { expr }`
936     ///
937     /// This is desugared to a `match` expression.
938     IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
939     /// A while loop, with an optional label
940     ///
941     /// `'label: while expr { block }`
942     While(P<Expr>, P<Block>, Option<SpannedIdent>),
943     /// A while-let loop, with an optional label
944     ///
945     /// `'label: while let pat = expr { block }`
946     ///
947     /// This is desugared to a combination of `loop` and `match` expressions.
948     WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
949     /// A for loop, with an optional label
950     ///
951     /// `'label: for pat in expr { block }`
952     ///
953     /// This is desugared to a combination of `loop` and `match` expressions.
954     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
955     /// Conditionless loop (can be exited with break, continue, or return)
956     ///
957     /// `'label: loop { block }`
958     Loop(P<Block>, Option<SpannedIdent>),
959     /// A `match` block.
960     Match(P<Expr>, Vec<Arm>),
961     /// A closure (for example, `move |a, b, c| a + b + c`)
962     ///
963     /// The final span is the span of the argument block `|...|`
964     Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
965     /// A block (`{ ... }`)
966     Block(P<Block>),
967     /// A catch block (`catch { ... }`)
968     Catch(P<Block>),
969
970     /// An assignment (`a = foo()`)
971     Assign(P<Expr>, P<Expr>),
972     /// An assignment with an operator
973     ///
974     /// For example, `a += 1`.
975     AssignOp(BinOp, P<Expr>, P<Expr>),
976     /// Access of a named struct field (`obj.foo`)
977     Field(P<Expr>, SpannedIdent),
978     /// Access of an unnamed field of a struct or tuple-struct
979     ///
980     /// For example, `foo.0`.
981     TupField(P<Expr>, Spanned<usize>),
982     /// An indexing operation (`foo[2]`)
983     Index(P<Expr>, P<Expr>),
984     /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
985     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
986
987     /// Variable reference, possibly containing `::` and/or type
988     /// parameters, e.g. foo::bar::<baz>.
989     ///
990     /// Optionally "qualified",
991     /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
992     Path(Option<QSelf>, Path),
993
994     /// A referencing operation (`&a` or `&mut a`)
995     AddrOf(Mutability, P<Expr>),
996     /// A `break`, with an optional label to break, and an optional expression
997     Break(Option<SpannedIdent>, Option<P<Expr>>),
998     /// A `continue`, with an optional label
999     Continue(Option<SpannedIdent>),
1000     /// A `return`, with an optional value to be returned
1001     Ret(Option<P<Expr>>),
1002
1003     /// Output of the `asm!()` macro
1004     InlineAsm(P<InlineAsm>),
1005
1006     /// A macro invocation; pre-expansion
1007     Mac(Mac),
1008
1009     /// A struct literal expression.
1010     ///
1011     /// For example, `Foo {x: 1, y: 2}`, or
1012     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1013     Struct(Path, Vec<Field>, Option<P<Expr>>),
1014
1015     /// An array literal constructed from one repeated element.
1016     ///
1017     /// For example, `[1; 5]`. The first expression is the element
1018     /// to be repeated; the second is the number of times to repeat it.
1019     Repeat(P<Expr>, P<Expr>),
1020
1021     /// No-op: used solely so we can pretty-print faithfully
1022     Paren(P<Expr>),
1023
1024     /// `expr?`
1025     Try(P<Expr>),
1026
1027     /// A `yield`, with an optional value to be yielded
1028     Yield(Option<P<Expr>>),
1029 }
1030
1031 /// The explicit Self type in a "qualified path". The actual
1032 /// path, including the trait and the associated item, is stored
1033 /// separately. `position` represents the index of the associated
1034 /// item qualified with this Self type.
1035 ///
1036 /// ```ignore (only-for-syntax-highlight)
1037 /// <Vec<T> as a::b::Trait>::AssociatedItem
1038 ///  ^~~~~     ~~~~~~~~~~~~~~^
1039 ///  ty        position = 3
1040 ///
1041 /// <Vec<T>>::AssociatedItem
1042 ///  ^~~~~    ^
1043 ///  ty       position = 0
1044 /// ```
1045 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1046 pub struct QSelf {
1047     pub ty: P<Ty>,
1048     pub position: usize
1049 }
1050
1051 /// A capture clause
1052 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1053 pub enum CaptureBy {
1054     Value,
1055     Ref,
1056 }
1057
1058 pub type Mac = Spanned<Mac_>;
1059
1060 /// Represents a macro invocation. The Path indicates which macro
1061 /// is being invoked, and the vector of token-trees contains the source
1062 /// of the macro invocation.
1063 ///
1064 /// NB: the additional ident for a macro_rules-style macro is actually
1065 /// stored in the enclosing item. Oog.
1066 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1067 pub struct Mac_ {
1068     pub path: Path,
1069     pub tts: ThinTokenStream,
1070 }
1071
1072 impl Mac_ {
1073     pub fn stream(&self) -> TokenStream {
1074         self.tts.clone().into()
1075     }
1076 }
1077
1078 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1079 pub struct MacroDef {
1080     pub tokens: ThinTokenStream,
1081     pub legacy: bool,
1082 }
1083
1084 impl MacroDef {
1085     pub fn stream(&self) -> TokenStream {
1086         self.tokens.clone().into()
1087     }
1088 }
1089
1090 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1091 pub enum StrStyle {
1092     /// A regular string, like `"foo"`
1093     Cooked,
1094     /// A raw string, like `r##"foo"##`
1095     ///
1096     /// The uint is the number of `#` symbols used
1097     Raw(usize)
1098 }
1099
1100 /// A literal
1101 pub type Lit = Spanned<LitKind>;
1102
1103 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1104 pub enum LitIntType {
1105     Signed(IntTy),
1106     Unsigned(UintTy),
1107     Unsuffixed,
1108 }
1109
1110 /// Literal kind.
1111 ///
1112 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1113 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1114 pub enum LitKind {
1115     /// A string literal (`"foo"`)
1116     Str(Symbol, StrStyle),
1117     /// A byte string (`b"foo"`)
1118     ByteStr(Rc<Vec<u8>>),
1119     /// A byte char (`b'f'`)
1120     Byte(u8),
1121     /// A character literal (`'a'`)
1122     Char(char),
1123     /// An integer literal (`1`)
1124     Int(u128, LitIntType),
1125     /// A float literal (`1f64` or `1E10f64`)
1126     Float(Symbol, FloatTy),
1127     /// A float literal without a suffix (`1.0 or 1.0E10`)
1128     FloatUnsuffixed(Symbol),
1129     /// A boolean literal
1130     Bool(bool),
1131 }
1132
1133 impl LitKind {
1134     /// Returns true if this literal is a string and false otherwise.
1135     pub fn is_str(&self) -> bool {
1136         match *self {
1137             LitKind::Str(..) => true,
1138             _ => false,
1139         }
1140     }
1141
1142     /// Returns true if this literal has no suffix. Note: this will return true
1143     /// for literals with prefixes such as raw strings and byte strings.
1144     pub fn is_unsuffixed(&self) -> bool {
1145         match *self {
1146             // unsuffixed variants
1147             LitKind::Str(..) |
1148             LitKind::ByteStr(..) |
1149             LitKind::Byte(..) |
1150             LitKind::Char(..) |
1151             LitKind::Int(_, LitIntType::Unsuffixed) |
1152             LitKind::FloatUnsuffixed(..) |
1153             LitKind::Bool(..) => true,
1154             // suffixed variants
1155             LitKind::Int(_, LitIntType::Signed(..)) |
1156             LitKind::Int(_, LitIntType::Unsigned(..)) |
1157             LitKind::Float(..) => false,
1158         }
1159     }
1160
1161     /// Returns true if this literal has a suffix.
1162     pub fn is_suffixed(&self) -> bool {
1163         !self.is_unsuffixed()
1164     }
1165 }
1166
1167 // NB: If you change this, you'll probably want to change the corresponding
1168 // type structure in middle/ty.rs as well.
1169 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1170 pub struct MutTy {
1171     pub ty: P<Ty>,
1172     pub mutbl: Mutability,
1173 }
1174
1175 /// Represents a method's signature in a trait declaration,
1176 /// or in an implementation.
1177 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1178 pub struct MethodSig {
1179     pub unsafety: Unsafety,
1180     pub constness: Spanned<Constness>,
1181     pub abi: Abi,
1182     pub decl: P<FnDecl>,
1183     pub generics: Generics,
1184 }
1185
1186 /// Represents an item declaration within a trait declaration,
1187 /// possibly including a default implementation. A trait item is
1188 /// either required (meaning it doesn't have an implementation, just a
1189 /// signature) or provided (meaning it has a default implementation).
1190 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1191 pub struct TraitItem {
1192     pub id: NodeId,
1193     pub ident: Ident,
1194     pub attrs: Vec<Attribute>,
1195     pub node: TraitItemKind,
1196     pub span: Span,
1197     /// See `Item::tokens` for what this is
1198     pub tokens: Option<TokenStream>,
1199 }
1200
1201 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1202 pub enum TraitItemKind {
1203     Const(P<Ty>, Option<P<Expr>>),
1204     Method(MethodSig, Option<P<Block>>),
1205     Type(TyParamBounds, Option<P<Ty>>),
1206     Macro(Mac),
1207 }
1208
1209 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1210 pub struct ImplItem {
1211     pub id: NodeId,
1212     pub ident: Ident,
1213     pub vis: Visibility,
1214     pub defaultness: Defaultness,
1215     pub attrs: Vec<Attribute>,
1216     pub node: ImplItemKind,
1217     pub span: Span,
1218     /// See `Item::tokens` for what this is
1219     pub tokens: Option<TokenStream>,
1220 }
1221
1222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1223 pub enum ImplItemKind {
1224     Const(P<Ty>, P<Expr>),
1225     Method(MethodSig, P<Block>),
1226     Type(P<Ty>),
1227     Macro(Mac),
1228 }
1229
1230 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1231          PartialOrd, Ord)]
1232 pub enum IntTy {
1233     Is,
1234     I8,
1235     I16,
1236     I32,
1237     I64,
1238     I128,
1239 }
1240
1241 impl fmt::Debug for IntTy {
1242     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1243         fmt::Display::fmt(self, f)
1244     }
1245 }
1246
1247 impl fmt::Display for IntTy {
1248     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1249         write!(f, "{}", self.ty_to_string())
1250     }
1251 }
1252
1253 impl IntTy {
1254     pub fn ty_to_string(&self) -> &'static str {
1255         match *self {
1256             IntTy::Is => "isize",
1257             IntTy::I8 => "i8",
1258             IntTy::I16 => "i16",
1259             IntTy::I32 => "i32",
1260             IntTy::I64 => "i64",
1261             IntTy::I128 => "i128",
1262         }
1263     }
1264
1265     pub fn val_to_string(&self, val: i128) -> String {
1266         // cast to a u128 so we can correctly print INT128_MIN. All integral types
1267         // are parsed as u128, so we wouldn't want to print an extra negative
1268         // sign.
1269         format!("{}{}", val as u128, self.ty_to_string())
1270     }
1271
1272     pub fn bit_width(&self) -> Option<usize> {
1273         Some(match *self {
1274             IntTy::Is => return None,
1275             IntTy::I8 => 8,
1276             IntTy::I16 => 16,
1277             IntTy::I32 => 32,
1278             IntTy::I64 => 64,
1279             IntTy::I128 => 128,
1280         })
1281     }
1282 }
1283
1284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1285          PartialOrd, Ord)]
1286 pub enum UintTy {
1287     Us,
1288     U8,
1289     U16,
1290     U32,
1291     U64,
1292     U128,
1293 }
1294
1295 impl UintTy {
1296     pub fn ty_to_string(&self) -> &'static str {
1297         match *self {
1298             UintTy::Us => "usize",
1299             UintTy::U8 => "u8",
1300             UintTy::U16 => "u16",
1301             UintTy::U32 => "u32",
1302             UintTy::U64 => "u64",
1303             UintTy::U128 => "u128",
1304         }
1305     }
1306
1307     pub fn val_to_string(&self, val: u128) -> String {
1308         format!("{}{}", val, self.ty_to_string())
1309     }
1310
1311     pub fn bit_width(&self) -> Option<usize> {
1312         Some(match *self {
1313             UintTy::Us => return None,
1314             UintTy::U8 => 8,
1315             UintTy::U16 => 16,
1316             UintTy::U32 => 32,
1317             UintTy::U64 => 64,
1318             UintTy::U128 => 128,
1319         })
1320     }
1321 }
1322
1323 impl fmt::Debug for UintTy {
1324     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1325         fmt::Display::fmt(self, f)
1326     }
1327 }
1328
1329 impl fmt::Display for UintTy {
1330     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1331         write!(f, "{}", self.ty_to_string())
1332     }
1333 }
1334
1335 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1336          PartialOrd, Ord)]
1337 pub enum FloatTy {
1338     F32,
1339     F64,
1340 }
1341
1342 impl fmt::Debug for FloatTy {
1343     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1344         fmt::Display::fmt(self, f)
1345     }
1346 }
1347
1348 impl fmt::Display for FloatTy {
1349     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1350         write!(f, "{}", self.ty_to_string())
1351     }
1352 }
1353
1354 impl FloatTy {
1355     pub fn ty_to_string(&self) -> &'static str {
1356         match *self {
1357             FloatTy::F32 => "f32",
1358             FloatTy::F64 => "f64",
1359         }
1360     }
1361
1362     pub fn bit_width(&self) -> usize {
1363         match *self {
1364             FloatTy::F32 => 32,
1365             FloatTy::F64 => 64,
1366         }
1367     }
1368 }
1369
1370 // Bind a type to an associated type: `A=Foo`.
1371 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1372 pub struct TypeBinding {
1373     pub id: NodeId,
1374     pub ident: Ident,
1375     pub ty: P<Ty>,
1376     pub span: Span,
1377 }
1378
1379 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1380 pub struct Ty {
1381     pub id: NodeId,
1382     pub node: TyKind,
1383     pub span: Span,
1384 }
1385
1386 impl fmt::Debug for Ty {
1387     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1388         write!(f, "type({})", pprust::ty_to_string(self))
1389     }
1390 }
1391
1392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1393 pub struct BareFnTy {
1394     pub unsafety: Unsafety,
1395     pub abi: Abi,
1396     pub lifetimes: Vec<LifetimeDef>,
1397     pub decl: P<FnDecl>
1398 }
1399
1400 /// The different kinds of types recognized by the compiler
1401 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1402 pub enum TyKind {
1403     /// A variable-length slice (`[T]`)
1404     Slice(P<Ty>),
1405     /// A fixed length array (`[T; n]`)
1406     Array(P<Ty>, P<Expr>),
1407     /// A raw pointer (`*const T` or `*mut T`)
1408     Ptr(MutTy),
1409     /// A reference (`&'a T` or `&'a mut T`)
1410     Rptr(Option<Lifetime>, MutTy),
1411     /// A bare function (e.g. `fn(usize) -> bool`)
1412     BareFn(P<BareFnTy>),
1413     /// The never type (`!`)
1414     Never,
1415     /// A tuple (`(A, B, C, D,...)`)
1416     Tup(Vec<P<Ty>> ),
1417     /// A path (`module::module::...::Type`), optionally
1418     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1419     ///
1420     /// Type parameters are stored in the Path itself
1421     Path(Option<QSelf>, Path),
1422     /// A trait object type `Bound1 + Bound2 + Bound3`
1423     /// where `Bound` is a trait or a lifetime.
1424     TraitObject(TyParamBounds),
1425     /// An `impl Bound1 + Bound2 + Bound3` type
1426     /// where `Bound` is a trait or a lifetime.
1427     ImplTrait(TyParamBounds),
1428     /// No-op; kept solely so that we can pretty-print faithfully
1429     Paren(P<Ty>),
1430     /// Unused for now
1431     Typeof(P<Expr>),
1432     /// TyKind::Infer means the type should be inferred instead of it having been
1433     /// specified. This can appear anywhere in a type.
1434     Infer,
1435     /// Inferred type of a `self` or `&self` argument in a method.
1436     ImplicitSelf,
1437     // A macro in the type position.
1438     Mac(Mac),
1439     /// Placeholder for a kind that has failed to be defined.
1440     Err,
1441 }
1442
1443 /// Inline assembly dialect.
1444 ///
1445 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1446 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1447 pub enum AsmDialect {
1448     Att,
1449     Intel,
1450 }
1451
1452 /// Inline assembly.
1453 ///
1454 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1455 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1456 pub struct InlineAsmOutput {
1457     pub constraint: Symbol,
1458     pub expr: P<Expr>,
1459     pub is_rw: bool,
1460     pub is_indirect: bool,
1461 }
1462
1463 /// Inline assembly.
1464 ///
1465 /// E.g. `asm!("NOP");`
1466 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1467 pub struct InlineAsm {
1468     pub asm: Symbol,
1469     pub asm_str_style: StrStyle,
1470     pub outputs: Vec<InlineAsmOutput>,
1471     pub inputs: Vec<(Symbol, P<Expr>)>,
1472     pub clobbers: Vec<Symbol>,
1473     pub volatile: bool,
1474     pub alignstack: bool,
1475     pub dialect: AsmDialect,
1476     pub ctxt: SyntaxContext,
1477 }
1478
1479 /// An argument in a function header.
1480 ///
1481 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1483 pub struct Arg {
1484     pub ty: P<Ty>,
1485     pub pat: P<Pat>,
1486     pub id: NodeId,
1487 }
1488
1489 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1490 ///
1491 /// E.g. `&mut self` as in `fn foo(&mut self)`
1492 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1493 pub enum SelfKind {
1494     /// `self`, `mut self`
1495     Value(Mutability),
1496     /// `&'lt self`, `&'lt mut self`
1497     Region(Option<Lifetime>, Mutability),
1498     /// `self: TYPE`, `mut self: TYPE`
1499     Explicit(P<Ty>, Mutability),
1500 }
1501
1502 pub type ExplicitSelf = Spanned<SelfKind>;
1503
1504 impl Arg {
1505     pub fn to_self(&self) -> Option<ExplicitSelf> {
1506         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1507             if ident.node.name == keywords::SelfValue.name() {
1508                 return match self.ty.node {
1509                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1510                     TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1511                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1512                     }
1513                     _ => Some(respan(self.pat.span.to(self.ty.span),
1514                                      SelfKind::Explicit(self.ty.clone(), mutbl))),
1515                 }
1516             }
1517         }
1518         None
1519     }
1520
1521     pub fn is_self(&self) -> bool {
1522         if let PatKind::Ident(_, ident, _) = self.pat.node {
1523             ident.node.name == keywords::SelfValue.name()
1524         } else {
1525             false
1526         }
1527     }
1528
1529     pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1530         let span = eself.span.to(eself_ident.span);
1531         let infer_ty = P(Ty {
1532             id: DUMMY_NODE_ID,
1533             node: TyKind::ImplicitSelf,
1534             span,
1535         });
1536         let arg = |mutbl, ty| Arg {
1537             pat: P(Pat {
1538                 id: DUMMY_NODE_ID,
1539                 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1540                 span,
1541             }),
1542             ty,
1543             id: DUMMY_NODE_ID,
1544         };
1545         match eself.node {
1546             SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1547             SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1548             SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1549                 id: DUMMY_NODE_ID,
1550                 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1551                 span,
1552             })),
1553         }
1554     }
1555 }
1556
1557 /// Header (not the body) of a function declaration.
1558 ///
1559 /// E.g. `fn foo(bar: baz)`
1560 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1561 pub struct FnDecl {
1562     pub inputs: Vec<Arg>,
1563     pub output: FunctionRetTy,
1564     pub variadic: bool
1565 }
1566
1567 impl FnDecl {
1568     pub fn get_self(&self) -> Option<ExplicitSelf> {
1569         self.inputs.get(0).and_then(Arg::to_self)
1570     }
1571     pub fn has_self(&self) -> bool {
1572         self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1573     }
1574 }
1575
1576 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1577 pub enum Unsafety {
1578     Unsafe,
1579     Normal,
1580 }
1581
1582 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1583 pub enum Constness {
1584     Const,
1585     NotConst,
1586 }
1587
1588 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1589 pub enum Defaultness {
1590     Default,
1591     Final,
1592 }
1593
1594 impl fmt::Display for Unsafety {
1595     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1596         fmt::Display::fmt(match *self {
1597             Unsafety::Normal => "normal",
1598             Unsafety::Unsafe => "unsafe",
1599         }, f)
1600     }
1601 }
1602
1603 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1604 pub enum ImplPolarity {
1605     /// `impl Trait for Type`
1606     Positive,
1607     /// `impl !Trait for Type`
1608     Negative,
1609 }
1610
1611 impl fmt::Debug for ImplPolarity {
1612     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1613         match *self {
1614             ImplPolarity::Positive => "positive".fmt(f),
1615             ImplPolarity::Negative => "negative".fmt(f),
1616         }
1617     }
1618 }
1619
1620
1621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1622 pub enum FunctionRetTy {
1623     /// Return type is not specified.
1624     ///
1625     /// Functions default to `()` and
1626     /// closures default to inference. Span points to where return
1627     /// type would be inserted.
1628     Default(Span),
1629     /// Everything else
1630     Ty(P<Ty>),
1631 }
1632
1633 impl FunctionRetTy {
1634     pub fn span(&self) -> Span {
1635         match *self {
1636             FunctionRetTy::Default(span) => span,
1637             FunctionRetTy::Ty(ref ty) => ty.span,
1638         }
1639     }
1640 }
1641
1642 /// Module declaration.
1643 ///
1644 /// E.g. `mod foo;` or `mod foo { .. }`
1645 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1646 pub struct Mod {
1647     /// A span from the first token past `{` to the last token until `}`.
1648     /// For `mod foo;`, the inner span ranges from the first token
1649     /// to the last token in the external file.
1650     pub inner: Span,
1651     pub items: Vec<P<Item>>,
1652 }
1653
1654 /// Foreign module declaration.
1655 ///
1656 /// E.g. `extern { .. }` or `extern C { .. }`
1657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1658 pub struct ForeignMod {
1659     pub abi: Abi,
1660     pub items: Vec<ForeignItem>,
1661 }
1662
1663 /// Global inline assembly
1664 ///
1665 /// aka module-level assembly or file-scoped assembly
1666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1667 pub struct GlobalAsm {
1668     pub asm: Symbol,
1669     pub ctxt: SyntaxContext,
1670 }
1671
1672 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1673 pub struct EnumDef {
1674     pub variants: Vec<Variant>,
1675 }
1676
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 pub struct Variant_ {
1679     pub name: Ident,
1680     pub attrs: Vec<Attribute>,
1681     pub data: VariantData,
1682     /// Explicit discriminant, e.g. `Foo = 1`
1683     pub disr_expr: Option<P<Expr>>,
1684 }
1685
1686 pub type Variant = Spanned<Variant_>;
1687
1688 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1689 pub struct PathListItem_ {
1690     pub name: Ident,
1691     /// renamed in list, e.g. `use foo::{bar as baz};`
1692     pub rename: Option<Ident>,
1693     pub id: NodeId,
1694 }
1695
1696 pub type PathListItem = Spanned<PathListItem_>;
1697
1698 pub type ViewPath = Spanned<ViewPath_>;
1699
1700 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1701 pub enum ViewPath_ {
1702
1703     /// `foo::bar::baz as quux`
1704     ///
1705     /// or just
1706     ///
1707     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1708     ViewPathSimple(Ident, Path),
1709
1710     /// `foo::bar::*`
1711     ViewPathGlob(Path),
1712
1713     /// `foo::bar::{a,b,c}`
1714     ViewPathList(Path, Vec<PathListItem>)
1715 }
1716
1717 impl ViewPath_ {
1718     pub fn path(&self) -> &Path {
1719         match *self {
1720             ViewPathSimple(_, ref path) |
1721             ViewPathGlob (ref path) |
1722             ViewPathList(ref path, _) => path
1723         }
1724     }
1725 }
1726
1727
1728 /// Distinguishes between Attributes that decorate items and Attributes that
1729 /// are contained as statements within items. These two cases need to be
1730 /// distinguished for pretty-printing.
1731 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1732 pub enum AttrStyle {
1733     Outer,
1734     Inner,
1735 }
1736
1737 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1738 pub struct AttrId(pub usize);
1739
1740 /// Meta-data associated with an item
1741 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1743 pub struct Attribute {
1744     pub id: AttrId,
1745     pub style: AttrStyle,
1746     pub path: Path,
1747     pub tokens: TokenStream,
1748     pub is_sugared_doc: bool,
1749     pub span: Span,
1750 }
1751
1752 /// TraitRef's appear in impls.
1753 ///
1754 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1755 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1756 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1757 /// same as the impl's node id).
1758 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1759 pub struct TraitRef {
1760     pub path: Path,
1761     pub ref_id: NodeId,
1762 }
1763
1764 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1765 pub struct PolyTraitRef {
1766     /// The `'a` in `<'a> Foo<&'a T>`
1767     pub bound_lifetimes: Vec<LifetimeDef>,
1768
1769     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1770     pub trait_ref: TraitRef,
1771
1772     pub span: Span,
1773 }
1774
1775 impl PolyTraitRef {
1776     pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1777         PolyTraitRef {
1778             bound_lifetimes: lifetimes,
1779             trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1780             span,
1781         }
1782     }
1783 }
1784
1785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1786 pub enum Visibility {
1787     Public,
1788     Crate(Span),
1789     Restricted { path: P<Path>, id: NodeId },
1790     Inherited,
1791 }
1792
1793 /// Field of a struct.
1794 ///
1795 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1796 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1797 pub struct StructField {
1798     pub span: Span,
1799     pub ident: Option<Ident>,
1800     pub vis: Visibility,
1801     pub id: NodeId,
1802     pub ty: P<Ty>,
1803     pub attrs: Vec<Attribute>,
1804 }
1805
1806 /// Fields and Ids of enum variants and structs
1807 ///
1808 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1809 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1810 /// One shared Id can be successfully used for these two purposes.
1811 /// Id of the whole enum lives in `Item`.
1812 ///
1813 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1814 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1815 /// the variant itself" from enum variants.
1816 /// Id of the whole struct lives in `Item`.
1817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1818 pub enum VariantData {
1819     /// Struct variant.
1820     ///
1821     /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1822     Struct(Vec<StructField>, NodeId),
1823     /// Tuple variant.
1824     ///
1825     /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1826     Tuple(Vec<StructField>, NodeId),
1827     /// Unit variant.
1828     ///
1829     /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1830     Unit(NodeId),
1831 }
1832
1833 impl VariantData {
1834     pub fn fields(&self) -> &[StructField] {
1835         match *self {
1836             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1837             _ => &[],
1838         }
1839     }
1840     pub fn id(&self) -> NodeId {
1841         match *self {
1842             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1843         }
1844     }
1845     pub fn is_struct(&self) -> bool {
1846         if let VariantData::Struct(..) = *self { true } else { false }
1847     }
1848     pub fn is_tuple(&self) -> bool {
1849         if let VariantData::Tuple(..) = *self { true } else { false }
1850     }
1851     pub fn is_unit(&self) -> bool {
1852         if let VariantData::Unit(..) = *self { true } else { false }
1853     }
1854 }
1855
1856 /// An item
1857 ///
1858 /// The name might be a dummy name in case of anonymous items
1859 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1860 pub struct Item {
1861     pub ident: Ident,
1862     pub attrs: Vec<Attribute>,
1863     pub id: NodeId,
1864     pub node: ItemKind,
1865     pub vis: Visibility,
1866     pub span: Span,
1867
1868     /// Original tokens this item was parsed from. This isn't necessarily
1869     /// available for all items, although over time more and more items should
1870     /// have this be `Some`. Right now this is primarily used for procedural
1871     /// macros, notably custom attributes.
1872     ///
1873     /// Note that the tokens here do not include the outer attributes, but will
1874     /// include inner attributes.
1875     pub tokens: Option<TokenStream>,
1876 }
1877
1878 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1879 pub enum ItemKind {
1880     /// An `extern crate` item, with optional original crate name.
1881     ///
1882     /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1883     ExternCrate(Option<Name>),
1884     /// A use declaration (`use` or `pub use`) item.
1885     ///
1886     /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1887     Use(P<ViewPath>),
1888     /// A static item (`static` or `pub static`).
1889     ///
1890     /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1891     Static(P<Ty>, Mutability, P<Expr>),
1892     /// A constant item (`const` or `pub const`).
1893     ///
1894     /// E.g. `const FOO: i32 = 42;`
1895     Const(P<Ty>, P<Expr>),
1896     /// A function declaration (`fn` or `pub fn`).
1897     ///
1898     /// E.g. `fn foo(bar: usize) -> usize { .. }`
1899     Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1900     /// A module declaration (`mod` or `pub mod`).
1901     ///
1902     /// E.g. `mod foo;` or `mod foo { .. }`
1903     Mod(Mod),
1904     /// An external module (`extern` or `pub extern`).
1905     ///
1906     /// E.g. `extern {}` or `extern "C" {}`
1907     ForeignMod(ForeignMod),
1908     /// Module-level inline assembly (from `global_asm!()`)
1909     GlobalAsm(P<GlobalAsm>),
1910     /// A type alias (`type` or `pub type`).
1911     ///
1912     /// E.g. `type Foo = Bar<u8>;`
1913     Ty(P<Ty>, Generics),
1914     /// An enum definition (`enum` or `pub enum`).
1915     ///
1916     /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1917     Enum(EnumDef, Generics),
1918     /// A struct definition (`struct` or `pub struct`).
1919     ///
1920     /// E.g. `struct Foo<A> { x: A }`
1921     Struct(VariantData, Generics),
1922     /// A union definition (`union` or `pub union`).
1923     ///
1924     /// E.g. `union Foo<A, B> { x: A, y: B }`
1925     Union(VariantData, Generics),
1926     /// A Trait declaration (`trait` or `pub trait`).
1927     ///
1928     /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1929     Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1930     // Default trait implementation.
1931     ///
1932     /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1933     DefaultImpl(Unsafety, TraitRef),
1934     /// An implementation.
1935     ///
1936     /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1937     Impl(Unsafety,
1938              ImplPolarity,
1939              Defaultness,
1940              Generics,
1941              Option<TraitRef>, // (optional) trait this impl implements
1942              P<Ty>, // self
1943              Vec<ImplItem>),
1944     /// A macro invocation.
1945     ///
1946     /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1947     Mac(Mac),
1948
1949     /// A macro definition.
1950     MacroDef(MacroDef),
1951 }
1952
1953 impl ItemKind {
1954     pub fn descriptive_variant(&self) -> &str {
1955         match *self {
1956             ItemKind::ExternCrate(..) => "extern crate",
1957             ItemKind::Use(..) => "use",
1958             ItemKind::Static(..) => "static item",
1959             ItemKind::Const(..) => "constant item",
1960             ItemKind::Fn(..) => "function",
1961             ItemKind::Mod(..) => "module",
1962             ItemKind::ForeignMod(..) => "foreign module",
1963             ItemKind::GlobalAsm(..) => "global asm",
1964             ItemKind::Ty(..) => "type alias",
1965             ItemKind::Enum(..) => "enum",
1966             ItemKind::Struct(..) => "struct",
1967             ItemKind::Union(..) => "union",
1968             ItemKind::Trait(..) => "trait",
1969             ItemKind::Mac(..) |
1970             ItemKind::MacroDef(..) |
1971             ItemKind::Impl(..) |
1972             ItemKind::DefaultImpl(..) => "item"
1973         }
1974     }
1975 }
1976
1977 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1978 pub struct ForeignItem {
1979     pub ident: Ident,
1980     pub attrs: Vec<Attribute>,
1981     pub node: ForeignItemKind,
1982     pub id: NodeId,
1983     pub span: Span,
1984     pub vis: Visibility,
1985 }
1986
1987 /// An item within an `extern` block
1988 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1989 pub enum ForeignItemKind {
1990     /// A foreign function
1991     Fn(P<FnDecl>, Generics),
1992     /// A foreign static item (`static ext: u8`), with optional mutability
1993     /// (the boolean is true when mutable)
1994     Static(P<Ty>, bool),
1995 }
1996
1997 impl ForeignItemKind {
1998     pub fn descriptive_variant(&self) -> &str {
1999         match *self {
2000             ForeignItemKind::Fn(..) => "foreign function",
2001             ForeignItemKind::Static(..) => "foreign static item"
2002         }
2003     }
2004 }
2005
2006 #[cfg(test)]
2007 mod tests {
2008     use serialize;
2009     use super::*;
2010
2011     // are ASTs encodable?
2012     #[test]
2013     fn check_asts_encodable() {
2014         fn assert_encodable<T: serialize::Encodable>() {}
2015         assert_encodable::<Crate>();
2016     }
2017 }