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