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