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