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