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