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