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