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