]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Changed issue number to 36105
[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::TyParamBound::*;
14 pub use self::UnsafeSource::*;
15 pub use self::ViewPath_::*;
16 pub use self::PathParameters::*;
17 pub use util::ThinVec;
18
19 use syntax_pos::{mk_sp, Span, DUMMY_SP, ExpnId};
20 use codemap::{respan, Spanned};
21 use abi::Abi;
22 use ext::hygiene::SyntaxContext;
23 use parse::token::{self, keywords, InternedString};
24 use print::pprust;
25 use ptr::P;
26 use tokenstream::{TokenTree};
27
28 use std::fmt;
29 use std::rc::Rc;
30 use serialize::{Encodable, Decodable, Encoder, Decoder};
31
32 /// A name is a part of an identifier, representing a string or gensym. It's
33 /// the result of interning.
34 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
35 pub struct Name(pub u32);
36
37 /// An identifier contains a Name (index into the interner
38 /// table) and a SyntaxContext to track renaming and
39 /// macro expansion per Flatt et al., "Macros That Work Together"
40 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
41 pub struct Ident {
42     pub name: Name,
43     pub ctxt: SyntaxContext
44 }
45
46 impl Name {
47     pub fn as_str(self) -> token::InternedString {
48         token::InternedString::new_from_name(self)
49     }
50 }
51
52 impl fmt::Debug for Name {
53     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54         write!(f, "{}({})", self, self.0)
55     }
56 }
57
58 impl fmt::Display for Name {
59     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60         fmt::Display::fmt(&self.as_str(), f)
61     }
62 }
63
64 impl Encodable for Name {
65     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
66         s.emit_str(&self.as_str())
67     }
68 }
69
70 impl Decodable for Name {
71     fn decode<D: Decoder>(d: &mut D) -> Result<Name, D::Error> {
72         Ok(token::intern(&d.read_str()?[..]))
73     }
74 }
75
76 impl Ident {
77     pub const fn with_empty_ctxt(name: Name) -> Ident {
78         Ident { name: name, ctxt: SyntaxContext::empty() }
79     }
80 }
81
82 impl fmt::Debug for Ident {
83     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84         write!(f, "{}{:?}", self.name, self.ctxt)
85     }
86 }
87
88 impl fmt::Display for Ident {
89     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90         fmt::Display::fmt(&self.name, f)
91     }
92 }
93
94 impl Encodable for Ident {
95     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
96         self.name.encode(s)
97     }
98 }
99
100 impl Decodable for Ident {
101     fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
102         Ok(Ident::with_empty_ctxt(Name::decode(d)?))
103     }
104 }
105
106 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
107 pub struct Lifetime {
108     pub id: NodeId,
109     pub span: Span,
110     pub name: Name
111 }
112
113 impl fmt::Debug for Lifetime {
114     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115         write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
116     }
117 }
118
119 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
120 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
121 pub struct LifetimeDef {
122     pub lifetime: Lifetime,
123     pub bounds: Vec<Lifetime>
124 }
125
126 /// A "Path" is essentially Rust's notion of a name.
127 ///
128 /// It's represented as a sequence of identifiers,
129 /// along with a bunch of supporting information.
130 ///
131 /// E.g. `std::cmp::PartialEq`
132 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
133 pub struct Path {
134     pub span: Span,
135     /// A `::foo` path, is relative to the crate root rather than current
136     /// module (like paths in an import).
137     pub global: bool,
138     /// The segments in the path: the things separated by `::`.
139     pub segments: Vec<PathSegment>,
140 }
141
142 impl fmt::Debug for Path {
143     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144         write!(f, "path({})", pprust::path_to_string(self))
145     }
146 }
147
148 impl fmt::Display for Path {
149     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150         write!(f, "{}", pprust::path_to_string(self))
151     }
152 }
153
154 impl Path {
155     // convert a span and an identifier to the corresponding
156     // 1-segment path
157     pub fn from_ident(s: Span, identifier: Ident) -> Path {
158         Path {
159             span: s,
160             global: false,
161             segments: vec!(
162                 PathSegment {
163                     identifier: identifier,
164                     parameters: PathParameters::none()
165                 }
166             ),
167         }
168     }
169 }
170
171 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
172 ///
173 /// E.g. `std`, `String` or `Box<T>`
174 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
175 pub struct PathSegment {
176     /// The identifier portion of this path segment.
177     pub identifier: Ident,
178
179     /// Type/lifetime parameters attached to this path. They come in
180     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
181     /// this is more than just simple syntactic sugar; the use of
182     /// parens affects the region binding rules, so we preserve the
183     /// distinction.
184     pub parameters: PathParameters,
185 }
186
187 /// Parameters of a path segment.
188 ///
189 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
190 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
191 pub enum PathParameters {
192     /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
193     AngleBracketed(AngleBracketedParameterData),
194     /// The `(A,B)` and `C` in `Foo(A,B) -> C`
195     Parenthesized(ParenthesizedParameterData),
196 }
197
198 impl PathParameters {
199     pub fn none() -> PathParameters {
200         PathParameters::AngleBracketed(AngleBracketedParameterData {
201             lifetimes: Vec::new(),
202             types: P::new(),
203             bindings: P::new(),
204         })
205     }
206
207     pub fn is_empty(&self) -> bool {
208         match *self {
209             PathParameters::AngleBracketed(ref data) => data.is_empty(),
210
211             // Even if the user supplied no types, something like
212             // `X()` is equivalent to `X<(),()>`.
213             PathParameters::Parenthesized(..) => false,
214         }
215     }
216
217     pub fn has_lifetimes(&self) -> bool {
218         match *self {
219             PathParameters::AngleBracketed(ref data) => !data.lifetimes.is_empty(),
220             PathParameters::Parenthesized(_) => false,
221         }
222     }
223
224     pub fn has_types(&self) -> bool {
225         match *self {
226             PathParameters::AngleBracketed(ref data) => !data.types.is_empty(),
227             PathParameters::Parenthesized(..) => true,
228         }
229     }
230
231     /// Returns the types that the user wrote. Note that these do not necessarily map to the type
232     /// parameters in the parenthesized case.
233     pub fn types(&self) -> Vec<&P<Ty>> {
234         match *self {
235             PathParameters::AngleBracketed(ref data) => {
236                 data.types.iter().collect()
237             }
238             PathParameters::Parenthesized(ref data) => {
239                 data.inputs.iter()
240                     .chain(data.output.iter())
241                     .collect()
242             }
243         }
244     }
245
246     pub fn lifetimes(&self) -> Vec<&Lifetime> {
247         match *self {
248             PathParameters::AngleBracketed(ref data) => {
249                 data.lifetimes.iter().collect()
250             }
251             PathParameters::Parenthesized(_) => {
252                 Vec::new()
253             }
254         }
255     }
256
257     pub fn bindings(&self) -> Vec<&TypeBinding> {
258         match *self {
259             PathParameters::AngleBracketed(ref data) => {
260                 data.bindings.iter().collect()
261             }
262             PathParameters::Parenthesized(_) => {
263                 Vec::new()
264             }
265         }
266     }
267 }
268
269 /// A path like `Foo<'a, T>`
270 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
271 pub struct AngleBracketedParameterData {
272     /// The lifetime parameters for this path segment.
273     pub lifetimes: Vec<Lifetime>,
274     /// The type parameters for this path segment, if present.
275     pub types: P<[P<Ty>]>,
276     /// Bindings (equality constraints) on associated types, if present.
277     ///
278     /// E.g., `Foo<A=Bar>`.
279     pub bindings: P<[TypeBinding]>,
280 }
281
282 impl AngleBracketedParameterData {
283     fn is_empty(&self) -> bool {
284         self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
285     }
286 }
287
288 /// A path like `Foo(A,B) -> C`
289 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
290 pub struct ParenthesizedParameterData {
291     /// Overall span
292     pub span: Span,
293
294     /// `(A,B)`
295     pub inputs: Vec<P<Ty>>,
296
297     /// `C`
298     pub output: Option<P<Ty>>,
299 }
300
301 pub type CrateNum = u32;
302
303 pub type NodeId = u32;
304
305 /// Node id used to represent the root of the crate.
306 pub const CRATE_NODE_ID: NodeId = 0;
307
308 /// When parsing and doing expansions, we initially give all AST nodes this AST
309 /// node value. Then later, in the renumber pass, we renumber them to have
310 /// small, positive ids.
311 pub const DUMMY_NODE_ID: NodeId = !0;
312
313 /// The AST represents all type param bounds as types.
314 /// typeck::collect::compute_bounds matches these against
315 /// the "special" built-in traits (see middle::lang_items) and
316 /// detects Copy, Send and Sync.
317 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
318 pub enum TyParamBound {
319     TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
320     RegionTyParamBound(Lifetime)
321 }
322
323 /// A modifier on a bound, currently this is only used for `?Sized`, where the
324 /// modifier is `Maybe`. Negative bounds should also be handled here.
325 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
326 pub enum TraitBoundModifier {
327     None,
328     Maybe,
329 }
330
331 pub type TyParamBounds = P<[TyParamBound]>;
332
333 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
334 pub struct TyParam {
335     pub ident: Ident,
336     pub id: NodeId,
337     pub bounds: TyParamBounds,
338     pub default: Option<P<Ty>>,
339     pub span: Span
340 }
341
342 /// Represents lifetimes and type parameters attached to a declaration
343 /// of a function, enum, trait, etc.
344 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
345 pub struct Generics {
346     pub lifetimes: Vec<LifetimeDef>,
347     pub ty_params: P<[TyParam]>,
348     pub where_clause: WhereClause,
349 }
350
351 impl Generics {
352     pub fn is_lt_parameterized(&self) -> bool {
353         !self.lifetimes.is_empty()
354     }
355     pub fn is_type_parameterized(&self) -> bool {
356         !self.ty_params.is_empty()
357     }
358     pub fn is_parameterized(&self) -> bool {
359         self.is_lt_parameterized() || self.is_type_parameterized()
360     }
361 }
362
363 impl Default for Generics {
364     fn default() ->  Generics {
365         Generics {
366             lifetimes: Vec::new(),
367             ty_params: P::new(),
368             where_clause: WhereClause {
369                 id: DUMMY_NODE_ID,
370                 predicates: Vec::new(),
371             }
372         }
373     }
374 }
375
376 /// A `where` clause in a definition
377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
378 pub struct WhereClause {
379     pub id: NodeId,
380     pub predicates: Vec<WherePredicate>,
381 }
382
383 /// A single predicate in a `where` clause
384 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
385 pub enum WherePredicate {
386     /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
387     BoundPredicate(WhereBoundPredicate),
388     /// A lifetime predicate, e.g. `'a: 'b+'c`
389     RegionPredicate(WhereRegionPredicate),
390     /// An equality predicate (unsupported)
391     EqPredicate(WhereEqPredicate),
392 }
393
394 /// A type bound.
395 ///
396 /// E.g. `for<'c> Foo: Send+Clone+'c`
397 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
398 pub struct WhereBoundPredicate {
399     pub span: Span,
400     /// Any lifetimes from a `for` binding
401     pub bound_lifetimes: Vec<LifetimeDef>,
402     /// The type being bounded
403     pub bounded_ty: P<Ty>,
404     /// Trait and lifetime bounds (`Clone+Send+'static`)
405     pub bounds: TyParamBounds,
406 }
407
408 /// A lifetime predicate.
409 ///
410 /// E.g. `'a: 'b+'c`
411 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
412 pub struct WhereRegionPredicate {
413     pub span: Span,
414     pub lifetime: Lifetime,
415     pub bounds: Vec<Lifetime>,
416 }
417
418 /// An equality predicate (unsupported).
419 ///
420 /// E.g. `T=int`
421 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
422 pub struct WhereEqPredicate {
423     pub id: NodeId,
424     pub span: Span,
425     pub path: Path,
426     pub ty: P<Ty>,
427 }
428
429 /// The set of MetaItems that define the compilation environment of the crate,
430 /// used to drive conditional compilation
431 pub type CrateConfig = Vec<P<MetaItem>>;
432
433 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
434 pub struct Crate {
435     pub module: Mod,
436     pub attrs: Vec<Attribute>,
437     pub config: CrateConfig,
438     pub span: Span,
439     pub exported_macros: Vec<MacroDef>,
440 }
441
442 /// A spanned compile-time attribute item.
443 ///
444 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
445 pub type MetaItem = Spanned<MetaItemKind>;
446
447 /// A compile-time attribute item.
448 ///
449 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
450 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
451 pub enum MetaItemKind {
452     /// Word meta item.
453     ///
454     /// E.g. `test` as in `#[test]`
455     Word(InternedString),
456     /// List meta item.
457     ///
458     /// E.g. `derive(..)` as in `#[derive(..)]`
459     List(InternedString, Vec<P<MetaItem>>),
460     /// Name value meta item.
461     ///
462     /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
463     NameValue(InternedString, Lit),
464 }
465
466 // can't be derived because the MetaItemKind::List requires an unordered comparison
467 impl PartialEq for MetaItemKind {
468     fn eq(&self, other: &MetaItemKind) -> bool {
469         use self::MetaItemKind::*;
470         match *self {
471             Word(ref ns) => match *other {
472                 Word(ref no) => (*ns) == (*no),
473                 _ => false
474             },
475             NameValue(ref ns, ref vs) => match *other {
476                 NameValue(ref no, ref vo) => {
477                     (*ns) == (*no) && vs.node == vo.node
478                 }
479                 _ => false
480             },
481             List(ref ns, ref miss) => match *other {
482                 List(ref no, ref miso) => {
483                     ns == no &&
484                         miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
485                 }
486                 _ => false
487             }
488         }
489     }
490 }
491
492 /// A Block (`{ .. }`).
493 ///
494 /// E.g. `{ .. }` as in `fn foo() { .. }`
495 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
496 pub struct Block {
497     /// Statements in a block
498     pub stmts: Vec<Stmt>,
499     pub id: NodeId,
500     /// Distinguishes between `unsafe { ... }` and `{ ... }`
501     pub rules: BlockCheckMode,
502     pub span: Span,
503 }
504
505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
506 pub struct Pat {
507     pub id: NodeId,
508     pub node: PatKind,
509     pub span: Span,
510 }
511
512 impl fmt::Debug for Pat {
513     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
514         write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
515     }
516 }
517
518 impl Pat {
519     pub fn walk<F>(&self, it: &mut F) -> bool
520         where F: FnMut(&Pat) -> bool
521     {
522         if !it(self) {
523             return false;
524         }
525
526         match self.node {
527             PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
528             PatKind::Struct(_, ref fields, _) => {
529                 fields.iter().all(|field| field.node.pat.walk(it))
530             }
531             PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
532                 s.iter().all(|p| p.walk(it))
533             }
534             PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
535                 s.walk(it)
536             }
537             PatKind::Vec(ref before, ref slice, ref after) => {
538                 before.iter().all(|p| p.walk(it)) &&
539                 slice.iter().all(|p| p.walk(it)) &&
540                 after.iter().all(|p| p.walk(it))
541             }
542             PatKind::Wild |
543             PatKind::Lit(_) |
544             PatKind::Range(_, _) |
545             PatKind::Ident(_, _, _) |
546             PatKind::Path(..) |
547             PatKind::Mac(_) => {
548                 true
549             }
550         }
551     }
552 }
553
554 /// A single field in a struct pattern
555 ///
556 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
557 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
558 /// except is_shorthand is true
559 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
560 pub struct FieldPat {
561     /// The identifier for the field
562     pub ident: Ident,
563     /// The pattern the field is destructured to
564     pub pat: P<Pat>,
565     pub is_shorthand: bool,
566 }
567
568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
569 pub enum BindingMode {
570     ByRef(Mutability),
571     ByValue(Mutability),
572 }
573
574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
575 pub enum PatKind {
576     /// Represents a wildcard pattern (`_`)
577     Wild,
578
579     /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
580     /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
581     /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
582     /// during name resolution.
583     Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
584
585     /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
586     /// The `bool` is `true` in the presence of a `..`.
587     Struct(Path, Vec<Spanned<FieldPat>>, bool),
588
589     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
590     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
591     /// 0 <= position <= subpats.len()
592     TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
593
594     /// A possibly qualified path pattern.
595     /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
596     /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
597     /// only legally refer to associated constants.
598     Path(Option<QSelf>, Path),
599
600     /// A tuple pattern `(a, b)`.
601     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
602     /// 0 <= position <= subpats.len()
603     Tuple(Vec<P<Pat>>, Option<usize>),
604     /// A `box` pattern
605     Box(P<Pat>),
606     /// A reference pattern, e.g. `&mut (a, b)`
607     Ref(P<Pat>, Mutability),
608     /// A literal
609     Lit(P<Expr>),
610     /// A range pattern, e.g. `1...2`
611     Range(P<Expr>, P<Expr>),
612     /// `[a, b, ..i, y, z]` is represented as:
613     ///     `PatKind::Vec(box [a, b], Some(i), box [y, z])`
614     Vec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
615     /// A macro pattern; pre-expansion
616     Mac(Mac),
617 }
618
619 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
620 pub enum Mutability {
621     Mutable,
622     Immutable,
623 }
624
625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
626 pub enum BinOpKind {
627     /// The `+` operator (addition)
628     Add,
629     /// The `-` operator (subtraction)
630     Sub,
631     /// The `*` operator (multiplication)
632     Mul,
633     /// The `/` operator (division)
634     Div,
635     /// The `%` operator (modulus)
636     Rem,
637     /// The `&&` operator (logical and)
638     And,
639     /// The `||` operator (logical or)
640     Or,
641     /// The `^` operator (bitwise xor)
642     BitXor,
643     /// The `&` operator (bitwise and)
644     BitAnd,
645     /// The `|` operator (bitwise or)
646     BitOr,
647     /// The `<<` operator (shift left)
648     Shl,
649     /// The `>>` operator (shift right)
650     Shr,
651     /// The `==` operator (equality)
652     Eq,
653     /// The `<` operator (less than)
654     Lt,
655     /// The `<=` operator (less than or equal to)
656     Le,
657     /// The `!=` operator (not equal to)
658     Ne,
659     /// The `>=` operator (greater than or equal to)
660     Ge,
661     /// The `>` operator (greater than)
662     Gt,
663 }
664
665 impl BinOpKind {
666     pub fn to_string(&self) -> &'static str {
667         use self::BinOpKind::*;
668         match *self {
669             Add => "+",
670             Sub => "-",
671             Mul => "*",
672             Div => "/",
673             Rem => "%",
674             And => "&&",
675             Or => "||",
676             BitXor => "^",
677             BitAnd => "&",
678             BitOr => "|",
679             Shl => "<<",
680             Shr => ">>",
681             Eq => "==",
682             Lt => "<",
683             Le => "<=",
684             Ne => "!=",
685             Ge => ">=",
686             Gt => ">",
687         }
688     }
689     pub fn lazy(&self) -> bool {
690         match *self {
691             BinOpKind::And | BinOpKind::Or => true,
692             _ => false
693         }
694     }
695
696     pub fn is_shift(&self) -> bool {
697         match *self {
698             BinOpKind::Shl | BinOpKind::Shr => true,
699             _ => false
700         }
701     }
702     pub fn is_comparison(&self) -> bool {
703         use self::BinOpKind::*;
704         match *self {
705             Eq | Lt | Le | Ne | Gt | Ge =>
706             true,
707             And | Or | Add | Sub | Mul | Div | Rem |
708             BitXor | BitAnd | BitOr | Shl | Shr =>
709             false,
710         }
711     }
712     /// Returns `true` if the binary operator takes its arguments by value
713     pub fn is_by_value(&self) -> bool {
714         !self.is_comparison()
715     }
716 }
717
718 pub type BinOp = Spanned<BinOpKind>;
719
720 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
721 pub enum UnOp {
722     /// The `*` operator for dereferencing
723     Deref,
724     /// The `!` operator for logical inversion
725     Not,
726     /// The `-` operator for negation
727     Neg,
728 }
729
730 impl UnOp {
731     /// Returns `true` if the unary operator takes its argument by value
732     pub fn is_by_value(u: UnOp) -> bool {
733         match u {
734             UnOp::Neg | UnOp::Not => true,
735             _ => false,
736         }
737     }
738
739     pub fn to_string(op: UnOp) -> &'static str {
740         match op {
741             UnOp::Deref => "*",
742             UnOp::Not => "!",
743             UnOp::Neg => "-",
744         }
745     }
746 }
747
748 /// A statement
749 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
750 pub struct Stmt {
751     pub id: NodeId,
752     pub node: StmtKind,
753     pub span: Span,
754 }
755
756 impl Stmt {
757     pub fn add_trailing_semicolon(mut self) -> Self {
758         self.node = match self.node {
759             StmtKind::Expr(expr) => StmtKind::Semi(expr),
760             StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
761                 (mac, MacStmtStyle::Semicolon, attrs)
762             })),
763             node @ _ => node,
764         };
765         self
766     }
767 }
768
769 impl fmt::Debug for Stmt {
770     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771         write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
772     }
773 }
774
775
776 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
777 pub enum StmtKind {
778     /// A local (let) binding.
779     Local(P<Local>),
780
781     /// An item definition.
782     Item(P<Item>),
783
784     /// Expr without trailing semi-colon.
785     Expr(P<Expr>),
786
787     Semi(P<Expr>),
788
789     Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
790 }
791
792 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
793 pub enum MacStmtStyle {
794     /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
795     /// `foo!(...);`, `foo![...];`
796     Semicolon,
797     /// The macro statement had braces; e.g. foo! { ... }
798     Braces,
799     /// The macro statement had parentheses or brackets and no semicolon; e.g.
800     /// `foo!(...)`. All of these will end up being converted into macro
801     /// expressions.
802     NoBraces,
803 }
804
805 // FIXME (pending discussion of #1697, #2178...): local should really be
806 // a refinement on pat.
807 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
808 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
809 pub struct Local {
810     pub pat: P<Pat>,
811     pub ty: Option<P<Ty>>,
812     /// Initializer expression to set the value, if any
813     pub init: Option<P<Expr>>,
814     pub id: NodeId,
815     pub span: Span,
816     pub attrs: ThinVec<Attribute>,
817 }
818
819 /// An arm of a 'match'.
820 ///
821 /// E.g. `0...10 => { println!("match!") }` as in
822 ///
823 /// ```rust,ignore
824 /// match n {
825 ///     0...10 => { println!("match!") },
826 ///     // ..
827 /// }
828 /// ```
829 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
830 pub struct Arm {
831     pub attrs: Vec<Attribute>,
832     pub pats: Vec<P<Pat>>,
833     pub guard: Option<P<Expr>>,
834     pub body: P<Expr>,
835 }
836
837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
838 pub struct Field {
839     pub ident: SpannedIdent,
840     pub expr: P<Expr>,
841     pub span: Span,
842 }
843
844 pub type SpannedIdent = Spanned<Ident>;
845
846 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
847 pub enum BlockCheckMode {
848     Default,
849     Unsafe(UnsafeSource),
850 }
851
852 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
853 pub enum UnsafeSource {
854     CompilerGenerated,
855     UserProvided,
856 }
857
858 /// An expression
859 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
860 pub struct Expr {
861     pub id: NodeId,
862     pub node: ExprKind,
863     pub span: Span,
864     pub attrs: ThinVec<Attribute>
865 }
866
867 impl fmt::Debug for Expr {
868     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
869         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
870     }
871 }
872
873 /// Limit types of a range (inclusive or exclusive)
874 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
875 pub enum RangeLimits {
876     /// Inclusive at the beginning, exclusive at the end
877     HalfOpen,
878     /// Inclusive at the beginning and end
879     Closed,
880 }
881
882 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
883 pub enum ExprKind {
884     /// A `box x` expression.
885     Box(P<Expr>),
886     /// First expr is the place; second expr is the value.
887     InPlace(P<Expr>, P<Expr>),
888     /// An array (`[a, b, c, d]`)
889     Vec(Vec<P<Expr>>),
890     /// A function call
891     ///
892     /// The first field resolves to the function itself,
893     /// and the second field is the list of arguments
894     Call(P<Expr>, Vec<P<Expr>>),
895     /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
896     ///
897     /// The `SpannedIdent` is the identifier for the method name.
898     /// The vector of `Ty`s are the ascripted type parameters for the method
899     /// (within the angle brackets).
900     ///
901     /// The first element of the vector of `Expr`s is the expression that evaluates
902     /// to the object on which the method is being called on (the receiver),
903     /// and the remaining elements are the rest of the arguments.
904     ///
905     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
906     /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
907     MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
908     /// A tuple (`(a, b, c ,d)`)
909     Tup(Vec<P<Expr>>),
910     /// A binary operation (For example: `a + b`, `a * b`)
911     Binary(BinOp, P<Expr>, P<Expr>),
912     /// A unary operation (For example: `!x`, `*x`)
913     Unary(UnOp, P<Expr>),
914     /// A literal (For example: `1`, `"foo"`)
915     Lit(P<Lit>),
916     /// A cast (`foo as f64`)
917     Cast(P<Expr>, P<Ty>),
918     Type(P<Expr>, P<Ty>),
919     /// An `if` block, with an optional else block
920     ///
921     /// `if expr { block } else { expr }`
922     If(P<Expr>, P<Block>, Option<P<Expr>>),
923     /// An `if let` expression with an optional else block
924     ///
925     /// `if let pat = expr { block } else { expr }`
926     ///
927     /// This is desugared to a `match` expression.
928     IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
929     /// A while loop, with an optional label
930     ///
931     /// `'label: while expr { block }`
932     While(P<Expr>, P<Block>, Option<SpannedIdent>),
933     /// A while-let loop, with an optional label
934     ///
935     /// `'label: while let pat = expr { block }`
936     ///
937     /// This is desugared to a combination of `loop` and `match` expressions.
938     WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
939     /// A for loop, with an optional label
940     ///
941     /// `'label: for pat in expr { block }`
942     ///
943     /// This is desugared to a combination of `loop` and `match` expressions.
944     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
945     /// Conditionless loop (can be exited with break, continue, or return)
946     ///
947     /// `'label: loop { block }`
948     Loop(P<Block>, Option<SpannedIdent>),
949     /// A `match` block.
950     Match(P<Expr>, Vec<Arm>),
951     /// A closure (for example, `move |a, b, c| {a + b + c}`)
952     ///
953     /// The final span is the span of the argument block `|...|`
954     Closure(CaptureBy, P<FnDecl>, P<Block>, Span),
955     /// A block (`{ ... }`)
956     Block(P<Block>),
957
958     /// An assignment (`a = foo()`)
959     Assign(P<Expr>, P<Expr>),
960     /// An assignment with an operator
961     ///
962     /// For example, `a += 1`.
963     AssignOp(BinOp, P<Expr>, P<Expr>),
964     /// Access of a named struct field (`obj.foo`)
965     Field(P<Expr>, SpannedIdent),
966     /// Access of an unnamed field of a struct or tuple-struct
967     ///
968     /// For example, `foo.0`.
969     TupField(P<Expr>, Spanned<usize>),
970     /// An indexing operation (`foo[2]`)
971     Index(P<Expr>, P<Expr>),
972     /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
973     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
974
975     /// Variable reference, possibly containing `::` and/or type
976     /// parameters, e.g. foo::bar::<baz>.
977     ///
978     /// Optionally "qualified",
979     /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
980     Path(Option<QSelf>, Path),
981
982     /// A referencing operation (`&a` or `&mut a`)
983     AddrOf(Mutability, P<Expr>),
984     /// A `break`, with an optional label to break
985     Break(Option<SpannedIdent>),
986     /// A `continue`, with an optional label
987     Continue(Option<SpannedIdent>),
988     /// A `return`, with an optional value to be returned
989     Ret(Option<P<Expr>>),
990
991     /// Output of the `asm!()` macro
992     InlineAsm(InlineAsm),
993
994     /// A macro invocation; pre-expansion
995     Mac(Mac),
996
997     /// A struct literal expression.
998     ///
999     /// For example, `Foo {x: 1, y: 2}`, or
1000     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1001     Struct(Path, Vec<Field>, Option<P<Expr>>),
1002
1003     /// An array literal constructed from one repeated element.
1004     ///
1005     /// For example, `[1; 5]`. The first expression is the element
1006     /// to be repeated; the second is the number of times to repeat it.
1007     Repeat(P<Expr>, P<Expr>),
1008
1009     /// No-op: used solely so we can pretty-print faithfully
1010     Paren(P<Expr>),
1011
1012     /// `expr?`
1013     Try(P<Expr>),
1014 }
1015
1016 /// The explicit Self type in a "qualified path". The actual
1017 /// path, including the trait and the associated item, is stored
1018 /// separately. `position` represents the index of the associated
1019 /// item qualified with this Self type.
1020 ///
1021 /// ```rust,ignore
1022 /// <Vec<T> as a::b::Trait>::AssociatedItem
1023 ///  ^~~~~     ~~~~~~~~~~~~~~^
1024 ///  ty        position = 3
1025 ///
1026 /// <Vec<T>>::AssociatedItem
1027 ///  ^~~~~    ^
1028 ///  ty       position = 0
1029 /// ```
1030 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1031 pub struct QSelf {
1032     pub ty: P<Ty>,
1033     pub position: usize
1034 }
1035
1036 /// A capture clause
1037 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1038 pub enum CaptureBy {
1039     Value,
1040     Ref,
1041 }
1042
1043 pub type Mac = Spanned<Mac_>;
1044
1045 /// Represents a macro invocation. The Path indicates which macro
1046 /// is being invoked, and the vector of token-trees contains the source
1047 /// of the macro invocation.
1048 ///
1049 /// NB: the additional ident for a macro_rules-style macro is actually
1050 /// stored in the enclosing item. Oog.
1051 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1052 pub struct Mac_ {
1053     pub path: Path,
1054     pub tts: Vec<TokenTree>,
1055 }
1056
1057 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1058 pub enum StrStyle {
1059     /// A regular string, like `"foo"`
1060     Cooked,
1061     /// A raw string, like `r##"foo"##`
1062     ///
1063     /// The uint is the number of `#` symbols used
1064     Raw(usize)
1065 }
1066
1067 /// A literal
1068 pub type Lit = Spanned<LitKind>;
1069
1070 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1071 pub enum LitIntType {
1072     Signed(IntTy),
1073     Unsigned(UintTy),
1074     Unsuffixed,
1075 }
1076
1077 /// Literal kind.
1078 ///
1079 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1080 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1081 pub enum LitKind {
1082     /// A string literal (`"foo"`)
1083     Str(InternedString, StrStyle),
1084     /// A byte string (`b"foo"`)
1085     ByteStr(Rc<Vec<u8>>),
1086     /// A byte char (`b'f'`)
1087     Byte(u8),
1088     /// A character literal (`'a'`)
1089     Char(char),
1090     /// An integer literal (`1`)
1091     Int(u64, LitIntType),
1092     /// A float literal (`1f64` or `1E10f64`)
1093     Float(InternedString, FloatTy),
1094     /// A float literal without a suffix (`1.0 or 1.0E10`)
1095     FloatUnsuffixed(InternedString),
1096     /// A boolean literal
1097     Bool(bool),
1098 }
1099
1100 impl LitKind {
1101     /// Returns true if this literal is a string and false otherwise.
1102     pub fn is_str(&self) -> bool {
1103         match *self {
1104             LitKind::Str(..) => true,
1105             _ => false,
1106         }
1107     }
1108 }
1109
1110 // NB: If you change this, you'll probably want to change the corresponding
1111 // type structure in middle/ty.rs as well.
1112 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1113 pub struct MutTy {
1114     pub ty: P<Ty>,
1115     pub mutbl: Mutability,
1116 }
1117
1118 /// Represents a method's signature in a trait declaration,
1119 /// or in an implementation.
1120 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1121 pub struct MethodSig {
1122     pub unsafety: Unsafety,
1123     pub constness: Constness,
1124     pub abi: Abi,
1125     pub decl: P<FnDecl>,
1126     pub generics: Generics,
1127 }
1128
1129 /// Represents an item declaration within a trait declaration,
1130 /// possibly including a default implementation. A trait item is
1131 /// either required (meaning it doesn't have an implementation, just a
1132 /// signature) or provided (meaning it has a default implementation).
1133 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1134 pub struct TraitItem {
1135     pub id: NodeId,
1136     pub ident: Ident,
1137     pub attrs: Vec<Attribute>,
1138     pub node: TraitItemKind,
1139     pub span: Span,
1140 }
1141
1142 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1143 pub enum TraitItemKind {
1144     Const(P<Ty>, Option<P<Expr>>),
1145     Method(MethodSig, Option<P<Block>>),
1146     Type(TyParamBounds, Option<P<Ty>>),
1147     Macro(Mac),
1148 }
1149
1150 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1151 pub struct ImplItem {
1152     pub id: NodeId,
1153     pub ident: Ident,
1154     pub vis: Visibility,
1155     pub defaultness: Defaultness,
1156     pub attrs: Vec<Attribute>,
1157     pub node: ImplItemKind,
1158     pub span: Span,
1159 }
1160
1161 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1162 pub enum ImplItemKind {
1163     Const(P<Ty>, P<Expr>),
1164     Method(MethodSig, P<Block>),
1165     Type(P<Ty>),
1166     Macro(Mac),
1167 }
1168
1169 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1170 pub enum IntTy {
1171     Is,
1172     I8,
1173     I16,
1174     I32,
1175     I64,
1176 }
1177
1178 impl fmt::Debug for IntTy {
1179     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1180         fmt::Display::fmt(self, f)
1181     }
1182 }
1183
1184 impl fmt::Display for IntTy {
1185     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1186         write!(f, "{}", self.ty_to_string())
1187     }
1188 }
1189
1190 impl IntTy {
1191     pub fn ty_to_string(&self) -> &'static str {
1192         match *self {
1193             IntTy::Is => "isize",
1194             IntTy::I8 => "i8",
1195             IntTy::I16 => "i16",
1196             IntTy::I32 => "i32",
1197             IntTy::I64 => "i64"
1198         }
1199     }
1200
1201     pub fn val_to_string(&self, val: i64) -> String {
1202         // cast to a u64 so we can correctly print INT64_MIN. All integral types
1203         // are parsed as u64, so we wouldn't want to print an extra negative
1204         // sign.
1205         format!("{}{}", val as u64, self.ty_to_string())
1206     }
1207
1208     pub fn ty_max(&self) -> u64 {
1209         match *self {
1210             IntTy::I8 => 0x80,
1211             IntTy::I16 => 0x8000,
1212             IntTy::Is | IntTy::I32 => 0x80000000, // FIXME: actually ni about Is
1213             IntTy::I64 => 0x8000000000000000
1214         }
1215     }
1216
1217     pub fn bit_width(&self) -> Option<usize> {
1218         Some(match *self {
1219             IntTy::Is => return None,
1220             IntTy::I8 => 8,
1221             IntTy::I16 => 16,
1222             IntTy::I32 => 32,
1223             IntTy::I64 => 64,
1224         })
1225     }
1226 }
1227
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1229 pub enum UintTy {
1230     Us,
1231     U8,
1232     U16,
1233     U32,
1234     U64,
1235 }
1236
1237 impl UintTy {
1238     pub fn ty_to_string(&self) -> &'static str {
1239         match *self {
1240             UintTy::Us => "usize",
1241             UintTy::U8 => "u8",
1242             UintTy::U16 => "u16",
1243             UintTy::U32 => "u32",
1244             UintTy::U64 => "u64"
1245         }
1246     }
1247
1248     pub fn val_to_string(&self, val: u64) -> String {
1249         format!("{}{}", val, self.ty_to_string())
1250     }
1251
1252     pub fn ty_max(&self) -> u64 {
1253         match *self {
1254             UintTy::U8 => 0xff,
1255             UintTy::U16 => 0xffff,
1256             UintTy::Us | UintTy::U32 => 0xffffffff, // FIXME: actually ni about Us
1257             UintTy::U64 => 0xffffffffffffffff
1258         }
1259     }
1260
1261     pub fn bit_width(&self) -> Option<usize> {
1262         Some(match *self {
1263             UintTy::Us => return None,
1264             UintTy::U8 => 8,
1265             UintTy::U16 => 16,
1266             UintTy::U32 => 32,
1267             UintTy::U64 => 64,
1268         })
1269     }
1270 }
1271
1272 impl fmt::Debug for UintTy {
1273     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1274         fmt::Display::fmt(self, f)
1275     }
1276 }
1277
1278 impl fmt::Display for UintTy {
1279     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1280         write!(f, "{}", self.ty_to_string())
1281     }
1282 }
1283
1284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1285 pub enum FloatTy {
1286     F32,
1287     F64,
1288 }
1289
1290 impl fmt::Debug for FloatTy {
1291     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1292         fmt::Display::fmt(self, f)
1293     }
1294 }
1295
1296 impl fmt::Display for FloatTy {
1297     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1298         write!(f, "{}", self.ty_to_string())
1299     }
1300 }
1301
1302 impl FloatTy {
1303     pub fn ty_to_string(&self) -> &'static str {
1304         match *self {
1305             FloatTy::F32 => "f32",
1306             FloatTy::F64 => "f64",
1307         }
1308     }
1309
1310     pub fn bit_width(&self) -> usize {
1311         match *self {
1312             FloatTy::F32 => 32,
1313             FloatTy::F64 => 64,
1314         }
1315     }
1316 }
1317
1318 // Bind a type to an associated type: `A=Foo`.
1319 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1320 pub struct TypeBinding {
1321     pub id: NodeId,
1322     pub ident: Ident,
1323     pub ty: P<Ty>,
1324     pub span: Span,
1325 }
1326
1327 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1328 pub struct Ty {
1329     pub id: NodeId,
1330     pub node: TyKind,
1331     pub span: Span,
1332 }
1333
1334 impl fmt::Debug for Ty {
1335     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1336         write!(f, "type({})", pprust::ty_to_string(self))
1337     }
1338 }
1339
1340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1341 pub struct BareFnTy {
1342     pub unsafety: Unsafety,
1343     pub abi: Abi,
1344     pub lifetimes: Vec<LifetimeDef>,
1345     pub decl: P<FnDecl>
1346 }
1347
1348 /// The different kinds of types recognized by the compiler
1349 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1350 pub enum TyKind {
1351     /// A variable-length array (`[T]`)
1352     Vec(P<Ty>),
1353     /// A fixed length array (`[T; n]`)
1354     FixedLengthVec(P<Ty>, P<Expr>),
1355     /// A raw pointer (`*const T` or `*mut T`)
1356     Ptr(MutTy),
1357     /// A reference (`&'a T` or `&'a mut T`)
1358     Rptr(Option<Lifetime>, MutTy),
1359     /// A bare function (e.g. `fn(usize) -> bool`)
1360     BareFn(P<BareFnTy>),
1361     /// The never type (`!`)
1362     Never,
1363     /// A tuple (`(A, B, C, D,...)`)
1364     Tup(Vec<P<Ty>> ),
1365     /// A path (`module::module::...::Type`), optionally
1366     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1367     ///
1368     /// Type parameters are stored in the Path itself
1369     Path(Option<QSelf>, Path),
1370     /// Something like `A+B`. Note that `B` must always be a path.
1371     ObjectSum(P<Ty>, TyParamBounds),
1372     /// A type like `for<'a> Foo<&'a Bar>`
1373     PolyTraitRef(TyParamBounds),
1374     /// An `impl TraitA+TraitB` type.
1375     ImplTrait(TyParamBounds),
1376     /// No-op; kept solely so that we can pretty-print faithfully
1377     Paren(P<Ty>),
1378     /// Unused for now
1379     Typeof(P<Expr>),
1380     /// TyKind::Infer means the type should be inferred instead of it having been
1381     /// specified. This can appear anywhere in a type.
1382     Infer,
1383     /// Inferred type of a `self` or `&self` argument in a method.
1384     ImplicitSelf,
1385     // A macro in the type position.
1386     Mac(Mac),
1387 }
1388
1389 /// Inline assembly dialect.
1390 ///
1391 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1393 pub enum AsmDialect {
1394     Att,
1395     Intel,
1396 }
1397
1398 /// Inline assembly.
1399 ///
1400 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1401 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1402 pub struct InlineAsmOutput {
1403     pub constraint: InternedString,
1404     pub expr: P<Expr>,
1405     pub is_rw: bool,
1406     pub is_indirect: bool,
1407 }
1408
1409 /// Inline assembly.
1410 ///
1411 /// E.g. `asm!("NOP");`
1412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1413 pub struct InlineAsm {
1414     pub asm: InternedString,
1415     pub asm_str_style: StrStyle,
1416     pub outputs: Vec<InlineAsmOutput>,
1417     pub inputs: Vec<(InternedString, P<Expr>)>,
1418     pub clobbers: Vec<InternedString>,
1419     pub volatile: bool,
1420     pub alignstack: bool,
1421     pub dialect: AsmDialect,
1422     pub expn_id: ExpnId,
1423 }
1424
1425 /// An argument in a function header.
1426 ///
1427 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1428 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1429 pub struct Arg {
1430     pub ty: P<Ty>,
1431     pub pat: P<Pat>,
1432     pub id: NodeId,
1433 }
1434
1435 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1436 ///
1437 /// E.g. `&mut self` as in `fn foo(&mut self)`
1438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1439 pub enum SelfKind {
1440     /// `self`, `mut self`
1441     Value(Mutability),
1442     /// `&'lt self`, `&'lt mut self`
1443     Region(Option<Lifetime>, Mutability),
1444     /// `self: TYPE`, `mut self: TYPE`
1445     Explicit(P<Ty>, Mutability),
1446 }
1447
1448 pub type ExplicitSelf = Spanned<SelfKind>;
1449
1450 impl Arg {
1451     pub fn to_self(&self) -> Option<ExplicitSelf> {
1452         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1453             if ident.node.name == keywords::SelfValue.name() {
1454                 return match self.ty.node {
1455                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1456                     TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1457                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1458                     }
1459                     _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1460                                      SelfKind::Explicit(self.ty.clone(), mutbl))),
1461                 }
1462             }
1463         }
1464         None
1465     }
1466
1467     pub fn is_self(&self) -> bool {
1468         if let PatKind::Ident(_, ident, _) = self.pat.node {
1469             ident.node.name == keywords::SelfValue.name()
1470         } else {
1471             false
1472         }
1473     }
1474
1475     pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1476         let infer_ty = P(Ty {
1477             id: DUMMY_NODE_ID,
1478             node: TyKind::ImplicitSelf,
1479             span: DUMMY_SP,
1480         });
1481         let arg = |mutbl, ty, span| Arg {
1482             pat: P(Pat {
1483                 id: DUMMY_NODE_ID,
1484                 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1485                 span: span,
1486             }),
1487             ty: ty,
1488             id: DUMMY_NODE_ID,
1489         };
1490         match eself.node {
1491             SelfKind::Explicit(ty, mutbl) => {
1492                 arg(mutbl, ty, mk_sp(eself.span.lo, eself_ident.span.hi))
1493             }
1494             SelfKind::Value(mutbl) => arg(mutbl, infer_ty, eself.span),
1495             SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1496                 id: DUMMY_NODE_ID,
1497                 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1498                 span: DUMMY_SP,
1499             }), eself.span),
1500         }
1501     }
1502 }
1503
1504 /// Header (not the body) of a function declaration.
1505 ///
1506 /// E.g. `fn foo(bar: baz)`
1507 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1508 pub struct FnDecl {
1509     pub inputs: Vec<Arg>,
1510     pub output: FunctionRetTy,
1511     pub variadic: bool
1512 }
1513
1514 impl FnDecl {
1515     pub fn get_self(&self) -> Option<ExplicitSelf> {
1516         self.inputs.get(0).and_then(Arg::to_self)
1517     }
1518     pub fn has_self(&self) -> bool {
1519         self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1520     }
1521 }
1522
1523 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1524 pub enum Unsafety {
1525     Unsafe,
1526     Normal,
1527 }
1528
1529 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1530 pub enum Constness {
1531     Const,
1532     NotConst,
1533 }
1534
1535 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub enum Defaultness {
1537     Default,
1538     Final,
1539 }
1540
1541 impl fmt::Display for Unsafety {
1542     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543         fmt::Display::fmt(match *self {
1544             Unsafety::Normal => "normal",
1545             Unsafety::Unsafe => "unsafe",
1546         }, f)
1547     }
1548 }
1549
1550 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1551 pub enum ImplPolarity {
1552     /// `impl Trait for Type`
1553     Positive,
1554     /// `impl !Trait for Type`
1555     Negative,
1556 }
1557
1558 impl fmt::Debug for ImplPolarity {
1559     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1560         match *self {
1561             ImplPolarity::Positive => "positive".fmt(f),
1562             ImplPolarity::Negative => "negative".fmt(f),
1563         }
1564     }
1565 }
1566
1567
1568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1569 pub enum FunctionRetTy {
1570     /// Return type is not specified.
1571     ///
1572     /// Functions default to `()` and
1573     /// closures default to inference. Span points to where return
1574     /// type would be inserted.
1575     Default(Span),
1576     /// Everything else
1577     Ty(P<Ty>),
1578 }
1579
1580 impl FunctionRetTy {
1581     pub fn span(&self) -> Span {
1582         match *self {
1583             FunctionRetTy::Default(span) => span,
1584             FunctionRetTy::Ty(ref ty) => ty.span,
1585         }
1586     }
1587 }
1588
1589 /// Module declaration.
1590 ///
1591 /// E.g. `mod foo;` or `mod foo { .. }`
1592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1593 pub struct Mod {
1594     /// A span from the first token past `{` to the last token until `}`.
1595     /// For `mod foo;`, the inner span ranges from the first token
1596     /// to the last token in the external file.
1597     pub inner: Span,
1598     pub items: Vec<P<Item>>,
1599 }
1600
1601 /// Foreign module declaration.
1602 ///
1603 /// E.g. `extern { .. }` or `extern C { .. }`
1604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1605 pub struct ForeignMod {
1606     pub abi: Abi,
1607     pub items: Vec<ForeignItem>,
1608 }
1609
1610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1611 pub struct EnumDef {
1612     pub variants: Vec<Variant>,
1613 }
1614
1615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1616 pub struct Variant_ {
1617     pub name: Ident,
1618     pub attrs: Vec<Attribute>,
1619     pub data: VariantData,
1620     /// Explicit discriminant, e.g. `Foo = 1`
1621     pub disr_expr: Option<P<Expr>>,
1622 }
1623
1624 pub type Variant = Spanned<Variant_>;
1625
1626 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1627 pub enum PathListItemKind {
1628     Ident {
1629         name: Ident,
1630         /// renamed in list, e.g. `use foo::{bar as baz};`
1631         rename: Option<Ident>,
1632         id: NodeId
1633     },
1634     Mod {
1635         /// renamed in list, e.g. `use foo::{self as baz};`
1636         rename: Option<Ident>,
1637         id: NodeId
1638     }
1639 }
1640
1641 impl PathListItemKind {
1642     pub fn id(&self) -> NodeId {
1643         match *self {
1644             PathListItemKind::Ident { id, .. } | PathListItemKind::Mod { id, .. } => id
1645         }
1646     }
1647
1648     pub fn name(&self) -> Option<Ident> {
1649         match *self {
1650             PathListItemKind::Ident { name, .. } => Some(name),
1651             PathListItemKind::Mod { .. } => None,
1652         }
1653     }
1654
1655     pub fn rename(&self) -> Option<Ident> {
1656         match *self {
1657             PathListItemKind::Ident { rename, .. } | PathListItemKind::Mod { rename, .. } => rename
1658         }
1659     }
1660 }
1661
1662 pub type PathListItem = Spanned<PathListItemKind>;
1663
1664 pub type ViewPath = Spanned<ViewPath_>;
1665
1666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1667 pub enum ViewPath_ {
1668
1669     /// `foo::bar::baz as quux`
1670     ///
1671     /// or just
1672     ///
1673     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1674     ViewPathSimple(Ident, Path),
1675
1676     /// `foo::bar::*`
1677     ViewPathGlob(Path),
1678
1679     /// `foo::bar::{a,b,c}`
1680     ViewPathList(Path, Vec<PathListItem>)
1681 }
1682
1683 impl ViewPath_ {
1684     pub fn path(&self) -> &Path {
1685         match *self {
1686             ViewPathSimple(_, ref path) |
1687             ViewPathGlob (ref path) |
1688             ViewPathList(ref path, _) => path
1689         }
1690     }
1691 }
1692
1693 /// Meta-data associated with an item
1694 pub type Attribute = Spanned<Attribute_>;
1695
1696 /// Distinguishes between Attributes that decorate items and Attributes that
1697 /// are contained as statements within items. These two cases need to be
1698 /// distinguished for pretty-printing.
1699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1700 pub enum AttrStyle {
1701     Outer,
1702     Inner,
1703 }
1704
1705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1706 pub struct AttrId(pub usize);
1707
1708 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1709 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1710 pub struct Attribute_ {
1711     pub id: AttrId,
1712     pub style: AttrStyle,
1713     pub value: P<MetaItem>,
1714     pub is_sugared_doc: bool,
1715 }
1716
1717 /// TraitRef's appear in impls.
1718 ///
1719 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1720 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1721 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1722 /// same as the impl's node id).
1723 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1724 pub struct TraitRef {
1725     pub path: Path,
1726     pub ref_id: NodeId,
1727 }
1728
1729 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1730 pub struct PolyTraitRef {
1731     /// The `'a` in `<'a> Foo<&'a T>`
1732     pub bound_lifetimes: Vec<LifetimeDef>,
1733
1734     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1735     pub trait_ref: TraitRef,
1736
1737     pub span: Span,
1738 }
1739
1740 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1741 pub enum Visibility {
1742     Public,
1743     Crate(Span),
1744     Restricted { path: P<Path>, id: NodeId },
1745     Inherited,
1746 }
1747
1748 /// Field of a struct.
1749 ///
1750 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1751 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1752 pub struct StructField {
1753     pub span: Span,
1754     pub ident: Option<Ident>,
1755     pub vis: Visibility,
1756     pub id: NodeId,
1757     pub ty: P<Ty>,
1758     pub attrs: Vec<Attribute>,
1759 }
1760
1761 /// Fields and Ids of enum variants and structs
1762 ///
1763 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1764 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1765 /// One shared Id can be successfully used for these two purposes.
1766 /// Id of the whole enum lives in `Item`.
1767 ///
1768 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1769 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1770 /// the variant itself" from enum variants.
1771 /// Id of the whole struct lives in `Item`.
1772 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1773 pub enum VariantData {
1774     /// Struct variant.
1775     ///
1776     /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1777     Struct(Vec<StructField>, NodeId),
1778     /// Tuple variant.
1779     ///
1780     /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1781     Tuple(Vec<StructField>, NodeId),
1782     /// Unit variant.
1783     ///
1784     /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1785     Unit(NodeId),
1786 }
1787
1788 impl VariantData {
1789     pub fn fields(&self) -> &[StructField] {
1790         match *self {
1791             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1792             _ => &[],
1793         }
1794     }
1795     pub fn id(&self) -> NodeId {
1796         match *self {
1797             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1798         }
1799     }
1800     pub fn is_struct(&self) -> bool {
1801         if let VariantData::Struct(..) = *self { true } else { false }
1802     }
1803     pub fn is_tuple(&self) -> bool {
1804         if let VariantData::Tuple(..) = *self { true } else { false }
1805     }
1806     pub fn is_unit(&self) -> bool {
1807         if let VariantData::Unit(..) = *self { true } else { false }
1808     }
1809 }
1810
1811 /*
1812   FIXME (#3300): Should allow items to be anonymous. Right now
1813   we just use dummy names for anon items.
1814  */
1815 /// An item
1816 ///
1817 /// The name might be a dummy name in case of anonymous items
1818 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1819 pub struct Item {
1820     pub ident: Ident,
1821     pub attrs: Vec<Attribute>,
1822     pub id: NodeId,
1823     pub node: ItemKind,
1824     pub vis: Visibility,
1825     pub span: Span,
1826 }
1827
1828 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1829 pub enum ItemKind {
1830     /// An`extern crate` item, with optional original crate name.
1831     ///
1832     /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1833     ExternCrate(Option<Name>),
1834     /// A use declaration (`use` or `pub use`) item.
1835     ///
1836     /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1837     Use(P<ViewPath>),
1838     /// A static item (`static` or `pub static`).
1839     ///
1840     /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1841     Static(P<Ty>, Mutability, P<Expr>),
1842     /// A constant item (`const` or `pub const`).
1843     ///
1844     /// E.g. `const FOO: i32 = 42;`
1845     Const(P<Ty>, P<Expr>),
1846     /// A function declaration (`fn` or `pub fn`).
1847     ///
1848     /// E.g. `fn foo(bar: usize) -> usize { .. }`
1849     Fn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1850     /// A module declaration (`mod` or `pub mod`).
1851     ///
1852     /// E.g. `mod foo;` or `mod foo { .. }`
1853     Mod(Mod),
1854     /// An external module (`extern` or `pub extern`).
1855     ///
1856     /// E.g. `extern {}` or `extern "C" {}`
1857     ForeignMod(ForeignMod),
1858     /// A type alias (`type` or `pub type`).
1859     ///
1860     /// E.g. `type Foo = Bar<u8>;`
1861     Ty(P<Ty>, Generics),
1862     /// An enum definition (`enum` or `pub enum`).
1863     ///
1864     /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1865     Enum(EnumDef, Generics),
1866     /// A struct definition (`struct` or `pub struct`).
1867     ///
1868     /// E.g. `struct Foo<A> { x: A }`
1869     Struct(VariantData, Generics),
1870     /// A Trait declaration (`trait` or `pub trait`).
1871     ///
1872     /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1873     Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1874     // Default trait implementation.
1875     ///
1876     /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1877     DefaultImpl(Unsafety, TraitRef),
1878     /// An implementation.
1879     ///
1880     /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1881     Impl(Unsafety,
1882              ImplPolarity,
1883              Generics,
1884              Option<TraitRef>, // (optional) trait this impl implements
1885              P<Ty>, // self
1886              Vec<ImplItem>),
1887     /// A macro invocation (which includes macro definition).
1888     ///
1889     /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1890     Mac(Mac),
1891 }
1892
1893 impl ItemKind {
1894     pub fn descriptive_variant(&self) -> &str {
1895         match *self {
1896             ItemKind::ExternCrate(..) => "extern crate",
1897             ItemKind::Use(..) => "use",
1898             ItemKind::Static(..) => "static item",
1899             ItemKind::Const(..) => "constant item",
1900             ItemKind::Fn(..) => "function",
1901             ItemKind::Mod(..) => "module",
1902             ItemKind::ForeignMod(..) => "foreign module",
1903             ItemKind::Ty(..) => "type alias",
1904             ItemKind::Enum(..) => "enum",
1905             ItemKind::Struct(..) => "struct",
1906             ItemKind::Trait(..) => "trait",
1907             ItemKind::Mac(..) |
1908             ItemKind::Impl(..) |
1909             ItemKind::DefaultImpl(..) => "item"
1910         }
1911     }
1912 }
1913
1914 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1915 pub struct ForeignItem {
1916     pub ident: Ident,
1917     pub attrs: Vec<Attribute>,
1918     pub node: ForeignItemKind,
1919     pub id: NodeId,
1920     pub span: Span,
1921     pub vis: Visibility,
1922 }
1923
1924 /// An item within an `extern` block
1925 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1926 pub enum ForeignItemKind {
1927     /// A foreign function
1928     Fn(P<FnDecl>, Generics),
1929     /// A foreign static item (`static ext: u8`), with optional mutability
1930     /// (the boolean is true when mutable)
1931     Static(P<Ty>, bool),
1932 }
1933
1934 impl ForeignItemKind {
1935     pub fn descriptive_variant(&self) -> &str {
1936         match *self {
1937             ForeignItemKind::Fn(..) => "foreign function",
1938             ForeignItemKind::Static(..) => "foreign static item"
1939         }
1940     }
1941 }
1942
1943 /// A macro definition, in this crate or imported from another.
1944 ///
1945 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1946 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1947 pub struct MacroDef {
1948     pub ident: Ident,
1949     pub attrs: Vec<Attribute>,
1950     pub id: NodeId,
1951     pub span: Span,
1952     pub imported_from: Option<Ident>,
1953     pub export: bool,
1954     pub use_locally: bool,
1955     pub allow_internal_unstable: bool,
1956     pub body: Vec<TokenTree>,
1957 }
1958
1959 #[cfg(test)]
1960 mod tests {
1961     use serialize;
1962     use super::*;
1963
1964     // are ASTs encodable?
1965     #[test]
1966     fn check_asts_encodable() {
1967         fn assert_encodable<T: serialize::Encodable>() {}
1968         assert_encodable::<Crate>();
1969     }
1970 }