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