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