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