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