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