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