]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
bc457f49fcffda325941eeae5760eb4f77818114
[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 rustc_target::spec::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(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`
478 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
479 pub struct MetaItem {
480     pub name: Path,
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::Item(_) => 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::Index(..) => ExprPrecedence::Index,
1022             ExprKind::Range(..) => ExprPrecedence::Range,
1023             ExprKind::Path(..) => ExprPrecedence::Path,
1024             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1025             ExprKind::Break(..) => ExprPrecedence::Break,
1026             ExprKind::Continue(..) => ExprPrecedence::Continue,
1027             ExprKind::Ret(..) => ExprPrecedence::Ret,
1028             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1029             ExprKind::Mac(..) => ExprPrecedence::Mac,
1030             ExprKind::Struct(..) => ExprPrecedence::Struct,
1031             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1032             ExprKind::Paren(..) => ExprPrecedence::Paren,
1033             ExprKind::Try(..) => ExprPrecedence::Try,
1034             ExprKind::Yield(..) => ExprPrecedence::Yield,
1035         }
1036     }
1037 }
1038
1039 impl fmt::Debug for Expr {
1040     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1041         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1042     }
1043 }
1044
1045 /// Limit types of a range (inclusive or exclusive)
1046 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1047 pub enum RangeLimits {
1048     /// Inclusive at the beginning, exclusive at the end
1049     HalfOpen,
1050     /// Inclusive at the beginning and end
1051     Closed,
1052 }
1053
1054 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1055 pub enum ExprKind {
1056     /// A `box x` expression.
1057     Box(P<Expr>),
1058     /// An array (`[a, b, c, d]`)
1059     Array(Vec<P<Expr>>),
1060     /// A function call
1061     ///
1062     /// The first field resolves to the function itself,
1063     /// and the second field is the list of arguments.
1064     /// This also represents calling the constructor of
1065     /// tuple-like ADTs such as tuple structs and enum variants.
1066     Call(P<Expr>, Vec<P<Expr>>),
1067     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1068     ///
1069     /// The `PathSegment` represents the method name and its generic arguments
1070     /// (within the angle brackets).
1071     /// The first element of the vector of `Expr`s is the expression that evaluates
1072     /// to the object on which the method is being called on (the receiver),
1073     /// and the remaining elements are the rest of the arguments.
1074     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1075     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1076     MethodCall(PathSegment, Vec<P<Expr>>),
1077     /// A tuple (`(a, b, c ,d)`)
1078     Tup(Vec<P<Expr>>),
1079     /// A binary operation (For example: `a + b`, `a * b`)
1080     Binary(BinOp, P<Expr>, P<Expr>),
1081     /// A unary operation (For example: `!x`, `*x`)
1082     Unary(UnOp, P<Expr>),
1083     /// A literal (For example: `1`, `"foo"`)
1084     Lit(P<Lit>),
1085     /// A cast (`foo as f64`)
1086     Cast(P<Expr>, P<Ty>),
1087     Type(P<Expr>, P<Ty>),
1088     /// An `if` block, with an optional else block
1089     ///
1090     /// `if expr { block } else { expr }`
1091     If(P<Expr>, P<Block>, Option<P<Expr>>),
1092     /// An `if let` expression with an optional else block
1093     ///
1094     /// `if let pat = expr { block } else { expr }`
1095     ///
1096     /// This is desugared to a `match` expression.
1097     IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1098     /// A while loop, with an optional label
1099     ///
1100     /// `'label: while expr { block }`
1101     While(P<Expr>, P<Block>, Option<Label>),
1102     /// A while-let loop, with an optional label
1103     ///
1104     /// `'label: while let pat = expr { block }`
1105     ///
1106     /// This is desugared to a combination of `loop` and `match` expressions.
1107     WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1108     /// A for loop, with an optional label
1109     ///
1110     /// `'label: for pat in expr { block }`
1111     ///
1112     /// This is desugared to a combination of `loop` and `match` expressions.
1113     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1114     /// Conditionless loop (can be exited with break, continue, or return)
1115     ///
1116     /// `'label: loop { block }`
1117     Loop(P<Block>, Option<Label>),
1118     /// A `match` block.
1119     Match(P<Expr>, Vec<Arm>),
1120     /// A closure (for example, `move |a, b, c| a + b + c`)
1121     ///
1122     /// The final span is the span of the argument block `|...|`
1123     Closure(CaptureBy, Movability, P<FnDecl>, P<Expr>, Span),
1124     /// A block (`{ ... }`)
1125     Block(P<Block>),
1126     /// A catch block (`catch { ... }`)
1127     Catch(P<Block>),
1128
1129     /// An assignment (`a = foo()`)
1130     Assign(P<Expr>, P<Expr>),
1131     /// An assignment with an operator
1132     ///
1133     /// For example, `a += 1`.
1134     AssignOp(BinOp, P<Expr>, P<Expr>),
1135     /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct field
1136     Field(P<Expr>, Ident),
1137     /// An indexing operation (`foo[2]`)
1138     Index(P<Expr>, P<Expr>),
1139     /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
1140     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1141
1142     /// Variable reference, possibly containing `::` and/or type
1143     /// parameters, e.g. foo::bar::<baz>.
1144     ///
1145     /// Optionally "qualified",
1146     /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1147     Path(Option<QSelf>, Path),
1148
1149     /// A referencing operation (`&a` or `&mut a`)
1150     AddrOf(Mutability, P<Expr>),
1151     /// A `break`, with an optional label to break, and an optional expression
1152     Break(Option<Label>, Option<P<Expr>>),
1153     /// A `continue`, with an optional label
1154     Continue(Option<Label>),
1155     /// A `return`, with an optional value to be returned
1156     Ret(Option<P<Expr>>),
1157
1158     /// Output of the `asm!()` macro
1159     InlineAsm(P<InlineAsm>),
1160
1161     /// A macro invocation; pre-expansion
1162     Mac(Mac),
1163
1164     /// A struct literal expression.
1165     ///
1166     /// For example, `Foo {x: 1, y: 2}`, or
1167     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1168     Struct(Path, Vec<Field>, Option<P<Expr>>),
1169
1170     /// An array literal constructed from one repeated element.
1171     ///
1172     /// For example, `[1; 5]`. The first expression is the element
1173     /// to be repeated; the second is the number of times to repeat it.
1174     Repeat(P<Expr>, P<Expr>),
1175
1176     /// No-op: used solely so we can pretty-print faithfully
1177     Paren(P<Expr>),
1178
1179     /// `expr?`
1180     Try(P<Expr>),
1181
1182     /// A `yield`, with an optional value to be yielded
1183     Yield(Option<P<Expr>>),
1184 }
1185
1186 /// The explicit Self type in a "qualified path". The actual
1187 /// path, including the trait and the associated item, is stored
1188 /// separately. `position` represents the index of the associated
1189 /// item qualified with this Self type.
1190 ///
1191 /// ```ignore (only-for-syntax-highlight)
1192 /// <Vec<T> as a::b::Trait>::AssociatedItem
1193 ///  ^~~~~     ~~~~~~~~~~~~~~^
1194 ///  ty        position = 3
1195 ///
1196 /// <Vec<T>>::AssociatedItem
1197 ///  ^~~~~    ^
1198 ///  ty       position = 0
1199 /// ```
1200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1201 pub struct QSelf {
1202     pub ty: P<Ty>,
1203     pub position: usize
1204 }
1205
1206 /// A capture clause
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1208 pub enum CaptureBy {
1209     Value,
1210     Ref,
1211 }
1212
1213 /// The movability of a generator / closure literal
1214 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1215 pub enum Movability {
1216     Static,
1217     Movable,
1218 }
1219
1220 pub type Mac = Spanned<Mac_>;
1221
1222 /// Represents a macro invocation. The Path indicates which macro
1223 /// is being invoked, and the vector of token-trees contains the source
1224 /// of the macro invocation.
1225 ///
1226 /// NB: the additional ident for a macro_rules-style macro is actually
1227 /// stored in the enclosing item. Oog.
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1229 pub struct Mac_ {
1230     pub path: Path,
1231     pub tts: ThinTokenStream,
1232 }
1233
1234 impl Mac_ {
1235     pub fn stream(&self) -> TokenStream {
1236         self.tts.clone().into()
1237     }
1238 }
1239
1240 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1241 pub struct MacroDef {
1242     pub tokens: ThinTokenStream,
1243     pub legacy: bool,
1244 }
1245
1246 impl MacroDef {
1247     pub fn stream(&self) -> TokenStream {
1248         self.tokens.clone().into()
1249     }
1250 }
1251
1252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1253 pub enum StrStyle {
1254     /// A regular string, like `"foo"`
1255     Cooked,
1256     /// A raw string, like `r##"foo"##`
1257     ///
1258     /// The value is the number of `#` symbols used.
1259     Raw(u16)
1260 }
1261
1262 /// A literal
1263 pub type Lit = Spanned<LitKind>;
1264
1265 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1266 pub enum LitIntType {
1267     Signed(IntTy),
1268     Unsigned(UintTy),
1269     Unsuffixed,
1270 }
1271
1272 /// Literal kind.
1273 ///
1274 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1275 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1276 pub enum LitKind {
1277     /// A string literal (`"foo"`)
1278     Str(Symbol, StrStyle),
1279     /// A byte string (`b"foo"`)
1280     ByteStr(Lrc<Vec<u8>>),
1281     /// A byte char (`b'f'`)
1282     Byte(u8),
1283     /// A character literal (`'a'`)
1284     Char(char),
1285     /// An integer literal (`1`)
1286     Int(u128, LitIntType),
1287     /// A float literal (`1f64` or `1E10f64`)
1288     Float(Symbol, FloatTy),
1289     /// A float literal without a suffix (`1.0 or 1.0E10`)
1290     FloatUnsuffixed(Symbol),
1291     /// A boolean literal
1292     Bool(bool),
1293 }
1294
1295 impl LitKind {
1296     /// Returns true if this literal is a string and false otherwise.
1297     pub fn is_str(&self) -> bool {
1298         match *self {
1299             LitKind::Str(..) => true,
1300             _ => false,
1301         }
1302     }
1303
1304     /// Returns true if this literal has no suffix. Note: this will return true
1305     /// for literals with prefixes such as raw strings and byte strings.
1306     pub fn is_unsuffixed(&self) -> bool {
1307         match *self {
1308             // unsuffixed variants
1309             LitKind::Str(..) |
1310             LitKind::ByteStr(..) |
1311             LitKind::Byte(..) |
1312             LitKind::Char(..) |
1313             LitKind::Int(_, LitIntType::Unsuffixed) |
1314             LitKind::FloatUnsuffixed(..) |
1315             LitKind::Bool(..) => true,
1316             // suffixed variants
1317             LitKind::Int(_, LitIntType::Signed(..)) |
1318             LitKind::Int(_, LitIntType::Unsigned(..)) |
1319             LitKind::Float(..) => false,
1320         }
1321     }
1322
1323     /// Returns true if this literal has a suffix.
1324     pub fn is_suffixed(&self) -> bool {
1325         !self.is_unsuffixed()
1326     }
1327 }
1328
1329 // NB: If you change this, you'll probably want to change the corresponding
1330 // type structure in middle/ty.rs as well.
1331 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1332 pub struct MutTy {
1333     pub ty: P<Ty>,
1334     pub mutbl: Mutability,
1335 }
1336
1337 /// Represents a method's signature in a trait declaration,
1338 /// or in an implementation.
1339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1340 pub struct MethodSig {
1341     pub unsafety: Unsafety,
1342     pub constness: Spanned<Constness>,
1343     pub abi: Abi,
1344     pub decl: P<FnDecl>,
1345 }
1346
1347 /// Represents an item declaration within a trait declaration,
1348 /// possibly including a default implementation. A trait item is
1349 /// either required (meaning it doesn't have an implementation, just a
1350 /// signature) or provided (meaning it has a default implementation).
1351 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1352 pub struct TraitItem {
1353     pub id: NodeId,
1354     pub ident: Ident,
1355     pub attrs: Vec<Attribute>,
1356     pub generics: Generics,
1357     pub node: TraitItemKind,
1358     pub span: Span,
1359     /// See `Item::tokens` for what this is
1360     pub tokens: Option<TokenStream>,
1361 }
1362
1363 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1364 pub enum TraitItemKind {
1365     Const(P<Ty>, Option<P<Expr>>),
1366     Method(MethodSig, Option<P<Block>>),
1367     Type(TyParamBounds, Option<P<Ty>>),
1368     Macro(Mac),
1369 }
1370
1371 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1372 pub struct ImplItem {
1373     pub id: NodeId,
1374     pub ident: Ident,
1375     pub vis: Visibility,
1376     pub defaultness: Defaultness,
1377     pub attrs: Vec<Attribute>,
1378     pub generics: Generics,
1379     pub node: ImplItemKind,
1380     pub span: Span,
1381     /// See `Item::tokens` for what this is
1382     pub tokens: Option<TokenStream>,
1383 }
1384
1385 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1386 pub enum ImplItemKind {
1387     Const(P<Ty>, P<Expr>),
1388     Method(MethodSig, P<Block>),
1389     Type(P<Ty>),
1390     Macro(Mac),
1391 }
1392
1393 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1394          PartialOrd, Ord)]
1395 pub enum IntTy {
1396     Isize,
1397     I8,
1398     I16,
1399     I32,
1400     I64,
1401     I128,
1402 }
1403
1404 impl fmt::Debug for IntTy {
1405     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1406         fmt::Display::fmt(self, f)
1407     }
1408 }
1409
1410 impl fmt::Display for IntTy {
1411     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1412         write!(f, "{}", self.ty_to_string())
1413     }
1414 }
1415
1416 impl IntTy {
1417     pub fn ty_to_string(&self) -> &'static str {
1418         match *self {
1419             IntTy::Isize => "isize",
1420             IntTy::I8 => "i8",
1421             IntTy::I16 => "i16",
1422             IntTy::I32 => "i32",
1423             IntTy::I64 => "i64",
1424             IntTy::I128 => "i128",
1425         }
1426     }
1427
1428     pub fn val_to_string(&self, val: i128) -> String {
1429         // cast to a u128 so we can correctly print INT128_MIN. All integral types
1430         // are parsed as u128, so we wouldn't want to print an extra negative
1431         // sign.
1432         format!("{}{}", val as u128, self.ty_to_string())
1433     }
1434
1435     pub fn bit_width(&self) -> Option<usize> {
1436         Some(match *self {
1437             IntTy::Isize => return None,
1438             IntTy::I8 => 8,
1439             IntTy::I16 => 16,
1440             IntTy::I32 => 32,
1441             IntTy::I64 => 64,
1442             IntTy::I128 => 128,
1443         })
1444     }
1445 }
1446
1447 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1448          PartialOrd, Ord)]
1449 pub enum UintTy {
1450     Usize,
1451     U8,
1452     U16,
1453     U32,
1454     U64,
1455     U128,
1456 }
1457
1458 impl UintTy {
1459     pub fn ty_to_string(&self) -> &'static str {
1460         match *self {
1461             UintTy::Usize => "usize",
1462             UintTy::U8 => "u8",
1463             UintTy::U16 => "u16",
1464             UintTy::U32 => "u32",
1465             UintTy::U64 => "u64",
1466             UintTy::U128 => "u128",
1467         }
1468     }
1469
1470     pub fn val_to_string(&self, val: u128) -> String {
1471         format!("{}{}", val, self.ty_to_string())
1472     }
1473
1474     pub fn bit_width(&self) -> Option<usize> {
1475         Some(match *self {
1476             UintTy::Usize => return None,
1477             UintTy::U8 => 8,
1478             UintTy::U16 => 16,
1479             UintTy::U32 => 32,
1480             UintTy::U64 => 64,
1481             UintTy::U128 => 128,
1482         })
1483     }
1484 }
1485
1486 impl fmt::Debug for UintTy {
1487     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1488         fmt::Display::fmt(self, f)
1489     }
1490 }
1491
1492 impl fmt::Display for UintTy {
1493     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1494         write!(f, "{}", self.ty_to_string())
1495     }
1496 }
1497
1498 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1499          PartialOrd, Ord)]
1500 pub enum FloatTy {
1501     F32,
1502     F64,
1503 }
1504
1505 impl fmt::Debug for FloatTy {
1506     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1507         fmt::Display::fmt(self, f)
1508     }
1509 }
1510
1511 impl fmt::Display for FloatTy {
1512     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1513         write!(f, "{}", self.ty_to_string())
1514     }
1515 }
1516
1517 impl FloatTy {
1518     pub fn ty_to_string(&self) -> &'static str {
1519         match *self {
1520             FloatTy::F32 => "f32",
1521             FloatTy::F64 => "f64",
1522         }
1523     }
1524
1525     pub fn bit_width(&self) -> usize {
1526         match *self {
1527             FloatTy::F32 => 32,
1528             FloatTy::F64 => 64,
1529         }
1530     }
1531 }
1532
1533 // Bind a type to an associated type: `A=Foo`.
1534 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1535 pub struct TypeBinding {
1536     pub id: NodeId,
1537     pub ident: Ident,
1538     pub ty: P<Ty>,
1539     pub span: Span,
1540 }
1541
1542 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1543 pub struct Ty {
1544     pub id: NodeId,
1545     pub node: TyKind,
1546     pub span: Span,
1547 }
1548
1549 impl fmt::Debug for Ty {
1550     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1551         write!(f, "type({})", pprust::ty_to_string(self))
1552     }
1553 }
1554
1555 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1556 pub struct BareFnTy {
1557     pub unsafety: Unsafety,
1558     pub abi: Abi,
1559     pub generic_params: Vec<GenericParam>,
1560     pub decl: P<FnDecl>
1561 }
1562
1563 /// The different kinds of types recognized by the compiler
1564 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1565 pub enum TyKind {
1566     /// A variable-length slice (`[T]`)
1567     Slice(P<Ty>),
1568     /// A fixed length array (`[T; n]`)
1569     Array(P<Ty>, P<Expr>),
1570     /// A raw pointer (`*const T` or `*mut T`)
1571     Ptr(MutTy),
1572     /// A reference (`&'a T` or `&'a mut T`)
1573     Rptr(Option<Lifetime>, MutTy),
1574     /// A bare function (e.g. `fn(usize) -> bool`)
1575     BareFn(P<BareFnTy>),
1576     /// The never type (`!`)
1577     Never,
1578     /// A tuple (`(A, B, C, D,...)`)
1579     Tup(Vec<P<Ty>> ),
1580     /// A path (`module::module::...::Type`), optionally
1581     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1582     ///
1583     /// Type parameters are stored in the Path itself
1584     Path(Option<QSelf>, Path),
1585     /// A trait object type `Bound1 + Bound2 + Bound3`
1586     /// where `Bound` is a trait or a lifetime.
1587     TraitObject(TyParamBounds, TraitObjectSyntax),
1588     /// An `impl Bound1 + Bound2 + Bound3` type
1589     /// where `Bound` is a trait or a lifetime.
1590     ImplTrait(TyParamBounds),
1591     /// No-op; kept solely so that we can pretty-print faithfully
1592     Paren(P<Ty>),
1593     /// Unused for now
1594     Typeof(P<Expr>),
1595     /// TyKind::Infer means the type should be inferred instead of it having been
1596     /// specified. This can appear anywhere in a type.
1597     Infer,
1598     /// Inferred type of a `self` or `&self` argument in a method.
1599     ImplicitSelf,
1600     // A macro in the type position.
1601     Mac(Mac),
1602     /// Placeholder for a kind that has failed to be defined.
1603     Err,
1604 }
1605
1606 /// Syntax used to declare a trait object.
1607 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1608 pub enum TraitObjectSyntax {
1609     Dyn,
1610     None,
1611 }
1612
1613 /// Inline assembly dialect.
1614 ///
1615 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1617 pub enum AsmDialect {
1618     Att,
1619     Intel,
1620 }
1621
1622 /// Inline assembly.
1623 ///
1624 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1626 pub struct InlineAsmOutput {
1627     pub constraint: Symbol,
1628     pub expr: P<Expr>,
1629     pub is_rw: bool,
1630     pub is_indirect: bool,
1631 }
1632
1633 /// Inline assembly.
1634 ///
1635 /// E.g. `asm!("NOP");`
1636 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1637 pub struct InlineAsm {
1638     pub asm: Symbol,
1639     pub asm_str_style: StrStyle,
1640     pub outputs: Vec<InlineAsmOutput>,
1641     pub inputs: Vec<(Symbol, P<Expr>)>,
1642     pub clobbers: Vec<Symbol>,
1643     pub volatile: bool,
1644     pub alignstack: bool,
1645     pub dialect: AsmDialect,
1646     pub ctxt: SyntaxContext,
1647 }
1648
1649 /// An argument in a function header.
1650 ///
1651 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1652 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1653 pub struct Arg {
1654     pub ty: P<Ty>,
1655     pub pat: P<Pat>,
1656     pub id: NodeId,
1657 }
1658
1659 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1660 ///
1661 /// E.g. `&mut self` as in `fn foo(&mut self)`
1662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1663 pub enum SelfKind {
1664     /// `self`, `mut self`
1665     Value(Mutability),
1666     /// `&'lt self`, `&'lt mut self`
1667     Region(Option<Lifetime>, Mutability),
1668     /// `self: TYPE`, `mut self: TYPE`
1669     Explicit(P<Ty>, Mutability),
1670 }
1671
1672 pub type ExplicitSelf = Spanned<SelfKind>;
1673
1674 impl Arg {
1675     pub fn to_self(&self) -> Option<ExplicitSelf> {
1676         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1677             if ident.name == keywords::SelfValue.name() {
1678                 return match self.ty.node {
1679                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1680                     TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1681                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1682                     }
1683                     _ => Some(respan(self.pat.span.to(self.ty.span),
1684                                      SelfKind::Explicit(self.ty.clone(), mutbl))),
1685                 }
1686             }
1687         }
1688         None
1689     }
1690
1691     pub fn is_self(&self) -> bool {
1692         if let PatKind::Ident(_, ident, _) = self.pat.node {
1693             ident.name == keywords::SelfValue.name()
1694         } else {
1695             false
1696         }
1697     }
1698
1699     pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1700         let span = eself.span.to(eself_ident.span);
1701         let infer_ty = P(Ty {
1702             id: DUMMY_NODE_ID,
1703             node: TyKind::ImplicitSelf,
1704             span,
1705         });
1706         let arg = |mutbl, ty| Arg {
1707             pat: P(Pat {
1708                 id: DUMMY_NODE_ID,
1709                 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1710                 span,
1711             }),
1712             ty,
1713             id: DUMMY_NODE_ID,
1714         };
1715         match eself.node {
1716             SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1717             SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1718             SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1719                 id: DUMMY_NODE_ID,
1720                 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1721                 span,
1722             })),
1723         }
1724     }
1725 }
1726
1727 /// Header (not the body) of a function declaration.
1728 ///
1729 /// E.g. `fn foo(bar: baz)`
1730 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1731 pub struct FnDecl {
1732     pub inputs: Vec<Arg>,
1733     pub output: FunctionRetTy,
1734     pub variadic: bool
1735 }
1736
1737 impl FnDecl {
1738     pub fn get_self(&self) -> Option<ExplicitSelf> {
1739         self.inputs.get(0).and_then(Arg::to_self)
1740     }
1741     pub fn has_self(&self) -> bool {
1742         self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1743     }
1744 }
1745
1746 /// Is the trait definition an auto trait?
1747 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1748 pub enum IsAuto {
1749     Yes,
1750     No
1751 }
1752
1753 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1754 pub enum Unsafety {
1755     Unsafe,
1756     Normal,
1757 }
1758
1759 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1760 pub enum Constness {
1761     Const,
1762     NotConst,
1763 }
1764
1765 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1766 pub enum Defaultness {
1767     Default,
1768     Final,
1769 }
1770
1771 impl fmt::Display for Unsafety {
1772     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1773         fmt::Display::fmt(match *self {
1774             Unsafety::Normal => "normal",
1775             Unsafety::Unsafe => "unsafe",
1776         }, f)
1777     }
1778 }
1779
1780 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1781 pub enum ImplPolarity {
1782     /// `impl Trait for Type`
1783     Positive,
1784     /// `impl !Trait for Type`
1785     Negative,
1786 }
1787
1788 impl fmt::Debug for ImplPolarity {
1789     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1790         match *self {
1791             ImplPolarity::Positive => "positive".fmt(f),
1792             ImplPolarity::Negative => "negative".fmt(f),
1793         }
1794     }
1795 }
1796
1797
1798 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1799 pub enum FunctionRetTy {
1800     /// Return type is not specified.
1801     ///
1802     /// Functions default to `()` and
1803     /// closures default to inference. Span points to where return
1804     /// type would be inserted.
1805     Default(Span),
1806     /// Everything else
1807     Ty(P<Ty>),
1808 }
1809
1810 impl FunctionRetTy {
1811     pub fn span(&self) -> Span {
1812         match *self {
1813             FunctionRetTy::Default(span) => span,
1814             FunctionRetTy::Ty(ref ty) => ty.span,
1815         }
1816     }
1817 }
1818
1819 /// Module declaration.
1820 ///
1821 /// E.g. `mod foo;` or `mod foo { .. }`
1822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1823 pub struct Mod {
1824     /// A span from the first token past `{` to the last token until `}`.
1825     /// For `mod foo;`, the inner span ranges from the first token
1826     /// to the last token in the external file.
1827     pub inner: Span,
1828     pub items: Vec<P<Item>>,
1829 }
1830
1831 /// Foreign module declaration.
1832 ///
1833 /// E.g. `extern { .. }` or `extern C { .. }`
1834 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1835 pub struct ForeignMod {
1836     pub abi: Abi,
1837     pub items: Vec<ForeignItem>,
1838 }
1839
1840 /// Global inline assembly
1841 ///
1842 /// aka module-level assembly or file-scoped assembly
1843 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1844 pub struct GlobalAsm {
1845     pub asm: Symbol,
1846     pub ctxt: SyntaxContext,
1847 }
1848
1849 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1850 pub struct EnumDef {
1851     pub variants: Vec<Variant>,
1852 }
1853
1854 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1855 pub struct Variant_ {
1856     pub ident: Ident,
1857     pub attrs: Vec<Attribute>,
1858     pub data: VariantData,
1859     /// Explicit discriminant, e.g. `Foo = 1`
1860     pub disr_expr: Option<P<Expr>>,
1861 }
1862
1863 pub type Variant = Spanned<Variant_>;
1864
1865 /// Part of `use` item to the right of its prefix.
1866 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1867 pub enum UseTreeKind {
1868     /// `use prefix` or `use prefix as rename`
1869     Simple(Option<Ident>),
1870     /// `use prefix::{...}`
1871     Nested(Vec<(UseTree, NodeId)>),
1872     /// `use prefix::*`
1873     Glob,
1874 }
1875
1876 /// A tree of paths sharing common prefixes.
1877 /// Used in `use` items both at top-level and inside of braces in import groups.
1878 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1879 pub struct UseTree {
1880     pub prefix: Path,
1881     pub kind: UseTreeKind,
1882     pub span: Span,
1883 }
1884
1885 impl UseTree {
1886     pub fn ident(&self) -> Ident {
1887         match self.kind {
1888             UseTreeKind::Simple(Some(rename)) => rename,
1889             UseTreeKind::Simple(None) =>
1890                 self.prefix.segments.last().expect("empty prefix in a simple import").ident,
1891             _ => panic!("`UseTree::ident` can only be used on a simple import"),
1892         }
1893     }
1894 }
1895
1896 /// Distinguishes between Attributes that decorate items and Attributes that
1897 /// are contained as statements within items. These two cases need to be
1898 /// distinguished for pretty-printing.
1899 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1900 pub enum AttrStyle {
1901     Outer,
1902     Inner,
1903 }
1904
1905 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1906 pub struct AttrId(pub usize);
1907
1908 /// Meta-data associated with an item
1909 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1910 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1911 pub struct Attribute {
1912     pub id: AttrId,
1913     pub style: AttrStyle,
1914     pub path: Path,
1915     pub tokens: TokenStream,
1916     pub is_sugared_doc: bool,
1917     pub span: Span,
1918 }
1919
1920 /// TraitRef's appear in impls.
1921 ///
1922 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1923 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1924 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1925 /// same as the impl's node id).
1926 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1927 pub struct TraitRef {
1928     pub path: Path,
1929     pub ref_id: NodeId,
1930 }
1931
1932 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1933 pub struct PolyTraitRef {
1934     /// The `'a` in `<'a> Foo<&'a T>`
1935     pub bound_generic_params: Vec<GenericParam>,
1936
1937     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1938     pub trait_ref: TraitRef,
1939
1940     pub span: Span,
1941 }
1942
1943 impl PolyTraitRef {
1944     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
1945         PolyTraitRef {
1946             bound_generic_params: generic_params,
1947             trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1948             span,
1949         }
1950     }
1951 }
1952
1953 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1954 pub enum CrateSugar {
1955     /// Source is `pub(crate)`
1956     PubCrate,
1957
1958     /// Source is (just) `crate`
1959     JustCrate,
1960 }
1961
1962 pub type Visibility = Spanned<VisibilityKind>;
1963
1964 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1965 pub enum VisibilityKind {
1966     Public,
1967     Crate(CrateSugar),
1968     Restricted { path: P<Path>, id: NodeId },
1969     Inherited,
1970 }
1971
1972 /// Field of a struct.
1973 ///
1974 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1975 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1976 pub struct StructField {
1977     pub span: Span,
1978     pub ident: Option<Ident>,
1979     pub vis: Visibility,
1980     pub id: NodeId,
1981     pub ty: P<Ty>,
1982     pub attrs: Vec<Attribute>,
1983 }
1984
1985 /// Fields and Ids of enum variants and structs
1986 ///
1987 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1988 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1989 /// One shared Id can be successfully used for these two purposes.
1990 /// Id of the whole enum lives in `Item`.
1991 ///
1992 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1993 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1994 /// the variant itself" from enum variants.
1995 /// Id of the whole struct lives in `Item`.
1996 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1997 pub enum VariantData {
1998     /// Struct variant.
1999     ///
2000     /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
2001     Struct(Vec<StructField>, NodeId),
2002     /// Tuple variant.
2003     ///
2004     /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
2005     Tuple(Vec<StructField>, NodeId),
2006     /// Unit variant.
2007     ///
2008     /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
2009     Unit(NodeId),
2010 }
2011
2012 impl VariantData {
2013     pub fn fields(&self) -> &[StructField] {
2014         match *self {
2015             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2016             _ => &[],
2017         }
2018     }
2019     pub fn id(&self) -> NodeId {
2020         match *self {
2021             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
2022         }
2023     }
2024     pub fn is_struct(&self) -> bool {
2025         if let VariantData::Struct(..) = *self { true } else { false }
2026     }
2027     pub fn is_tuple(&self) -> bool {
2028         if let VariantData::Tuple(..) = *self { true } else { false }
2029     }
2030     pub fn is_unit(&self) -> bool {
2031         if let VariantData::Unit(..) = *self { true } else { false }
2032     }
2033 }
2034
2035 /// An item
2036 ///
2037 /// The name might be a dummy name in case of anonymous items
2038 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2039 pub struct Item {
2040     pub ident: Ident,
2041     pub attrs: Vec<Attribute>,
2042     pub id: NodeId,
2043     pub node: ItemKind,
2044     pub vis: Visibility,
2045     pub span: Span,
2046
2047     /// Original tokens this item was parsed from. This isn't necessarily
2048     /// available for all items, although over time more and more items should
2049     /// have this be `Some`. Right now this is primarily used for procedural
2050     /// macros, notably custom attributes.
2051     ///
2052     /// Note that the tokens here do not include the outer attributes, but will
2053     /// include inner attributes.
2054     pub tokens: Option<TokenStream>,
2055 }
2056
2057 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2058 pub enum ItemKind {
2059     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2060     ///
2061     /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2062     ExternCrate(Option<Name>),
2063     /// A use declaration (`use` or `pub use`) item.
2064     ///
2065     /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
2066     Use(P<UseTree>),
2067     /// A static item (`static` or `pub static`).
2068     ///
2069     /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
2070     Static(P<Ty>, Mutability, P<Expr>),
2071     /// A constant item (`const` or `pub const`).
2072     ///
2073     /// E.g. `const FOO: i32 = 42;`
2074     Const(P<Ty>, P<Expr>),
2075     /// A function declaration (`fn` or `pub fn`).
2076     ///
2077     /// E.g. `fn foo(bar: usize) -> usize { .. }`
2078     Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
2079     /// A module declaration (`mod` or `pub mod`).
2080     ///
2081     /// E.g. `mod foo;` or `mod foo { .. }`
2082     Mod(Mod),
2083     /// An external module (`extern` or `pub extern`).
2084     ///
2085     /// E.g. `extern {}` or `extern "C" {}`
2086     ForeignMod(ForeignMod),
2087     /// Module-level inline assembly (from `global_asm!()`)
2088     GlobalAsm(P<GlobalAsm>),
2089     /// A type alias (`type` or `pub type`).
2090     ///
2091     /// E.g. `type Foo = Bar<u8>;`
2092     Ty(P<Ty>, Generics),
2093     /// An enum definition (`enum` or `pub enum`).
2094     ///
2095     /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
2096     Enum(EnumDef, Generics),
2097     /// A struct definition (`struct` or `pub struct`).
2098     ///
2099     /// E.g. `struct Foo<A> { x: A }`
2100     Struct(VariantData, Generics),
2101     /// A union definition (`union` or `pub union`).
2102     ///
2103     /// E.g. `union Foo<A, B> { x: A, y: B }`
2104     Union(VariantData, Generics),
2105     /// A Trait declaration (`trait` or `pub trait`).
2106     ///
2107     /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
2108     Trait(IsAuto, Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
2109     /// Trait alias
2110     ///
2111     /// E.g. `trait Foo = Bar + Quux;`
2112     TraitAlias(Generics, TyParamBounds),
2113     /// An implementation.
2114     ///
2115     /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
2116     Impl(Unsafety,
2117              ImplPolarity,
2118              Defaultness,
2119              Generics,
2120              Option<TraitRef>, // (optional) trait this impl implements
2121              P<Ty>, // self
2122              Vec<ImplItem>),
2123     /// A macro invocation.
2124     ///
2125     /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
2126     Mac(Mac),
2127
2128     /// A macro definition.
2129     MacroDef(MacroDef),
2130 }
2131
2132 impl ItemKind {
2133     pub fn descriptive_variant(&self) -> &str {
2134         match *self {
2135             ItemKind::ExternCrate(..) => "extern crate",
2136             ItemKind::Use(..) => "use",
2137             ItemKind::Static(..) => "static item",
2138             ItemKind::Const(..) => "constant item",
2139             ItemKind::Fn(..) => "function",
2140             ItemKind::Mod(..) => "module",
2141             ItemKind::ForeignMod(..) => "foreign module",
2142             ItemKind::GlobalAsm(..) => "global asm",
2143             ItemKind::Ty(..) => "type alias",
2144             ItemKind::Enum(..) => "enum",
2145             ItemKind::Struct(..) => "struct",
2146             ItemKind::Union(..) => "union",
2147             ItemKind::Trait(..) => "trait",
2148             ItemKind::TraitAlias(..) => "trait alias",
2149             ItemKind::Mac(..) |
2150             ItemKind::MacroDef(..) |
2151             ItemKind::Impl(..) => "item"
2152         }
2153     }
2154 }
2155
2156 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2157 pub struct ForeignItem {
2158     pub ident: Ident,
2159     pub attrs: Vec<Attribute>,
2160     pub node: ForeignItemKind,
2161     pub id: NodeId,
2162     pub span: Span,
2163     pub vis: Visibility,
2164 }
2165
2166 /// An item within an `extern` block
2167 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2168 pub enum ForeignItemKind {
2169     /// A foreign function
2170     Fn(P<FnDecl>, Generics),
2171     /// A foreign static item (`static ext: u8`), with optional mutability
2172     /// (the boolean is true when mutable)
2173     Static(P<Ty>, bool),
2174     /// A foreign type
2175     Ty,
2176     /// A macro invocation
2177     Macro(Mac),
2178 }
2179
2180 impl ForeignItemKind {
2181     pub fn descriptive_variant(&self) -> &str {
2182         match *self {
2183             ForeignItemKind::Fn(..) => "foreign function",
2184             ForeignItemKind::Static(..) => "foreign static item",
2185             ForeignItemKind::Ty => "foreign type",
2186             ForeignItemKind::Macro(..) => "macro in foreign module",
2187         }
2188     }
2189 }
2190
2191 #[cfg(test)]
2192 mod tests {
2193     use serialize;
2194     use super::*;
2195
2196     // are ASTs encodable?
2197     #[test]
2198     fn check_asts_encodable() {
2199         fn assert_encodable<T: serialize::Encodable>() {}
2200         assert_encodable::<Crate>();
2201     }
2202 }