]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Rollup merge of #58476 - nnethercote:rm-LazyTokenStream, r=petrochenkov
[rust.git] / src / libsyntax / ast.rs
1 // The Rust abstract syntax tree.
2
3 pub use GenericArgs::*;
4 pub use UnsafeSource::*;
5 pub use crate::symbol::{Ident, Symbol as Name};
6 pub use crate::util::parser::ExprPrecedence;
7
8 use crate::ext::hygiene::{Mark, SyntaxContext};
9 use crate::print::pprust;
10 use crate::ptr::P;
11 use crate::source_map::{dummy_spanned, respan, Spanned};
12 use crate::symbol::{keywords, Symbol};
13 use crate::tokenstream::TokenStream;
14 use crate::ThinVec;
15
16 use rustc_data_structures::indexed_vec::Idx;
17 #[cfg(target_arch = "x86_64")]
18 use rustc_data_structures::static_assert;
19 use rustc_target::spec::abi::Abi;
20 use syntax_pos::{Span, DUMMY_SP};
21
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::sync::Lrc;
24 use serialize::{self, Decoder, Encoder};
25 use std::fmt;
26
27 pub use rustc_target::abi::FloatTy;
28
29 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
30 pub struct Label {
31     pub ident: Ident,
32 }
33
34 impl fmt::Debug for Label {
35     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36         write!(f, "label({:?})", self.ident)
37     }
38 }
39
40 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
41 pub struct Lifetime {
42     pub id: NodeId,
43     pub ident: Ident,
44 }
45
46 impl fmt::Debug for Lifetime {
47     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48         write!(
49             f,
50             "lifetime({}: {})",
51             self.id,
52             pprust::lifetime_to_string(self)
53         )
54     }
55 }
56
57 /// A "Path" is essentially Rust's notion of a name.
58 ///
59 /// It's represented as a sequence of identifiers,
60 /// along with a bunch of supporting information.
61 ///
62 /// E.g., `std::cmp::PartialEq`.
63 #[derive(Clone, RustcEncodable, RustcDecodable)]
64 pub struct Path {
65     pub span: Span,
66     /// The segments in the path: the things separated by `::`.
67     /// Global paths begin with `keywords::PathRoot`.
68     pub segments: Vec<PathSegment>,
69 }
70
71 impl<'a> PartialEq<&'a str> for Path {
72     fn eq(&self, string: &&'a str) -> bool {
73         self.segments.len() == 1 && self.segments[0].ident.name == *string
74     }
75 }
76
77 impl fmt::Debug for Path {
78     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79         write!(f, "path({})", pprust::path_to_string(self))
80     }
81 }
82
83 impl fmt::Display for Path {
84     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85         write!(f, "{}", pprust::path_to_string(self))
86     }
87 }
88
89 impl Path {
90     // Convert a span and an identifier to the corresponding
91     // one-segment path.
92     pub fn from_ident(ident: Ident) -> Path {
93         Path {
94             segments: vec![PathSegment::from_ident(ident)],
95             span: ident.span,
96         }
97     }
98
99     pub fn is_global(&self) -> bool {
100         !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
101     }
102 }
103
104 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
105 ///
106 /// E.g., `std`, `String` or `Box<T>`.
107 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
108 pub struct PathSegment {
109     /// The identifier portion of this path segment.
110     pub ident: Ident,
111
112     pub id: NodeId,
113
114     /// Type/lifetime parameters attached to this path. They come in
115     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
116     /// `None` means that no parameter list is supplied (`Path`),
117     /// `Some` means that parameter list is supplied (`Path<X, Y>`)
118     /// but it can be empty (`Path<>`).
119     /// `P` is used as a size optimization for the common case with no parameters.
120     pub args: Option<P<GenericArgs>>,
121 }
122
123 impl PathSegment {
124     pub fn from_ident(ident: Ident) -> Self {
125         PathSegment { ident, id: DUMMY_NODE_ID, args: None }
126     }
127     pub fn path_root(span: Span) -> Self {
128         PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span))
129     }
130 }
131
132 /// The arguments of a path segment.
133 ///
134 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
135 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
136 pub enum GenericArgs {
137     /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
138     AngleBracketed(AngleBracketedArgs),
139     /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
140     Parenthesized(ParenthesizedArgs),
141 }
142
143 impl GenericArgs {
144     pub fn is_parenthesized(&self) -> bool {
145         match *self {
146             Parenthesized(..) => true,
147             _ => false,
148         }
149     }
150
151     pub fn is_angle_bracketed(&self) -> bool {
152         match *self {
153             AngleBracketed(..) => true,
154             _ => false,
155         }
156     }
157
158     pub fn span(&self) -> Span {
159         match *self {
160             AngleBracketed(ref data) => data.span,
161             Parenthesized(ref data) => data.span,
162         }
163     }
164 }
165
166 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
167 pub enum GenericArg {
168     Lifetime(Lifetime),
169     Type(P<Ty>),
170     Const(AnonConst),
171 }
172
173 impl GenericArg {
174     pub fn span(&self) -> Span {
175         match self {
176             GenericArg::Lifetime(lt) => lt.ident.span,
177             GenericArg::Type(ty) => ty.span,
178             GenericArg::Const(ct) => ct.value.span,
179         }
180     }
181 }
182
183 /// A path like `Foo<'a, T>`.
184 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
185 pub struct AngleBracketedArgs {
186     /// The overall span.
187     pub span: Span,
188     /// The arguments for this path segment.
189     pub args: Vec<GenericArg>,
190     /// Bindings (equality constraints) on associated types, if present.
191     /// E.g., `Foo<A = Bar>`.
192     pub bindings: Vec<TypeBinding>,
193 }
194
195 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
196     fn into(self) -> Option<P<GenericArgs>> {
197         Some(P(GenericArgs::AngleBracketed(self)))
198     }
199 }
200
201 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
202     fn into(self) -> Option<P<GenericArgs>> {
203         Some(P(GenericArgs::Parenthesized(self)))
204     }
205 }
206
207 /// A path like `Foo(A, B) -> C`.
208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
209 pub struct ParenthesizedArgs {
210     /// Overall span
211     pub span: Span,
212
213     /// `(A,B)`
214     pub inputs: Vec<P<Ty>>,
215
216     /// `C`
217     pub output: Option<P<Ty>>,
218 }
219
220 impl ParenthesizedArgs {
221     pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
222         AngleBracketedArgs {
223             span: self.span,
224             args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
225             bindings: vec![],
226         }
227     }
228 }
229
230 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
231 mod node_id_inner {
232     use rustc_data_structures::indexed_vec::Idx;
233     use rustc_data_structures::newtype_index;
234     newtype_index! {
235         pub struct NodeId {
236             ENCODABLE = custom
237             DEBUG_FORMAT = "NodeId({})"
238         }
239     }
240 }
241
242 pub use node_id_inner::NodeId;
243
244 impl NodeId {
245     pub fn placeholder_from_mark(mark: Mark) -> Self {
246         NodeId::from_u32(mark.as_u32())
247     }
248
249     pub fn placeholder_to_mark(self) -> Mark {
250         Mark::from_u32(self.as_u32())
251     }
252 }
253
254 impl fmt::Display for NodeId {
255     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256         fmt::Display::fmt(&self.as_u32(), f)
257     }
258 }
259
260 impl serialize::UseSpecializedEncodable for NodeId {
261     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
262         s.emit_u32(self.as_u32())
263     }
264 }
265
266 impl serialize::UseSpecializedDecodable for NodeId {
267     fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
268         d.read_u32().map(NodeId::from_u32)
269     }
270 }
271
272 /// `NodeId` used to represent the root of the crate.
273 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
274
275 /// When parsing and doing expansions, we initially give all AST nodes this AST
276 /// node value. Then later, in the renumber pass, we renumber them to have
277 /// small, positive ids.
278 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
279
280 /// A modifier on a bound, currently this is only used for `?Sized`, where the
281 /// modifier is `Maybe`. Negative bounds should also be handled here.
282 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
283 pub enum TraitBoundModifier {
284     None,
285     Maybe,
286 }
287
288 /// The AST represents all type param bounds as types.
289 /// `typeck::collect::compute_bounds` matches these against
290 /// the "special" built-in traits (see `middle::lang_items`) and
291 /// detects `Copy`, `Send` and `Sync`.
292 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
293 pub enum GenericBound {
294     Trait(PolyTraitRef, TraitBoundModifier),
295     Outlives(Lifetime),
296 }
297
298 impl GenericBound {
299     pub fn span(&self) -> Span {
300         match self {
301             &GenericBound::Trait(ref t, ..) => t.span,
302             &GenericBound::Outlives(ref l) => l.ident.span,
303         }
304     }
305 }
306
307 pub type GenericBounds = Vec<GenericBound>;
308
309 /// Specifies the enforced ordering for generic parameters. In the future,
310 /// if we wanted to relax this order, we could override `PartialEq` and
311 /// `PartialOrd`, to allow the kinds to be unordered.
312 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
313 pub enum ParamKindOrd {
314     Lifetime,
315     Type,
316     Const,
317 }
318
319 impl fmt::Display for ParamKindOrd {
320     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321         match self {
322             ParamKindOrd::Lifetime => "lifetime".fmt(f),
323             ParamKindOrd::Type => "type".fmt(f),
324             ParamKindOrd::Const => "const".fmt(f),
325         }
326     }
327 }
328
329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
330 pub enum GenericParamKind {
331     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
332     Lifetime,
333     Type { default: Option<P<Ty>> },
334     Const { ty: P<Ty> },
335 }
336
337 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
338 pub struct GenericParam {
339     pub id: NodeId,
340     pub ident: Ident,
341     pub attrs: ThinVec<Attribute>,
342     pub bounds: GenericBounds,
343
344     pub kind: GenericParamKind,
345 }
346
347 /// Represents lifetime, type and const parameters attached to a declaration of
348 /// a function, enum, trait, etc.
349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
350 pub struct Generics {
351     pub params: Vec<GenericParam>,
352     pub where_clause: WhereClause,
353     pub span: Span,
354 }
355
356 impl Default for Generics {
357     /// Creates an instance of `Generics`.
358     fn default() -> Generics {
359         Generics {
360             params: Vec::new(),
361             where_clause: WhereClause {
362                 id: DUMMY_NODE_ID,
363                 predicates: Vec::new(),
364                 span: DUMMY_SP,
365             },
366             span: DUMMY_SP,
367         }
368     }
369 }
370
371 /// A where-clause in a definition.
372 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
373 pub struct WhereClause {
374     pub id: NodeId,
375     pub predicates: Vec<WherePredicate>,
376     pub span: Span,
377 }
378
379 /// A single predicate in a where-clause.
380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
381 pub enum WherePredicate {
382     /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
383     BoundPredicate(WhereBoundPredicate),
384     /// A lifetime predicate (e.g., `'a: 'b + 'c`).
385     RegionPredicate(WhereRegionPredicate),
386     /// An equality predicate (unsupported).
387     EqPredicate(WhereEqPredicate),
388 }
389
390 impl WherePredicate {
391     pub fn span(&self) -> Span {
392         match self {
393             &WherePredicate::BoundPredicate(ref p) => p.span,
394             &WherePredicate::RegionPredicate(ref p) => p.span,
395             &WherePredicate::EqPredicate(ref p) => p.span,
396         }
397     }
398 }
399
400 /// A type bound.
401 ///
402 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
403 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
404 pub struct WhereBoundPredicate {
405     pub span: Span,
406     /// Any generics from a `for` binding
407     pub bound_generic_params: Vec<GenericParam>,
408     /// The type being bounded
409     pub bounded_ty: P<Ty>,
410     /// Trait and lifetime bounds (`Clone+Send+'static`)
411     pub bounds: GenericBounds,
412 }
413
414 /// A lifetime predicate.
415 ///
416 /// E.g., `'a: 'b + 'c`.
417 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
418 pub struct WhereRegionPredicate {
419     pub span: Span,
420     pub lifetime: Lifetime,
421     pub bounds: GenericBounds,
422 }
423
424 /// An equality predicate (unsupported).
425 ///
426 /// E.g., `T = int`.
427 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
428 pub struct WhereEqPredicate {
429     pub id: NodeId,
430     pub span: Span,
431     pub lhs_ty: P<Ty>,
432     pub rhs_ty: P<Ty>,
433 }
434
435 /// The set of `MetaItem`s that define the compilation environment of the crate,
436 /// used to drive conditional compilation.
437 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
438
439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
440 pub struct Crate {
441     pub module: Mod,
442     pub attrs: Vec<Attribute>,
443     pub span: Span,
444 }
445
446 /// A spanned compile-time attribute list item.
447 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
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 NestedMetaItemKind {
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 ident: 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>>, 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 }
901
902 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
903 pub enum Guard {
904     If(P<Expr>),
905 }
906
907 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
908 pub struct Field {
909     pub ident: Ident,
910     pub expr: P<Expr>,
911     pub span: Span,
912     pub is_shorthand: bool,
913     pub attrs: ThinVec<Attribute>,
914 }
915
916 pub type SpannedIdent = Spanned<Ident>;
917
918 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
919 pub enum BlockCheckMode {
920     Default,
921     Unsafe(UnsafeSource),
922 }
923
924 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
925 pub enum UnsafeSource {
926     CompilerGenerated,
927     UserProvided,
928 }
929
930 /// A constant (expression) that's not an item or associated item,
931 /// but needs its own `DefId` for type-checking, const-eval, etc.
932 /// These are usually found nested inside types (e.g., array lengths)
933 /// or expressions (e.g., repeat counts), and also used to define
934 /// explicit discriminant values for enum variants.
935 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
936 pub struct AnonConst {
937     pub id: NodeId,
938     pub value: P<Expr>,
939 }
940
941 /// An expression
942 #[derive(Clone, RustcEncodable, RustcDecodable)]
943 pub struct Expr {
944     pub id: NodeId,
945     pub node: ExprKind,
946     pub span: Span,
947     pub attrs: ThinVec<Attribute>,
948 }
949
950 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
951 #[cfg(target_arch = "x86_64")]
952 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
953
954 impl Expr {
955     /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
956     /// condition.
957     pub fn returns(&self) -> bool {
958         if let ExprKind::Block(ref block, _) = self.node {
959             match block.stmts.last().map(|last_stmt| &last_stmt.node) {
960                 // implicit return
961                 Some(&StmtKind::Expr(_)) => true,
962                 Some(&StmtKind::Semi(ref expr)) => {
963                     if let ExprKind::Ret(_) = expr.node {
964                         // last statement is explicit return
965                         true
966                     } else {
967                         false
968                     }
969                 }
970                 // This is a block that doesn't end in either an implicit or explicit return
971                 _ => false,
972             }
973         } else {
974             // This is not a block, it is a value
975             true
976         }
977     }
978
979     fn to_bound(&self) -> Option<GenericBound> {
980         match &self.node {
981             ExprKind::Path(None, path) => Some(GenericBound::Trait(
982                 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
983                 TraitBoundModifier::None,
984             )),
985             _ => None,
986         }
987     }
988
989     pub(super) fn to_ty(&self) -> Option<P<Ty>> {
990         let node = match &self.node {
991             ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
992             ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
993             ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
994             ExprKind::AddrOf(mutbl, expr) => expr
995                 .to_ty()
996                 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
997             ExprKind::Repeat(expr, expr_len) => {
998                 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
999             }
1000             ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1001             ExprKind::Tup(exprs) => {
1002                 let tys = exprs
1003                     .iter()
1004                     .map(|expr| expr.to_ty())
1005                     .collect::<Option<Vec<_>>>()?;
1006                 TyKind::Tup(tys)
1007             }
1008             ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1009                 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1010                     TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1011                 } else {
1012                     return None;
1013                 }
1014             }
1015             _ => return None,
1016         };
1017
1018         Some(P(Ty {
1019             node,
1020             id: self.id,
1021             span: self.span,
1022         }))
1023     }
1024
1025     pub fn precedence(&self) -> ExprPrecedence {
1026         match self.node {
1027             ExprKind::Box(_) => ExprPrecedence::Box,
1028             ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
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::Assign(..) => ExprPrecedence::Assign,
1049             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1050             ExprKind::Field(..) => ExprPrecedence::Field,
1051             ExprKind::Index(..) => ExprPrecedence::Index,
1052             ExprKind::Range(..) => ExprPrecedence::Range,
1053             ExprKind::Path(..) => ExprPrecedence::Path,
1054             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1055             ExprKind::Break(..) => ExprPrecedence::Break,
1056             ExprKind::Continue(..) => ExprPrecedence::Continue,
1057             ExprKind::Ret(..) => ExprPrecedence::Ret,
1058             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1059             ExprKind::Mac(..) => ExprPrecedence::Mac,
1060             ExprKind::Struct(..) => ExprPrecedence::Struct,
1061             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1062             ExprKind::Paren(..) => ExprPrecedence::Paren,
1063             ExprKind::Try(..) => ExprPrecedence::Try,
1064             ExprKind::Yield(..) => ExprPrecedence::Yield,
1065             ExprKind::Err => ExprPrecedence::Err,
1066         }
1067     }
1068 }
1069
1070 impl fmt::Debug for Expr {
1071     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1072         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1073     }
1074 }
1075
1076 /// Limit types of a range (inclusive or exclusive)
1077 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1078 pub enum RangeLimits {
1079     /// Inclusive at the beginning, exclusive at the end
1080     HalfOpen,
1081     /// Inclusive at the beginning and end
1082     Closed,
1083 }
1084
1085 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1086 pub enum ExprKind {
1087     /// A `box x` expression.
1088     Box(P<Expr>),
1089     /// First expr is the place; second expr is the value.
1090     ObsoleteInPlace(P<Expr>, P<Expr>),
1091     /// An array (`[a, b, c, d]`)
1092     Array(Vec<P<Expr>>),
1093     /// A function call
1094     ///
1095     /// The first field resolves to the function itself,
1096     /// and the second field is the list of arguments.
1097     /// This also represents calling the constructor of
1098     /// tuple-like ADTs such as tuple structs and enum variants.
1099     Call(P<Expr>, Vec<P<Expr>>),
1100     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1101     ///
1102     /// The `PathSegment` represents the method name and its generic arguments
1103     /// (within the angle brackets).
1104     /// The first element of the vector of an `Expr` is the expression that evaluates
1105     /// to the object on which the method is being called on (the receiver),
1106     /// and the remaining elements are the rest of the arguments.
1107     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1108     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1109     MethodCall(PathSegment, Vec<P<Expr>>),
1110     /// A tuple (e.g., `(a, b, c, d)`).
1111     Tup(Vec<P<Expr>>),
1112     /// A binary operation (e.g., `a + b`, `a * b`).
1113     Binary(BinOp, P<Expr>, P<Expr>),
1114     /// A unary operation (e.g., `!x`, `*x`).
1115     Unary(UnOp, P<Expr>),
1116     /// A literal (e.g., `1`, `"foo"`).
1117     Lit(Lit),
1118     /// A cast (e.g., `foo as f64`).
1119     Cast(P<Expr>, P<Ty>),
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     /// A try block (`try { ... }`).
1169     TryBlock(P<Block>),
1170
1171     /// An assignment (`a = foo()`).
1172     Assign(P<Expr>, P<Expr>),
1173     /// An assignment with an operator.
1174     ///
1175     /// E.g., `a += 1`.
1176     AssignOp(BinOp, P<Expr>, P<Expr>),
1177     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1178     Field(P<Expr>, Ident),
1179     /// An indexing operation (e.g., `foo[2]`).
1180     Index(P<Expr>, P<Expr>),
1181     /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
1182     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1183
1184     /// Variable reference, possibly containing `::` and/or type
1185     /// parameters (e.g., `foo::bar::<baz>`).
1186     ///
1187     /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1188     Path(Option<QSelf>, Path),
1189
1190     /// A referencing operation (`&a` or `&mut a`).
1191     AddrOf(Mutability, P<Expr>),
1192     /// A `break`, with an optional label to break, and an optional expression.
1193     Break(Option<Label>, Option<P<Expr>>),
1194     /// A `continue`, with an optional label.
1195     Continue(Option<Label>),
1196     /// A `return`, with an optional value to be returned.
1197     Ret(Option<P<Expr>>),
1198
1199     /// Output of the `asm!()` macro.
1200     InlineAsm(P<InlineAsm>),
1201
1202     /// A macro invocation; pre-expansion.
1203     Mac(Mac),
1204
1205     /// A struct literal expression.
1206     ///
1207     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1208     /// where `base` is the `Option<Expr>`.
1209     Struct(Path, Vec<Field>, Option<P<Expr>>),
1210
1211     /// An array literal constructed from one repeated element.
1212     ///
1213     /// E.g., `[1; 5]`. The expression is the element to be
1214     /// repeated; the constant is the number of times to repeat it.
1215     Repeat(P<Expr>, AnonConst),
1216
1217     /// No-op: used solely so we can pretty-print faithfully.
1218     Paren(P<Expr>),
1219
1220     /// A try expression (`expr?`).
1221     Try(P<Expr>),
1222
1223     /// A `yield`, with an optional value to be yielded.
1224     Yield(Option<P<Expr>>),
1225
1226     /// Placeholder for an expression that wasn't syntactically well formed in some way.
1227     Err,
1228 }
1229
1230 /// The explicit `Self` type in a "qualified path". The actual
1231 /// path, including the trait and the associated item, is stored
1232 /// separately. `position` represents the index of the associated
1233 /// item qualified with this `Self` type.
1234 ///
1235 /// ```ignore (only-for-syntax-highlight)
1236 /// <Vec<T> as a::b::Trait>::AssociatedItem
1237 ///  ^~~~~     ~~~~~~~~~~~~~~^
1238 ///  ty        position = 3
1239 ///
1240 /// <Vec<T>>::AssociatedItem
1241 ///  ^~~~~    ^
1242 ///  ty       position = 0
1243 /// ```
1244 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1245 pub struct QSelf {
1246     pub ty: P<Ty>,
1247
1248     /// The span of `a::b::Trait` in a path like `<Vec<T> as
1249     /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1250     /// 0`, this is an empty span.
1251     pub path_span: Span,
1252     pub position: usize,
1253 }
1254
1255 /// A capture clause.
1256 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1257 pub enum CaptureBy {
1258     Value,
1259     Ref,
1260 }
1261
1262 /// The movability of a generator / closure literal.
1263 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1264 pub enum Movability {
1265     Static,
1266     Movable,
1267 }
1268
1269 pub type Mac = Spanned<Mac_>;
1270
1271 /// Represents a macro invocation. The `Path` indicates which macro
1272 /// is being invoked, and the vector of token-trees contains the source
1273 /// of the macro invocation.
1274 ///
1275 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1276 /// stored in the enclosing item.
1277 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1278 pub struct Mac_ {
1279     pub path: Path,
1280     pub delim: MacDelimiter,
1281     pub tts: TokenStream,
1282 }
1283
1284 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1285 pub enum MacDelimiter {
1286     Parenthesis,
1287     Bracket,
1288     Brace,
1289 }
1290
1291 impl Mac_ {
1292     pub fn stream(&self) -> TokenStream {
1293         self.tts.clone()
1294     }
1295 }
1296
1297 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1298 pub struct MacroDef {
1299     pub tokens: TokenStream,
1300     pub legacy: bool,
1301 }
1302
1303 impl MacroDef {
1304     pub fn stream(&self) -> TokenStream {
1305         self.tokens.clone().into()
1306     }
1307 }
1308
1309 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1310 pub enum StrStyle {
1311     /// A regular string, like `"foo"`.
1312     Cooked,
1313     /// A raw string, like `r##"foo"##`.
1314     ///
1315     /// The value is the number of `#` symbols used.
1316     Raw(u16),
1317 }
1318
1319 /// A literal.
1320 pub type Lit = Spanned<LitKind>;
1321
1322 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1323 pub enum LitIntType {
1324     Signed(IntTy),
1325     Unsigned(UintTy),
1326     Unsuffixed,
1327 }
1328
1329 /// Literal kind.
1330 ///
1331 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1332 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1333 pub enum LitKind {
1334     /// A string literal (`"foo"`).
1335     Str(Symbol, StrStyle),
1336     /// A byte string (`b"foo"`).
1337     ByteStr(Lrc<Vec<u8>>),
1338     /// A byte char (`b'f'`).
1339     Byte(u8),
1340     /// A character literal (`'a'`).
1341     Char(char),
1342     /// An integer literal (`1`).
1343     Int(u128, LitIntType),
1344     /// A float literal (`1f64` or `1E10f64`).
1345     Float(Symbol, FloatTy),
1346     /// A float literal without a suffix (`1.0 or 1.0E10`).
1347     FloatUnsuffixed(Symbol),
1348     /// A boolean literal.
1349     Bool(bool),
1350     /// A recovered character literal that contains mutliple `char`s, most likely a typo.
1351     Err(Symbol),
1352 }
1353
1354 impl LitKind {
1355     /// Returns `true` if this literal is a string.
1356     pub fn is_str(&self) -> bool {
1357         match *self {
1358             LitKind::Str(..) => true,
1359             _ => false,
1360         }
1361     }
1362
1363     /// Returns `true` if this literal is byte literal string.
1364     pub fn is_bytestr(&self) -> bool {
1365         match self {
1366             LitKind::ByteStr(_) => true,
1367             _ => false,
1368         }
1369     }
1370
1371     /// Returns `true` if this is a numeric literal.
1372     pub fn is_numeric(&self) -> bool {
1373         match *self {
1374             LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1375             _ => false,
1376         }
1377     }
1378
1379     /// Returns `true` if this literal has no suffix.
1380     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1381     pub fn is_unsuffixed(&self) -> bool {
1382         match *self {
1383             // unsuffixed variants
1384             LitKind::Str(..)
1385             | LitKind::ByteStr(..)
1386             | LitKind::Byte(..)
1387             | LitKind::Char(..)
1388             | LitKind::Err(..)
1389             | LitKind::Int(_, LitIntType::Unsuffixed)
1390             | LitKind::FloatUnsuffixed(..)
1391             | LitKind::Bool(..) => true,
1392             // suffixed variants
1393             LitKind::Int(_, LitIntType::Signed(..))
1394             | LitKind::Int(_, LitIntType::Unsigned(..))
1395             | LitKind::Float(..) => false,
1396         }
1397     }
1398
1399     /// Returns `true` if this literal has a suffix.
1400     pub fn is_suffixed(&self) -> bool {
1401         !self.is_unsuffixed()
1402     }
1403 }
1404
1405 // N.B., If you change this, you'll probably want to change the corresponding
1406 // type structure in `middle/ty.rs` as well.
1407 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1408 pub struct MutTy {
1409     pub ty: P<Ty>,
1410     pub mutbl: Mutability,
1411 }
1412
1413 /// Represents a method's signature in a trait declaration,
1414 /// or in an implementation.
1415 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1416 pub struct MethodSig {
1417     pub header: FnHeader,
1418     pub decl: P<FnDecl>,
1419 }
1420
1421 /// Represents an item declaration within a trait declaration,
1422 /// possibly including a default implementation. A trait item is
1423 /// either required (meaning it doesn't have an implementation, just a
1424 /// signature) or provided (meaning it has a default implementation).
1425 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1426 pub struct TraitItem {
1427     pub id: NodeId,
1428     pub ident: Ident,
1429     pub attrs: Vec<Attribute>,
1430     pub generics: Generics,
1431     pub node: TraitItemKind,
1432     pub span: Span,
1433     /// See `Item::tokens` for what this is.
1434     pub tokens: Option<TokenStream>,
1435 }
1436
1437 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1438 pub enum TraitItemKind {
1439     Const(P<Ty>, Option<P<Expr>>),
1440     Method(MethodSig, Option<P<Block>>),
1441     Type(GenericBounds, Option<P<Ty>>),
1442     Macro(Mac),
1443 }
1444
1445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1446 pub struct ImplItem {
1447     pub id: NodeId,
1448     pub ident: Ident,
1449     pub vis: Visibility,
1450     pub defaultness: Defaultness,
1451     pub attrs: Vec<Attribute>,
1452     pub generics: Generics,
1453     pub node: ImplItemKind,
1454     pub span: Span,
1455     /// See `Item::tokens` for what this is.
1456     pub tokens: Option<TokenStream>,
1457 }
1458
1459 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1460 pub enum ImplItemKind {
1461     Const(P<Ty>, P<Expr>),
1462     Method(MethodSig, P<Block>),
1463     Type(P<Ty>),
1464     Existential(GenericBounds),
1465     Macro(Mac),
1466 }
1467
1468 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1469 pub enum IntTy {
1470     Isize,
1471     I8,
1472     I16,
1473     I32,
1474     I64,
1475     I128,
1476 }
1477
1478 impl fmt::Debug for IntTy {
1479     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1480         fmt::Display::fmt(self, f)
1481     }
1482 }
1483
1484 impl fmt::Display for IntTy {
1485     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1486         write!(f, "{}", self.ty_to_string())
1487     }
1488 }
1489
1490 impl IntTy {
1491     pub fn ty_to_string(&self) -> &'static str {
1492         match *self {
1493             IntTy::Isize => "isize",
1494             IntTy::I8 => "i8",
1495             IntTy::I16 => "i16",
1496             IntTy::I32 => "i32",
1497             IntTy::I64 => "i64",
1498             IntTy::I128 => "i128",
1499         }
1500     }
1501
1502     pub fn val_to_string(&self, val: i128) -> String {
1503         // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1504         // are parsed as `u128`, so we wouldn't want to print an extra negative
1505         // sign.
1506         format!("{}{}", val as u128, self.ty_to_string())
1507     }
1508
1509     pub fn bit_width(&self) -> Option<usize> {
1510         Some(match *self {
1511             IntTy::Isize => return None,
1512             IntTy::I8 => 8,
1513             IntTy::I16 => 16,
1514             IntTy::I32 => 32,
1515             IntTy::I64 => 64,
1516             IntTy::I128 => 128,
1517         })
1518     }
1519 }
1520
1521 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1522 pub enum UintTy {
1523     Usize,
1524     U8,
1525     U16,
1526     U32,
1527     U64,
1528     U128,
1529 }
1530
1531 impl UintTy {
1532     pub fn ty_to_string(&self) -> &'static str {
1533         match *self {
1534             UintTy::Usize => "usize",
1535             UintTy::U8 => "u8",
1536             UintTy::U16 => "u16",
1537             UintTy::U32 => "u32",
1538             UintTy::U64 => "u64",
1539             UintTy::U128 => "u128",
1540         }
1541     }
1542
1543     pub fn val_to_string(&self, val: u128) -> String {
1544         format!("{}{}", val, self.ty_to_string())
1545     }
1546
1547     pub fn bit_width(&self) -> Option<usize> {
1548         Some(match *self {
1549             UintTy::Usize => return None,
1550             UintTy::U8 => 8,
1551             UintTy::U16 => 16,
1552             UintTy::U32 => 32,
1553             UintTy::U64 => 64,
1554             UintTy::U128 => 128,
1555         })
1556     }
1557 }
1558
1559 impl fmt::Debug for UintTy {
1560     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1561         fmt::Display::fmt(self, f)
1562     }
1563 }
1564
1565 impl fmt::Display for UintTy {
1566     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1567         write!(f, "{}", self.ty_to_string())
1568     }
1569 }
1570
1571 // Bind a type to an associated type: `A = Foo`.
1572 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1573 pub struct TypeBinding {
1574     pub id: NodeId,
1575     pub ident: Ident,
1576     pub ty: P<Ty>,
1577     pub span: Span,
1578 }
1579
1580 #[derive(Clone, RustcEncodable, RustcDecodable)]
1581 pub struct Ty {
1582     pub id: NodeId,
1583     pub node: TyKind,
1584     pub span: Span,
1585 }
1586
1587 impl fmt::Debug for Ty {
1588     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1589         write!(f, "type({})", pprust::ty_to_string(self))
1590     }
1591 }
1592
1593 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1594 pub struct BareFnTy {
1595     pub unsafety: Unsafety,
1596     pub abi: Abi,
1597     pub generic_params: Vec<GenericParam>,
1598     pub decl: P<FnDecl>,
1599 }
1600
1601 /// The various kinds of type recognized by the compiler.
1602 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1603 pub enum TyKind {
1604     /// A variable-length slice (`[T]`).
1605     Slice(P<Ty>),
1606     /// A fixed length array (`[T; n]`).
1607     Array(P<Ty>, AnonConst),
1608     /// A raw pointer (`*const T` or `*mut T`).
1609     Ptr(MutTy),
1610     /// A reference (`&'a T` or `&'a mut T`).
1611     Rptr(Option<Lifetime>, MutTy),
1612     /// A bare function (e.g., `fn(usize) -> bool`).
1613     BareFn(P<BareFnTy>),
1614     /// The never type (`!`).
1615     Never,
1616     /// A tuple (`(A, B, C, D,...)`).
1617     Tup(Vec<P<Ty>>),
1618     /// A path (`module::module::...::Type`), optionally
1619     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1620     ///
1621     /// Type parameters are stored in the `Path` itself.
1622     Path(Option<QSelf>, Path),
1623     /// A trait object type `Bound1 + Bound2 + Bound3`
1624     /// where `Bound` is a trait or a lifetime.
1625     TraitObject(GenericBounds, TraitObjectSyntax),
1626     /// An `impl Bound1 + Bound2 + Bound3` type
1627     /// where `Bound` is a trait or a lifetime.
1628     ///
1629     /// The `NodeId` exists to prevent lowering from having to
1630     /// generate `NodeId`s on the fly, which would complicate
1631     /// the generation of `existential type` items significantly.
1632     ImplTrait(NodeId, GenericBounds),
1633     /// No-op; kept solely so that we can pretty-print faithfully.
1634     Paren(P<Ty>),
1635     /// Unused for now.
1636     Typeof(AnonConst),
1637     /// This means the type should be inferred instead of it having been
1638     /// specified. This can appear anywhere in a type.
1639     Infer,
1640     /// Inferred type of a `self` or `&self` argument in a method.
1641     ImplicitSelf,
1642     /// A macro in the type position.
1643     Mac(Mac),
1644     /// Placeholder for a kind that has failed to be defined.
1645     Err,
1646 }
1647
1648 impl TyKind {
1649     pub fn is_implicit_self(&self) -> bool {
1650         if let TyKind::ImplicitSelf = *self {
1651             true
1652         } else {
1653             false
1654         }
1655     }
1656
1657     pub fn is_unit(&self) -> bool {
1658         if let TyKind::Tup(ref tys) = *self {
1659             tys.is_empty()
1660         } else {
1661             false
1662         }
1663     }
1664 }
1665
1666 /// Syntax used to declare a trait object.
1667 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1668 pub enum TraitObjectSyntax {
1669     Dyn,
1670     None,
1671 }
1672
1673 /// Inline assembly dialect.
1674 ///
1675 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1676 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1677 pub enum AsmDialect {
1678     Att,
1679     Intel,
1680 }
1681
1682 /// Inline assembly.
1683 ///
1684 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1685 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1686 pub struct InlineAsmOutput {
1687     pub constraint: Symbol,
1688     pub expr: P<Expr>,
1689     pub is_rw: bool,
1690     pub is_indirect: bool,
1691 }
1692
1693 /// Inline assembly.
1694 ///
1695 /// E.g., `asm!("NOP");`.
1696 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1697 pub struct InlineAsm {
1698     pub asm: Symbol,
1699     pub asm_str_style: StrStyle,
1700     pub outputs: Vec<InlineAsmOutput>,
1701     pub inputs: Vec<(Symbol, P<Expr>)>,
1702     pub clobbers: Vec<Symbol>,
1703     pub volatile: bool,
1704     pub alignstack: bool,
1705     pub dialect: AsmDialect,
1706     pub ctxt: SyntaxContext,
1707 }
1708
1709 /// An argument in a function header.
1710 ///
1711 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1712 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1713 pub struct Arg {
1714     pub ty: P<Ty>,
1715     pub pat: P<Pat>,
1716     pub id: NodeId,
1717 }
1718
1719 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1720 ///
1721 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1722 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1723 pub enum SelfKind {
1724     /// `self`, `mut self`
1725     Value(Mutability),
1726     /// `&'lt self`, `&'lt mut self`
1727     Region(Option<Lifetime>, Mutability),
1728     /// `self: TYPE`, `mut self: TYPE`
1729     Explicit(P<Ty>, Mutability),
1730 }
1731
1732 pub type ExplicitSelf = Spanned<SelfKind>;
1733
1734 impl Arg {
1735     pub fn to_self(&self) -> Option<ExplicitSelf> {
1736         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1737             if ident.name == keywords::SelfLower.name() {
1738                 return match self.ty.node {
1739                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1740                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1741                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1742                     }
1743                     _ => Some(respan(
1744                         self.pat.span.to(self.ty.span),
1745                         SelfKind::Explicit(self.ty.clone(), mutbl),
1746                     )),
1747                 };
1748             }
1749         }
1750         None
1751     }
1752
1753     pub fn is_self(&self) -> bool {
1754         if let PatKind::Ident(_, ident, _) = self.pat.node {
1755             ident.name == keywords::SelfLower.name()
1756         } else {
1757             false
1758         }
1759     }
1760
1761     pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1762         let span = eself.span.to(eself_ident.span);
1763         let infer_ty = P(Ty {
1764             id: DUMMY_NODE_ID,
1765             node: TyKind::ImplicitSelf,
1766             span,
1767         });
1768         let arg = |mutbl, ty| Arg {
1769             pat: P(Pat {
1770                 id: DUMMY_NODE_ID,
1771                 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1772                 span,
1773             }),
1774             ty,
1775             id: DUMMY_NODE_ID,
1776         };
1777         match eself.node {
1778             SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1779             SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1780             SelfKind::Region(lt, mutbl) => arg(
1781                 Mutability::Immutable,
1782                 P(Ty {
1783                     id: DUMMY_NODE_ID,
1784                     node: TyKind::Rptr(
1785                         lt,
1786                         MutTy {
1787                             ty: infer_ty,
1788                             mutbl: mutbl,
1789                         },
1790                     ),
1791                     span,
1792                 }),
1793             ),
1794         }
1795     }
1796 }
1797
1798 /// Header (not the body) of a function declaration.
1799 ///
1800 /// E.g., `fn foo(bar: baz)`.
1801 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1802 pub struct FnDecl {
1803     pub inputs: Vec<Arg>,
1804     pub output: FunctionRetTy,
1805     pub variadic: bool,
1806 }
1807
1808 impl FnDecl {
1809     pub fn get_self(&self) -> Option<ExplicitSelf> {
1810         self.inputs.get(0).and_then(Arg::to_self)
1811     }
1812     pub fn has_self(&self) -> bool {
1813         self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1814     }
1815 }
1816
1817 /// Is the trait definition an auto trait?
1818 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1819 pub enum IsAuto {
1820     Yes,
1821     No,
1822 }
1823
1824 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1825 pub enum Unsafety {
1826     Unsafe,
1827     Normal,
1828 }
1829
1830 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1831 pub enum IsAsync {
1832     Async {
1833         closure_id: NodeId,
1834         return_impl_trait_id: NodeId,
1835     },
1836     NotAsync,
1837 }
1838
1839 impl IsAsync {
1840     pub fn is_async(self) -> bool {
1841         if let IsAsync::Async { .. } = self {
1842             true
1843         } else {
1844             false
1845         }
1846     }
1847
1848     /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1849     pub fn opt_return_id(self) -> Option<NodeId> {
1850         match self {
1851             IsAsync::Async {
1852                 return_impl_trait_id,
1853                 ..
1854             } => Some(return_impl_trait_id),
1855             IsAsync::NotAsync => None,
1856         }
1857     }
1858 }
1859
1860 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1861 pub enum Constness {
1862     Const,
1863     NotConst,
1864 }
1865
1866 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1867 pub enum Defaultness {
1868     Default,
1869     Final,
1870 }
1871
1872 impl fmt::Display for Unsafety {
1873     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1874         fmt::Display::fmt(
1875             match *self {
1876                 Unsafety::Normal => "normal",
1877                 Unsafety::Unsafe => "unsafe",
1878             },
1879             f,
1880         )
1881     }
1882 }
1883
1884 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1885 pub enum ImplPolarity {
1886     /// `impl Trait for Type`
1887     Positive,
1888     /// `impl !Trait for Type`
1889     Negative,
1890 }
1891
1892 impl fmt::Debug for ImplPolarity {
1893     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894         match *self {
1895             ImplPolarity::Positive => "positive".fmt(f),
1896             ImplPolarity::Negative => "negative".fmt(f),
1897         }
1898     }
1899 }
1900
1901 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1902 pub enum FunctionRetTy {
1903     /// Returns type is not specified.
1904     ///
1905     /// Functions default to `()` and closures default to inference.
1906     /// Span points to where return type would be inserted.
1907     Default(Span),
1908     /// Everything else.
1909     Ty(P<Ty>),
1910 }
1911
1912 impl FunctionRetTy {
1913     pub fn span(&self) -> Span {
1914         match *self {
1915             FunctionRetTy::Default(span) => span,
1916             FunctionRetTy::Ty(ref ty) => ty.span,
1917         }
1918     }
1919 }
1920
1921 /// Module declaration.
1922 ///
1923 /// E.g., `mod foo;` or `mod foo { .. }`.
1924 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1925 pub struct Mod {
1926     /// A span from the first token past `{` to the last token until `}`.
1927     /// For `mod foo;`, the inner span ranges from the first token
1928     /// to the last token in the external file.
1929     pub inner: Span,
1930     pub items: Vec<P<Item>>,
1931     /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
1932     pub inline: bool,
1933 }
1934
1935 /// Foreign module declaration.
1936 ///
1937 /// E.g., `extern { .. }` or `extern C { .. }`.
1938 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1939 pub struct ForeignMod {
1940     pub abi: Abi,
1941     pub items: Vec<ForeignItem>,
1942 }
1943
1944 /// Global inline assembly.
1945 ///
1946 /// Also known as "module-level assembly" or "file-scoped assembly".
1947 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1948 pub struct GlobalAsm {
1949     pub asm: Symbol,
1950     pub ctxt: SyntaxContext,
1951 }
1952
1953 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1954 pub struct EnumDef {
1955     pub variants: Vec<Variant>,
1956 }
1957
1958 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1959 pub struct Variant_ {
1960     pub ident: Ident,
1961     pub attrs: Vec<Attribute>,
1962     pub data: VariantData,
1963     /// Explicit discriminant, e.g., `Foo = 1`.
1964     pub disr_expr: Option<AnonConst>,
1965 }
1966
1967 pub type Variant = Spanned<Variant_>;
1968
1969 /// Part of `use` item to the right of its prefix.
1970 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1971 pub enum UseTreeKind {
1972     /// `use prefix` or `use prefix as rename`
1973     ///
1974     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1975     /// namespace.
1976     Simple(Option<Ident>, NodeId, NodeId),
1977     /// `use prefix::{...}`
1978     Nested(Vec<(UseTree, NodeId)>),
1979     /// `use prefix::*`
1980     Glob,
1981 }
1982
1983 /// A tree of paths sharing common prefixes.
1984 /// Used in `use` items both at top-level and inside of braces in import groups.
1985 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1986 pub struct UseTree {
1987     pub prefix: Path,
1988     pub kind: UseTreeKind,
1989     pub span: Span,
1990 }
1991
1992 impl UseTree {
1993     pub fn ident(&self) -> Ident {
1994         match self.kind {
1995             UseTreeKind::Simple(Some(rename), ..) => rename,
1996             UseTreeKind::Simple(None, ..) => {
1997                 self.prefix
1998                     .segments
1999                     .last()
2000                     .expect("empty prefix in a simple import")
2001                     .ident
2002             }
2003             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2004         }
2005     }
2006 }
2007
2008 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2009 /// are contained as statements within items. These two cases need to be
2010 /// distinguished for pretty-printing.
2011 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2012 pub enum AttrStyle {
2013     Outer,
2014     Inner,
2015 }
2016
2017 #[derive(
2018     Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
2019 )]
2020 pub struct AttrId(pub usize);
2021
2022 impl Idx for AttrId {
2023     fn new(idx: usize) -> Self {
2024         AttrId(idx)
2025     }
2026     fn index(self) -> usize {
2027         self.0
2028     }
2029 }
2030
2031 /// Metadata associated with an item.
2032 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2033 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2034 pub struct Attribute {
2035     pub id: AttrId,
2036     pub style: AttrStyle,
2037     pub path: Path,
2038     pub tokens: TokenStream,
2039     pub is_sugared_doc: bool,
2040     pub span: Span,
2041 }
2042
2043 /// `TraitRef`s appear in impls.
2044 ///
2045 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2046 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2047 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2048 /// same as the impl's `NodeId`).
2049 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2050 pub struct TraitRef {
2051     pub path: Path,
2052     pub ref_id: NodeId,
2053 }
2054
2055 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2056 pub struct PolyTraitRef {
2057     /// The `'a` in `<'a> Foo<&'a T>`
2058     pub bound_generic_params: Vec<GenericParam>,
2059
2060     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2061     pub trait_ref: TraitRef,
2062
2063     pub span: Span,
2064 }
2065
2066 impl PolyTraitRef {
2067     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2068         PolyTraitRef {
2069             bound_generic_params: generic_params,
2070             trait_ref: TraitRef {
2071                 path: path,
2072                 ref_id: DUMMY_NODE_ID,
2073             },
2074             span,
2075         }
2076     }
2077 }
2078
2079 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2080 pub enum CrateSugar {
2081     /// Source is `pub(crate)`.
2082     PubCrate,
2083
2084     /// Source is (just) `crate`.
2085     JustCrate,
2086 }
2087
2088 pub type Visibility = Spanned<VisibilityKind>;
2089
2090 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2091 pub enum VisibilityKind {
2092     Public,
2093     Crate(CrateSugar),
2094     Restricted { path: P<Path>, id: NodeId },
2095     Inherited,
2096 }
2097
2098 impl VisibilityKind {
2099     pub fn is_pub(&self) -> bool {
2100         if let VisibilityKind::Public = *self {
2101             true
2102         } else {
2103             false
2104         }
2105     }
2106 }
2107
2108 /// Field of a struct.
2109 ///
2110 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2111 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2112 pub struct StructField {
2113     pub span: Span,
2114     pub ident: Option<Ident>,
2115     pub vis: Visibility,
2116     pub id: NodeId,
2117     pub ty: P<Ty>,
2118     pub attrs: Vec<Attribute>,
2119 }
2120
2121 /// Fields and Ids of enum variants and structs
2122 ///
2123 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2124 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2125 /// One shared Id can be successfully used for these two purposes.
2126 /// Id of the whole enum lives in `Item`.
2127 ///
2128 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2129 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2130 /// the variant itself" from enum variants.
2131 /// Id of the whole struct lives in `Item`.
2132 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2133 pub enum VariantData {
2134     /// Struct variant.
2135     ///
2136     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2137     Struct(Vec<StructField>, NodeId),
2138     /// Tuple variant.
2139     ///
2140     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2141     Tuple(Vec<StructField>, NodeId),
2142     /// Unit variant.
2143     ///
2144     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2145     Unit(NodeId),
2146 }
2147
2148 impl VariantData {
2149     pub fn fields(&self) -> &[StructField] {
2150         match *self {
2151             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2152             _ => &[],
2153         }
2154     }
2155     pub fn id(&self) -> NodeId {
2156         match *self {
2157             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2158         }
2159     }
2160     pub fn is_struct(&self) -> bool {
2161         if let VariantData::Struct(..) = *self {
2162             true
2163         } else {
2164             false
2165         }
2166     }
2167     pub fn is_tuple(&self) -> bool {
2168         if let VariantData::Tuple(..) = *self {
2169             true
2170         } else {
2171             false
2172         }
2173     }
2174     pub fn is_unit(&self) -> bool {
2175         if let VariantData::Unit(..) = *self {
2176             true
2177         } else {
2178             false
2179         }
2180     }
2181 }
2182
2183 /// An item.
2184 ///
2185 /// The name might be a dummy name in case of anonymous items.
2186 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2187 pub struct Item {
2188     pub ident: Ident,
2189     pub attrs: Vec<Attribute>,
2190     pub id: NodeId,
2191     pub node: ItemKind,
2192     pub vis: Visibility,
2193     pub span: Span,
2194
2195     /// Original tokens this item was parsed from. This isn't necessarily
2196     /// available for all items, although over time more and more items should
2197     /// have this be `Some`. Right now this is primarily used for procedural
2198     /// macros, notably custom attributes.
2199     ///
2200     /// Note that the tokens here do not include the outer attributes, but will
2201     /// include inner attributes.
2202     pub tokens: Option<TokenStream>,
2203 }
2204
2205 impl Item {
2206     /// Return the span that encompasses the attributes.
2207     pub fn span_with_attributes(&self) -> Span {
2208         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span()))
2209     }
2210 }
2211
2212 /// A function header.
2213 ///
2214 /// All the information between the visibility and the name of the function is
2215 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2216 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2217 pub struct FnHeader {
2218     pub unsafety: Unsafety,
2219     pub asyncness: IsAsync,
2220     pub constness: Spanned<Constness>,
2221     pub abi: Abi,
2222 }
2223
2224 impl Default for FnHeader {
2225     fn default() -> FnHeader {
2226         FnHeader {
2227             unsafety: Unsafety::Normal,
2228             asyncness: IsAsync::NotAsync,
2229             constness: dummy_spanned(Constness::NotConst),
2230             abi: Abi::Rust,
2231         }
2232     }
2233 }
2234
2235 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2236 pub enum ItemKind {
2237     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2238     ///
2239     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2240     ExternCrate(Option<Name>),
2241     /// A use declaration (`use` or `pub use`) item.
2242     ///
2243     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2244     Use(P<UseTree>),
2245     /// A static item (`static` or `pub static`).
2246     ///
2247     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2248     Static(P<Ty>, Mutability, P<Expr>),
2249     /// A constant item (`const` or `pub const`).
2250     ///
2251     /// E.g., `const FOO: i32 = 42;`.
2252     Const(P<Ty>, P<Expr>),
2253     /// A function declaration (`fn` or `pub fn`).
2254     ///
2255     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2256     Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2257     /// A module declaration (`mod` or `pub mod`).
2258     ///
2259     /// E.g., `mod foo;` or `mod foo { .. }`.
2260     Mod(Mod),
2261     /// An external module (`extern` or `pub extern`).
2262     ///
2263     /// E.g., `extern {}` or `extern "C" {}`.
2264     ForeignMod(ForeignMod),
2265     /// Module-level inline assembly (from `global_asm!()`).
2266     GlobalAsm(P<GlobalAsm>),
2267     /// A type alias (`type` or `pub type`).
2268     ///
2269     /// E.g., `type Foo = Bar<u8>;`.
2270     Ty(P<Ty>, Generics),
2271     /// An existential type declaration (`existential type`).
2272     ///
2273     /// E.g., `existential type Foo: Bar + Boo;`.
2274     Existential(GenericBounds, Generics),
2275     /// An enum definition (`enum` or `pub enum`).
2276     ///
2277     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2278     Enum(EnumDef, Generics),
2279     /// A struct definition (`struct` or `pub struct`).
2280     ///
2281     /// E.g., `struct Foo<A> { x: A }`.
2282     Struct(VariantData, Generics),
2283     /// A union definition (`union` or `pub union`).
2284     ///
2285     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2286     Union(VariantData, Generics),
2287     /// A Trait declaration (`trait` or `pub trait`).
2288     ///
2289     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2290     Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2291     /// Trait alias
2292     ///
2293     /// E.g., `trait Foo = Bar + Quux;`.
2294     TraitAlias(Generics, GenericBounds),
2295     /// An implementation.
2296     ///
2297     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2298     Impl(
2299         Unsafety,
2300         ImplPolarity,
2301         Defaultness,
2302         Generics,
2303         Option<TraitRef>, // (optional) trait this impl implements
2304         P<Ty>,            // self
2305         Vec<ImplItem>,
2306     ),
2307     /// A macro invocation.
2308     ///
2309     /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2310     Mac(Mac),
2311
2312     /// A macro definition.
2313     MacroDef(MacroDef),
2314 }
2315
2316 impl ItemKind {
2317     pub fn descriptive_variant(&self) -> &str {
2318         match *self {
2319             ItemKind::ExternCrate(..) => "extern crate",
2320             ItemKind::Use(..) => "use",
2321             ItemKind::Static(..) => "static item",
2322             ItemKind::Const(..) => "constant item",
2323             ItemKind::Fn(..) => "function",
2324             ItemKind::Mod(..) => "module",
2325             ItemKind::ForeignMod(..) => "foreign module",
2326             ItemKind::GlobalAsm(..) => "global asm",
2327             ItemKind::Ty(..) => "type alias",
2328             ItemKind::Existential(..) => "existential type",
2329             ItemKind::Enum(..) => "enum",
2330             ItemKind::Struct(..) => "struct",
2331             ItemKind::Union(..) => "union",
2332             ItemKind::Trait(..) => "trait",
2333             ItemKind::TraitAlias(..) => "trait alias",
2334             ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2335         }
2336     }
2337 }
2338
2339 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2340 pub struct ForeignItem {
2341     pub ident: Ident,
2342     pub attrs: Vec<Attribute>,
2343     pub node: ForeignItemKind,
2344     pub id: NodeId,
2345     pub span: Span,
2346     pub vis: Visibility,
2347 }
2348
2349 /// An item within an `extern` block.
2350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2351 pub enum ForeignItemKind {
2352     /// A foreign function.
2353     Fn(P<FnDecl>, Generics),
2354     /// A foreign static item (`static ext: u8`), with optional mutability.
2355     /// (The boolean is `true` for mutable items).
2356     Static(P<Ty>, bool),
2357     /// A foreign type.
2358     Ty,
2359     /// A macro invocation.
2360     Macro(Mac),
2361 }
2362
2363 impl ForeignItemKind {
2364     pub fn descriptive_variant(&self) -> &str {
2365         match *self {
2366             ForeignItemKind::Fn(..) => "foreign function",
2367             ForeignItemKind::Static(..) => "foreign static item",
2368             ForeignItemKind::Ty => "foreign type",
2369             ForeignItemKind::Macro(..) => "macro in foreign module",
2370         }
2371     }
2372 }
2373
2374 #[cfg(test)]
2375 mod tests {
2376     use super::*;
2377     use serialize;
2378
2379     // Are ASTs encodable?
2380     #[test]
2381     fn check_asts_encodable() {
2382         fn assert_encodable<T: serialize::Encodable>() {}
2383         assert_encodable::<Crate>();
2384     }
2385 }