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