]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Rollup merge of #27934 - MatejLach:spacing_fix, r=steveklabnik
[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::AsmDialect::*;
14 pub use self::AttrStyle::*;
15 pub use self::BindingMode::*;
16 pub use self::BinOp_::*;
17 pub use self::BlockCheckMode::*;
18 pub use self::CaptureClause::*;
19 pub use self::Decl_::*;
20 pub use self::ExplicitSelf_::*;
21 pub use self::Expr_::*;
22 pub use self::FloatTy::*;
23 pub use self::FunctionRetTy::*;
24 pub use self::ForeignItem_::*;
25 pub use self::ImplItem_::*;
26 pub use self::IntTy::*;
27 pub use self::Item_::*;
28 pub use self::KleeneOp::*;
29 pub use self::Lit_::*;
30 pub use self::LitIntType::*;
31 pub use self::Mac_::*;
32 pub use self::MacStmtStyle::*;
33 pub use self::MetaItem_::*;
34 pub use self::Mutability::*;
35 pub use self::Pat_::*;
36 pub use self::PathListItem_::*;
37 pub use self::PatWildKind::*;
38 pub use self::PrimTy::*;
39 pub use self::Sign::*;
40 pub use self::Stmt_::*;
41 pub use self::StrStyle::*;
42 pub use self::StructFieldKind::*;
43 pub use self::TokenTree::*;
44 pub use self::TraitItem_::*;
45 pub use self::Ty_::*;
46 pub use self::TyParamBound::*;
47 pub use self::UintTy::*;
48 pub use self::UnOp::*;
49 pub use self::UnsafeSource::*;
50 pub use self::VariantKind::*;
51 pub use self::ViewPath_::*;
52 pub use self::Visibility::*;
53 pub use self::PathParameters::*;
54
55 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
56 use abi::Abi;
57 use ast_util;
58 use ext::base;
59 use ext::tt::macro_parser;
60 use owned_slice::OwnedSlice;
61 use parse::token::{InternedString, str_to_ident};
62 use parse::token;
63 use parse::lexer;
64 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
65 use print::pprust;
66 use ptr::P;
67
68 use std::cell::Cell;
69 use std::fmt;
70 use std::rc::Rc;
71 use serialize::{Encodable, Decodable, Encoder, Decoder};
72
73 // FIXME #6993: in librustc, uses of "ident" should be replaced
74 // by just "Name".
75
76 /// An identifier contains a Name (index into the interner
77 /// table) and a SyntaxContext to track renaming and
78 /// macro expansion per Flatt et al., "Macros
79 /// That Work Together"
80 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
81 pub struct Ident {
82     pub name: Name,
83     pub ctxt: SyntaxContext
84 }
85
86 impl Ident {
87     /// Construct an identifier with the given name and an empty context:
88     pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
89 }
90
91 impl fmt::Debug for Ident {
92     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93         write!(f, "{}#{}", self.name, self.ctxt)
94     }
95 }
96
97 impl fmt::Display for Ident {
98     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99         fmt::Display::fmt(&self.name, f)
100     }
101 }
102
103 impl fmt::Debug for Name {
104     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105         let Name(nm) = *self;
106         write!(f, "{}({})", self, nm)
107     }
108 }
109
110 impl fmt::Display for Name {
111     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
112         fmt::Display::fmt(&self.as_str(), f)
113     }
114 }
115
116 impl PartialEq for Ident {
117     fn eq(&self, other: &Ident) -> bool {
118         if self.ctxt == other.ctxt {
119             self.name == other.name
120         } else {
121             // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
122             // idents that have different contexts. You can't fix this without
123             // knowing whether the comparison should be hygienic or non-hygienic.
124             // if it should be non-hygienic (most things are), just compare the
125             // 'name' fields of the idents. Or, even better, replace the idents
126             // with Name's.
127             //
128             // On the other hand, if the comparison does need to be hygienic,
129             // one example and its non-hygienic counterpart would be:
130             //      syntax::parse::token::Token::mtwt_eq
131             //      syntax::ext::tt::macro_parser::token_name_eq
132             panic!("not allowed to compare these idents: {:?}, {:?}. \
133                    Probably related to issue \\#6993", self, other);
134         }
135     }
136 }
137
138 /// A SyntaxContext represents a chain of macro-expandings
139 /// and renamings. Each macro expansion corresponds to
140 /// a fresh u32
141
142 // I'm representing this syntax context as an index into
143 // a table, in order to work around a compiler bug
144 // that's causing unreleased memory to cause core dumps
145 // and also perhaps to save some work in destructor checks.
146 // the special uint '0' will be used to indicate an empty
147 // syntax context.
148
149 // this uint is a reference to a table stored in thread-local
150 // storage.
151 pub type SyntaxContext = u32;
152 pub const EMPTY_CTXT : SyntaxContext = 0;
153 pub const ILLEGAL_CTXT : SyntaxContext = 1;
154
155 /// A name is a part of an identifier, representing a string or gensym. It's
156 /// the result of interning.
157 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
158            RustcEncodable, RustcDecodable, Clone, Copy)]
159 pub struct Name(pub u32);
160
161 impl<T: AsRef<str>> PartialEq<T> for Name {
162     fn eq(&self, other: &T) -> bool {
163         self.as_str() == other.as_ref()
164     }
165 }
166
167 impl Name {
168     pub fn as_str(&self) -> token::InternedString {
169         token::InternedString::new_from_name(*self)
170     }
171
172     pub fn usize(&self) -> usize {
173         let Name(nm) = *self;
174         nm as usize
175     }
176
177     pub fn ident(&self) -> Ident {
178         Ident { name: *self, ctxt: 0 }
179     }
180 }
181
182 /// A mark represents a unique id associated with a macro expansion
183 pub type Mrk = u32;
184
185 impl Encodable for Ident {
186     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
187         s.emit_str(&self.name.as_str())
188     }
189 }
190
191 impl Decodable for Ident {
192     fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
193         Ok(str_to_ident(&try!(d.read_str())[..]))
194     }
195 }
196
197 /// Function name (not all functions have names)
198 pub type FnIdent = Option<Ident>;
199
200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
201 pub struct Lifetime {
202     pub id: NodeId,
203     pub span: Span,
204     pub name: Name
205 }
206
207 impl fmt::Debug for Lifetime {
208     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
209         write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
210     }
211 }
212
213 /// A lifetime definition, eg `'a: 'b+'c+'d`
214 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
215 pub struct LifetimeDef {
216     pub lifetime: Lifetime,
217     pub bounds: Vec<Lifetime>
218 }
219
220 /// A "Path" is essentially Rust's notion of a name; for instance:
221 /// std::cmp::PartialEq  .  It's represented as a sequence of identifiers,
222 /// along with a bunch of supporting information.
223 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
224 pub struct Path {
225     pub span: Span,
226     /// A `::foo` path, is relative to the crate root rather than current
227     /// module (like paths in an import).
228     pub global: bool,
229     /// The segments in the path: the things separated by `::`.
230     pub segments: Vec<PathSegment>,
231 }
232
233 impl fmt::Debug for Path {
234     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
235         write!(f, "path({})", pprust::path_to_string(self))
236     }
237 }
238
239 impl fmt::Display for Path {
240     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
241         write!(f, "{}", pprust::path_to_string(self))
242     }
243 }
244
245 /// A segment of a path: an identifier, an optional lifetime, and a set of
246 /// types.
247 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
248 pub struct PathSegment {
249     /// The identifier portion of this path segment.
250     pub identifier: Ident,
251
252     /// Type/lifetime parameters attached to this path. They come in
253     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
254     /// this is more than just simple syntactic sugar; the use of
255     /// parens affects the region binding rules, so we preserve the
256     /// distinction.
257     pub parameters: PathParameters,
258 }
259
260 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
261 pub enum PathParameters {
262     /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
263     AngleBracketedParameters(AngleBracketedParameterData),
264     /// The `(A,B)` and `C` in `Foo(A,B) -> C`
265     ParenthesizedParameters(ParenthesizedParameterData),
266 }
267
268 impl PathParameters {
269     pub fn none() -> PathParameters {
270         AngleBracketedParameters(AngleBracketedParameterData {
271             lifetimes: Vec::new(),
272             types: OwnedSlice::empty(),
273             bindings: OwnedSlice::empty(),
274         })
275     }
276
277     pub fn is_empty(&self) -> bool {
278         match *self {
279             AngleBracketedParameters(ref data) => data.is_empty(),
280
281             // Even if the user supplied no types, something like
282             // `X()` is equivalent to `X<(),()>`.
283             ParenthesizedParameters(..) => false,
284         }
285     }
286
287     pub fn has_lifetimes(&self) -> bool {
288         match *self {
289             AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
290             ParenthesizedParameters(_) => false,
291         }
292     }
293
294     pub fn has_types(&self) -> bool {
295         match *self {
296             AngleBracketedParameters(ref data) => !data.types.is_empty(),
297             ParenthesizedParameters(..) => true,
298         }
299     }
300
301     /// Returns the types that the user wrote. Note that these do not necessarily map to the type
302     /// parameters in the parenthesized case.
303     pub fn types(&self) -> Vec<&P<Ty>> {
304         match *self {
305             AngleBracketedParameters(ref data) => {
306                 data.types.iter().collect()
307             }
308             ParenthesizedParameters(ref data) => {
309                 data.inputs.iter()
310                     .chain(data.output.iter())
311                     .collect()
312             }
313         }
314     }
315
316     pub fn lifetimes(&self) -> Vec<&Lifetime> {
317         match *self {
318             AngleBracketedParameters(ref data) => {
319                 data.lifetimes.iter().collect()
320             }
321             ParenthesizedParameters(_) => {
322                 Vec::new()
323             }
324         }
325     }
326
327     pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
328         match *self {
329             AngleBracketedParameters(ref data) => {
330                 data.bindings.iter().collect()
331             }
332             ParenthesizedParameters(_) => {
333                 Vec::new()
334             }
335         }
336     }
337 }
338
339 /// A path like `Foo<'a, T>`
340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
341 pub struct AngleBracketedParameterData {
342     /// The lifetime parameters for this path segment.
343     pub lifetimes: Vec<Lifetime>,
344     /// The type parameters for this path segment, if present.
345     pub types: OwnedSlice<P<Ty>>,
346     /// Bindings (equality constraints) on associated types, if present.
347     /// E.g., `Foo<A=Bar>`.
348     pub bindings: OwnedSlice<P<TypeBinding>>,
349 }
350
351 impl AngleBracketedParameterData {
352     fn is_empty(&self) -> bool {
353         self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
354     }
355 }
356
357 /// A path like `Foo(A,B) -> C`
358 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
359 pub struct ParenthesizedParameterData {
360     /// Overall span
361     pub span: Span,
362
363     /// `(A,B)`
364     pub inputs: Vec<P<Ty>>,
365
366     /// `C`
367     pub output: Option<P<Ty>>,
368 }
369
370 pub type CrateNum = u32;
371
372 pub type NodeId = u32;
373
374 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
375            RustcDecodable, Hash, Copy)]
376 pub struct DefId {
377     pub krate: CrateNum,
378     pub node: NodeId,
379 }
380
381 fn default_def_id_debug(_: DefId, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
382
383 thread_local!(pub static DEF_ID_DEBUG: Cell<fn(DefId, &mut fmt::Formatter) -> fmt::Result> =
384                 Cell::new(default_def_id_debug));
385
386 impl fmt::Debug for DefId {
387     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
388         try!(write!(f, "DefId {{ krate: {}, node: {} }}",
389                     self.krate, self.node));
390         DEF_ID_DEBUG.with(|def_id_debug| def_id_debug.get()(*self, f))
391     }
392 }
393
394 impl DefId {
395     /// Read the node id, asserting that this def-id is krate-local.
396     pub fn local_id(&self) -> NodeId {
397         assert_eq!(self.krate, LOCAL_CRATE);
398         self.node
399     }
400 }
401
402 /// Item definitions in the currently-compiled crate would have the CrateNum
403 /// LOCAL_CRATE in their DefId.
404 pub const LOCAL_CRATE: CrateNum = 0;
405 pub const CRATE_NODE_ID: NodeId = 0;
406
407 /// When parsing and doing expansions, we initially give all AST nodes this AST
408 /// node value. Then later, in the renumber pass, we renumber them to have
409 /// small, positive ids.
410 pub const DUMMY_NODE_ID: NodeId = !0;
411
412 /// The AST represents all type param bounds as types.
413 /// typeck::collect::compute_bounds matches these against
414 /// the "special" built-in traits (see middle::lang_items) and
415 /// detects Copy, Send and Sync.
416 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
417 pub enum TyParamBound {
418     TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
419     RegionTyParamBound(Lifetime)
420 }
421
422 /// A modifier on a bound, currently this is only used for `?Sized`, where the
423 /// modifier is `Maybe`. Negative bounds should also be handled here.
424 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
425 pub enum TraitBoundModifier {
426     None,
427     Maybe,
428 }
429
430 pub type TyParamBounds = OwnedSlice<TyParamBound>;
431
432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
433 pub struct TyParam {
434     pub ident: Ident,
435     pub id: NodeId,
436     pub bounds: TyParamBounds,
437     pub default: Option<P<Ty>>,
438     pub span: Span
439 }
440
441 /// Represents lifetimes and type parameters attached to a declaration
442 /// of a function, enum, trait, etc.
443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
444 pub struct Generics {
445     pub lifetimes: Vec<LifetimeDef>,
446     pub ty_params: OwnedSlice<TyParam>,
447     pub where_clause: WhereClause,
448 }
449
450 impl Generics {
451     pub fn is_lt_parameterized(&self) -> bool {
452         !self.lifetimes.is_empty()
453     }
454     pub fn is_type_parameterized(&self) -> bool {
455         !self.ty_params.is_empty()
456     }
457     pub fn is_parameterized(&self) -> bool {
458         self.is_lt_parameterized() || self.is_type_parameterized()
459     }
460 }
461
462 /// A `where` clause in a definition
463 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
464 pub struct WhereClause {
465     pub id: NodeId,
466     pub predicates: Vec<WherePredicate>,
467 }
468
469 /// A single predicate in a `where` clause
470 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
471 pub enum WherePredicate {
472     /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
473     BoundPredicate(WhereBoundPredicate),
474     /// A lifetime predicate, e.g. `'a: 'b+'c`
475     RegionPredicate(WhereRegionPredicate),
476     /// An equality predicate (unsupported)
477     EqPredicate(WhereEqPredicate),
478 }
479
480 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
481 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
482 pub struct WhereBoundPredicate {
483     pub span: Span,
484     /// Any lifetimes from a `for` binding
485     pub bound_lifetimes: Vec<LifetimeDef>,
486     /// The type being bounded
487     pub bounded_ty: P<Ty>,
488     /// Trait and lifetime bounds (`Clone+Send+'static`)
489     pub bounds: OwnedSlice<TyParamBound>,
490 }
491
492 /// A lifetime predicate, e.g. `'a: 'b+'c`
493 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
494 pub struct WhereRegionPredicate {
495     pub span: Span,
496     pub lifetime: Lifetime,
497     pub bounds: Vec<Lifetime>,
498 }
499
500 /// An equality predicate (unsupported), e.g. `T=int`
501 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
502 pub struct WhereEqPredicate {
503     pub id: NodeId,
504     pub span: Span,
505     pub path: Path,
506     pub ty: P<Ty>,
507 }
508
509 /// The set of MetaItems that define the compilation environment of the crate,
510 /// used to drive conditional compilation
511 pub type CrateConfig = Vec<P<MetaItem>> ;
512
513 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
514 pub struct Crate {
515     pub module: Mod,
516     pub attrs: Vec<Attribute>,
517     pub config: CrateConfig,
518     pub span: Span,
519     pub exported_macros: Vec<MacroDef>,
520 }
521
522 pub type MetaItem = Spanned<MetaItem_>;
523
524 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
525 pub enum MetaItem_ {
526     MetaWord(InternedString),
527     MetaList(InternedString, Vec<P<MetaItem>>),
528     MetaNameValue(InternedString, Lit),
529 }
530
531 // can't be derived because the MetaList requires an unordered comparison
532 impl PartialEq for MetaItem_ {
533     fn eq(&self, other: &MetaItem_) -> bool {
534         match *self {
535             MetaWord(ref ns) => match *other {
536                 MetaWord(ref no) => (*ns) == (*no),
537                 _ => false
538             },
539             MetaNameValue(ref ns, ref vs) => match *other {
540                 MetaNameValue(ref no, ref vo) => {
541                     (*ns) == (*no) && vs.node == vo.node
542                 }
543                 _ => false
544             },
545             MetaList(ref ns, ref miss) => match *other {
546                 MetaList(ref no, ref miso) => {
547                     ns == no &&
548                         miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
549                 }
550                 _ => false
551             }
552         }
553     }
554 }
555
556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
557 pub struct Block {
558     /// Statements in a block
559     pub stmts: Vec<P<Stmt>>,
560     /// An expression at the end of the block
561     /// without a semicolon, if any
562     pub expr: Option<P<Expr>>,
563     pub id: NodeId,
564     /// Distinguishes between `unsafe { ... }` and `{ ... }`
565     pub rules: BlockCheckMode,
566     pub span: Span,
567 }
568
569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
570 pub struct Pat {
571     pub id: NodeId,
572     pub node: Pat_,
573     pub span: Span,
574 }
575
576 impl fmt::Debug for Pat {
577     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
578         write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
579     }
580 }
581
582 /// A single field in a struct pattern
583 ///
584 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
585 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
586 /// except is_shorthand is true
587 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
588 pub struct FieldPat {
589     /// The identifier for the field
590     pub ident: Ident,
591     /// The pattern the field is destructured to
592     pub pat: P<Pat>,
593     pub is_shorthand: bool,
594 }
595
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
597 pub enum BindingMode {
598     BindByRef(Mutability),
599     BindByValue(Mutability),
600 }
601
602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
603 pub enum PatWildKind {
604     /// Represents the wildcard pattern `_`
605     PatWildSingle,
606
607     /// Represents the wildcard pattern `..`
608     PatWildMulti,
609 }
610
611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
612 pub enum Pat_ {
613     /// Represents a wildcard pattern (either `_` or `..`)
614     PatWild(PatWildKind),
615
616     /// A PatIdent may either be a new bound variable,
617     /// or a nullary enum (in which case the third field
618     /// is None).
619     ///
620     /// In the nullary enum case, the parser can't determine
621     /// which it is. The resolver determines this, and
622     /// records this pattern's NodeId in an auxiliary
623     /// set (of "PatIdents that refer to nullary enums")
624     PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
625
626     /// "None" means a * pattern where we don't bind the fields to names.
627     PatEnum(Path, Option<Vec<P<Pat>>>),
628
629     /// An associated const named using the qualified path `<T>::CONST` or
630     /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
631     /// referred to as simply `T::CONST`, in which case they will end up as
632     /// PatEnum, and the resolver will have to sort that out.
633     PatQPath(QSelf, Path),
634
635     /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
636     /// The `bool` is `true` in the presence of a `..`
637     PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
638     /// A tuple pattern `(a, b)`
639     PatTup(Vec<P<Pat>>),
640     /// A `box` pattern
641     PatBox(P<Pat>),
642     /// A reference pattern, e.g. `&mut (a, b)`
643     PatRegion(P<Pat>, Mutability),
644     /// A literal
645     PatLit(P<Expr>),
646     /// A range pattern, e.g. `1...2`
647     PatRange(P<Expr>, P<Expr>),
648     /// [a, b, ..i, y, z] is represented as:
649     ///     PatVec(box [a, b], Some(i), box [y, z])
650     PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
651     /// A macro pattern; pre-expansion
652     PatMac(Mac),
653 }
654
655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
656 pub enum Mutability {
657     MutMutable,
658     MutImmutable,
659 }
660
661 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
662 pub enum BinOp_ {
663     /// The `+` operator (addition)
664     BiAdd,
665     /// The `-` operator (subtraction)
666     BiSub,
667     /// The `*` operator (multiplication)
668     BiMul,
669     /// The `/` operator (division)
670     BiDiv,
671     /// The `%` operator (modulus)
672     BiRem,
673     /// The `&&` operator (logical and)
674     BiAnd,
675     /// The `||` operator (logical or)
676     BiOr,
677     /// The `^` operator (bitwise xor)
678     BiBitXor,
679     /// The `&` operator (bitwise and)
680     BiBitAnd,
681     /// The `|` operator (bitwise or)
682     BiBitOr,
683     /// The `<<` operator (shift left)
684     BiShl,
685     /// The `>>` operator (shift right)
686     BiShr,
687     /// The `==` operator (equality)
688     BiEq,
689     /// The `<` operator (less than)
690     BiLt,
691     /// The `<=` operator (less than or equal to)
692     BiLe,
693     /// The `!=` operator (not equal to)
694     BiNe,
695     /// The `>=` operator (greater than or equal to)
696     BiGe,
697     /// The `>` operator (greater than)
698     BiGt,
699 }
700
701 pub type BinOp = Spanned<BinOp_>;
702
703 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
704 pub enum UnOp {
705     /// The `box` operator
706     UnUniq,
707     /// The `*` operator for dereferencing
708     UnDeref,
709     /// The `!` operator for logical inversion
710     UnNot,
711     /// The `-` operator for negation
712     UnNeg
713 }
714
715 /// A statement
716 pub type Stmt = Spanned<Stmt_>;
717
718 impl fmt::Debug for Stmt {
719     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
720         write!(f, "stmt({}: {})",
721                ast_util::stmt_id(self),
722                pprust::stmt_to_string(self))
723     }
724 }
725
726
727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
728 pub enum Stmt_ {
729     /// Could be an item or a local (let) binding:
730     StmtDecl(P<Decl>, NodeId),
731
732     /// Expr without trailing semi-colon (must have unit type):
733     StmtExpr(P<Expr>, NodeId),
734
735     /// Expr with trailing semi-colon (may have any type):
736     StmtSemi(P<Expr>, NodeId),
737
738     StmtMac(P<Mac>, MacStmtStyle),
739 }
740 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
741 pub enum MacStmtStyle {
742     /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
743     /// `foo!(...);`, `foo![...];`
744     MacStmtWithSemicolon,
745     /// The macro statement had braces; e.g. foo! { ... }
746     MacStmtWithBraces,
747     /// The macro statement had parentheses or brackets and no semicolon; e.g.
748     /// `foo!(...)`. All of these will end up being converted into macro
749     /// expressions.
750     MacStmtWithoutBraces,
751 }
752
753 // FIXME (pending discussion of #1697, #2178...): local should really be
754 // a refinement on pat.
755 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
756 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
757 pub struct Local {
758     pub pat: P<Pat>,
759     pub ty: Option<P<Ty>>,
760     /// Initializer expression to set the value, if any
761     pub init: Option<P<Expr>>,
762     pub id: NodeId,
763     pub span: Span,
764 }
765
766 pub type Decl = Spanned<Decl_>;
767
768 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
769 pub enum Decl_ {
770     /// A local (let) binding:
771     DeclLocal(P<Local>),
772     /// An item binding:
773     DeclItem(P<Item>),
774 }
775
776 /// represents one arm of a 'match'
777 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
778 pub struct Arm {
779     pub attrs: Vec<Attribute>,
780     pub pats: Vec<P<Pat>>,
781     pub guard: Option<P<Expr>>,
782     pub body: P<Expr>,
783 }
784
785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
786 pub struct Field {
787     pub ident: SpannedIdent,
788     pub expr: P<Expr>,
789     pub span: Span,
790 }
791
792 pub type SpannedIdent = Spanned<Ident>;
793
794 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
795 pub enum BlockCheckMode {
796     DefaultBlock,
797     UnsafeBlock(UnsafeSource),
798     PushUnsafeBlock(UnsafeSource),
799     PopUnsafeBlock(UnsafeSource),
800 }
801
802 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
803 pub enum UnsafeSource {
804     CompilerGenerated,
805     UserProvided,
806 }
807
808 /// An expression
809 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
810 pub struct Expr {
811     pub id: NodeId,
812     pub node: Expr_,
813     pub span: Span,
814 }
815
816 impl fmt::Debug for Expr {
817     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
818         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
819     }
820 }
821
822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
823 pub enum Expr_ {
824     /// First expr is the place; second expr is the value.
825     ExprBox(Option<P<Expr>>, P<Expr>),
826     /// An array (`[a, b, c, d]`)
827     ExprVec(Vec<P<Expr>>),
828     /// A function call
829     ///
830     /// The first field resolves to the function itself,
831     /// and the second field is the list of arguments
832     ExprCall(P<Expr>, Vec<P<Expr>>),
833     /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
834     ///
835     /// The `SpannedIdent` is the identifier for the method name.
836     /// The vector of `Ty`s are the ascripted type parameters for the method
837     /// (within the angle brackets).
838     ///
839     /// The first element of the vector of `Expr`s is the expression that evaluates
840     /// to the object on which the method is being called on (the receiver),
841     /// and the remaining elements are the rest of the arguments.
842     ///
843     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
844     /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
845     ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
846     /// A tuple (`(a, b, c ,d)`)
847     ExprTup(Vec<P<Expr>>),
848     /// A binary operation (For example: `a + b`, `a * b`)
849     ExprBinary(BinOp, P<Expr>, P<Expr>),
850     /// A unary operation (For example: `!x`, `*x`)
851     ExprUnary(UnOp, P<Expr>),
852     /// A literal (For example: `1u8`, `"foo"`)
853     ExprLit(P<Lit>),
854     /// A cast (`foo as f64`)
855     ExprCast(P<Expr>, P<Ty>),
856     /// An `if` block, with an optional else block
857     ///
858     /// `if expr { block } else { expr }`
859     ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
860     /// An `if let` expression with an optional else block
861     ///
862     /// `if let pat = expr { block } else { expr }`
863     ///
864     /// This is desugared to a `match` expression.
865     ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
866     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
867     /// A while loop, with an optional label
868     ///
869     /// `'label: while expr { block }`
870     ExprWhile(P<Expr>, P<Block>, Option<Ident>),
871     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
872     /// A while-let loop, with an optional label
873     ///
874     /// `'label: while let pat = expr { block }`
875     ///
876     /// This is desugared to a combination of `loop` and `match` expressions.
877     ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
878     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
879     /// A for loop, with an optional label
880     ///
881     /// `'label: for pat in expr { block }`
882     ///
883     /// This is desugared to a combination of `loop` and `match` expressions.
884     ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
885     /// Conditionless loop (can be exited with break, continue, or return)
886     ///
887     /// `'label: loop { block }`
888     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
889     ExprLoop(P<Block>, Option<Ident>),
890     /// A `match` block, with a source that indicates whether or not it is
891     /// the result of a desugaring, and if so, which kind.
892     ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
893     /// A closure (for example, `move |a, b, c| {a + b + c}`)
894     ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
895     /// A block (`{ ... }`)
896     ExprBlock(P<Block>),
897
898     /// An assignment (`a = foo()`)
899     ExprAssign(P<Expr>, P<Expr>),
900     /// An assignment with an operator
901     ///
902     /// For example, `a += 1`.
903     ExprAssignOp(BinOp, P<Expr>, P<Expr>),
904     /// Access of a named struct field (`obj.foo`)
905     ExprField(P<Expr>, SpannedIdent),
906     /// Access of an unnamed field of a struct or tuple-struct
907     ///
908     /// For example, `foo.0`.
909     ExprTupField(P<Expr>, Spanned<usize>),
910     /// An indexing operation (`foo[2]`)
911     ExprIndex(P<Expr>, P<Expr>),
912     /// A range (`1..2`, `1..`, or `..2`)
913     ExprRange(Option<P<Expr>>, Option<P<Expr>>),
914
915     /// Variable reference, possibly containing `::` and/or type
916     /// parameters, e.g. foo::bar::<baz>.
917     ///
918     /// Optionally "qualified",
919     /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
920     ExprPath(Option<QSelf>, Path),
921
922     /// A referencing operation (`&a` or `&mut a`)
923     ExprAddrOf(Mutability, P<Expr>),
924     /// A `break`, with an optional label to break
925     ExprBreak(Option<Ident>),
926     /// A `continue`, with an optional label
927     ExprAgain(Option<Ident>),
928     /// A `return`, with an optional value to be returned
929     ExprRet(Option<P<Expr>>),
930
931     /// Output of the `asm!()` macro
932     ExprInlineAsm(InlineAsm),
933
934     /// A macro invocation; pre-expansion
935     ExprMac(Mac),
936
937     /// A struct literal expression.
938     ///
939     /// For example, `Foo {x: 1, y: 2}`, or
940     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
941     ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
942
943     /// An array literal constructed from one repeated element.
944     ///
945     /// For example, `[1u8; 5]`. The first expression is the element
946     /// to be repeated; the second is the number of times to repeat it.
947     ExprRepeat(P<Expr>, P<Expr>),
948
949     /// No-op: used solely so we can pretty-print faithfully
950     ExprParen(P<Expr>)
951 }
952
953 /// The explicit Self type in a "qualified path". The actual
954 /// path, including the trait and the associated item, is stored
955 /// separately. `position` represents the index of the associated
956 /// item qualified with this Self type.
957 ///
958 ///     <Vec<T> as a::b::Trait>::AssociatedItem
959 ///      ^~~~~     ~~~~~~~~~~~~~~^
960 ///      ty        position = 3
961 ///
962 ///     <Vec<T>>::AssociatedItem
963 ///      ^~~~~    ^
964 ///      ty       position = 0
965 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
966 pub struct QSelf {
967     pub ty: P<Ty>,
968     pub position: usize
969 }
970
971 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
972 pub enum MatchSource {
973     Normal,
974     IfLetDesugar { contains_else_clause: bool },
975     WhileLetDesugar,
976     ForLoopDesugar,
977 }
978
979 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
980 pub enum CaptureClause {
981     CaptureByValue,
982     CaptureByRef,
983 }
984
985 /// A delimited sequence of token trees
986 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
987 pub struct Delimited {
988     /// The type of delimiter
989     pub delim: token::DelimToken,
990     /// The span covering the opening delimiter
991     pub open_span: Span,
992     /// The delimited sequence of token trees
993     pub tts: Vec<TokenTree>,
994     /// The span covering the closing delimiter
995     pub close_span: Span,
996 }
997
998 impl Delimited {
999     /// Returns the opening delimiter as a token.
1000     pub fn open_token(&self) -> token::Token {
1001         token::OpenDelim(self.delim)
1002     }
1003
1004     /// Returns the closing delimiter as a token.
1005     pub fn close_token(&self) -> token::Token {
1006         token::CloseDelim(self.delim)
1007     }
1008
1009     /// Returns the opening delimiter as a token tree.
1010     pub fn open_tt(&self) -> TokenTree {
1011         TtToken(self.open_span, self.open_token())
1012     }
1013
1014     /// Returns the closing delimiter as a token tree.
1015     pub fn close_tt(&self) -> TokenTree {
1016         TtToken(self.close_span, self.close_token())
1017     }
1018 }
1019
1020 /// A sequence of token treesee
1021 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1022 pub struct SequenceRepetition {
1023     /// The sequence of token trees
1024     pub tts: Vec<TokenTree>,
1025     /// The optional separator
1026     pub separator: Option<token::Token>,
1027     /// Whether the sequence can be repeated zero (*), or one or more times (+)
1028     pub op: KleeneOp,
1029     /// The number of `MatchNt`s that appear in the sequence (and subsequences)
1030     pub num_captures: usize,
1031 }
1032
1033 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
1034 /// for token sequences.
1035 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1036 pub enum KleeneOp {
1037     ZeroOrMore,
1038     OneOrMore,
1039 }
1040
1041 /// When the main rust parser encounters a syntax-extension invocation, it
1042 /// parses the arguments to the invocation as a token-tree. This is a very
1043 /// loose structure, such that all sorts of different AST-fragments can
1044 /// be passed to syntax extensions using a uniform type.
1045 ///
1046 /// If the syntax extension is an MBE macro, it will attempt to match its
1047 /// LHS token tree against the provided token tree, and if it finds a
1048 /// match, will transcribe the RHS token tree, splicing in any captured
1049 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1050 ///
1051 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1052 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1053 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1054 pub enum TokenTree {
1055     /// A single token
1056     TtToken(Span, token::Token),
1057     /// A delimited sequence of token trees
1058     TtDelimited(Span, Rc<Delimited>),
1059
1060     // This only makes sense in MBE macros.
1061
1062     /// A kleene-style repetition sequence with a span
1063     // FIXME(eddyb) #12938 Use DST.
1064     TtSequence(Span, Rc<SequenceRepetition>),
1065 }
1066
1067 impl TokenTree {
1068     pub fn len(&self) -> usize {
1069         match *self {
1070             TtToken(_, token::DocComment(name)) => {
1071                 match doc_comment_style(&name.as_str()) {
1072                     AttrOuter => 2,
1073                     AttrInner => 3
1074                 }
1075             }
1076             TtToken(_, token::SpecialVarNt(..)) => 2,
1077             TtToken(_, token::MatchNt(..)) => 3,
1078             TtDelimited(_, ref delimed) => {
1079                 delimed.tts.len() + 2
1080             }
1081             TtSequence(_, ref seq) => {
1082                 seq.tts.len()
1083             }
1084             TtToken(..) => 0
1085         }
1086     }
1087
1088     pub fn get_tt(&self, index: usize) -> TokenTree {
1089         match (self, index) {
1090             (&TtToken(sp, token::DocComment(_)), 0) => {
1091                 TtToken(sp, token::Pound)
1092             }
1093             (&TtToken(sp, token::DocComment(name)), 1)
1094             if doc_comment_style(&name.as_str()) == AttrInner => {
1095                 TtToken(sp, token::Not)
1096             }
1097             (&TtToken(sp, token::DocComment(name)), _) => {
1098                 let stripped = strip_doc_comment_decoration(&name.as_str());
1099                 TtDelimited(sp, Rc::new(Delimited {
1100                     delim: token::Bracket,
1101                     open_span: sp,
1102                     tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1103                                                        token::Plain)),
1104                               TtToken(sp, token::Eq),
1105                               TtToken(sp, token::Literal(
1106                                   token::StrRaw(token::intern(&stripped), 0), None))],
1107                     close_span: sp,
1108                 }))
1109             }
1110             (&TtDelimited(_, ref delimed), _) => {
1111                 if index == 0 {
1112                     return delimed.open_tt();
1113                 }
1114                 if index == delimed.tts.len() + 1 {
1115                     return delimed.close_tt();
1116                 }
1117                 delimed.tts[index - 1].clone()
1118             }
1119             (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1120                 let v = [TtToken(sp, token::Dollar),
1121                          TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1122                                                   token::Plain))];
1123                 v[index].clone()
1124             }
1125             (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1126                 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1127                          TtToken(sp, token::Colon),
1128                          TtToken(sp, token::Ident(kind, kind_st))];
1129                 v[index].clone()
1130             }
1131             (&TtSequence(_, ref seq), _) => {
1132                 seq.tts[index].clone()
1133             }
1134             _ => panic!("Cannot expand a token tree")
1135         }
1136     }
1137
1138     /// Returns the `Span` corresponding to this token tree.
1139     pub fn get_span(&self) -> Span {
1140         match *self {
1141             TtToken(span, _)     => span,
1142             TtDelimited(span, _) => span,
1143             TtSequence(span, _)  => span,
1144         }
1145     }
1146
1147     /// Use this token tree as a matcher to parse given tts.
1148     pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1149                  -> macro_parser::NamedParseResult {
1150         // `None` is because we're not interpolating
1151         let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1152                                                          None,
1153                                                          None,
1154                                                          tts.iter().cloned().collect(),
1155                                                          true);
1156         macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1157     }
1158 }
1159
1160 pub type Mac = Spanned<Mac_>;
1161
1162 /// Represents a macro invocation. The Path indicates which macro
1163 /// is being invoked, and the vector of token-trees contains the source
1164 /// of the macro invocation.
1165 ///
1166 /// There's only one flavor, now, so this could presumably be simplified.
1167 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1168 pub enum Mac_ {
1169     // NB: the additional ident for a macro_rules-style macro is actually
1170     // stored in the enclosing item. Oog.
1171     MacInvocTT(Path, Vec<TokenTree>, SyntaxContext),   // new macro-invocation
1172 }
1173
1174 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1175 pub enum StrStyle {
1176     /// A regular string, like `"foo"`
1177     CookedStr,
1178     /// A raw string, like `r##"foo"##`
1179     ///
1180     /// The uint is the number of `#` symbols used
1181     RawStr(usize)
1182 }
1183
1184 /// A literal
1185 pub type Lit = Spanned<Lit_>;
1186
1187 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1188 pub enum Sign {
1189     Minus,
1190     Plus
1191 }
1192
1193 impl Sign {
1194     pub fn new<T: IntSign>(n: T) -> Sign {
1195         n.sign()
1196     }
1197 }
1198
1199 pub trait IntSign {
1200     fn sign(&self) -> Sign;
1201 }
1202 macro_rules! doit {
1203     ($($t:ident)*) => ($(impl IntSign for $t {
1204         #[allow(unused_comparisons)]
1205         fn sign(&self) -> Sign {
1206             if *self < 0 {Minus} else {Plus}
1207         }
1208     })*)
1209 }
1210 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1211
1212 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1213 pub enum LitIntType {
1214     SignedIntLit(IntTy, Sign),
1215     UnsignedIntLit(UintTy),
1216     UnsuffixedIntLit(Sign)
1217 }
1218
1219 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1220 pub enum Lit_ {
1221     /// A string literal (`"foo"`)
1222     LitStr(InternedString, StrStyle),
1223     /// A byte string (`b"foo"`)
1224     LitBinary(Rc<Vec<u8>>),
1225     /// A byte char (`b'f'`)
1226     LitByte(u8),
1227     /// A character literal (`'a'`)
1228     LitChar(char),
1229     /// An integer literal (`1u8`)
1230     LitInt(u64, LitIntType),
1231     /// A float literal (`1f64` or `1E10f64`)
1232     LitFloat(InternedString, FloatTy),
1233     /// A float literal without a suffix (`1.0 or 1.0E10`)
1234     LitFloatUnsuffixed(InternedString),
1235     /// A boolean literal
1236     LitBool(bool),
1237 }
1238
1239 // NB: If you change this, you'll probably want to change the corresponding
1240 // type structure in middle/ty.rs as well.
1241 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1242 pub struct MutTy {
1243     pub ty: P<Ty>,
1244     pub mutbl: Mutability,
1245 }
1246
1247 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1248 pub struct TypeField {
1249     pub ident: Ident,
1250     pub mt: MutTy,
1251     pub span: Span,
1252 }
1253
1254 /// Represents a method's signature in a trait declaration,
1255 /// or in an implementation.
1256 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1257 pub struct MethodSig {
1258     pub unsafety: Unsafety,
1259     pub constness: Constness,
1260     pub abi: Abi,
1261     pub decl: P<FnDecl>,
1262     pub generics: Generics,
1263     pub explicit_self: ExplicitSelf,
1264 }
1265
1266 /// Represents a method declaration in a trait declaration, possibly including
1267 /// a default implementation A trait method is either required (meaning it
1268 /// doesn't have an implementation, just a signature) or provided (meaning it
1269 /// has a default implementation).
1270 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1271 pub struct TraitItem {
1272     pub id: NodeId,
1273     pub ident: Ident,
1274     pub attrs: Vec<Attribute>,
1275     pub node: TraitItem_,
1276     pub span: Span,
1277 }
1278
1279 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1280 pub enum TraitItem_ {
1281     ConstTraitItem(P<Ty>, Option<P<Expr>>),
1282     MethodTraitItem(MethodSig, Option<P<Block>>),
1283     TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1284 }
1285
1286 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1287 pub struct ImplItem {
1288     pub id: NodeId,
1289     pub ident: Ident,
1290     pub vis: Visibility,
1291     pub attrs: Vec<Attribute>,
1292     pub node: ImplItem_,
1293     pub span: Span,
1294 }
1295
1296 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1297 pub enum ImplItem_ {
1298     ConstImplItem(P<Ty>, P<Expr>),
1299     MethodImplItem(MethodSig, P<Block>),
1300     TypeImplItem(P<Ty>),
1301     MacImplItem(Mac),
1302 }
1303
1304 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1305 pub enum IntTy {
1306     TyIs,
1307     TyI8,
1308     TyI16,
1309     TyI32,
1310     TyI64,
1311 }
1312
1313 impl fmt::Debug for IntTy {
1314     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1315         fmt::Display::fmt(self, f)
1316     }
1317 }
1318
1319 impl fmt::Display for IntTy {
1320     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1321         write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1322     }
1323 }
1324
1325 impl IntTy {
1326     pub fn bit_width(&self) -> Option<usize> {
1327         Some(match *self {
1328             TyIs => return None,
1329             TyI8 => 8,
1330             TyI16 => 16,
1331             TyI32 => 32,
1332             TyI64 => 64,
1333         })
1334     }
1335 }
1336
1337 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1338 pub enum UintTy {
1339     TyUs,
1340     TyU8,
1341     TyU16,
1342     TyU32,
1343     TyU64,
1344 }
1345
1346 impl UintTy {
1347     pub fn bit_width(&self) -> Option<usize> {
1348         Some(match *self {
1349             TyUs => return None,
1350             TyU8 => 8,
1351             TyU16 => 16,
1352             TyU32 => 32,
1353             TyU64 => 64,
1354         })
1355     }
1356 }
1357
1358 impl fmt::Debug for UintTy {
1359     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1360         fmt::Display::fmt(self, f)
1361     }
1362 }
1363
1364 impl fmt::Display for UintTy {
1365     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1366         write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1367     }
1368 }
1369
1370 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1371 pub enum FloatTy {
1372     TyF32,
1373     TyF64,
1374 }
1375
1376 impl fmt::Debug for FloatTy {
1377     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1378         fmt::Display::fmt(self, f)
1379     }
1380 }
1381
1382 impl fmt::Display for FloatTy {
1383     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1384         write!(f, "{}", ast_util::float_ty_to_string(*self))
1385     }
1386 }
1387
1388 impl FloatTy {
1389     pub fn bit_width(&self) -> usize {
1390         match *self {
1391             TyF32 => 32,
1392             TyF64 => 64,
1393         }
1394     }
1395 }
1396
1397 // Bind a type to an associated type: `A=Foo`.
1398 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1399 pub struct TypeBinding {
1400     pub id: NodeId,
1401     pub ident: Ident,
1402     pub ty: P<Ty>,
1403     pub span: Span,
1404 }
1405
1406
1407 // NB PartialEq method appears below.
1408 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1409 pub struct Ty {
1410     pub id: NodeId,
1411     pub node: Ty_,
1412     pub span: Span,
1413 }
1414
1415 impl fmt::Debug for Ty {
1416     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1417         write!(f, "type({})", pprust::ty_to_string(self))
1418     }
1419 }
1420
1421 /// Not represented directly in the AST, referred to by name through a ty_path.
1422 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1423 pub enum PrimTy {
1424     TyInt(IntTy),
1425     TyUint(UintTy),
1426     TyFloat(FloatTy),
1427     TyStr,
1428     TyBool,
1429     TyChar
1430 }
1431
1432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1433 pub struct BareFnTy {
1434     pub unsafety: Unsafety,
1435     pub abi: Abi,
1436     pub lifetimes: Vec<LifetimeDef>,
1437     pub decl: P<FnDecl>
1438 }
1439
1440 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1441 /// The different kinds of types recognized by the compiler
1442 pub enum Ty_ {
1443     TyVec(P<Ty>),
1444     /// A fixed length array (`[T; n]`)
1445     TyFixedLengthVec(P<Ty>, P<Expr>),
1446     /// A raw pointer (`*const T` or `*mut T`)
1447     TyPtr(MutTy),
1448     /// A reference (`&'a T` or `&'a mut T`)
1449     TyRptr(Option<Lifetime>, MutTy),
1450     /// A bare function (e.g. `fn(usize) -> bool`)
1451     TyBareFn(P<BareFnTy>),
1452     /// A tuple (`(A, B, C, D,...)`)
1453     TyTup(Vec<P<Ty>> ),
1454     /// A path (`module::module::...::Type`), optionally
1455     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1456     ///
1457     /// Type parameters are stored in the Path itself
1458     TyPath(Option<QSelf>, Path),
1459     /// Something like `A+B`. Note that `B` must always be a path.
1460     TyObjectSum(P<Ty>, TyParamBounds),
1461     /// A type like `for<'a> Foo<&'a Bar>`
1462     TyPolyTraitRef(TyParamBounds),
1463     /// No-op; kept solely so that we can pretty-print faithfully
1464     TyParen(P<Ty>),
1465     /// Unused for now
1466     TyTypeof(P<Expr>),
1467     /// TyInfer means the type should be inferred instead of it having been
1468     /// specified. This can appear anywhere in a type.
1469     TyInfer,
1470     // A macro in the type position.
1471     TyMac(Mac)
1472 }
1473
1474 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1475 pub enum AsmDialect {
1476     AsmAtt,
1477     AsmIntel
1478 }
1479
1480 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1481 pub struct InlineAsm {
1482     pub asm: InternedString,
1483     pub asm_str_style: StrStyle,
1484     pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1485     pub inputs: Vec<(InternedString, P<Expr>)>,
1486     pub clobbers: Vec<InternedString>,
1487     pub volatile: bool,
1488     pub alignstack: bool,
1489     pub dialect: AsmDialect,
1490     pub expn_id: ExpnId,
1491 }
1492
1493 /// represents an argument in a function header
1494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1495 pub struct Arg {
1496     pub ty: P<Ty>,
1497     pub pat: P<Pat>,
1498     pub id: NodeId,
1499 }
1500
1501 impl Arg {
1502     pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1503         let path = Spanned{span:span,node:self_ident};
1504         Arg {
1505             // HACK(eddyb) fake type for the self argument.
1506             ty: P(Ty {
1507                 id: DUMMY_NODE_ID,
1508                 node: TyInfer,
1509                 span: DUMMY_SP,
1510             }),
1511             pat: P(Pat {
1512                 id: DUMMY_NODE_ID,
1513                 node: PatIdent(BindByValue(mutability), path, None),
1514                 span: span
1515             }),
1516             id: DUMMY_NODE_ID
1517         }
1518     }
1519 }
1520
1521 /// Represents the header (not the body) of a function declaration
1522 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1523 pub struct FnDecl {
1524     pub inputs: Vec<Arg>,
1525     pub output: FunctionRetTy,
1526     pub variadic: bool
1527 }
1528
1529 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1530 pub enum Unsafety {
1531     Unsafe,
1532     Normal,
1533 }
1534
1535 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub enum Constness {
1537     Const,
1538     NotConst,
1539 }
1540
1541 impl fmt::Display for Unsafety {
1542     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543         fmt::Display::fmt(match *self {
1544             Unsafety::Normal => "normal",
1545             Unsafety::Unsafe => "unsafe",
1546         }, f)
1547     }
1548 }
1549
1550 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1551 pub enum ImplPolarity {
1552     /// `impl Trait for Type`
1553     Positive,
1554     /// `impl !Trait for Type`
1555     Negative,
1556 }
1557
1558 impl fmt::Debug for ImplPolarity {
1559     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1560         match *self {
1561             ImplPolarity::Positive => "positive".fmt(f),
1562             ImplPolarity::Negative => "negative".fmt(f),
1563         }
1564     }
1565 }
1566
1567
1568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1569 pub enum FunctionRetTy {
1570     /// Functions with return type `!`that always
1571     /// raise an error or exit (i.e. never return to the caller)
1572     NoReturn(Span),
1573     /// Return type is not specified.
1574     ///
1575     /// Functions default to `()` and
1576     /// closures default to inference. Span points to where return
1577     /// type would be inserted.
1578     DefaultReturn(Span),
1579     /// Everything else
1580     Return(P<Ty>),
1581 }
1582
1583 impl FunctionRetTy {
1584     pub fn span(&self) -> Span {
1585         match *self {
1586             NoReturn(span) => span,
1587             DefaultReturn(span) => span,
1588             Return(ref ty) => ty.span
1589         }
1590     }
1591 }
1592
1593 /// Represents the kind of 'self' associated with a method
1594 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1595 pub enum ExplicitSelf_ {
1596     /// No self
1597     SelfStatic,
1598     /// `self`
1599     SelfValue(Ident),
1600     /// `&'lt self`, `&'lt mut self`
1601     SelfRegion(Option<Lifetime>, Mutability, Ident),
1602     /// `self: TYPE`
1603     SelfExplicit(P<Ty>, Ident),
1604 }
1605
1606 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1607
1608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1609 pub struct Mod {
1610     /// A span from the first token past `{` to the last token until `}`.
1611     /// For `mod foo;`, the inner span ranges from the first token
1612     /// to the last token in the external file.
1613     pub inner: Span,
1614     pub items: Vec<P<Item>>,
1615 }
1616
1617 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1618 pub struct ForeignMod {
1619     pub abi: Abi,
1620     pub items: Vec<P<ForeignItem>>,
1621 }
1622
1623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1624 pub struct VariantArg {
1625     pub ty: P<Ty>,
1626     pub id: NodeId,
1627 }
1628
1629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1630 pub enum VariantKind {
1631     /// Tuple variant, e.g. `Foo(A, B)`
1632     TupleVariantKind(Vec<VariantArg>),
1633     /// Struct variant, e.g. `Foo {x: A, y: B}`
1634     StructVariantKind(P<StructDef>),
1635 }
1636
1637 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1638 pub struct EnumDef {
1639     pub variants: Vec<P<Variant>>,
1640 }
1641
1642 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1643 pub struct Variant_ {
1644     pub name: Ident,
1645     pub attrs: Vec<Attribute>,
1646     pub kind: VariantKind,
1647     pub id: NodeId,
1648     /// Explicit discriminant, eg `Foo = 1`
1649     pub disr_expr: Option<P<Expr>>,
1650     pub vis: Visibility,
1651 }
1652
1653 pub type Variant = Spanned<Variant_>;
1654
1655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1656 pub enum PathListItem_ {
1657     PathListIdent {
1658         name: Ident,
1659         /// renamed in list, eg `use foo::{bar as baz};`
1660         rename: Option<Ident>,
1661         id: NodeId
1662     },
1663     PathListMod {
1664         /// renamed in list, eg `use foo::{self as baz};`
1665         rename: Option<Ident>,
1666         id: NodeId
1667     }
1668 }
1669
1670 impl PathListItem_ {
1671     pub fn id(&self) -> NodeId {
1672         match *self {
1673             PathListIdent { id, .. } | PathListMod { id, .. } => id
1674         }
1675     }
1676
1677     pub fn rename(&self) -> Option<Ident> {
1678         match *self {
1679             PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1680         }
1681     }
1682 }
1683
1684 pub type PathListItem = Spanned<PathListItem_>;
1685
1686 pub type ViewPath = Spanned<ViewPath_>;
1687
1688 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1689 pub enum ViewPath_ {
1690
1691     /// `foo::bar::baz as quux`
1692     ///
1693     /// or just
1694     ///
1695     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1696     ViewPathSimple(Ident, Path),
1697
1698     /// `foo::bar::*`
1699     ViewPathGlob(Path),
1700
1701     /// `foo::bar::{a,b,c}`
1702     ViewPathList(Path, Vec<PathListItem>)
1703 }
1704
1705 /// Meta-data associated with an item
1706 pub type Attribute = Spanned<Attribute_>;
1707
1708 /// Distinguishes between Attributes that decorate items and Attributes that
1709 /// are contained as statements within items. These two cases need to be
1710 /// distinguished for pretty-printing.
1711 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1712 pub enum AttrStyle {
1713     AttrOuter,
1714     AttrInner,
1715 }
1716
1717 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1718 pub struct AttrId(pub usize);
1719
1720 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1722 pub struct Attribute_ {
1723     pub id: AttrId,
1724     pub style: AttrStyle,
1725     pub value: P<MetaItem>,
1726     pub is_sugared_doc: bool,
1727 }
1728
1729 /// TraitRef's appear in impls.
1730 ///
1731 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1732 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1733 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1734 /// same as the impl's node id).
1735 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1736 pub struct TraitRef {
1737     pub path: Path,
1738     pub ref_id: NodeId,
1739 }
1740
1741 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1742 pub struct PolyTraitRef {
1743     /// The `'a` in `<'a> Foo<&'a T>`
1744     pub bound_lifetimes: Vec<LifetimeDef>,
1745
1746     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1747     pub trait_ref: TraitRef,
1748
1749     pub span: Span,
1750 }
1751
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1753 pub enum Visibility {
1754     Public,
1755     Inherited,
1756 }
1757
1758 impl Visibility {
1759     pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1760         match self {
1761             &Inherited => parent_visibility,
1762             &Public => *self
1763         }
1764     }
1765 }
1766
1767 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1768 pub struct StructField_ {
1769     pub kind: StructFieldKind,
1770     pub id: NodeId,
1771     pub ty: P<Ty>,
1772     pub attrs: Vec<Attribute>,
1773 }
1774
1775 impl StructField_ {
1776     pub fn ident(&self) -> Option<Ident> {
1777         match self.kind {
1778             NamedField(ref ident, _) => Some(ident.clone()),
1779             UnnamedField(_) => None
1780         }
1781     }
1782 }
1783
1784 pub type StructField = Spanned<StructField_>;
1785
1786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1787 pub enum StructFieldKind {
1788     NamedField(Ident, Visibility),
1789     /// Element of a tuple-like struct
1790     UnnamedField(Visibility),
1791 }
1792
1793 impl StructFieldKind {
1794     pub fn is_unnamed(&self) -> bool {
1795         match *self {
1796             UnnamedField(..) => true,
1797             NamedField(..) => false,
1798         }
1799     }
1800 }
1801
1802 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1803 pub struct StructDef {
1804     /// Fields, not including ctor
1805     pub fields: Vec<StructField>,
1806     /// ID of the constructor. This is only used for tuple- or enum-like
1807     /// structs.
1808     pub ctor_id: Option<NodeId>,
1809 }
1810
1811 /*
1812   FIXME (#3300): Should allow items to be anonymous. Right now
1813   we just use dummy names for anon items.
1814  */
1815 /// An item
1816 ///
1817 /// The name might be a dummy name in case of anonymous items
1818 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1819 pub struct Item {
1820     pub ident: Ident,
1821     pub attrs: Vec<Attribute>,
1822     pub id: NodeId,
1823     pub node: Item_,
1824     pub vis: Visibility,
1825     pub span: Span,
1826 }
1827
1828 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1829 pub enum Item_ {
1830     /// An`extern crate` item, with optional original crate name,
1831     ///
1832     /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1833     ItemExternCrate(Option<Name>),
1834     /// A `use` or `pub use` item
1835     ItemUse(P<ViewPath>),
1836
1837     /// A `static` item
1838     ItemStatic(P<Ty>, Mutability, P<Expr>),
1839     /// A `const` item
1840     ItemConst(P<Ty>, P<Expr>),
1841     /// A function declaration
1842     ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1843     /// A module
1844     ItemMod(Mod),
1845     /// An external module
1846     ItemForeignMod(ForeignMod),
1847     /// A type alias, e.g. `type Foo = Bar<u8>`
1848     ItemTy(P<Ty>, Generics),
1849     /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1850     ItemEnum(EnumDef, Generics),
1851     /// A struct definition, e.g. `struct Foo<A> {x: A}`
1852     ItemStruct(P<StructDef>, Generics),
1853     /// Represents a Trait Declaration
1854     ItemTrait(Unsafety,
1855               Generics,
1856               TyParamBounds,
1857               Vec<P<TraitItem>>),
1858
1859     // Default trait implementations
1860     ///
1861     // `impl Trait for .. {}`
1862     ItemDefaultImpl(Unsafety, TraitRef),
1863     /// An implementation, eg `impl<A> Trait for Foo { .. }`
1864     ItemImpl(Unsafety,
1865              ImplPolarity,
1866              Generics,
1867              Option<TraitRef>, // (optional) trait this impl implements
1868              P<Ty>, // self
1869              Vec<P<ImplItem>>),
1870     /// A macro invocation (which includes macro definition)
1871     ItemMac(Mac),
1872 }
1873
1874 impl Item_ {
1875     pub fn descriptive_variant(&self) -> &str {
1876         match *self {
1877             ItemExternCrate(..) => "extern crate",
1878             ItemUse(..) => "use",
1879             ItemStatic(..) => "static item",
1880             ItemConst(..) => "constant item",
1881             ItemFn(..) => "function",
1882             ItemMod(..) => "module",
1883             ItemForeignMod(..) => "foreign module",
1884             ItemTy(..) => "type alias",
1885             ItemEnum(..) => "enum",
1886             ItemStruct(..) => "struct",
1887             ItemTrait(..) => "trait",
1888             ItemMac(..) |
1889             ItemImpl(..) |
1890             ItemDefaultImpl(..) => "item"
1891         }
1892     }
1893 }
1894
1895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1896 pub struct ForeignItem {
1897     pub ident: Ident,
1898     pub attrs: Vec<Attribute>,
1899     pub node: ForeignItem_,
1900     pub id: NodeId,
1901     pub span: Span,
1902     pub vis: Visibility,
1903 }
1904
1905 /// An item within an `extern` block
1906 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1907 pub enum ForeignItem_ {
1908     /// A foreign function
1909     ForeignItemFn(P<FnDecl>, Generics),
1910     /// A foreign static item (`static ext: u8`), with optional mutability
1911     /// (the boolean is true when mutable)
1912     ForeignItemStatic(P<Ty>, bool),
1913 }
1914
1915 impl ForeignItem_ {
1916     pub fn descriptive_variant(&self) -> &str {
1917         match *self {
1918             ForeignItemFn(..) => "foreign function",
1919             ForeignItemStatic(..) => "foreign static item"
1920         }
1921     }
1922 }
1923
1924 /// A macro definition, in this crate or imported from another.
1925 ///
1926 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1927 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1928 pub struct MacroDef {
1929     pub ident: Ident,
1930     pub attrs: Vec<Attribute>,
1931     pub id: NodeId,
1932     pub span: Span,
1933     pub imported_from: Option<Ident>,
1934     pub export: bool,
1935     pub use_locally: bool,
1936     pub allow_internal_unstable: bool,
1937     pub body: Vec<TokenTree>,
1938 }
1939
1940 #[cfg(test)]
1941 mod tests {
1942     use serialize;
1943     use super::*;
1944
1945     // are ASTs encodable?
1946     #[test]
1947     fn check_asts_encodable() {
1948         fn assert_encodable<T: serialize::Encodable>() {}
1949         assert_encodable::<Crate>();
1950     }
1951 }