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