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