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