]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Rollup merge of #31351 - steveklabnik:gh31318, 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::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
1178                 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
1179                 // required to wrap the text.
1180                 let num_of_hashes = stripped.chars().scan(0, |cnt, x| {
1181                     *cnt = if x == '"' {
1182                         1
1183                     } else if *cnt != 0 && x == '#' {
1184                         *cnt + 1
1185                     } else {
1186                         0
1187                     };
1188                     Some(*cnt)
1189                 }).max().unwrap_or(0);
1190
1191                 TokenTree::Delimited(sp, Rc::new(Delimited {
1192                     delim: token::Bracket,
1193                     open_span: sp,
1194                     tts: vec![TokenTree::Token(sp, token::Ident(token::str_to_ident("doc"),
1195                                                                 token::Plain)),
1196                               TokenTree::Token(sp, token::Eq),
1197                               TokenTree::Token(sp, token::Literal(
1198                                   token::StrRaw(token::intern(&stripped), num_of_hashes), None))],
1199                     close_span: sp,
1200                 }))
1201             }
1202             (&TokenTree::Delimited(_, ref delimed), _) => {
1203                 if index == 0 {
1204                     return delimed.open_tt();
1205                 }
1206                 if index == delimed.tts.len() + 1 {
1207                     return delimed.close_tt();
1208                 }
1209                 delimed.tts[index - 1].clone()
1210             }
1211             (&TokenTree::Token(sp, token::SpecialVarNt(var)), _) => {
1212                 let v = [TokenTree::Token(sp, token::Dollar),
1213                          TokenTree::Token(sp, token::Ident(token::str_to_ident(var.as_str()),
1214                                                   token::Plain))];
1215                 v[index].clone()
1216             }
1217             (&TokenTree::Token(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1218                 let v = [TokenTree::Token(sp, token::SubstNt(name, name_st)),
1219                          TokenTree::Token(sp, token::Colon),
1220                          TokenTree::Token(sp, token::Ident(kind, kind_st))];
1221                 v[index].clone()
1222             }
1223             (&TokenTree::Sequence(_, ref seq), _) => {
1224                 seq.tts[index].clone()
1225             }
1226             _ => panic!("Cannot expand a token tree")
1227         }
1228     }
1229
1230     /// Returns the `Span` corresponding to this token tree.
1231     pub fn get_span(&self) -> Span {
1232         match *self {
1233             TokenTree::Token(span, _)     => span,
1234             TokenTree::Delimited(span, _) => span,
1235             TokenTree::Sequence(span, _)  => span,
1236         }
1237     }
1238
1239     /// Use this token tree as a matcher to parse given tts.
1240     pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1241                  -> macro_parser::NamedParseResult {
1242         // `None` is because we're not interpolating
1243         let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1244                                                          None,
1245                                                          None,
1246                                                          tts.iter().cloned().collect(),
1247                                                          true);
1248         macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1249     }
1250 }
1251
1252 pub type Mac = Spanned<Mac_>;
1253
1254 /// Represents a macro invocation. The Path indicates which macro
1255 /// is being invoked, and the vector of token-trees contains the source
1256 /// of the macro invocation.
1257 ///
1258 /// NB: the additional ident for a macro_rules-style macro is actually
1259 /// stored in the enclosing item. Oog.
1260 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1261 pub struct Mac_ {
1262     pub path: Path,
1263     pub tts: Vec<TokenTree>,
1264     pub ctxt: SyntaxContext,
1265 }
1266
1267 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1268 pub enum StrStyle {
1269     /// A regular string, like `"foo"`
1270     CookedStr,
1271     /// A raw string, like `r##"foo"##`
1272     ///
1273     /// The uint is the number of `#` symbols used
1274     RawStr(usize)
1275 }
1276
1277 /// A literal
1278 pub type Lit = Spanned<Lit_>;
1279
1280 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1281 pub enum Sign {
1282     Minus,
1283     Plus
1284 }
1285
1286 impl Sign {
1287     pub fn new<T: IntSign>(n: T) -> Sign {
1288         n.sign()
1289     }
1290 }
1291
1292 pub trait IntSign {
1293     fn sign(&self) -> Sign;
1294 }
1295 macro_rules! doit {
1296     ($($t:ident)*) => ($(impl IntSign for $t {
1297         #[allow(unused_comparisons)]
1298         fn sign(&self) -> Sign {
1299             if *self < 0 {Minus} else {Plus}
1300         }
1301     })*)
1302 }
1303 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1304
1305 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1306 pub enum LitIntType {
1307     SignedIntLit(IntTy, Sign),
1308     UnsignedIntLit(UintTy),
1309     UnsuffixedIntLit(Sign)
1310 }
1311
1312 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1313 pub enum Lit_ {
1314     /// A string literal (`"foo"`)
1315     LitStr(InternedString, StrStyle),
1316     /// A byte string (`b"foo"`)
1317     LitByteStr(Rc<Vec<u8>>),
1318     /// A byte char (`b'f'`)
1319     LitByte(u8),
1320     /// A character literal (`'a'`)
1321     LitChar(char),
1322     /// An integer literal (`1u8`)
1323     LitInt(u64, LitIntType),
1324     /// A float literal (`1f64` or `1E10f64`)
1325     LitFloat(InternedString, FloatTy),
1326     /// A float literal without a suffix (`1.0 or 1.0E10`)
1327     LitFloatUnsuffixed(InternedString),
1328     /// A boolean literal
1329     LitBool(bool),
1330 }
1331
1332 impl Lit_ {
1333     /// Returns true if this literal is a string and false otherwise.
1334     pub fn is_str(&self) -> bool {
1335         match *self {
1336             LitStr(..) => true,
1337             _ => false,
1338         }
1339     }
1340 }
1341
1342 // NB: If you change this, you'll probably want to change the corresponding
1343 // type structure in middle/ty.rs as well.
1344 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1345 pub struct MutTy {
1346     pub ty: P<Ty>,
1347     pub mutbl: Mutability,
1348 }
1349
1350 /// Represents a method's signature in a trait declaration,
1351 /// or in an implementation.
1352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1353 pub struct MethodSig {
1354     pub unsafety: Unsafety,
1355     pub constness: Constness,
1356     pub abi: Abi,
1357     pub decl: P<FnDecl>,
1358     pub generics: Generics,
1359     pub explicit_self: ExplicitSelf,
1360 }
1361
1362 /// Represents a method declaration in a trait declaration, possibly including
1363 /// a default implementation. A trait method is either required (meaning it
1364 /// doesn't have an implementation, just a signature) or provided (meaning it
1365 /// has a default implementation).
1366 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1367 pub struct TraitItem {
1368     pub id: NodeId,
1369     pub ident: Ident,
1370     pub attrs: Vec<Attribute>,
1371     pub node: TraitItem_,
1372     pub span: Span,
1373 }
1374
1375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1376 pub enum TraitItem_ {
1377     ConstTraitItem(P<Ty>, Option<P<Expr>>),
1378     MethodTraitItem(MethodSig, Option<P<Block>>),
1379     TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1380 }
1381
1382 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1383 pub struct ImplItem {
1384     pub id: NodeId,
1385     pub ident: Ident,
1386     pub vis: Visibility,
1387     pub attrs: Vec<Attribute>,
1388     pub node: ImplItemKind,
1389     pub span: Span,
1390 }
1391
1392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1393 pub enum ImplItemKind {
1394     Const(P<Ty>, P<Expr>),
1395     Method(MethodSig, P<Block>),
1396     Type(P<Ty>),
1397     Macro(Mac),
1398 }
1399
1400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1401 pub enum IntTy {
1402     TyIs,
1403     TyI8,
1404     TyI16,
1405     TyI32,
1406     TyI64,
1407 }
1408
1409 impl fmt::Debug for IntTy {
1410     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1411         fmt::Display::fmt(self, f)
1412     }
1413 }
1414
1415 impl fmt::Display for IntTy {
1416     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1417         write!(f, "{}", self.ty_to_string())
1418     }
1419 }
1420
1421 impl IntTy {
1422     pub fn ty_to_string(&self) -> &'static str {
1423         match *self {
1424             TyIs => "isize",
1425             TyI8 => "i8",
1426             TyI16 => "i16",
1427             TyI32 => "i32",
1428             TyI64 => "i64"
1429         }
1430     }
1431
1432     pub fn val_to_string(&self, val: i64) -> String {
1433         // cast to a u64 so we can correctly print INT64_MIN. All integral types
1434         // are parsed as u64, so we wouldn't want to print an extra negative
1435         // sign.
1436         format!("{}{}", val as u64, self.ty_to_string())
1437     }
1438
1439     pub fn ty_max(&self) -> u64 {
1440         match *self {
1441             TyI8 => 0x80,
1442             TyI16 => 0x8000,
1443             TyIs | TyI32 => 0x80000000, // actually ni about TyIs
1444             TyI64 => 0x8000000000000000
1445         }
1446     }
1447
1448     pub fn bit_width(&self) -> Option<usize> {
1449         Some(match *self {
1450             TyIs => return None,
1451             TyI8 => 8,
1452             TyI16 => 16,
1453             TyI32 => 32,
1454             TyI64 => 64,
1455         })
1456     }
1457 }
1458
1459 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1460 pub enum UintTy {
1461     TyUs,
1462     TyU8,
1463     TyU16,
1464     TyU32,
1465     TyU64,
1466 }
1467
1468 impl UintTy {
1469     pub fn ty_to_string(&self) -> &'static str {
1470         match *self {
1471             TyUs => "usize",
1472             TyU8 => "u8",
1473             TyU16 => "u16",
1474             TyU32 => "u32",
1475             TyU64 => "u64"
1476         }
1477     }
1478
1479     pub fn val_to_string(&self, val: u64) -> String {
1480         format!("{}{}", val, self.ty_to_string())
1481     }
1482
1483     pub fn ty_max(&self) -> u64 {
1484         match *self {
1485             TyU8 => 0xff,
1486             TyU16 => 0xffff,
1487             TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
1488             TyU64 => 0xffffffffffffffff
1489         }
1490     }
1491
1492     pub fn bit_width(&self) -> Option<usize> {
1493         Some(match *self {
1494             TyUs => return None,
1495             TyU8 => 8,
1496             TyU16 => 16,
1497             TyU32 => 32,
1498             TyU64 => 64,
1499         })
1500     }
1501 }
1502
1503 impl fmt::Debug for UintTy {
1504     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1505         fmt::Display::fmt(self, f)
1506     }
1507 }
1508
1509 impl fmt::Display for UintTy {
1510     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511         write!(f, "{}", self.ty_to_string())
1512     }
1513 }
1514
1515 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1516 pub enum FloatTy {
1517     TyF32,
1518     TyF64,
1519 }
1520
1521 impl fmt::Debug for FloatTy {
1522     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1523         fmt::Display::fmt(self, f)
1524     }
1525 }
1526
1527 impl fmt::Display for FloatTy {
1528     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1529         write!(f, "{}", self.ty_to_string())
1530     }
1531 }
1532
1533 impl FloatTy {
1534     pub fn ty_to_string(&self) -> &'static str {
1535         match *self {
1536             TyF32 => "f32",
1537             TyF64 => "f64",
1538         }
1539     }
1540
1541     pub fn bit_width(&self) -> usize {
1542         match *self {
1543             TyF32 => 32,
1544             TyF64 => 64,
1545         }
1546     }
1547 }
1548
1549 // Bind a type to an associated type: `A=Foo`.
1550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1551 pub struct TypeBinding {
1552     pub id: NodeId,
1553     pub ident: Ident,
1554     pub ty: P<Ty>,
1555     pub span: Span,
1556 }
1557
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1559 pub struct Ty {
1560     pub id: NodeId,
1561     pub node: Ty_,
1562     pub span: Span,
1563 }
1564
1565 impl fmt::Debug for Ty {
1566     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1567         write!(f, "type({})", pprust::ty_to_string(self))
1568     }
1569 }
1570
1571 /// Not represented directly in the AST, referred to by name through a ty_path.
1572 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1573 pub enum PrimTy {
1574     TyInt(IntTy),
1575     TyUint(UintTy),
1576     TyFloat(FloatTy),
1577     TyStr,
1578     TyBool,
1579     TyChar
1580 }
1581
1582 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1583 pub struct BareFnTy {
1584     pub unsafety: Unsafety,
1585     pub abi: Abi,
1586     pub lifetimes: Vec<LifetimeDef>,
1587     pub decl: P<FnDecl>
1588 }
1589
1590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1591 /// The different kinds of types recognized by the compiler
1592 pub enum Ty_ {
1593     TyVec(P<Ty>),
1594     /// A fixed length array (`[T; n]`)
1595     TyFixedLengthVec(P<Ty>, P<Expr>),
1596     /// A raw pointer (`*const T` or `*mut T`)
1597     TyPtr(MutTy),
1598     /// A reference (`&'a T` or `&'a mut T`)
1599     TyRptr(Option<Lifetime>, MutTy),
1600     /// A bare function (e.g. `fn(usize) -> bool`)
1601     TyBareFn(P<BareFnTy>),
1602     /// A tuple (`(A, B, C, D,...)`)
1603     TyTup(Vec<P<Ty>> ),
1604     /// A path (`module::module::...::Type`), optionally
1605     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1606     ///
1607     /// Type parameters are stored in the Path itself
1608     TyPath(Option<QSelf>, Path),
1609     /// Something like `A+B`. Note that `B` must always be a path.
1610     TyObjectSum(P<Ty>, TyParamBounds),
1611     /// A type like `for<'a> Foo<&'a Bar>`
1612     TyPolyTraitRef(TyParamBounds),
1613     /// No-op; kept solely so that we can pretty-print faithfully
1614     TyParen(P<Ty>),
1615     /// Unused for now
1616     TyTypeof(P<Expr>),
1617     /// TyInfer means the type should be inferred instead of it having been
1618     /// specified. This can appear anywhere in a type.
1619     TyInfer,
1620     // A macro in the type position.
1621     TyMac(Mac)
1622 }
1623
1624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1625 pub enum AsmDialect {
1626     Att,
1627     Intel,
1628 }
1629
1630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1631 pub struct InlineAsmOutput {
1632     pub constraint: InternedString,
1633     pub expr: P<Expr>,
1634     pub is_rw: bool,
1635     pub is_indirect: bool,
1636 }
1637
1638 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1639 pub struct InlineAsm {
1640     pub asm: InternedString,
1641     pub asm_str_style: StrStyle,
1642     pub outputs: Vec<InlineAsmOutput>,
1643     pub inputs: Vec<(InternedString, P<Expr>)>,
1644     pub clobbers: Vec<InternedString>,
1645     pub volatile: bool,
1646     pub alignstack: bool,
1647     pub dialect: AsmDialect,
1648     pub expn_id: ExpnId,
1649 }
1650
1651 /// represents an argument in a function header
1652 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1653 pub struct Arg {
1654     pub ty: P<Ty>,
1655     pub pat: P<Pat>,
1656     pub id: NodeId,
1657 }
1658
1659 impl Arg {
1660     pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1661         let path = Spanned{span:span,node:self_ident};
1662         Arg {
1663             // HACK(eddyb) fake type for the self argument.
1664             ty: P(Ty {
1665                 id: DUMMY_NODE_ID,
1666                 node: TyInfer,
1667                 span: DUMMY_SP,
1668             }),
1669             pat: P(Pat {
1670                 id: DUMMY_NODE_ID,
1671                 node: PatIdent(BindingMode::ByValue(mutability), path, None),
1672                 span: span
1673             }),
1674             id: DUMMY_NODE_ID
1675         }
1676     }
1677 }
1678
1679 /// Represents the header (not the body) of a function declaration
1680 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1681 pub struct FnDecl {
1682     pub inputs: Vec<Arg>,
1683     pub output: FunctionRetTy,
1684     pub variadic: bool
1685 }
1686
1687 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1688 pub enum Unsafety {
1689     Unsafe,
1690     Normal,
1691 }
1692
1693 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1694 pub enum Constness {
1695     Const,
1696     NotConst,
1697 }
1698
1699 impl fmt::Display for Unsafety {
1700     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1701         fmt::Display::fmt(match *self {
1702             Unsafety::Normal => "normal",
1703             Unsafety::Unsafe => "unsafe",
1704         }, f)
1705     }
1706 }
1707
1708 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1709 pub enum ImplPolarity {
1710     /// `impl Trait for Type`
1711     Positive,
1712     /// `impl !Trait for Type`
1713     Negative,
1714 }
1715
1716 impl fmt::Debug for ImplPolarity {
1717     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1718         match *self {
1719             ImplPolarity::Positive => "positive".fmt(f),
1720             ImplPolarity::Negative => "negative".fmt(f),
1721         }
1722     }
1723 }
1724
1725
1726 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1727 pub enum FunctionRetTy {
1728     /// Functions with return type `!`that always
1729     /// raise an error or exit (i.e. never return to the caller)
1730     NoReturn(Span),
1731     /// Return type is not specified.
1732     ///
1733     /// Functions default to `()` and
1734     /// closures default to inference. Span points to where return
1735     /// type would be inserted.
1736     DefaultReturn(Span),
1737     /// Everything else
1738     Return(P<Ty>),
1739 }
1740
1741 impl FunctionRetTy {
1742     pub fn span(&self) -> Span {
1743         match *self {
1744             NoReturn(span) => span,
1745             DefaultReturn(span) => span,
1746             Return(ref ty) => ty.span
1747         }
1748     }
1749 }
1750
1751 /// Represents the kind of 'self' associated with a method
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1753 pub enum ExplicitSelf_ {
1754     /// No self
1755     SelfStatic,
1756     /// `self`
1757     SelfValue(Ident),
1758     /// `&'lt self`, `&'lt mut self`
1759     SelfRegion(Option<Lifetime>, Mutability, Ident),
1760     /// `self: TYPE`
1761     SelfExplicit(P<Ty>, Ident),
1762 }
1763
1764 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1765
1766 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1767 pub struct Mod {
1768     /// A span from the first token past `{` to the last token until `}`.
1769     /// For `mod foo;`, the inner span ranges from the first token
1770     /// to the last token in the external file.
1771     pub inner: Span,
1772     pub items: Vec<P<Item>>,
1773 }
1774
1775 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1776 pub struct ForeignMod {
1777     pub abi: Abi,
1778     pub items: Vec<P<ForeignItem>>,
1779 }
1780
1781 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1782 pub struct EnumDef {
1783     pub variants: Vec<P<Variant>>,
1784 }
1785
1786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1787 pub struct Variant_ {
1788     pub name: Ident,
1789     pub attrs: Vec<Attribute>,
1790     pub data: VariantData,
1791     /// Explicit discriminant, eg `Foo = 1`
1792     pub disr_expr: Option<P<Expr>>,
1793 }
1794
1795 pub type Variant = Spanned<Variant_>;
1796
1797 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1798 pub enum PathListItem_ {
1799     PathListIdent {
1800         name: Ident,
1801         /// renamed in list, eg `use foo::{bar as baz};`
1802         rename: Option<Ident>,
1803         id: NodeId
1804     },
1805     PathListMod {
1806         /// renamed in list, eg `use foo::{self as baz};`
1807         rename: Option<Ident>,
1808         id: NodeId
1809     }
1810 }
1811
1812 impl PathListItem_ {
1813     pub fn id(&self) -> NodeId {
1814         match *self {
1815             PathListIdent { id, .. } | PathListMod { id, .. } => id
1816         }
1817     }
1818
1819     pub fn name(&self) -> Option<Ident> {
1820         match *self {
1821             PathListIdent { name, .. } => Some(name),
1822             PathListMod { .. } => None,
1823         }
1824     }
1825
1826     pub fn rename(&self) -> Option<Ident> {
1827         match *self {
1828             PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1829         }
1830     }
1831 }
1832
1833 pub type PathListItem = Spanned<PathListItem_>;
1834
1835 pub type ViewPath = Spanned<ViewPath_>;
1836
1837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1838 pub enum ViewPath_ {
1839
1840     /// `foo::bar::baz as quux`
1841     ///
1842     /// or just
1843     ///
1844     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1845     ViewPathSimple(Ident, Path),
1846
1847     /// `foo::bar::*`
1848     ViewPathGlob(Path),
1849
1850     /// `foo::bar::{a,b,c}`
1851     ViewPathList(Path, Vec<PathListItem>)
1852 }
1853
1854 /// Meta-data associated with an item
1855 pub type Attribute = Spanned<Attribute_>;
1856
1857 /// Distinguishes between Attributes that decorate items and Attributes that
1858 /// are contained as statements within items. These two cases need to be
1859 /// distinguished for pretty-printing.
1860 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1861 pub enum AttrStyle {
1862     Outer,
1863     Inner,
1864 }
1865
1866 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1867 pub struct AttrId(pub usize);
1868
1869 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1870 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1871 pub struct Attribute_ {
1872     pub id: AttrId,
1873     pub style: AttrStyle,
1874     pub value: P<MetaItem>,
1875     pub is_sugared_doc: bool,
1876 }
1877
1878 /// TraitRef's appear in impls.
1879 ///
1880 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1881 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1882 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1883 /// same as the impl's node id).
1884 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1885 pub struct TraitRef {
1886     pub path: Path,
1887     pub ref_id: NodeId,
1888 }
1889
1890 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1891 pub struct PolyTraitRef {
1892     /// The `'a` in `<'a> Foo<&'a T>`
1893     pub bound_lifetimes: Vec<LifetimeDef>,
1894
1895     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1896     pub trait_ref: TraitRef,
1897
1898     pub span: Span,
1899 }
1900
1901 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1902 pub enum Visibility {
1903     Public,
1904     Inherited,
1905 }
1906
1907 impl Visibility {
1908     pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1909         match *self {
1910             Inherited => parent_visibility,
1911             Public => *self
1912         }
1913     }
1914 }
1915
1916 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1917 pub struct StructField_ {
1918     pub kind: StructFieldKind,
1919     pub id: NodeId,
1920     pub ty: P<Ty>,
1921     pub attrs: Vec<Attribute>,
1922 }
1923
1924 impl StructField_ {
1925     pub fn ident(&self) -> Option<Ident> {
1926         match self.kind {
1927             NamedField(ref ident, _) => Some(ident.clone()),
1928             UnnamedField(_) => None
1929         }
1930     }
1931 }
1932
1933 pub type StructField = Spanned<StructField_>;
1934
1935 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1936 pub enum StructFieldKind {
1937     NamedField(Ident, Visibility),
1938     /// Element of a tuple-like struct
1939     UnnamedField(Visibility),
1940 }
1941
1942 impl StructFieldKind {
1943     pub fn is_unnamed(&self) -> bool {
1944         match *self {
1945             UnnamedField(..) => true,
1946             NamedField(..) => false,
1947         }
1948     }
1949
1950     pub fn visibility(&self) -> Visibility {
1951         match *self {
1952             NamedField(_, vis) | UnnamedField(vis) => vis
1953         }
1954     }
1955 }
1956
1957 /// Fields and Ids of enum variants and structs
1958 ///
1959 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1960 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1961 /// One shared Id can be successfully used for these two purposes.
1962 /// Id of the whole enum lives in `Item`.
1963 ///
1964 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1965 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1966 /// the variant itself" from enum variants.
1967 /// Id of the whole struct lives in `Item`.
1968 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1969 pub enum VariantData {
1970     Struct(Vec<StructField>, NodeId),
1971     Tuple(Vec<StructField>, NodeId),
1972     Unit(NodeId),
1973 }
1974
1975 impl VariantData {
1976     pub fn fields(&self) -> &[StructField] {
1977         match *self {
1978             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1979             _ => &[],
1980         }
1981     }
1982     pub fn id(&self) -> NodeId {
1983         match *self {
1984             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1985         }
1986     }
1987     pub fn is_struct(&self) -> bool {
1988         if let VariantData::Struct(..) = *self { true } else { false }
1989     }
1990     pub fn is_tuple(&self) -> bool {
1991         if let VariantData::Tuple(..) = *self { true } else { false }
1992     }
1993     pub fn is_unit(&self) -> bool {
1994         if let VariantData::Unit(..) = *self { true } else { false }
1995     }
1996 }
1997
1998 /*
1999   FIXME (#3300): Should allow items to be anonymous. Right now
2000   we just use dummy names for anon items.
2001  */
2002 /// An item
2003 ///
2004 /// The name might be a dummy name in case of anonymous items
2005 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2006 pub struct Item {
2007     pub ident: Ident,
2008     pub attrs: Vec<Attribute>,
2009     pub id: NodeId,
2010     pub node: Item_,
2011     pub vis: Visibility,
2012     pub span: Span,
2013 }
2014
2015 impl Item {
2016     pub fn attrs(&self) -> &[Attribute] {
2017         &self.attrs
2018     }
2019 }
2020
2021 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2022 pub enum Item_ {
2023     /// An`extern crate` item, with optional original crate name,
2024     ///
2025     /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
2026     ItemExternCrate(Option<Name>),
2027     /// A `use` or `pub use` item
2028     ItemUse(P<ViewPath>),
2029
2030     /// A `static` item
2031     ItemStatic(P<Ty>, Mutability, P<Expr>),
2032     /// A `const` item
2033     ItemConst(P<Ty>, P<Expr>),
2034     /// A function declaration
2035     ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
2036     /// A module
2037     ItemMod(Mod),
2038     /// An external module
2039     ItemForeignMod(ForeignMod),
2040     /// A type alias, e.g. `type Foo = Bar<u8>`
2041     ItemTy(P<Ty>, Generics),
2042     /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2043     ItemEnum(EnumDef, Generics),
2044     /// A struct definition, e.g. `struct Foo<A> {x: A}`
2045     ItemStruct(VariantData, Generics),
2046     /// Represents a Trait Declaration
2047     ItemTrait(Unsafety,
2048               Generics,
2049               TyParamBounds,
2050               Vec<P<TraitItem>>),
2051
2052     // Default trait implementations
2053     ///
2054     // `impl Trait for .. {}`
2055     ItemDefaultImpl(Unsafety, TraitRef),
2056     /// An implementation, eg `impl<A> Trait for Foo { .. }`
2057     ItemImpl(Unsafety,
2058              ImplPolarity,
2059              Generics,
2060              Option<TraitRef>, // (optional) trait this impl implements
2061              P<Ty>, // self
2062              Vec<P<ImplItem>>),
2063     /// A macro invocation (which includes macro definition)
2064     ItemMac(Mac),
2065 }
2066
2067 impl Item_ {
2068     pub fn descriptive_variant(&self) -> &str {
2069         match *self {
2070             ItemExternCrate(..) => "extern crate",
2071             ItemUse(..) => "use",
2072             ItemStatic(..) => "static item",
2073             ItemConst(..) => "constant item",
2074             ItemFn(..) => "function",
2075             ItemMod(..) => "module",
2076             ItemForeignMod(..) => "foreign module",
2077             ItemTy(..) => "type alias",
2078             ItemEnum(..) => "enum",
2079             ItemStruct(..) => "struct",
2080             ItemTrait(..) => "trait",
2081             ItemMac(..) |
2082             ItemImpl(..) |
2083             ItemDefaultImpl(..) => "item"
2084         }
2085     }
2086 }
2087
2088 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2089 pub struct ForeignItem {
2090     pub ident: Ident,
2091     pub attrs: Vec<Attribute>,
2092     pub node: ForeignItem_,
2093     pub id: NodeId,
2094     pub span: Span,
2095     pub vis: Visibility,
2096 }
2097
2098 /// An item within an `extern` block
2099 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2100 pub enum ForeignItem_ {
2101     /// A foreign function
2102     ForeignItemFn(P<FnDecl>, Generics),
2103     /// A foreign static item (`static ext: u8`), with optional mutability
2104     /// (the boolean is true when mutable)
2105     ForeignItemStatic(P<Ty>, bool),
2106 }
2107
2108 impl ForeignItem_ {
2109     pub fn descriptive_variant(&self) -> &str {
2110         match *self {
2111             ForeignItemFn(..) => "foreign function",
2112             ForeignItemStatic(..) => "foreign static item"
2113         }
2114     }
2115 }
2116
2117 /// A macro definition, in this crate or imported from another.
2118 ///
2119 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
2120 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2121 pub struct MacroDef {
2122     pub ident: Ident,
2123     pub attrs: Vec<Attribute>,
2124     pub id: NodeId,
2125     pub span: Span,
2126     pub imported_from: Option<Ident>,
2127     pub export: bool,
2128     pub use_locally: bool,
2129     pub allow_internal_unstable: bool,
2130     pub body: Vec<TokenTree>,
2131 }
2132
2133 #[cfg(test)]
2134 mod tests {
2135     use serialize;
2136     use super::*;
2137
2138     // are ASTs encodable?
2139     #[test]
2140     fn check_asts_encodable() {
2141         fn assert_encodable<T: serialize::Encodable>() {}
2142         assert_encodable::<Crate>();
2143     }
2144 }