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