]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Rollup merge of #56548 - Lucretiel:string-extend-optimize, r=sfackler
[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     // 1-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 MetaItems 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 `Expr`s 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 (`(a, b, c ,d)`)
1059     Tup(Vec<P<Expr>>),
1060     /// A binary operation (For example: `a + b`, `a * b`)
1061     Binary(BinOp, P<Expr>, P<Expr>),
1062     /// A unary operation (For example: `!x`, `*x`)
1063     Unary(UnOp, P<Expr>),
1064     /// A literal (For example: `1`, `"foo"`)
1065     Lit(Lit),
1066     /// A cast (`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 (for example, `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     /// For example, `a += 1`.
1124     AssignOp(BinOp, P<Expr>, P<Expr>),
1125     /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct field
1126     Field(P<Expr>, Ident),
1127     /// An indexing operation (`foo[2]`)
1128     Index(P<Expr>, P<Expr>),
1129     /// A range (`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",
1136     /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1137     Path(Option<QSelf>, Path),
1138
1139     /// A referencing operation (`&a` or `&mut a`)
1140     AddrOf(Mutability, P<Expr>),
1141     /// A `break`, with an optional label to break, and an optional expression
1142     Break(Option<Label>, Option<P<Expr>>),
1143     /// A `continue`, with an optional label
1144     Continue(Option<Label>),
1145     /// A `return`, with an optional value to be returned
1146     Ret(Option<P<Expr>>),
1147
1148     /// Output of the `asm!()` macro
1149     InlineAsm(P<InlineAsm>),
1150
1151     /// A macro invocation; pre-expansion
1152     Mac(Mac),
1153
1154     /// A struct literal expression.
1155     ///
1156     /// For example, `Foo {x: 1, y: 2}`, or
1157     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1158     Struct(Path, Vec<Field>, Option<P<Expr>>),
1159
1160     /// An array literal constructed from one repeated element.
1161     ///
1162     /// For example, `[1; 5]`. The expression is the element to be
1163     /// repeated; the constant is the number of times to repeat it.
1164     Repeat(P<Expr>, AnonConst),
1165
1166     /// No-op: used solely so we can pretty-print faithfully
1167     Paren(P<Expr>),
1168
1169     /// `expr?`
1170     Try(P<Expr>),
1171
1172     /// A `yield`, with an optional value to be yielded
1173     Yield(Option<P<Expr>>),
1174 }
1175
1176 /// The explicit Self type in a "qualified path". The actual
1177 /// path, including the trait and the associated item, is stored
1178 /// separately. `position` represents the index of the associated
1179 /// item qualified with this Self type.
1180 ///
1181 /// ```ignore (only-for-syntax-highlight)
1182 /// <Vec<T> as a::b::Trait>::AssociatedItem
1183 ///  ^~~~~     ~~~~~~~~~~~~~~^
1184 ///  ty        position = 3
1185 ///
1186 /// <Vec<T>>::AssociatedItem
1187 ///  ^~~~~    ^
1188 ///  ty       position = 0
1189 /// ```
1190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1191 pub struct QSelf {
1192     pub ty: P<Ty>,
1193
1194     /// The span of `a::b::Trait` in a path like `<Vec<T> as
1195     /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1196     /// 0`, this is an empty span.
1197     pub path_span: Span,
1198     pub position: usize,
1199 }
1200
1201 /// A capture clause
1202 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1203 pub enum CaptureBy {
1204     Value,
1205     Ref,
1206 }
1207
1208 /// The movability of a generator / closure literal
1209 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1210 pub enum Movability {
1211     Static,
1212     Movable,
1213 }
1214
1215 pub type Mac = Spanned<Mac_>;
1216
1217 /// Represents a macro invocation. The Path indicates which macro
1218 /// is being invoked, and the vector of token-trees contains the source
1219 /// of the macro invocation.
1220 ///
1221 /// NB: the additional ident for a macro_rules-style macro is actually
1222 /// stored in the enclosing item. Oog.
1223 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1224 pub struct Mac_ {
1225     pub path: Path,
1226     pub delim: MacDelimiter,
1227     pub tts: ThinTokenStream,
1228 }
1229
1230 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1231 pub enum MacDelimiter {
1232     Parenthesis,
1233     Bracket,
1234     Brace,
1235 }
1236
1237 impl Mac_ {
1238     pub fn stream(&self) -> TokenStream {
1239         self.tts.clone().into()
1240     }
1241 }
1242
1243 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1244 pub struct MacroDef {
1245     pub tokens: ThinTokenStream,
1246     pub legacy: bool,
1247 }
1248
1249 impl MacroDef {
1250     pub fn stream(&self) -> TokenStream {
1251         self.tokens.clone().into()
1252     }
1253 }
1254
1255 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1256 pub enum StrStyle {
1257     /// A regular string, like `"foo"`
1258     Cooked,
1259     /// A raw string, like `r##"foo"##`
1260     ///
1261     /// The value is the number of `#` symbols used.
1262     Raw(u16),
1263 }
1264
1265 /// A literal
1266 pub type Lit = Spanned<LitKind>;
1267
1268 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1269 pub enum LitIntType {
1270     Signed(IntTy),
1271     Unsigned(UintTy),
1272     Unsuffixed,
1273 }
1274
1275 /// Literal kind.
1276 ///
1277 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1278 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1279 pub enum LitKind {
1280     /// A string literal (`"foo"`)
1281     Str(Symbol, StrStyle),
1282     /// A byte string (`b"foo"`)
1283     ByteStr(Lrc<Vec<u8>>),
1284     /// A byte char (`b'f'`)
1285     Byte(u8),
1286     /// A character literal (`'a'`)
1287     Char(char),
1288     /// An integer literal (`1`)
1289     Int(u128, LitIntType),
1290     /// A float literal (`1f64` or `1E10f64`)
1291     Float(Symbol, FloatTy),
1292     /// A float literal without a suffix (`1.0 or 1.0E10`)
1293     FloatUnsuffixed(Symbol),
1294     /// A boolean literal
1295     Bool(bool),
1296 }
1297
1298 impl LitKind {
1299     /// Returns true if this literal is a string and false otherwise.
1300     pub fn is_str(&self) -> bool {
1301         match *self {
1302             LitKind::Str(..) => true,
1303             _ => false,
1304         }
1305     }
1306
1307     /// Returns true if this literal is byte literal string false otherwise.
1308     pub fn is_bytestr(&self) -> bool {
1309         match self {
1310             LitKind::ByteStr(_) => true,
1311             _ => false,
1312         }
1313     }
1314
1315     /// Returns true if this is a numeric literal.
1316     pub fn is_numeric(&self) -> bool {
1317         match *self {
1318             LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1319             _ => false,
1320         }
1321     }
1322
1323     /// Returns true if this literal has no suffix. Note: this will return true
1324     /// for literals with prefixes such as raw strings and byte strings.
1325     pub fn is_unsuffixed(&self) -> bool {
1326         match *self {
1327             // unsuffixed variants
1328             LitKind::Str(..)
1329             | LitKind::ByteStr(..)
1330             | LitKind::Byte(..)
1331             | LitKind::Char(..)
1332             | LitKind::Int(_, LitIntType::Unsuffixed)
1333             | LitKind::FloatUnsuffixed(..)
1334             | LitKind::Bool(..) => true,
1335             // suffixed variants
1336             LitKind::Int(_, LitIntType::Signed(..))
1337             | LitKind::Int(_, LitIntType::Unsigned(..))
1338             | LitKind::Float(..) => false,
1339         }
1340     }
1341
1342     /// Returns true if this literal has a suffix.
1343     pub fn is_suffixed(&self) -> bool {
1344         !self.is_unsuffixed()
1345     }
1346 }
1347
1348 // NB: If you change this, you'll probably want to change the corresponding
1349 // type structure in middle/ty.rs as well.
1350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1351 pub struct MutTy {
1352     pub ty: P<Ty>,
1353     pub mutbl: Mutability,
1354 }
1355
1356 /// Represents a method's signature in a trait declaration,
1357 /// or in an implementation.
1358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1359 pub struct MethodSig {
1360     pub header: FnHeader,
1361     pub decl: P<FnDecl>,
1362 }
1363
1364 /// Represents an item declaration within a trait declaration,
1365 /// possibly including a default implementation. A trait item is
1366 /// either required (meaning it doesn't have an implementation, just a
1367 /// signature) or provided (meaning it has a default implementation).
1368 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1369 pub struct TraitItem {
1370     pub id: NodeId,
1371     pub ident: Ident,
1372     pub attrs: Vec<Attribute>,
1373     pub generics: Generics,
1374     pub node: TraitItemKind,
1375     pub span: Span,
1376     /// See `Item::tokens` for what this is
1377     pub tokens: Option<TokenStream>,
1378 }
1379
1380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1381 pub enum TraitItemKind {
1382     Const(P<Ty>, Option<P<Expr>>),
1383     Method(MethodSig, Option<P<Block>>),
1384     Type(GenericBounds, Option<P<Ty>>),
1385     Macro(Mac),
1386 }
1387
1388 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1389 pub struct ImplItem {
1390     pub id: NodeId,
1391     pub ident: Ident,
1392     pub vis: Visibility,
1393     pub defaultness: Defaultness,
1394     pub attrs: Vec<Attribute>,
1395     pub generics: Generics,
1396     pub node: ImplItemKind,
1397     pub span: Span,
1398     /// See `Item::tokens` for what this is
1399     pub tokens: Option<TokenStream>,
1400 }
1401
1402 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1403 pub enum ImplItemKind {
1404     Const(P<Ty>, P<Expr>),
1405     Method(MethodSig, P<Block>),
1406     Type(P<Ty>),
1407     Existential(GenericBounds),
1408     Macro(Mac),
1409 }
1410
1411 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1412 pub enum IntTy {
1413     Isize,
1414     I8,
1415     I16,
1416     I32,
1417     I64,
1418     I128,
1419 }
1420
1421 impl fmt::Debug for IntTy {
1422     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1423         fmt::Display::fmt(self, f)
1424     }
1425 }
1426
1427 impl fmt::Display for IntTy {
1428     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1429         write!(f, "{}", self.ty_to_string())
1430     }
1431 }
1432
1433 impl IntTy {
1434     pub fn ty_to_string(&self) -> &'static str {
1435         match *self {
1436             IntTy::Isize => "isize",
1437             IntTy::I8 => "i8",
1438             IntTy::I16 => "i16",
1439             IntTy::I32 => "i32",
1440             IntTy::I64 => "i64",
1441             IntTy::I128 => "i128",
1442         }
1443     }
1444
1445     pub fn val_to_string(&self, val: i128) -> String {
1446         // cast to a u128 so we can correctly print INT128_MIN. All integral types
1447         // are parsed as u128, so we wouldn't want to print an extra negative
1448         // sign.
1449         format!("{}{}", val as u128, self.ty_to_string())
1450     }
1451
1452     pub fn bit_width(&self) -> Option<usize> {
1453         Some(match *self {
1454             IntTy::Isize => return None,
1455             IntTy::I8 => 8,
1456             IntTy::I16 => 16,
1457             IntTy::I32 => 32,
1458             IntTy::I64 => 64,
1459             IntTy::I128 => 128,
1460         })
1461     }
1462 }
1463
1464 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1465 pub enum UintTy {
1466     Usize,
1467     U8,
1468     U16,
1469     U32,
1470     U64,
1471     U128,
1472 }
1473
1474 impl UintTy {
1475     pub fn ty_to_string(&self) -> &'static str {
1476         match *self {
1477             UintTy::Usize => "usize",
1478             UintTy::U8 => "u8",
1479             UintTy::U16 => "u16",
1480             UintTy::U32 => "u32",
1481             UintTy::U64 => "u64",
1482             UintTy::U128 => "u128",
1483         }
1484     }
1485
1486     pub fn val_to_string(&self, val: u128) -> String {
1487         format!("{}{}", val, self.ty_to_string())
1488     }
1489
1490     pub fn bit_width(&self) -> Option<usize> {
1491         Some(match *self {
1492             UintTy::Usize => return None,
1493             UintTy::U8 => 8,
1494             UintTy::U16 => 16,
1495             UintTy::U32 => 32,
1496             UintTy::U64 => 64,
1497             UintTy::U128 => 128,
1498         })
1499     }
1500 }
1501
1502 impl fmt::Debug for UintTy {
1503     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1504         fmt::Display::fmt(self, f)
1505     }
1506 }
1507
1508 impl fmt::Display for UintTy {
1509     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1510         write!(f, "{}", self.ty_to_string())
1511     }
1512 }
1513
1514 // Bind a type to an associated type: `A=Foo`.
1515 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1516 pub struct TypeBinding {
1517     pub id: NodeId,
1518     pub ident: Ident,
1519     pub ty: P<Ty>,
1520     pub span: Span,
1521 }
1522
1523 #[derive(Clone, RustcEncodable, RustcDecodable)]
1524 pub struct Ty {
1525     pub id: NodeId,
1526     pub node: TyKind,
1527     pub span: Span,
1528 }
1529
1530 impl fmt::Debug for Ty {
1531     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1532         write!(f, "type({})", pprust::ty_to_string(self))
1533     }
1534 }
1535
1536 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1537 pub struct BareFnTy {
1538     pub unsafety: Unsafety,
1539     pub abi: Abi,
1540     pub generic_params: Vec<GenericParam>,
1541     pub decl: P<FnDecl>,
1542 }
1543
1544 /// The different kinds of types recognized by the compiler
1545 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1546 pub enum TyKind {
1547     /// A variable-length slice (`[T]`)
1548     Slice(P<Ty>),
1549     /// A fixed length array (`[T; n]`)
1550     Array(P<Ty>, AnonConst),
1551     /// A raw pointer (`*const T` or `*mut T`)
1552     Ptr(MutTy),
1553     /// A reference (`&'a T` or `&'a mut T`)
1554     Rptr(Option<Lifetime>, MutTy),
1555     /// A bare function (e.g. `fn(usize) -> bool`)
1556     BareFn(P<BareFnTy>),
1557     /// The never type (`!`)
1558     Never,
1559     /// A tuple (`(A, B, C, D,...)`)
1560     Tup(Vec<P<Ty>>),
1561     /// A path (`module::module::...::Type`), optionally
1562     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1563     ///
1564     /// Type parameters are stored in the Path itself
1565     Path(Option<QSelf>, Path),
1566     /// A trait object type `Bound1 + Bound2 + Bound3`
1567     /// where `Bound` is a trait or a lifetime.
1568     TraitObject(GenericBounds, TraitObjectSyntax),
1569     /// An `impl Bound1 + Bound2 + Bound3` type
1570     /// where `Bound` is a trait or a lifetime.
1571     ///
1572     /// The `NodeId` exists to prevent lowering from having to
1573     /// generate `NodeId`s on the fly, which would complicate
1574     /// the generation of `existential type` items significantly
1575     ImplTrait(NodeId, GenericBounds),
1576     /// No-op; kept solely so that we can pretty-print faithfully
1577     Paren(P<Ty>),
1578     /// Unused for now
1579     Typeof(AnonConst),
1580     /// TyKind::Infer means the type should be inferred instead of it having been
1581     /// specified. This can appear anywhere in a type.
1582     Infer,
1583     /// Inferred type of a `self` or `&self` argument in a method.
1584     ImplicitSelf,
1585     // A macro in the type position.
1586     Mac(Mac),
1587     /// Placeholder for a kind that has failed to be defined.
1588     Err,
1589 }
1590
1591 impl TyKind {
1592     pub fn is_implicit_self(&self) -> bool {
1593         if let TyKind::ImplicitSelf = *self {
1594             true
1595         } else {
1596             false
1597         }
1598     }
1599
1600     pub fn is_unit(&self) -> bool {
1601         if let TyKind::Tup(ref tys) = *self {
1602             tys.is_empty()
1603         } else {
1604             false
1605         }
1606     }
1607 }
1608
1609 /// Syntax used to declare a trait object.
1610 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1611 pub enum TraitObjectSyntax {
1612     Dyn,
1613     None,
1614 }
1615
1616 /// Inline assembly dialect.
1617 ///
1618 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1619 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1620 pub enum AsmDialect {
1621     Att,
1622     Intel,
1623 }
1624
1625 /// Inline assembly.
1626 ///
1627 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1628 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1629 pub struct InlineAsmOutput {
1630     pub constraint: Symbol,
1631     pub expr: P<Expr>,
1632     pub is_rw: bool,
1633     pub is_indirect: bool,
1634 }
1635
1636 /// Inline assembly.
1637 ///
1638 /// E.g. `asm!("NOP");`
1639 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1640 pub struct InlineAsm {
1641     pub asm: Symbol,
1642     pub asm_str_style: StrStyle,
1643     pub outputs: Vec<InlineAsmOutput>,
1644     pub inputs: Vec<(Symbol, P<Expr>)>,
1645     pub clobbers: Vec<Symbol>,
1646     pub volatile: bool,
1647     pub alignstack: bool,
1648     pub dialect: AsmDialect,
1649     pub ctxt: SyntaxContext,
1650 }
1651
1652 /// An argument in a function header.
1653 ///
1654 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1655 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1656 pub struct Arg {
1657     pub ty: P<Ty>,
1658     pub pat: P<Pat>,
1659     pub id: NodeId,
1660 }
1661
1662 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1663 ///
1664 /// E.g. `&mut self` as in `fn foo(&mut self)`
1665 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1666 pub enum SelfKind {
1667     /// `self`, `mut self`
1668     Value(Mutability),
1669     /// `&'lt self`, `&'lt mut self`
1670     Region(Option<Lifetime>, Mutability),
1671     /// `self: TYPE`, `mut self: TYPE`
1672     Explicit(P<Ty>, Mutability),
1673 }
1674
1675 pub type ExplicitSelf = Spanned<SelfKind>;
1676
1677 impl Arg {
1678     pub fn to_self(&self) -> Option<ExplicitSelf> {
1679         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1680             if ident.name == keywords::SelfLower.name() {
1681                 return match self.ty.node {
1682                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1683                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1684                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1685                     }
1686                     _ => Some(respan(
1687                         self.pat.span.to(self.ty.span),
1688                         SelfKind::Explicit(self.ty.clone(), mutbl),
1689                     )),
1690                 };
1691             }
1692         }
1693         None
1694     }
1695
1696     pub fn is_self(&self) -> bool {
1697         if let PatKind::Ident(_, ident, _) = self.pat.node {
1698             ident.name == keywords::SelfLower.name()
1699         } else {
1700             false
1701         }
1702     }
1703
1704     pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1705         let span = eself.span.to(eself_ident.span);
1706         let infer_ty = P(Ty {
1707             id: DUMMY_NODE_ID,
1708             node: TyKind::ImplicitSelf,
1709             span,
1710         });
1711         let arg = |mutbl, ty| Arg {
1712             pat: P(Pat {
1713                 id: DUMMY_NODE_ID,
1714                 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1715                 span,
1716             }),
1717             ty,
1718             id: DUMMY_NODE_ID,
1719         };
1720         match eself.node {
1721             SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1722             SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1723             SelfKind::Region(lt, mutbl) => arg(
1724                 Mutability::Immutable,
1725                 P(Ty {
1726                     id: DUMMY_NODE_ID,
1727                     node: TyKind::Rptr(
1728                         lt,
1729                         MutTy {
1730                             ty: infer_ty,
1731                             mutbl: mutbl,
1732                         },
1733                     ),
1734                     span,
1735                 }),
1736             ),
1737         }
1738     }
1739 }
1740
1741 /// Header (not the body) of a function declaration.
1742 ///
1743 /// E.g. `fn foo(bar: baz)`
1744 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1745 pub struct FnDecl {
1746     pub inputs: Vec<Arg>,
1747     pub output: FunctionRetTy,
1748     pub variadic: bool,
1749 }
1750
1751 impl FnDecl {
1752     pub fn get_self(&self) -> Option<ExplicitSelf> {
1753         self.inputs.get(0).and_then(Arg::to_self)
1754     }
1755     pub fn has_self(&self) -> bool {
1756         self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1757     }
1758 }
1759
1760 /// Is the trait definition an auto trait?
1761 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1762 pub enum IsAuto {
1763     Yes,
1764     No,
1765 }
1766
1767 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1768 pub enum Unsafety {
1769     Unsafe,
1770     Normal,
1771 }
1772
1773 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1774 pub enum IsAsync {
1775     Async {
1776         closure_id: NodeId,
1777         return_impl_trait_id: NodeId,
1778     },
1779     NotAsync,
1780 }
1781
1782 impl IsAsync {
1783     pub fn is_async(self) -> bool {
1784         if let IsAsync::Async { .. } = self {
1785             true
1786         } else {
1787             false
1788         }
1789     }
1790     /// In 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
1848     /// closures default to inference. Span points to where return
1849     /// type would be inserted.
1850     Default(Span),
1851     /// Everything else
1852     Ty(P<Ty>),
1853 }
1854
1855 impl FunctionRetTy {
1856     pub fn span(&self) -> Span {
1857         match *self {
1858             FunctionRetTy::Default(span) => span,
1859             FunctionRetTy::Ty(ref ty) => ty.span,
1860         }
1861     }
1862 }
1863
1864 /// Module declaration.
1865 ///
1866 /// E.g. `mod foo;` or `mod foo { .. }`
1867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1868 pub struct Mod {
1869     /// A span from the first token past `{` to the last token until `}`.
1870     /// For `mod foo;`, the inner span ranges from the first token
1871     /// to the last token in the external file.
1872     pub inner: Span,
1873     pub items: Vec<P<Item>>,
1874     /// For `mod foo;` inline is false, for `mod foo { .. }` it is true.
1875     pub inline: bool,
1876 }
1877
1878 /// Foreign module declaration.
1879 ///
1880 /// E.g. `extern { .. }` or `extern C { .. }`
1881 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1882 pub struct ForeignMod {
1883     pub abi: Abi,
1884     pub items: Vec<ForeignItem>,
1885 }
1886
1887 /// Global inline assembly
1888 ///
1889 /// aka module-level assembly or file-scoped assembly
1890 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1891 pub struct GlobalAsm {
1892     pub asm: Symbol,
1893     pub ctxt: SyntaxContext,
1894 }
1895
1896 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1897 pub struct EnumDef {
1898     pub variants: Vec<Variant>,
1899 }
1900
1901 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1902 pub struct Variant_ {
1903     pub ident: Ident,
1904     pub attrs: Vec<Attribute>,
1905     pub data: VariantData,
1906     /// Explicit discriminant, e.g. `Foo = 1`
1907     pub disr_expr: Option<AnonConst>,
1908 }
1909
1910 pub type Variant = Spanned<Variant_>;
1911
1912 /// Part of `use` item to the right of its prefix.
1913 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1914 pub enum UseTreeKind {
1915     /// `use prefix` or `use prefix as rename`
1916     ///
1917     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1918     /// namespace.
1919     Simple(Option<Ident>, NodeId, NodeId),
1920     /// `use prefix::{...}`
1921     Nested(Vec<(UseTree, NodeId)>),
1922     /// `use prefix::*`
1923     Glob,
1924 }
1925
1926 /// A tree of paths sharing common prefixes.
1927 /// Used in `use` items both at top-level and inside of braces in import groups.
1928 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1929 pub struct UseTree {
1930     pub prefix: Path,
1931     pub kind: UseTreeKind,
1932     pub span: Span,
1933 }
1934
1935 impl UseTree {
1936     pub fn ident(&self) -> Ident {
1937         match self.kind {
1938             UseTreeKind::Simple(Some(rename), ..) => rename,
1939             UseTreeKind::Simple(None, ..) => {
1940                 self.prefix
1941                     .segments
1942                     .last()
1943                     .expect("empty prefix in a simple import")
1944                     .ident
1945             }
1946             _ => panic!("`UseTree::ident` can only be used on a simple import"),
1947         }
1948     }
1949 }
1950
1951 /// Distinguishes between Attributes that decorate items and Attributes that
1952 /// are contained as statements within items. These two cases need to be
1953 /// distinguished for pretty-printing.
1954 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1955 pub enum AttrStyle {
1956     Outer,
1957     Inner,
1958 }
1959
1960 #[derive(
1961     Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
1962 )]
1963 pub struct AttrId(pub usize);
1964
1965 impl Idx for AttrId {
1966     fn new(idx: usize) -> Self {
1967         AttrId(idx)
1968     }
1969     fn index(self) -> usize {
1970         self.0
1971     }
1972 }
1973
1974 /// Meta-data associated with an item
1975 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1976 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1977 pub struct Attribute {
1978     pub id: AttrId,
1979     pub style: AttrStyle,
1980     pub path: Path,
1981     pub tokens: TokenStream,
1982     pub is_sugared_doc: bool,
1983     pub span: Span,
1984 }
1985
1986 /// TraitRef's appear in impls.
1987 ///
1988 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1989 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1990 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1991 /// same as the impl's node id).
1992 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1993 pub struct TraitRef {
1994     pub path: Path,
1995     pub ref_id: NodeId,
1996 }
1997
1998 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1999 pub struct PolyTraitRef {
2000     /// The `'a` in `<'a> Foo<&'a T>`
2001     pub bound_generic_params: Vec<GenericParam>,
2002
2003     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2004     pub trait_ref: TraitRef,
2005
2006     pub span: Span,
2007 }
2008
2009 impl PolyTraitRef {
2010     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2011         PolyTraitRef {
2012             bound_generic_params: generic_params,
2013             trait_ref: TraitRef {
2014                 path: path,
2015                 ref_id: DUMMY_NODE_ID,
2016             },
2017             span,
2018         }
2019     }
2020 }
2021
2022 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2023 pub enum CrateSugar {
2024     /// Source is `pub(crate)`
2025     PubCrate,
2026
2027     /// Source is (just) `crate`
2028     JustCrate,
2029 }
2030
2031 pub type Visibility = Spanned<VisibilityKind>;
2032
2033 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2034 pub enum VisibilityKind {
2035     Public,
2036     Crate(CrateSugar),
2037     Restricted { path: P<Path>, id: NodeId },
2038     Inherited,
2039 }
2040
2041 impl VisibilityKind {
2042     pub fn is_pub(&self) -> bool {
2043         if let VisibilityKind::Public = *self {
2044             true
2045         } else {
2046             false
2047         }
2048     }
2049 }
2050
2051 /// Field of a struct.
2052 ///
2053 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
2054 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2055 pub struct StructField {
2056     pub span: Span,
2057     pub ident: Option<Ident>,
2058     pub vis: Visibility,
2059     pub id: NodeId,
2060     pub ty: P<Ty>,
2061     pub attrs: Vec<Attribute>,
2062 }
2063
2064 /// Fields and Ids of enum variants and structs
2065 ///
2066 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2067 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2068 /// One shared Id can be successfully used for these two purposes.
2069 /// Id of the whole enum lives in `Item`.
2070 ///
2071 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2072 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2073 /// the variant itself" from enum variants.
2074 /// Id of the whole struct lives in `Item`.
2075 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2076 pub enum VariantData {
2077     /// Struct variant.
2078     ///
2079     /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
2080     Struct(Vec<StructField>, NodeId),
2081     /// Tuple variant.
2082     ///
2083     /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
2084     Tuple(Vec<StructField>, NodeId),
2085     /// Unit variant.
2086     ///
2087     /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
2088     Unit(NodeId),
2089 }
2090
2091 impl VariantData {
2092     pub fn fields(&self) -> &[StructField] {
2093         match *self {
2094             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2095             _ => &[],
2096         }
2097     }
2098     pub fn id(&self) -> NodeId {
2099         match *self {
2100             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2101         }
2102     }
2103     pub fn is_struct(&self) -> bool {
2104         if let VariantData::Struct(..) = *self {
2105             true
2106         } else {
2107             false
2108         }
2109     }
2110     pub fn is_tuple(&self) -> bool {
2111         if let VariantData::Tuple(..) = *self {
2112             true
2113         } else {
2114             false
2115         }
2116     }
2117     pub fn is_unit(&self) -> bool {
2118         if let VariantData::Unit(..) = *self {
2119             true
2120         } else {
2121             false
2122         }
2123     }
2124 }
2125
2126 /// An item
2127 ///
2128 /// The name might be a dummy name in case of anonymous items
2129 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2130 pub struct Item {
2131     pub ident: Ident,
2132     pub attrs: Vec<Attribute>,
2133     pub id: NodeId,
2134     pub node: ItemKind,
2135     pub vis: Visibility,
2136     pub span: Span,
2137
2138     /// Original tokens this item was parsed from. This isn't necessarily
2139     /// available for all items, although over time more and more items should
2140     /// have this be `Some`. Right now this is primarily used for procedural
2141     /// macros, notably custom attributes.
2142     ///
2143     /// Note that the tokens here do not include the outer attributes, but will
2144     /// include inner attributes.
2145     pub tokens: Option<TokenStream>,
2146 }
2147
2148 /// A function header
2149 ///
2150 /// All the information between the visibility & the name of the function is
2151 /// included in this struct (e.g. `async unsafe fn` or `const extern "C" fn`)
2152 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2153 pub struct FnHeader {
2154     pub unsafety: Unsafety,
2155     pub asyncness: IsAsync,
2156     pub constness: Spanned<Constness>,
2157     pub abi: Abi,
2158 }
2159
2160 impl Default for FnHeader {
2161     fn default() -> FnHeader {
2162         FnHeader {
2163             unsafety: Unsafety::Normal,
2164             asyncness: IsAsync::NotAsync,
2165             constness: dummy_spanned(Constness::NotConst),
2166             abi: Abi::Rust,
2167         }
2168     }
2169 }
2170
2171 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2172 pub enum ItemKind {
2173     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2174     ///
2175     /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2176     ExternCrate(Option<Name>),
2177     /// A use declaration (`use` or `pub use`) item.
2178     ///
2179     /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
2180     Use(P<UseTree>),
2181     /// A static item (`static` or `pub static`).
2182     ///
2183     /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
2184     Static(P<Ty>, Mutability, P<Expr>),
2185     /// A constant item (`const` or `pub const`).
2186     ///
2187     /// E.g. `const FOO: i32 = 42;`
2188     Const(P<Ty>, P<Expr>),
2189     /// A function declaration (`fn` or `pub fn`).
2190     ///
2191     /// E.g. `fn foo(bar: usize) -> usize { .. }`
2192     Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2193     /// A module declaration (`mod` or `pub mod`).
2194     ///
2195     /// E.g. `mod foo;` or `mod foo { .. }`
2196     Mod(Mod),
2197     /// An external module (`extern` or `pub extern`).
2198     ///
2199     /// E.g. `extern {}` or `extern "C" {}`
2200     ForeignMod(ForeignMod),
2201     /// Module-level inline assembly (from `global_asm!()`)
2202     GlobalAsm(P<GlobalAsm>),
2203     /// A type alias (`type` or `pub type`).
2204     ///
2205     /// E.g. `type Foo = Bar<u8>;`
2206     Ty(P<Ty>, Generics),
2207     /// An existential type declaration (`existential type`).
2208     ///
2209     /// E.g. `existential type Foo: Bar + Boo;`
2210     Existential(GenericBounds, Generics),
2211     /// An enum definition (`enum` or `pub enum`).
2212     ///
2213     /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
2214     Enum(EnumDef, Generics),
2215     /// A struct definition (`struct` or `pub struct`).
2216     ///
2217     /// E.g. `struct Foo<A> { x: A }`
2218     Struct(VariantData, Generics),
2219     /// A union definition (`union` or `pub union`).
2220     ///
2221     /// E.g. `union Foo<A, B> { x: A, y: B }`
2222     Union(VariantData, Generics),
2223     /// A Trait declaration (`trait` or `pub trait`).
2224     ///
2225     /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
2226     Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2227     /// Trait alias
2228     ///
2229     /// E.g. `trait Foo = Bar + Quux;`
2230     TraitAlias(Generics, GenericBounds),
2231     /// An implementation.
2232     ///
2233     /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
2234     Impl(
2235         Unsafety,
2236         ImplPolarity,
2237         Defaultness,
2238         Generics,
2239         Option<TraitRef>, // (optional) trait this impl implements
2240         P<Ty>,            // self
2241         Vec<ImplItem>,
2242     ),
2243     /// A macro invocation.
2244     ///
2245     /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
2246     Mac(Mac),
2247
2248     /// A macro definition.
2249     MacroDef(MacroDef),
2250 }
2251
2252 impl ItemKind {
2253     pub fn descriptive_variant(&self) -> &str {
2254         match *self {
2255             ItemKind::ExternCrate(..) => "extern crate",
2256             ItemKind::Use(..) => "use",
2257             ItemKind::Static(..) => "static item",
2258             ItemKind::Const(..) => "constant item",
2259             ItemKind::Fn(..) => "function",
2260             ItemKind::Mod(..) => "module",
2261             ItemKind::ForeignMod(..) => "foreign module",
2262             ItemKind::GlobalAsm(..) => "global asm",
2263             ItemKind::Ty(..) => "type alias",
2264             ItemKind::Existential(..) => "existential type",
2265             ItemKind::Enum(..) => "enum",
2266             ItemKind::Struct(..) => "struct",
2267             ItemKind::Union(..) => "union",
2268             ItemKind::Trait(..) => "trait",
2269             ItemKind::TraitAlias(..) => "trait alias",
2270             ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2271         }
2272     }
2273 }
2274
2275 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2276 pub struct ForeignItem {
2277     pub ident: Ident,
2278     pub attrs: Vec<Attribute>,
2279     pub node: ForeignItemKind,
2280     pub id: NodeId,
2281     pub span: Span,
2282     pub vis: Visibility,
2283 }
2284
2285 /// An item within an `extern` block
2286 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2287 pub enum ForeignItemKind {
2288     /// A foreign function
2289     Fn(P<FnDecl>, Generics),
2290     /// A foreign static item (`static ext: u8`), with optional mutability
2291     /// (the boolean is true when mutable)
2292     Static(P<Ty>, bool),
2293     /// A foreign type
2294     Ty,
2295     /// A macro invocation
2296     Macro(Mac),
2297 }
2298
2299 impl ForeignItemKind {
2300     pub fn descriptive_variant(&self) -> &str {
2301         match *self {
2302             ForeignItemKind::Fn(..) => "foreign function",
2303             ForeignItemKind::Static(..) => "foreign static item",
2304             ForeignItemKind::Ty => "foreign type",
2305             ForeignItemKind::Macro(..) => "macro in foreign module",
2306         }
2307     }
2308 }
2309
2310 #[cfg(test)]
2311 mod tests {
2312     use super::*;
2313     use serialize;
2314
2315     // are ASTs encodable?
2316     #[test]
2317     fn check_asts_encodable() {
2318         fn assert_encodable<T: serialize::Encodable>() {}
2319         assert_encodable::<Crate>();
2320     }
2321 }