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