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