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