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