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