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