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