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