]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Auto merge of #43604 - abonander:proc_macro_span_api, r=jseyfried
[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),
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 /// Inline assembly dialect.
1442 ///
1443 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1445 pub enum AsmDialect {
1446     Att,
1447     Intel,
1448 }
1449
1450 /// Inline assembly.
1451 ///
1452 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1453 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1454 pub struct InlineAsmOutput {
1455     pub constraint: Symbol,
1456     pub expr: P<Expr>,
1457     pub is_rw: bool,
1458     pub is_indirect: bool,
1459 }
1460
1461 /// Inline assembly.
1462 ///
1463 /// E.g. `asm!("NOP");`
1464 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1465 pub struct InlineAsm {
1466     pub asm: Symbol,
1467     pub asm_str_style: StrStyle,
1468     pub outputs: Vec<InlineAsmOutput>,
1469     pub inputs: Vec<(Symbol, P<Expr>)>,
1470     pub clobbers: Vec<Symbol>,
1471     pub volatile: bool,
1472     pub alignstack: bool,
1473     pub dialect: AsmDialect,
1474     pub ctxt: SyntaxContext,
1475 }
1476
1477 /// An argument in a function header.
1478 ///
1479 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1480 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1481 pub struct Arg {
1482     pub ty: P<Ty>,
1483     pub pat: P<Pat>,
1484     pub id: NodeId,
1485 }
1486
1487 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1488 ///
1489 /// E.g. `&mut self` as in `fn foo(&mut self)`
1490 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1491 pub enum SelfKind {
1492     /// `self`, `mut self`
1493     Value(Mutability),
1494     /// `&'lt self`, `&'lt mut self`
1495     Region(Option<Lifetime>, Mutability),
1496     /// `self: TYPE`, `mut self: TYPE`
1497     Explicit(P<Ty>, Mutability),
1498 }
1499
1500 pub type ExplicitSelf = Spanned<SelfKind>;
1501
1502 impl Arg {
1503     pub fn to_self(&self) -> Option<ExplicitSelf> {
1504         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1505             if ident.node.name == keywords::SelfValue.name() {
1506                 return match self.ty.node {
1507                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1508                     TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1509                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1510                     }
1511                     _ => Some(respan(self.pat.span.to(self.ty.span),
1512                                      SelfKind::Explicit(self.ty.clone(), mutbl))),
1513                 }
1514             }
1515         }
1516         None
1517     }
1518
1519     pub fn is_self(&self) -> bool {
1520         if let PatKind::Ident(_, ident, _) = self.pat.node {
1521             ident.node.name == keywords::SelfValue.name()
1522         } else {
1523             false
1524         }
1525     }
1526
1527     pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1528         let span = eself.span.to(eself_ident.span);
1529         let infer_ty = P(Ty {
1530             id: DUMMY_NODE_ID,
1531             node: TyKind::ImplicitSelf,
1532             span,
1533         });
1534         let arg = |mutbl, ty| Arg {
1535             pat: P(Pat {
1536                 id: DUMMY_NODE_ID,
1537                 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1538                 span,
1539             }),
1540             ty,
1541             id: DUMMY_NODE_ID,
1542         };
1543         match eself.node {
1544             SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1545             SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1546             SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1547                 id: DUMMY_NODE_ID,
1548                 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1549                 span,
1550             })),
1551         }
1552     }
1553 }
1554
1555 /// Header (not the body) of a function declaration.
1556 ///
1557 /// E.g. `fn foo(bar: baz)`
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1559 pub struct FnDecl {
1560     pub inputs: Vec<Arg>,
1561     pub output: FunctionRetTy,
1562     pub variadic: bool
1563 }
1564
1565 impl FnDecl {
1566     pub fn get_self(&self) -> Option<ExplicitSelf> {
1567         self.inputs.get(0).and_then(Arg::to_self)
1568     }
1569     pub fn has_self(&self) -> bool {
1570         self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1571     }
1572 }
1573
1574 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1575 pub enum Unsafety {
1576     Unsafe,
1577     Normal,
1578 }
1579
1580 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1581 pub enum Constness {
1582     Const,
1583     NotConst,
1584 }
1585
1586 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1587 pub enum Defaultness {
1588     Default,
1589     Final,
1590 }
1591
1592 impl fmt::Display for Unsafety {
1593     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1594         fmt::Display::fmt(match *self {
1595             Unsafety::Normal => "normal",
1596             Unsafety::Unsafe => "unsafe",
1597         }, f)
1598     }
1599 }
1600
1601 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1602 pub enum ImplPolarity {
1603     /// `impl Trait for Type`
1604     Positive,
1605     /// `impl !Trait for Type`
1606     Negative,
1607 }
1608
1609 impl fmt::Debug for ImplPolarity {
1610     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1611         match *self {
1612             ImplPolarity::Positive => "positive".fmt(f),
1613             ImplPolarity::Negative => "negative".fmt(f),
1614         }
1615     }
1616 }
1617
1618
1619 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1620 pub enum FunctionRetTy {
1621     /// Return type is not specified.
1622     ///
1623     /// Functions default to `()` and
1624     /// closures default to inference. Span points to where return
1625     /// type would be inserted.
1626     Default(Span),
1627     /// Everything else
1628     Ty(P<Ty>),
1629 }
1630
1631 impl FunctionRetTy {
1632     pub fn span(&self) -> Span {
1633         match *self {
1634             FunctionRetTy::Default(span) => span,
1635             FunctionRetTy::Ty(ref ty) => ty.span,
1636         }
1637     }
1638 }
1639
1640 /// Module declaration.
1641 ///
1642 /// E.g. `mod foo;` or `mod foo { .. }`
1643 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1644 pub struct Mod {
1645     /// A span from the first token past `{` to the last token until `}`.
1646     /// For `mod foo;`, the inner span ranges from the first token
1647     /// to the last token in the external file.
1648     pub inner: Span,
1649     pub items: Vec<P<Item>>,
1650 }
1651
1652 /// Foreign module declaration.
1653 ///
1654 /// E.g. `extern { .. }` or `extern C { .. }`
1655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1656 pub struct ForeignMod {
1657     pub abi: Abi,
1658     pub items: Vec<ForeignItem>,
1659 }
1660
1661 /// Global inline assembly
1662 ///
1663 /// aka module-level assembly or file-scoped assembly
1664 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1665 pub struct GlobalAsm {
1666     pub asm: Symbol,
1667     pub ctxt: SyntaxContext,
1668 }
1669
1670 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1671 pub struct EnumDef {
1672     pub variants: Vec<Variant>,
1673 }
1674
1675 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1676 pub struct Variant_ {
1677     pub name: Ident,
1678     pub attrs: Vec<Attribute>,
1679     pub data: VariantData,
1680     /// Explicit discriminant, e.g. `Foo = 1`
1681     pub disr_expr: Option<P<Expr>>,
1682 }
1683
1684 pub type Variant = Spanned<Variant_>;
1685
1686 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1687 pub struct PathListItem_ {
1688     pub name: Ident,
1689     /// renamed in list, e.g. `use foo::{bar as baz};`
1690     pub rename: Option<Ident>,
1691     pub id: NodeId,
1692 }
1693
1694 pub type PathListItem = Spanned<PathListItem_>;
1695
1696 pub type ViewPath = Spanned<ViewPath_>;
1697
1698 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1699 pub enum ViewPath_ {
1700
1701     /// `foo::bar::baz as quux`
1702     ///
1703     /// or just
1704     ///
1705     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1706     ViewPathSimple(Ident, Path),
1707
1708     /// `foo::bar::*`
1709     ViewPathGlob(Path),
1710
1711     /// `foo::bar::{a,b,c}`
1712     ViewPathList(Path, Vec<PathListItem>)
1713 }
1714
1715 impl ViewPath_ {
1716     pub fn path(&self) -> &Path {
1717         match *self {
1718             ViewPathSimple(_, ref path) |
1719             ViewPathGlob (ref path) |
1720             ViewPathList(ref path, _) => path
1721         }
1722     }
1723 }
1724
1725
1726 /// Distinguishes between Attributes that decorate items and Attributes that
1727 /// are contained as statements within items. These two cases need to be
1728 /// distinguished for pretty-printing.
1729 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1730 pub enum AttrStyle {
1731     Outer,
1732     Inner,
1733 }
1734
1735 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1736 pub struct AttrId(pub usize);
1737
1738 /// Meta-data associated with an item
1739 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1740 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1741 pub struct Attribute {
1742     pub id: AttrId,
1743     pub style: AttrStyle,
1744     pub path: Path,
1745     pub tokens: TokenStream,
1746     pub is_sugared_doc: bool,
1747     pub span: Span,
1748 }
1749
1750 /// TraitRef's appear in impls.
1751 ///
1752 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1753 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1754 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1755 /// same as the impl's node id).
1756 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1757 pub struct TraitRef {
1758     pub path: Path,
1759     pub ref_id: NodeId,
1760 }
1761
1762 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1763 pub struct PolyTraitRef {
1764     /// The `'a` in `<'a> Foo<&'a T>`
1765     pub bound_lifetimes: Vec<LifetimeDef>,
1766
1767     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1768     pub trait_ref: TraitRef,
1769
1770     pub span: Span,
1771 }
1772
1773 impl PolyTraitRef {
1774     pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1775         PolyTraitRef {
1776             bound_lifetimes: lifetimes,
1777             trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1778             span,
1779         }
1780     }
1781 }
1782
1783 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1784 pub enum Visibility {
1785     Public,
1786     Crate(Span),
1787     Restricted { path: P<Path>, id: NodeId },
1788     Inherited,
1789 }
1790
1791 /// Field of a struct.
1792 ///
1793 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1794 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1795 pub struct StructField {
1796     pub span: Span,
1797     pub ident: Option<Ident>,
1798     pub vis: Visibility,
1799     pub id: NodeId,
1800     pub ty: P<Ty>,
1801     pub attrs: Vec<Attribute>,
1802 }
1803
1804 /// Fields and Ids of enum variants and structs
1805 ///
1806 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1807 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1808 /// One shared Id can be successfully used for these two purposes.
1809 /// Id of the whole enum lives in `Item`.
1810 ///
1811 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1812 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1813 /// the variant itself" from enum variants.
1814 /// Id of the whole struct lives in `Item`.
1815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1816 pub enum VariantData {
1817     /// Struct variant.
1818     ///
1819     /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1820     Struct(Vec<StructField>, NodeId),
1821     /// Tuple variant.
1822     ///
1823     /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1824     Tuple(Vec<StructField>, NodeId),
1825     /// Unit variant.
1826     ///
1827     /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1828     Unit(NodeId),
1829 }
1830
1831 impl VariantData {
1832     pub fn fields(&self) -> &[StructField] {
1833         match *self {
1834             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1835             _ => &[],
1836         }
1837     }
1838     pub fn id(&self) -> NodeId {
1839         match *self {
1840             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1841         }
1842     }
1843     pub fn is_struct(&self) -> bool {
1844         if let VariantData::Struct(..) = *self { true } else { false }
1845     }
1846     pub fn is_tuple(&self) -> bool {
1847         if let VariantData::Tuple(..) = *self { true } else { false }
1848     }
1849     pub fn is_unit(&self) -> bool {
1850         if let VariantData::Unit(..) = *self { true } else { false }
1851     }
1852 }
1853
1854 /// An item
1855 ///
1856 /// The name might be a dummy name in case of anonymous items
1857 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1858 pub struct Item {
1859     pub ident: Ident,
1860     pub attrs: Vec<Attribute>,
1861     pub id: NodeId,
1862     pub node: ItemKind,
1863     pub vis: Visibility,
1864     pub span: Span,
1865
1866     /// Original tokens this item was parsed from. This isn't necessarily
1867     /// available for all items, although over time more and more items should
1868     /// have this be `Some`. Right now this is primarily used for procedural
1869     /// macros, notably custom attributes.
1870     ///
1871     /// Note that the tokens here do not include the outer attributes, but will
1872     /// include inner attributes.
1873     pub tokens: Option<TokenStream>,
1874 }
1875
1876 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1877 pub enum ItemKind {
1878     /// An `extern crate` item, with optional original crate name.
1879     ///
1880     /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1881     ExternCrate(Option<Name>),
1882     /// A use declaration (`use` or `pub use`) item.
1883     ///
1884     /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1885     Use(P<ViewPath>),
1886     /// A static item (`static` or `pub static`).
1887     ///
1888     /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1889     Static(P<Ty>, Mutability, P<Expr>),
1890     /// A constant item (`const` or `pub const`).
1891     ///
1892     /// E.g. `const FOO: i32 = 42;`
1893     Const(P<Ty>, P<Expr>),
1894     /// A function declaration (`fn` or `pub fn`).
1895     ///
1896     /// E.g. `fn foo(bar: usize) -> usize { .. }`
1897     Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1898     /// A module declaration (`mod` or `pub mod`).
1899     ///
1900     /// E.g. `mod foo;` or `mod foo { .. }`
1901     Mod(Mod),
1902     /// An external module (`extern` or `pub extern`).
1903     ///
1904     /// E.g. `extern {}` or `extern "C" {}`
1905     ForeignMod(ForeignMod),
1906     /// Module-level inline assembly (from `global_asm!()`)
1907     GlobalAsm(P<GlobalAsm>),
1908     /// A type alias (`type` or `pub type`).
1909     ///
1910     /// E.g. `type Foo = Bar<u8>;`
1911     Ty(P<Ty>, Generics),
1912     /// An enum definition (`enum` or `pub enum`).
1913     ///
1914     /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1915     Enum(EnumDef, Generics),
1916     /// A struct definition (`struct` or `pub struct`).
1917     ///
1918     /// E.g. `struct Foo<A> { x: A }`
1919     Struct(VariantData, Generics),
1920     /// A union definition (`union` or `pub union`).
1921     ///
1922     /// E.g. `union Foo<A, B> { x: A, y: B }`
1923     Union(VariantData, Generics),
1924     /// A Trait declaration (`trait` or `pub trait`).
1925     ///
1926     /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1927     Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1928     /// Auto trait implementation.
1929     ///
1930     /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1931     DefaultImpl(Unsafety, TraitRef),
1932     /// An implementation.
1933     ///
1934     /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1935     Impl(Unsafety,
1936              ImplPolarity,
1937              Defaultness,
1938              Generics,
1939              Option<TraitRef>, // (optional) trait this impl implements
1940              P<Ty>, // self
1941              Vec<ImplItem>),
1942     /// A macro invocation.
1943     ///
1944     /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1945     Mac(Mac),
1946
1947     /// A macro definition.
1948     MacroDef(MacroDef),
1949 }
1950
1951 impl ItemKind {
1952     pub fn descriptive_variant(&self) -> &str {
1953         match *self {
1954             ItemKind::ExternCrate(..) => "extern crate",
1955             ItemKind::Use(..) => "use",
1956             ItemKind::Static(..) => "static item",
1957             ItemKind::Const(..) => "constant item",
1958             ItemKind::Fn(..) => "function",
1959             ItemKind::Mod(..) => "module",
1960             ItemKind::ForeignMod(..) => "foreign module",
1961             ItemKind::GlobalAsm(..) => "global asm",
1962             ItemKind::Ty(..) => "type alias",
1963             ItemKind::Enum(..) => "enum",
1964             ItemKind::Struct(..) => "struct",
1965             ItemKind::Union(..) => "union",
1966             ItemKind::Trait(..) => "trait",
1967             ItemKind::Mac(..) |
1968             ItemKind::MacroDef(..) |
1969             ItemKind::Impl(..) |
1970             ItemKind::DefaultImpl(..) => "item"
1971         }
1972     }
1973 }
1974
1975 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1976 pub struct ForeignItem {
1977     pub ident: Ident,
1978     pub attrs: Vec<Attribute>,
1979     pub node: ForeignItemKind,
1980     pub id: NodeId,
1981     pub span: Span,
1982     pub vis: Visibility,
1983 }
1984
1985 /// An item within an `extern` block
1986 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1987 pub enum ForeignItemKind {
1988     /// A foreign function
1989     Fn(P<FnDecl>, Generics),
1990     /// A foreign static item (`static ext: u8`), with optional mutability
1991     /// (the boolean is true when mutable)
1992     Static(P<Ty>, bool),
1993 }
1994
1995 impl ForeignItemKind {
1996     pub fn descriptive_variant(&self) -> &str {
1997         match *self {
1998             ForeignItemKind::Fn(..) => "foreign function",
1999             ForeignItemKind::Static(..) => "foreign static item"
2000         }
2001     }
2002 }
2003
2004 #[cfg(test)]
2005 mod tests {
2006     use serialize;
2007     use super::*;
2008
2009     // are ASTs encodable?
2010     #[test]
2011     fn check_asts_encodable() {
2012         fn assert_encodable<T: serialize::Encodable>() {}
2013         assert_encodable::<Crate>();
2014     }
2015 }