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