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