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