]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/ast.rs
ast: Reduce size of `ExprKind` by boxing fields of `ExprKind::Struct`
[rust.git] / compiler / rustc_ast / src / ast.rs
1 //! The Rust abstract syntax tree module.
2 //!
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
7 //!
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
20
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
24
25 use crate::ptr::P;
26 use crate::token::{self, CommentKind, DelimToken, Token};
27 use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree};
28
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable_Generic;
34 use rustc_serialize::{self, Decoder, Encoder};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
38
39 use std::cmp::Ordering;
40 use std::convert::TryFrom;
41 use std::fmt;
42
43 #[cfg(test)]
44 mod tests;
45
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
48 ///
49 /// ```rust
50 /// 'outer: loop {
51 ///     break 'outer;
52 /// }
53 /// ```
54 ///
55 /// `'outer` is a label.
56 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
57 pub struct Label {
58     pub ident: Ident,
59 }
60
61 impl fmt::Debug for Label {
62     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63         write!(f, "label({:?})", self.ident)
64     }
65 }
66
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, Encodable, Decodable, Copy)]
70 pub struct Lifetime {
71     pub id: NodeId,
72     pub ident: Ident,
73 }
74
75 impl fmt::Debug for Lifetime {
76     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77         write!(f, "lifetime({}: {})", self.id, self)
78     }
79 }
80
81 impl fmt::Display for Lifetime {
82     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83         write!(f, "{}", self.ident.name)
84     }
85 }
86
87 /// A "Path" is essentially Rust's notion of a name.
88 ///
89 /// It's represented as a sequence of identifiers,
90 /// along with a bunch of supporting information.
91 ///
92 /// E.g., `std::cmp::PartialEq`.
93 #[derive(Clone, Encodable, Decodable, Debug)]
94 pub struct Path {
95     pub span: Span,
96     /// The segments in the path: the things separated by `::`.
97     /// Global paths begin with `kw::PathRoot`.
98     pub segments: Vec<PathSegment>,
99     pub tokens: Option<LazyTokenStream>,
100 }
101
102 impl PartialEq<Symbol> for Path {
103     fn eq(&self, symbol: &Symbol) -> bool {
104         self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
105     }
106 }
107
108 impl<CTX> HashStable<CTX> for Path {
109     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
110         self.segments.len().hash_stable(hcx, hasher);
111         for segment in &self.segments {
112             segment.ident.name.hash_stable(hcx, hasher);
113         }
114     }
115 }
116
117 impl Path {
118     // Convert a span and an identifier to the corresponding
119     // one-segment path.
120     pub fn from_ident(ident: Ident) -> Path {
121         Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
122     }
123
124     pub fn is_global(&self) -> bool {
125         !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
126     }
127 }
128
129 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
130 ///
131 /// E.g., `std`, `String` or `Box<T>`.
132 #[derive(Clone, Encodable, Decodable, Debug)]
133 pub struct PathSegment {
134     /// The identifier portion of this path segment.
135     pub ident: Ident,
136
137     pub id: NodeId,
138
139     /// Type/lifetime parameters attached to this path. They come in
140     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
141     /// `None` means that no parameter list is supplied (`Path`),
142     /// `Some` means that parameter list is supplied (`Path<X, Y>`)
143     /// but it can be empty (`Path<>`).
144     /// `P` is used as a size optimization for the common case with no parameters.
145     pub args: Option<P<GenericArgs>>,
146 }
147
148 impl PathSegment {
149     pub fn from_ident(ident: Ident) -> Self {
150         PathSegment { ident, id: DUMMY_NODE_ID, args: None }
151     }
152     pub fn path_root(span: Span) -> Self {
153         PathSegment::from_ident(Ident::new(kw::PathRoot, span))
154     }
155 }
156
157 /// The arguments of a path segment.
158 ///
159 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
160 #[derive(Clone, Encodable, Decodable, Debug)]
161 pub enum GenericArgs {
162     /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
163     AngleBracketed(AngleBracketedArgs),
164     /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
165     Parenthesized(ParenthesizedArgs),
166 }
167
168 impl GenericArgs {
169     pub fn is_angle_bracketed(&self) -> bool {
170         matches!(self, AngleBracketed(..))
171     }
172
173     pub fn span(&self) -> Span {
174         match *self {
175             AngleBracketed(ref data) => data.span,
176             Parenthesized(ref data) => data.span,
177         }
178     }
179 }
180
181 /// Concrete argument in the sequence of generic args.
182 #[derive(Clone, Encodable, Decodable, Debug)]
183 pub enum GenericArg {
184     /// `'a` in `Foo<'a>`
185     Lifetime(Lifetime),
186     /// `Bar` in `Foo<Bar>`
187     Type(P<Ty>),
188     /// `1` in `Foo<1>`
189     Const(AnonConst),
190 }
191
192 impl GenericArg {
193     pub fn span(&self) -> Span {
194         match self {
195             GenericArg::Lifetime(lt) => lt.ident.span,
196             GenericArg::Type(ty) => ty.span,
197             GenericArg::Const(ct) => ct.value.span,
198         }
199     }
200 }
201
202 /// A path like `Foo<'a, T>`.
203 #[derive(Clone, Encodable, Decodable, Debug, Default)]
204 pub struct AngleBracketedArgs {
205     /// The overall span.
206     pub span: Span,
207     /// The comma separated parts in the `<...>`.
208     pub args: Vec<AngleBracketedArg>,
209 }
210
211 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
212 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
213 #[derive(Clone, Encodable, Decodable, Debug)]
214 pub enum AngleBracketedArg {
215     /// Argument for a generic parameter.
216     Arg(GenericArg),
217     /// Constraint for an associated item.
218     Constraint(AssocTyConstraint),
219 }
220
221 impl AngleBracketedArg {
222     pub fn span(&self) -> Span {
223         match self {
224             AngleBracketedArg::Arg(arg) => arg.span(),
225             AngleBracketedArg::Constraint(constraint) => constraint.span,
226         }
227     }
228 }
229
230 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
231     fn into(self) -> Option<P<GenericArgs>> {
232         Some(P(GenericArgs::AngleBracketed(self)))
233     }
234 }
235
236 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
237     fn into(self) -> Option<P<GenericArgs>> {
238         Some(P(GenericArgs::Parenthesized(self)))
239     }
240 }
241
242 /// A path like `Foo(A, B) -> C`.
243 #[derive(Clone, Encodable, Decodable, Debug)]
244 pub struct ParenthesizedArgs {
245     /// ```text
246     /// Foo(A, B) -> C
247     /// ^^^^^^^^^^^^^^
248     /// ```
249     pub span: Span,
250
251     /// `(A, B)`
252     pub inputs: Vec<P<Ty>>,
253
254     /// ```text
255     /// Foo(A, B) -> C
256     ///    ^^^^^^
257     /// ```
258     pub inputs_span: Span,
259
260     /// `C`
261     pub output: FnRetTy,
262 }
263
264 impl ParenthesizedArgs {
265     pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
266         let args = self
267             .inputs
268             .iter()
269             .cloned()
270             .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
271             .collect();
272         AngleBracketedArgs { span: self.span, args }
273     }
274 }
275
276 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
277
278 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
279 ///
280 /// Negative bounds should also be handled here.
281 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
282 pub enum TraitBoundModifier {
283     /// No modifiers
284     None,
285
286     /// `?Trait`
287     Maybe,
288
289     /// `?const Trait`
290     MaybeConst,
291
292     /// `?const ?Trait`
293     //
294     // This parses but will be rejected during AST validation.
295     MaybeConstMaybe,
296 }
297
298 /// The AST represents all type param bounds as types.
299 /// `typeck::collect::compute_bounds` matches these against
300 /// the "special" built-in traits (see `middle::lang_items`) and
301 /// detects `Copy`, `Send` and `Sync`.
302 #[derive(Clone, Encodable, Decodable, Debug)]
303 pub enum GenericBound {
304     Trait(PolyTraitRef, TraitBoundModifier),
305     Outlives(Lifetime),
306 }
307
308 impl GenericBound {
309     pub fn span(&self) -> Span {
310         match self {
311             GenericBound::Trait(ref t, ..) => t.span,
312             GenericBound::Outlives(ref l) => l.ident.span,
313         }
314     }
315 }
316
317 pub type GenericBounds = Vec<GenericBound>;
318
319 /// Specifies the enforced ordering for generic parameters. In the future,
320 /// if we wanted to relax this order, we could override `PartialEq` and
321 /// `PartialOrd`, to allow the kinds to be unordered.
322 #[derive(Hash, Clone, Copy)]
323 pub enum ParamKindOrd {
324     Lifetime,
325     Type,
326     // `unordered` is only `true` if `sess.has_features().const_generics`
327     // is active. Specifically, if it's only `min_const_generics`, it will still require
328     // ordering consts after types.
329     Const { unordered: bool },
330 }
331
332 impl Ord for ParamKindOrd {
333     fn cmp(&self, other: &Self) -> Ordering {
334         use ParamKindOrd::*;
335         let to_int = |v| match v {
336             Lifetime => 0,
337             Type | Const { unordered: true } => 1,
338             // technically both consts should be ordered equally,
339             // but only one is ever encountered at a time, so this is
340             // fine.
341             Const { unordered: false } => 2,
342         };
343
344         to_int(*self).cmp(&to_int(*other))
345     }
346 }
347 impl PartialOrd for ParamKindOrd {
348     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
349         Some(self.cmp(other))
350     }
351 }
352 impl PartialEq for ParamKindOrd {
353     fn eq(&self, other: &Self) -> bool {
354         self.cmp(other) == Ordering::Equal
355     }
356 }
357 impl Eq for ParamKindOrd {}
358
359 impl fmt::Display for ParamKindOrd {
360     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361         match self {
362             ParamKindOrd::Lifetime => "lifetime".fmt(f),
363             ParamKindOrd::Type => "type".fmt(f),
364             ParamKindOrd::Const { .. } => "const".fmt(f),
365         }
366     }
367 }
368
369 #[derive(Clone, Encodable, Decodable, Debug)]
370 pub enum GenericParamKind {
371     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
372     Lifetime,
373     Type {
374         default: Option<P<Ty>>,
375     },
376     Const {
377         ty: P<Ty>,
378         /// Span of the `const` keyword.
379         kw_span: Span,
380         /// Optional default value for the const generic param
381         default: Option<AnonConst>,
382     },
383 }
384
385 #[derive(Clone, Encodable, Decodable, Debug)]
386 pub struct GenericParam {
387     pub id: NodeId,
388     pub ident: Ident,
389     pub attrs: AttrVec,
390     pub bounds: GenericBounds,
391     pub is_placeholder: bool,
392     pub kind: GenericParamKind,
393 }
394
395 /// Represents lifetime, type and const parameters attached to a declaration of
396 /// a function, enum, trait, etc.
397 #[derive(Clone, Encodable, Decodable, Debug)]
398 pub struct Generics {
399     pub params: Vec<GenericParam>,
400     pub where_clause: WhereClause,
401     pub span: Span,
402 }
403
404 impl Default for Generics {
405     /// Creates an instance of `Generics`.
406     fn default() -> Generics {
407         Generics {
408             params: Vec::new(),
409             where_clause: WhereClause {
410                 has_where_token: false,
411                 predicates: Vec::new(),
412                 span: DUMMY_SP,
413             },
414             span: DUMMY_SP,
415         }
416     }
417 }
418
419 /// A where-clause in a definition.
420 #[derive(Clone, Encodable, Decodable, Debug)]
421 pub struct WhereClause {
422     /// `true` if we ate a `where` token: this can happen
423     /// if we parsed no predicates (e.g. `struct Foo where {}`).
424     /// This allows us to accurately pretty-print
425     /// in `nt_to_tokenstream`
426     pub has_where_token: bool,
427     pub predicates: Vec<WherePredicate>,
428     pub span: Span,
429 }
430
431 /// A single predicate in a where-clause.
432 #[derive(Clone, Encodable, Decodable, Debug)]
433 pub enum WherePredicate {
434     /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
435     BoundPredicate(WhereBoundPredicate),
436     /// A lifetime predicate (e.g., `'a: 'b + 'c`).
437     RegionPredicate(WhereRegionPredicate),
438     /// An equality predicate (unsupported).
439     EqPredicate(WhereEqPredicate),
440 }
441
442 impl WherePredicate {
443     pub fn span(&self) -> Span {
444         match self {
445             WherePredicate::BoundPredicate(p) => p.span,
446             WherePredicate::RegionPredicate(p) => p.span,
447             WherePredicate::EqPredicate(p) => p.span,
448         }
449     }
450 }
451
452 /// A type bound.
453 ///
454 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
455 #[derive(Clone, Encodable, Decodable, Debug)]
456 pub struct WhereBoundPredicate {
457     pub span: Span,
458     /// Any generics from a `for` binding.
459     pub bound_generic_params: Vec<GenericParam>,
460     /// The type being bounded.
461     pub bounded_ty: P<Ty>,
462     /// Trait and lifetime bounds (`Clone + Send + 'static`).
463     pub bounds: GenericBounds,
464 }
465
466 /// A lifetime predicate.
467 ///
468 /// E.g., `'a: 'b + 'c`.
469 #[derive(Clone, Encodable, Decodable, Debug)]
470 pub struct WhereRegionPredicate {
471     pub span: Span,
472     pub lifetime: Lifetime,
473     pub bounds: GenericBounds,
474 }
475
476 /// An equality predicate (unsupported).
477 ///
478 /// E.g., `T = int`.
479 #[derive(Clone, Encodable, Decodable, Debug)]
480 pub struct WhereEqPredicate {
481     pub id: NodeId,
482     pub span: Span,
483     pub lhs_ty: P<Ty>,
484     pub rhs_ty: P<Ty>,
485 }
486
487 #[derive(Clone, Encodable, Decodable, Debug)]
488 pub struct Crate {
489     pub attrs: Vec<Attribute>,
490     pub items: Vec<P<Item>>,
491     pub span: Span,
492     /// The order of items in the HIR is unrelated to the order of
493     /// items in the AST. However, we generate proc macro harnesses
494     /// based on the AST order, and later refer to these harnesses
495     /// from the HIR. This field keeps track of the order in which
496     /// we generated proc macros harnesses, so that we can map
497     /// HIR proc macros items back to their harness items.
498     pub proc_macros: Vec<NodeId>,
499 }
500
501 /// Possible values inside of compile-time attribute lists.
502 ///
503 /// E.g., the '..' in `#[name(..)]`.
504 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
505 pub enum NestedMetaItem {
506     /// A full MetaItem, for recursive meta items.
507     MetaItem(MetaItem),
508     /// A literal.
509     ///
510     /// E.g., `"foo"`, `64`, `true`.
511     Literal(Lit),
512 }
513
514 /// A spanned compile-time attribute item.
515 ///
516 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
517 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
518 pub struct MetaItem {
519     pub path: Path,
520     pub kind: MetaItemKind,
521     pub span: Span,
522 }
523
524 /// A compile-time attribute item.
525 ///
526 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
527 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
528 pub enum MetaItemKind {
529     /// Word meta item.
530     ///
531     /// E.g., `test` as in `#[test]`.
532     Word,
533     /// List meta item.
534     ///
535     /// E.g., `derive(..)` as in `#[derive(..)]`.
536     List(Vec<NestedMetaItem>),
537     /// Name value meta item.
538     ///
539     /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
540     NameValue(Lit),
541 }
542
543 /// A block (`{ .. }`).
544 ///
545 /// E.g., `{ .. }` as in `fn foo() { .. }`.
546 #[derive(Clone, Encodable, Decodable, Debug)]
547 pub struct Block {
548     /// The statements in the block.
549     pub stmts: Vec<Stmt>,
550     pub id: NodeId,
551     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
552     pub rules: BlockCheckMode,
553     pub span: Span,
554     pub tokens: Option<LazyTokenStream>,
555 }
556
557 /// A match pattern.
558 ///
559 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
560 #[derive(Clone, Encodable, Decodable, Debug)]
561 pub struct Pat {
562     pub id: NodeId,
563     pub kind: PatKind,
564     pub span: Span,
565     pub tokens: Option<LazyTokenStream>,
566 }
567
568 impl Pat {
569     /// Attempt reparsing the pattern as a type.
570     /// This is intended for use by diagnostics.
571     pub fn to_ty(&self) -> Option<P<Ty>> {
572         let kind = match &self.kind {
573             // In a type expression `_` is an inference variable.
574             PatKind::Wild => TyKind::Infer,
575             // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
576             PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
577                 TyKind::Path(None, Path::from_ident(*ident))
578             }
579             PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
580             PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
581             // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
582             PatKind::Ref(pat, mutbl) => {
583                 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
584             }
585             // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
586             // when `P` can be reparsed as a type `T`.
587             PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
588             // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
589             // assuming `T0` to `Tn` are all syntactically valid as types.
590             PatKind::Tuple(pats) => {
591                 let mut tys = Vec::with_capacity(pats.len());
592                 // FIXME(#48994) - could just be collected into an Option<Vec>
593                 for pat in pats {
594                     tys.push(pat.to_ty()?);
595                 }
596                 TyKind::Tup(tys)
597             }
598             _ => return None,
599         };
600
601         Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
602     }
603
604     /// Walk top-down and call `it` in each place where a pattern occurs
605     /// starting with the root pattern `walk` is called on. If `it` returns
606     /// false then we will descend no further but siblings will be processed.
607     pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
608         if !it(self) {
609             return;
610         }
611
612         match &self.kind {
613             // Walk into the pattern associated with `Ident` (if any).
614             PatKind::Ident(_, _, Some(p)) => p.walk(it),
615
616             // Walk into each field of struct.
617             PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
618
619             // Sequence of patterns.
620             PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
621                 s.iter().for_each(|p| p.walk(it))
622             }
623
624             // Trivial wrappers over inner patterns.
625             PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
626
627             // These patterns do not contain subpatterns, skip.
628             PatKind::Wild
629             | PatKind::Rest
630             | PatKind::Lit(_)
631             | PatKind::Range(..)
632             | PatKind::Ident(..)
633             | PatKind::Path(..)
634             | PatKind::MacCall(_) => {}
635         }
636     }
637
638     /// Is this a `..` pattern?
639     pub fn is_rest(&self) -> bool {
640         matches!(self.kind, PatKind::Rest)
641     }
642 }
643
644 /// A single field in a struct pattern.
645 ///
646 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
647 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
648 /// except when `is_shorthand` is true.
649 #[derive(Clone, Encodable, Decodable, Debug)]
650 pub struct PatField {
651     /// The identifier for the field.
652     pub ident: Ident,
653     /// The pattern the field is destructured to.
654     pub pat: P<Pat>,
655     pub is_shorthand: bool,
656     pub attrs: AttrVec,
657     pub id: NodeId,
658     pub span: Span,
659     pub is_placeholder: bool,
660 }
661
662 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
663 pub enum BindingMode {
664     ByRef(Mutability),
665     ByValue(Mutability),
666 }
667
668 #[derive(Clone, Encodable, Decodable, Debug)]
669 pub enum RangeEnd {
670     Included(RangeSyntax),
671     Excluded,
672 }
673
674 #[derive(Clone, Encodable, Decodable, Debug)]
675 pub enum RangeSyntax {
676     /// `...`
677     DotDotDot,
678     /// `..=`
679     DotDotEq,
680 }
681
682 #[derive(Clone, Encodable, Decodable, Debug)]
683 pub enum PatKind {
684     /// Represents a wildcard pattern (`_`).
685     Wild,
686
687     /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
688     /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
689     /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
690     /// during name resolution.
691     Ident(BindingMode, Ident, Option<P<Pat>>),
692
693     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
694     /// The `bool` is `true` in the presence of a `..`.
695     Struct(Path, Vec<PatField>, /* recovered */ bool),
696
697     /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
698     TupleStruct(Path, Vec<P<Pat>>),
699
700     /// An or-pattern `A | B | C`.
701     /// Invariant: `pats.len() >= 2`.
702     Or(Vec<P<Pat>>),
703
704     /// A possibly qualified path pattern.
705     /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
706     /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
707     /// only legally refer to associated constants.
708     Path(Option<QSelf>, Path),
709
710     /// A tuple pattern (`(a, b)`).
711     Tuple(Vec<P<Pat>>),
712
713     /// A `box` pattern.
714     Box(P<Pat>),
715
716     /// A reference pattern (e.g., `&mut (a, b)`).
717     Ref(P<Pat>, Mutability),
718
719     /// A literal.
720     Lit(P<Expr>),
721
722     /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
723     Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
724
725     /// A slice pattern `[a, b, c]`.
726     Slice(Vec<P<Pat>>),
727
728     /// A rest pattern `..`.
729     ///
730     /// Syntactically it is valid anywhere.
731     ///
732     /// Semantically however, it only has meaning immediately inside:
733     /// - a slice pattern: `[a, .., b]`,
734     /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
735     /// - a tuple pattern: `(a, .., b)`,
736     /// - a tuple struct/variant pattern: `$path(a, .., b)`.
737     ///
738     /// In all of these cases, an additional restriction applies,
739     /// only one rest pattern may occur in the pattern sequences.
740     Rest,
741
742     /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
743     Paren(P<Pat>),
744
745     /// A macro pattern; pre-expansion.
746     MacCall(MacCall),
747 }
748
749 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
750 #[derive(HashStable_Generic, Encodable, Decodable)]
751 pub enum Mutability {
752     Mut,
753     Not,
754 }
755
756 impl Mutability {
757     /// Returns `MutMutable` only if both `self` and `other` are mutable.
758     pub fn and(self, other: Self) -> Self {
759         match self {
760             Mutability::Mut => other,
761             Mutability::Not => Mutability::Not,
762         }
763     }
764
765     pub fn invert(self) -> Self {
766         match self {
767             Mutability::Mut => Mutability::Not,
768             Mutability::Not => Mutability::Mut,
769         }
770     }
771
772     pub fn prefix_str(&self) -> &'static str {
773         match self {
774             Mutability::Mut => "mut ",
775             Mutability::Not => "",
776         }
777     }
778 }
779
780 /// The kind of borrow in an `AddrOf` expression,
781 /// e.g., `&place` or `&raw const place`.
782 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
783 #[derive(Encodable, Decodable, HashStable_Generic)]
784 pub enum BorrowKind {
785     /// A normal borrow, `&$expr` or `&mut $expr`.
786     /// The resulting type is either `&'a T` or `&'a mut T`
787     /// where `T = typeof($expr)` and `'a` is some lifetime.
788     Ref,
789     /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
790     /// The resulting type is either `*const T` or `*mut T`
791     /// where `T = typeof($expr)`.
792     Raw,
793 }
794
795 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
796 pub enum BinOpKind {
797     /// The `+` operator (addition)
798     Add,
799     /// The `-` operator (subtraction)
800     Sub,
801     /// The `*` operator (multiplication)
802     Mul,
803     /// The `/` operator (division)
804     Div,
805     /// The `%` operator (modulus)
806     Rem,
807     /// The `&&` operator (logical and)
808     And,
809     /// The `||` operator (logical or)
810     Or,
811     /// The `^` operator (bitwise xor)
812     BitXor,
813     /// The `&` operator (bitwise and)
814     BitAnd,
815     /// The `|` operator (bitwise or)
816     BitOr,
817     /// The `<<` operator (shift left)
818     Shl,
819     /// The `>>` operator (shift right)
820     Shr,
821     /// The `==` operator (equality)
822     Eq,
823     /// The `<` operator (less than)
824     Lt,
825     /// The `<=` operator (less than or equal to)
826     Le,
827     /// The `!=` operator (not equal to)
828     Ne,
829     /// The `>=` operator (greater than or equal to)
830     Ge,
831     /// The `>` operator (greater than)
832     Gt,
833 }
834
835 impl BinOpKind {
836     pub fn to_string(&self) -> &'static str {
837         use BinOpKind::*;
838         match *self {
839             Add => "+",
840             Sub => "-",
841             Mul => "*",
842             Div => "/",
843             Rem => "%",
844             And => "&&",
845             Or => "||",
846             BitXor => "^",
847             BitAnd => "&",
848             BitOr => "|",
849             Shl => "<<",
850             Shr => ">>",
851             Eq => "==",
852             Lt => "<",
853             Le => "<=",
854             Ne => "!=",
855             Ge => ">=",
856             Gt => ">",
857         }
858     }
859     pub fn lazy(&self) -> bool {
860         matches!(self, BinOpKind::And | BinOpKind::Or)
861     }
862
863     pub fn is_comparison(&self) -> bool {
864         use BinOpKind::*;
865         // Note for developers: please keep this as is;
866         // we want compilation to fail if another variant is added.
867         match *self {
868             Eq | Lt | Le | Ne | Gt | Ge => true,
869             And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
870         }
871     }
872 }
873
874 pub type BinOp = Spanned<BinOpKind>;
875
876 /// Unary operator.
877 ///
878 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
879 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
880 pub enum UnOp {
881     /// The `*` operator for dereferencing
882     Deref,
883     /// The `!` operator for logical inversion
884     Not,
885     /// The `-` operator for negation
886     Neg,
887 }
888
889 impl UnOp {
890     pub fn to_string(op: UnOp) -> &'static str {
891         match op {
892             UnOp::Deref => "*",
893             UnOp::Not => "!",
894             UnOp::Neg => "-",
895         }
896     }
897 }
898
899 /// A statement
900 #[derive(Clone, Encodable, Decodable, Debug)]
901 pub struct Stmt {
902     pub id: NodeId,
903     pub kind: StmtKind,
904     pub span: Span,
905 }
906
907 impl Stmt {
908     pub fn tokens(&self) -> Option<&LazyTokenStream> {
909         match self.kind {
910             StmtKind::Local(ref local) => local.tokens.as_ref(),
911             StmtKind::Item(ref item) => item.tokens.as_ref(),
912             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(),
913             StmtKind::Empty => None,
914             StmtKind::MacCall(ref mac) => mac.tokens.as_ref(),
915         }
916     }
917
918     pub fn has_trailing_semicolon(&self) -> bool {
919         match &self.kind {
920             StmtKind::Semi(_) => true,
921             StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
922             _ => false,
923         }
924     }
925
926     /// Converts a parsed `Stmt` to a `Stmt` with
927     /// a trailing semicolon.
928     ///
929     /// This only modifies the parsed AST struct, not the attached
930     /// `LazyTokenStream`. The parser is responsible for calling
931     /// `CreateTokenStream::add_trailing_semi` when there is actually
932     /// a semicolon in the tokenstream.
933     pub fn add_trailing_semicolon(mut self) -> Self {
934         self.kind = match self.kind {
935             StmtKind::Expr(expr) => StmtKind::Semi(expr),
936             StmtKind::MacCall(mac) => {
937                 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
938                     MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
939                 }))
940             }
941             kind => kind,
942         };
943
944         self
945     }
946
947     pub fn is_item(&self) -> bool {
948         matches!(self.kind, StmtKind::Item(_))
949     }
950
951     pub fn is_expr(&self) -> bool {
952         matches!(self.kind, StmtKind::Expr(_))
953     }
954 }
955
956 #[derive(Clone, Encodable, Decodable, Debug)]
957 pub enum StmtKind {
958     /// A local (let) binding.
959     Local(P<Local>),
960     /// An item definition.
961     Item(P<Item>),
962     /// Expr without trailing semi-colon.
963     Expr(P<Expr>),
964     /// Expr with a trailing semi-colon.
965     Semi(P<Expr>),
966     /// Just a trailing semi-colon.
967     Empty,
968     /// Macro.
969     MacCall(P<MacCallStmt>),
970 }
971
972 #[derive(Clone, Encodable, Decodable, Debug)]
973 pub struct MacCallStmt {
974     pub mac: MacCall,
975     pub style: MacStmtStyle,
976     pub attrs: AttrVec,
977     pub tokens: Option<LazyTokenStream>,
978 }
979
980 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
981 pub enum MacStmtStyle {
982     /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
983     /// `foo!(...);`, `foo![...];`).
984     Semicolon,
985     /// The macro statement had braces (e.g., `foo! { ... }`).
986     Braces,
987     /// The macro statement had parentheses or brackets and no semicolon (e.g.,
988     /// `foo!(...)`). All of these will end up being converted into macro
989     /// expressions.
990     NoBraces,
991 }
992
993 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
994 #[derive(Clone, Encodable, Decodable, Debug)]
995 pub struct Local {
996     pub id: NodeId,
997     pub pat: P<Pat>,
998     pub ty: Option<P<Ty>>,
999     /// Initializer expression to set the value, if any.
1000     pub init: Option<P<Expr>>,
1001     pub span: Span,
1002     pub attrs: AttrVec,
1003     pub tokens: Option<LazyTokenStream>,
1004 }
1005
1006 /// An arm of a 'match'.
1007 ///
1008 /// E.g., `0..=10 => { println!("match!") }` as in
1009 ///
1010 /// ```
1011 /// match 123 {
1012 ///     0..=10 => { println!("match!") },
1013 ///     _ => { println!("no match!") },
1014 /// }
1015 /// ```
1016 #[derive(Clone, Encodable, Decodable, Debug)]
1017 pub struct Arm {
1018     pub attrs: Vec<Attribute>,
1019     /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1020     pub pat: P<Pat>,
1021     /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1022     pub guard: Option<P<Expr>>,
1023     /// Match arm body.
1024     pub body: P<Expr>,
1025     pub span: Span,
1026     pub id: NodeId,
1027     pub is_placeholder: bool,
1028 }
1029
1030 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1031 #[derive(Clone, Encodable, Decodable, Debug)]
1032 pub struct ExprField {
1033     pub attrs: AttrVec,
1034     pub id: NodeId,
1035     pub span: Span,
1036     pub ident: Ident,
1037     pub expr: P<Expr>,
1038     pub is_shorthand: bool,
1039     pub is_placeholder: bool,
1040 }
1041
1042 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1043 pub enum BlockCheckMode {
1044     Default,
1045     Unsafe(UnsafeSource),
1046 }
1047
1048 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1049 pub enum UnsafeSource {
1050     CompilerGenerated,
1051     UserProvided,
1052 }
1053
1054 /// A constant (expression) that's not an item or associated item,
1055 /// but needs its own `DefId` for type-checking, const-eval, etc.
1056 /// These are usually found nested inside types (e.g., array lengths)
1057 /// or expressions (e.g., repeat counts), and also used to define
1058 /// explicit discriminant values for enum variants.
1059 #[derive(Clone, Encodable, Decodable, Debug)]
1060 pub struct AnonConst {
1061     pub id: NodeId,
1062     pub value: P<Expr>,
1063 }
1064
1065 /// An expression.
1066 #[derive(Clone, Encodable, Decodable, Debug)]
1067 pub struct Expr {
1068     pub id: NodeId,
1069     pub kind: ExprKind,
1070     pub span: Span,
1071     pub attrs: AttrVec,
1072     pub tokens: Option<LazyTokenStream>,
1073 }
1074
1075 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1076 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1077 rustc_data_structures::static_assert_size!(Expr, 104);
1078
1079 impl Expr {
1080     /// Returns `true` if this expression would be valid somewhere that expects a value;
1081     /// for example, an `if` condition.
1082     pub fn returns(&self) -> bool {
1083         if let ExprKind::Block(ref block, _) = self.kind {
1084             match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1085                 // Implicit return
1086                 Some(StmtKind::Expr(_)) => true,
1087                 // Last statement is an explicit return?
1088                 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1089                 // This is a block that doesn't end in either an implicit or explicit return.
1090                 _ => false,
1091             }
1092         } else {
1093             // This is not a block, it is a value.
1094             true
1095         }
1096     }
1097
1098     /// Is this expr either `N`, or `{ N }`.
1099     ///
1100     /// If this is not the case, name resolution does not resolve `N` when using
1101     /// `min_const_generics` as more complex expressions are not supported.
1102     pub fn is_potential_trivial_const_param(&self) -> bool {
1103         let this = if let ExprKind::Block(ref block, None) = self.kind {
1104             if block.stmts.len() == 1 {
1105                 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1106             } else {
1107                 self
1108             }
1109         } else {
1110             self
1111         };
1112
1113         if let ExprKind::Path(None, ref path) = this.kind {
1114             if path.segments.len() == 1 && path.segments[0].args.is_none() {
1115                 return true;
1116             }
1117         }
1118
1119         false
1120     }
1121
1122     pub fn to_bound(&self) -> Option<GenericBound> {
1123         match &self.kind {
1124             ExprKind::Path(None, path) => Some(GenericBound::Trait(
1125                 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1126                 TraitBoundModifier::None,
1127             )),
1128             _ => None,
1129         }
1130     }
1131
1132     pub fn peel_parens(&self) -> &Expr {
1133         let mut expr = self;
1134         while let ExprKind::Paren(inner) = &expr.kind {
1135             expr = &inner;
1136         }
1137         expr
1138     }
1139
1140     /// Attempts to reparse as `Ty` (for diagnostic purposes).
1141     pub fn to_ty(&self) -> Option<P<Ty>> {
1142         let kind = match &self.kind {
1143             // Trivial conversions.
1144             ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1145             ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1146
1147             ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1148
1149             ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1150                 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1151             }
1152
1153             ExprKind::Repeat(expr, expr_len) => {
1154                 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1155             }
1156
1157             ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1158
1159             ExprKind::Tup(exprs) => {
1160                 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1161                 TyKind::Tup(tys)
1162             }
1163
1164             // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1165             // then type of result is trait object.
1166             // Otherwise we don't assume the result type.
1167             ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1168                 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1169                     TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1170                 } else {
1171                     return None;
1172                 }
1173             }
1174
1175             // This expression doesn't look like a type syntactically.
1176             _ => return None,
1177         };
1178
1179         Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1180     }
1181
1182     pub fn precedence(&self) -> ExprPrecedence {
1183         match self.kind {
1184             ExprKind::Box(_) => ExprPrecedence::Box,
1185             ExprKind::Array(_) => ExprPrecedence::Array,
1186             ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1187             ExprKind::Call(..) => ExprPrecedence::Call,
1188             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1189             ExprKind::Tup(_) => ExprPrecedence::Tup,
1190             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1191             ExprKind::Unary(..) => ExprPrecedence::Unary,
1192             ExprKind::Lit(_) => ExprPrecedence::Lit,
1193             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1194             ExprKind::Let(..) => ExprPrecedence::Let,
1195             ExprKind::If(..) => ExprPrecedence::If,
1196             ExprKind::While(..) => ExprPrecedence::While,
1197             ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1198             ExprKind::Loop(..) => ExprPrecedence::Loop,
1199             ExprKind::Match(..) => ExprPrecedence::Match,
1200             ExprKind::Closure(..) => ExprPrecedence::Closure,
1201             ExprKind::Block(..) => ExprPrecedence::Block,
1202             ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1203             ExprKind::Async(..) => ExprPrecedence::Async,
1204             ExprKind::Await(..) => ExprPrecedence::Await,
1205             ExprKind::Assign(..) => ExprPrecedence::Assign,
1206             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1207             ExprKind::Field(..) => ExprPrecedence::Field,
1208             ExprKind::Index(..) => ExprPrecedence::Index,
1209             ExprKind::Range(..) => ExprPrecedence::Range,
1210             ExprKind::Underscore => ExprPrecedence::Path,
1211             ExprKind::Path(..) => ExprPrecedence::Path,
1212             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1213             ExprKind::Break(..) => ExprPrecedence::Break,
1214             ExprKind::Continue(..) => ExprPrecedence::Continue,
1215             ExprKind::Ret(..) => ExprPrecedence::Ret,
1216             ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1217             ExprKind::MacCall(..) => ExprPrecedence::Mac,
1218             ExprKind::Struct(..) => ExprPrecedence::Struct,
1219             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1220             ExprKind::Paren(..) => ExprPrecedence::Paren,
1221             ExprKind::Try(..) => ExprPrecedence::Try,
1222             ExprKind::Yield(..) => ExprPrecedence::Yield,
1223             ExprKind::Err => ExprPrecedence::Err,
1224         }
1225     }
1226 }
1227
1228 /// Limit types of a range (inclusive or exclusive)
1229 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1230 pub enum RangeLimits {
1231     /// Inclusive at the beginning, exclusive at the end
1232     HalfOpen,
1233     /// Inclusive at the beginning and end
1234     Closed,
1235 }
1236
1237 #[derive(Clone, Encodable, Decodable, Debug)]
1238 pub enum StructRest {
1239     /// `..x`.
1240     Base(P<Expr>),
1241     /// `..`.
1242     Rest(Span),
1243     /// No trailing `..` or expression.
1244     None,
1245 }
1246
1247 #[derive(Clone, Encodable, Decodable, Debug)]
1248 pub struct StructExpr {
1249     pub path: Path,
1250     pub fields: Vec<ExprField>,
1251     pub rest: StructRest,
1252 }
1253
1254 #[derive(Clone, Encodable, Decodable, Debug)]
1255 pub enum ExprKind {
1256     /// A `box x` expression.
1257     Box(P<Expr>),
1258     /// An array (`[a, b, c, d]`)
1259     Array(Vec<P<Expr>>),
1260     /// Allow anonymous constants from an inline `const` block
1261     ConstBlock(AnonConst),
1262     /// A function call
1263     ///
1264     /// The first field resolves to the function itself,
1265     /// and the second field is the list of arguments.
1266     /// This also represents calling the constructor of
1267     /// tuple-like ADTs such as tuple structs and enum variants.
1268     Call(P<Expr>, Vec<P<Expr>>),
1269     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1270     ///
1271     /// The `PathSegment` represents the method name and its generic arguments
1272     /// (within the angle brackets).
1273     /// The first element of the vector of an `Expr` is the expression that evaluates
1274     /// to the object on which the method is being called on (the receiver),
1275     /// and the remaining elements are the rest of the arguments.
1276     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1277     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1278     /// This `Span` is the span of the function, without the dot and receiver
1279     /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1280     MethodCall(PathSegment, Vec<P<Expr>>, Span),
1281     /// A tuple (e.g., `(a, b, c, d)`).
1282     Tup(Vec<P<Expr>>),
1283     /// A binary operation (e.g., `a + b`, `a * b`).
1284     Binary(BinOp, P<Expr>, P<Expr>),
1285     /// A unary operation (e.g., `!x`, `*x`).
1286     Unary(UnOp, P<Expr>),
1287     /// A literal (e.g., `1`, `"foo"`).
1288     Lit(Lit),
1289     /// A cast (e.g., `foo as f64`).
1290     Cast(P<Expr>, P<Ty>),
1291     /// A type ascription (e.g., `42: usize`).
1292     Type(P<Expr>, P<Ty>),
1293     /// A `let pat = expr` expression that is only semantically allowed in the condition
1294     /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1295     Let(P<Pat>, P<Expr>),
1296     /// An `if` block, with an optional `else` block.
1297     ///
1298     /// `if expr { block } else { expr }`
1299     If(P<Expr>, P<Block>, Option<P<Expr>>),
1300     /// A while loop, with an optional label.
1301     ///
1302     /// `'label: while expr { block }`
1303     While(P<Expr>, P<Block>, Option<Label>),
1304     /// A `for` loop, with an optional label.
1305     ///
1306     /// `'label: for pat in expr { block }`
1307     ///
1308     /// This is desugared to a combination of `loop` and `match` expressions.
1309     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1310     /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1311     ///
1312     /// `'label: loop { block }`
1313     Loop(P<Block>, Option<Label>),
1314     /// A `match` block.
1315     Match(P<Expr>, Vec<Arm>),
1316     /// A closure (e.g., `move |a, b, c| a + b + c`).
1317     ///
1318     /// The final span is the span of the argument block `|...|`.
1319     Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1320     /// A block (`'label: { ... }`).
1321     Block(P<Block>, Option<Label>),
1322     /// An async block (`async move { ... }`).
1323     ///
1324     /// The `NodeId` is the `NodeId` for the closure that results from
1325     /// desugaring an async block, just like the NodeId field in the
1326     /// `Async::Yes` variant. This is necessary in order to create a def for the
1327     /// closure which can be used as a parent of any child defs. Defs
1328     /// created during lowering cannot be made the parent of any other
1329     /// preexisting defs.
1330     Async(CaptureBy, NodeId, P<Block>),
1331     /// An await expression (`my_future.await`).
1332     Await(P<Expr>),
1333
1334     /// A try block (`try { ... }`).
1335     TryBlock(P<Block>),
1336
1337     /// An assignment (`a = foo()`).
1338     /// The `Span` argument is the span of the `=` token.
1339     Assign(P<Expr>, P<Expr>, Span),
1340     /// An assignment with an operator.
1341     ///
1342     /// E.g., `a += 1`.
1343     AssignOp(BinOp, P<Expr>, P<Expr>),
1344     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1345     Field(P<Expr>, Ident),
1346     /// An indexing operation (e.g., `foo[2]`).
1347     Index(P<Expr>, P<Expr>),
1348     /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assingment).
1349     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1350     /// An underscore, used in destructuring assignment to ignore a value.
1351     Underscore,
1352
1353     /// Variable reference, possibly containing `::` and/or type
1354     /// parameters (e.g., `foo::bar::<baz>`).
1355     ///
1356     /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1357     Path(Option<QSelf>, Path),
1358
1359     /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1360     AddrOf(BorrowKind, Mutability, P<Expr>),
1361     /// A `break`, with an optional label to break, and an optional expression.
1362     Break(Option<Label>, Option<P<Expr>>),
1363     /// A `continue`, with an optional label.
1364     Continue(Option<Label>),
1365     /// A `return`, with an optional value to be returned.
1366     Ret(Option<P<Expr>>),
1367
1368     /// Output of the `asm!()` macro.
1369     InlineAsm(P<InlineAsm>),
1370     /// Output of the `llvm_asm!()` macro.
1371     LlvmInlineAsm(P<LlvmInlineAsm>),
1372
1373     /// A macro invocation; pre-expansion.
1374     MacCall(MacCall),
1375
1376     /// A struct literal expression.
1377     ///
1378     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1379     Struct(P<StructExpr>),
1380
1381     /// An array literal constructed from one repeated element.
1382     ///
1383     /// E.g., `[1; 5]`. The expression is the element to be
1384     /// repeated; the constant is the number of times to repeat it.
1385     Repeat(P<Expr>, AnonConst),
1386
1387     /// No-op: used solely so we can pretty-print faithfully.
1388     Paren(P<Expr>),
1389
1390     /// A try expression (`expr?`).
1391     Try(P<Expr>),
1392
1393     /// A `yield`, with an optional value to be yielded.
1394     Yield(Option<P<Expr>>),
1395
1396     /// Placeholder for an expression that wasn't syntactically well formed in some way.
1397     Err,
1398 }
1399
1400 /// The explicit `Self` type in a "qualified path". The actual
1401 /// path, including the trait and the associated item, is stored
1402 /// separately. `position` represents the index of the associated
1403 /// item qualified with this `Self` type.
1404 ///
1405 /// ```ignore (only-for-syntax-highlight)
1406 /// <Vec<T> as a::b::Trait>::AssociatedItem
1407 ///  ^~~~~     ~~~~~~~~~~~~~~^
1408 ///  ty        position = 3
1409 ///
1410 /// <Vec<T>>::AssociatedItem
1411 ///  ^~~~~    ^
1412 ///  ty       position = 0
1413 /// ```
1414 #[derive(Clone, Encodable, Decodable, Debug)]
1415 pub struct QSelf {
1416     pub ty: P<Ty>,
1417
1418     /// The span of `a::b::Trait` in a path like `<Vec<T> as
1419     /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1420     /// 0`, this is an empty span.
1421     pub path_span: Span,
1422     pub position: usize,
1423 }
1424
1425 /// A capture clause used in closures and `async` blocks.
1426 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1427 pub enum CaptureBy {
1428     /// `move |x| y + x`.
1429     Value,
1430     /// `move` keyword was not specified.
1431     Ref,
1432 }
1433
1434 /// The movability of a generator / closure literal:
1435 /// whether a generator contains self-references, causing it to be `!Unpin`.
1436 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1437 #[derive(HashStable_Generic)]
1438 pub enum Movability {
1439     /// May contain self-references, `!Unpin`.
1440     Static,
1441     /// Must not contain self-references, `Unpin`.
1442     Movable,
1443 }
1444
1445 /// Represents a macro invocation. The `path` indicates which macro
1446 /// is being invoked, and the `args` are arguments passed to it.
1447 #[derive(Clone, Encodable, Decodable, Debug)]
1448 pub struct MacCall {
1449     pub path: Path,
1450     pub args: P<MacArgs>,
1451     pub prior_type_ascription: Option<(Span, bool)>,
1452 }
1453
1454 impl MacCall {
1455     pub fn span(&self) -> Span {
1456         self.path.span.to(self.args.span().unwrap_or(self.path.span))
1457     }
1458 }
1459
1460 /// Arguments passed to an attribute or a function-like macro.
1461 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1462 pub enum MacArgs {
1463     /// No arguments - `#[attr]`.
1464     Empty,
1465     /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1466     Delimited(DelimSpan, MacDelimiter, TokenStream),
1467     /// Arguments of a key-value attribute - `#[attr = "value"]`.
1468     Eq(
1469         /// Span of the `=` token.
1470         Span,
1471         /// "value" as a nonterminal token.
1472         Token,
1473     ),
1474 }
1475
1476 impl MacArgs {
1477     pub fn delim(&self) -> DelimToken {
1478         match self {
1479             MacArgs::Delimited(_, delim, _) => delim.to_token(),
1480             MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1481         }
1482     }
1483
1484     pub fn span(&self) -> Option<Span> {
1485         match self {
1486             MacArgs::Empty => None,
1487             MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1488             MacArgs::Eq(eq_span, token) => Some(eq_span.to(token.span)),
1489         }
1490     }
1491
1492     /// Tokens inside the delimiters or after `=`.
1493     /// Proc macros see these tokens, for example.
1494     pub fn inner_tokens(&self) -> TokenStream {
1495         match self {
1496             MacArgs::Empty => TokenStream::default(),
1497             MacArgs::Delimited(.., tokens) => tokens.clone(),
1498             MacArgs::Eq(.., token) => TokenTree::Token(token.clone()).into(),
1499         }
1500     }
1501
1502     /// Whether a macro with these arguments needs a semicolon
1503     /// when used as a standalone item or statement.
1504     pub fn need_semicolon(&self) -> bool {
1505         !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1506     }
1507 }
1508
1509 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1510 pub enum MacDelimiter {
1511     Parenthesis,
1512     Bracket,
1513     Brace,
1514 }
1515
1516 impl MacDelimiter {
1517     pub fn to_token(self) -> DelimToken {
1518         match self {
1519             MacDelimiter::Parenthesis => DelimToken::Paren,
1520             MacDelimiter::Bracket => DelimToken::Bracket,
1521             MacDelimiter::Brace => DelimToken::Brace,
1522         }
1523     }
1524
1525     pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1526         match delim {
1527             token::Paren => Some(MacDelimiter::Parenthesis),
1528             token::Bracket => Some(MacDelimiter::Bracket),
1529             token::Brace => Some(MacDelimiter::Brace),
1530             token::NoDelim => None,
1531         }
1532     }
1533 }
1534
1535 /// Represents a macro definition.
1536 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1537 pub struct MacroDef {
1538     pub body: P<MacArgs>,
1539     /// `true` if macro was defined with `macro_rules`.
1540     pub macro_rules: bool,
1541 }
1542
1543 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1544 #[derive(HashStable_Generic)]
1545 pub enum StrStyle {
1546     /// A regular string, like `"foo"`.
1547     Cooked,
1548     /// A raw string, like `r##"foo"##`.
1549     ///
1550     /// The value is the number of `#` symbols used.
1551     Raw(u16),
1552 }
1553
1554 /// An AST literal.
1555 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1556 pub struct Lit {
1557     /// The original literal token as written in source code.
1558     pub token: token::Lit,
1559     /// The "semantic" representation of the literal lowered from the original tokens.
1560     /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1561     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1562     pub kind: LitKind,
1563     pub span: Span,
1564 }
1565
1566 /// Same as `Lit`, but restricted to string literals.
1567 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1568 pub struct StrLit {
1569     /// The original literal token as written in source code.
1570     pub style: StrStyle,
1571     pub symbol: Symbol,
1572     pub suffix: Option<Symbol>,
1573     pub span: Span,
1574     /// The unescaped "semantic" representation of the literal lowered from the original token.
1575     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1576     pub symbol_unescaped: Symbol,
1577 }
1578
1579 impl StrLit {
1580     pub fn as_lit(&self) -> Lit {
1581         let token_kind = match self.style {
1582             StrStyle::Cooked => token::Str,
1583             StrStyle::Raw(n) => token::StrRaw(n),
1584         };
1585         Lit {
1586             token: token::Lit::new(token_kind, self.symbol, self.suffix),
1587             span: self.span,
1588             kind: LitKind::Str(self.symbol_unescaped, self.style),
1589         }
1590     }
1591 }
1592
1593 /// Type of the integer literal based on provided suffix.
1594 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1595 #[derive(HashStable_Generic)]
1596 pub enum LitIntType {
1597     /// e.g. `42_i32`.
1598     Signed(IntTy),
1599     /// e.g. `42_u32`.
1600     Unsigned(UintTy),
1601     /// e.g. `42`.
1602     Unsuffixed,
1603 }
1604
1605 /// Type of the float literal based on provided suffix.
1606 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1607 #[derive(HashStable_Generic)]
1608 pub enum LitFloatType {
1609     /// A float literal with a suffix (`1f32` or `1E10f32`).
1610     Suffixed(FloatTy),
1611     /// A float literal without a suffix (`1.0 or 1.0E10`).
1612     Unsuffixed,
1613 }
1614
1615 /// Literal kind.
1616 ///
1617 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1618 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1619 pub enum LitKind {
1620     /// A string literal (`"foo"`).
1621     Str(Symbol, StrStyle),
1622     /// A byte string (`b"foo"`).
1623     ByteStr(Lrc<[u8]>),
1624     /// A byte char (`b'f'`).
1625     Byte(u8),
1626     /// A character literal (`'a'`).
1627     Char(char),
1628     /// An integer literal (`1`).
1629     Int(u128, LitIntType),
1630     /// A float literal (`1f64` or `1E10f64`).
1631     Float(Symbol, LitFloatType),
1632     /// A boolean literal.
1633     Bool(bool),
1634     /// Placeholder for a literal that wasn't well-formed in some way.
1635     Err(Symbol),
1636 }
1637
1638 impl LitKind {
1639     /// Returns `true` if this literal is a string.
1640     pub fn is_str(&self) -> bool {
1641         matches!(self, LitKind::Str(..))
1642     }
1643
1644     /// Returns `true` if this literal is byte literal string.
1645     pub fn is_bytestr(&self) -> bool {
1646         matches!(self, LitKind::ByteStr(_))
1647     }
1648
1649     /// Returns `true` if this is a numeric literal.
1650     pub fn is_numeric(&self) -> bool {
1651         matches!(self, LitKind::Int(..) | LitKind::Float(..))
1652     }
1653
1654     /// Returns `true` if this literal has no suffix.
1655     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1656     pub fn is_unsuffixed(&self) -> bool {
1657         !self.is_suffixed()
1658     }
1659
1660     /// Returns `true` if this literal has a suffix.
1661     pub fn is_suffixed(&self) -> bool {
1662         match *self {
1663             // suffixed variants
1664             LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1665             | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1666             // unsuffixed variants
1667             LitKind::Str(..)
1668             | LitKind::ByteStr(..)
1669             | LitKind::Byte(..)
1670             | LitKind::Char(..)
1671             | LitKind::Int(_, LitIntType::Unsuffixed)
1672             | LitKind::Float(_, LitFloatType::Unsuffixed)
1673             | LitKind::Bool(..)
1674             | LitKind::Err(..) => false,
1675         }
1676     }
1677 }
1678
1679 // N.B., If you change this, you'll probably want to change the corresponding
1680 // type structure in `middle/ty.rs` as well.
1681 #[derive(Clone, Encodable, Decodable, Debug)]
1682 pub struct MutTy {
1683     pub ty: P<Ty>,
1684     pub mutbl: Mutability,
1685 }
1686
1687 /// Represents a function's signature in a trait declaration,
1688 /// trait implementation, or free function.
1689 #[derive(Clone, Encodable, Decodable, Debug)]
1690 pub struct FnSig {
1691     pub header: FnHeader,
1692     pub decl: P<FnDecl>,
1693     pub span: Span,
1694 }
1695
1696 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1697 #[derive(Encodable, Decodable, HashStable_Generic)]
1698 pub enum FloatTy {
1699     F32,
1700     F64,
1701 }
1702
1703 impl FloatTy {
1704     pub fn name_str(self) -> &'static str {
1705         match self {
1706             FloatTy::F32 => "f32",
1707             FloatTy::F64 => "f64",
1708         }
1709     }
1710
1711     pub fn name(self) -> Symbol {
1712         match self {
1713             FloatTy::F32 => sym::f32,
1714             FloatTy::F64 => sym::f64,
1715         }
1716     }
1717
1718     pub fn bit_width(self) -> u64 {
1719         match self {
1720             FloatTy::F32 => 32,
1721             FloatTy::F64 => 64,
1722         }
1723     }
1724 }
1725
1726 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1727 #[derive(Encodable, Decodable, HashStable_Generic)]
1728 pub enum IntTy {
1729     Isize,
1730     I8,
1731     I16,
1732     I32,
1733     I64,
1734     I128,
1735 }
1736
1737 impl IntTy {
1738     pub fn name_str(&self) -> &'static str {
1739         match *self {
1740             IntTy::Isize => "isize",
1741             IntTy::I8 => "i8",
1742             IntTy::I16 => "i16",
1743             IntTy::I32 => "i32",
1744             IntTy::I64 => "i64",
1745             IntTy::I128 => "i128",
1746         }
1747     }
1748
1749     pub fn name(&self) -> Symbol {
1750         match *self {
1751             IntTy::Isize => sym::isize,
1752             IntTy::I8 => sym::i8,
1753             IntTy::I16 => sym::i16,
1754             IntTy::I32 => sym::i32,
1755             IntTy::I64 => sym::i64,
1756             IntTy::I128 => sym::i128,
1757         }
1758     }
1759
1760     pub fn bit_width(&self) -> Option<u64> {
1761         Some(match *self {
1762             IntTy::Isize => return None,
1763             IntTy::I8 => 8,
1764             IntTy::I16 => 16,
1765             IntTy::I32 => 32,
1766             IntTy::I64 => 64,
1767             IntTy::I128 => 128,
1768         })
1769     }
1770
1771     pub fn normalize(&self, target_width: u32) -> Self {
1772         match self {
1773             IntTy::Isize => match target_width {
1774                 16 => IntTy::I16,
1775                 32 => IntTy::I32,
1776                 64 => IntTy::I64,
1777                 _ => unreachable!(),
1778             },
1779             _ => *self,
1780         }
1781     }
1782 }
1783
1784 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1785 #[derive(Encodable, Decodable, HashStable_Generic)]
1786 pub enum UintTy {
1787     Usize,
1788     U8,
1789     U16,
1790     U32,
1791     U64,
1792     U128,
1793 }
1794
1795 impl UintTy {
1796     pub fn name_str(&self) -> &'static str {
1797         match *self {
1798             UintTy::Usize => "usize",
1799             UintTy::U8 => "u8",
1800             UintTy::U16 => "u16",
1801             UintTy::U32 => "u32",
1802             UintTy::U64 => "u64",
1803             UintTy::U128 => "u128",
1804         }
1805     }
1806
1807     pub fn name(&self) -> Symbol {
1808         match *self {
1809             UintTy::Usize => sym::usize,
1810             UintTy::U8 => sym::u8,
1811             UintTy::U16 => sym::u16,
1812             UintTy::U32 => sym::u32,
1813             UintTy::U64 => sym::u64,
1814             UintTy::U128 => sym::u128,
1815         }
1816     }
1817
1818     pub fn bit_width(&self) -> Option<u64> {
1819         Some(match *self {
1820             UintTy::Usize => return None,
1821             UintTy::U8 => 8,
1822             UintTy::U16 => 16,
1823             UintTy::U32 => 32,
1824             UintTy::U64 => 64,
1825             UintTy::U128 => 128,
1826         })
1827     }
1828
1829     pub fn normalize(&self, target_width: u32) -> Self {
1830         match self {
1831             UintTy::Usize => match target_width {
1832                 16 => UintTy::U16,
1833                 32 => UintTy::U32,
1834                 64 => UintTy::U64,
1835                 _ => unreachable!(),
1836             },
1837             _ => *self,
1838         }
1839     }
1840 }
1841
1842 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1843 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1844 #[derive(Clone, Encodable, Decodable, Debug)]
1845 pub struct AssocTyConstraint {
1846     pub id: NodeId,
1847     pub ident: Ident,
1848     pub gen_args: Option<GenericArgs>,
1849     pub kind: AssocTyConstraintKind,
1850     pub span: Span,
1851 }
1852
1853 /// The kinds of an `AssocTyConstraint`.
1854 #[derive(Clone, Encodable, Decodable, Debug)]
1855 pub enum AssocTyConstraintKind {
1856     /// E.g., `A = Bar` in `Foo<A = Bar>`.
1857     Equality { ty: P<Ty> },
1858     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1859     Bound { bounds: GenericBounds },
1860 }
1861
1862 #[derive(Encodable, Decodable, Debug)]
1863 pub struct Ty {
1864     pub id: NodeId,
1865     pub kind: TyKind,
1866     pub span: Span,
1867     pub tokens: Option<LazyTokenStream>,
1868 }
1869
1870 impl Clone for Ty {
1871     fn clone(&self) -> Self {
1872         ensure_sufficient_stack(|| Self {
1873             id: self.id,
1874             kind: self.kind.clone(),
1875             span: self.span,
1876             tokens: self.tokens.clone(),
1877         })
1878     }
1879 }
1880
1881 impl Ty {
1882     pub fn peel_refs(&self) -> &Self {
1883         let mut final_ty = self;
1884         while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1885             final_ty = &ty;
1886         }
1887         final_ty
1888     }
1889 }
1890
1891 #[derive(Clone, Encodable, Decodable, Debug)]
1892 pub struct BareFnTy {
1893     pub unsafety: Unsafe,
1894     pub ext: Extern,
1895     pub generic_params: Vec<GenericParam>,
1896     pub decl: P<FnDecl>,
1897 }
1898
1899 /// The various kinds of type recognized by the compiler.
1900 #[derive(Clone, Encodable, Decodable, Debug)]
1901 pub enum TyKind {
1902     /// A variable-length slice (`[T]`).
1903     Slice(P<Ty>),
1904     /// A fixed length array (`[T; n]`).
1905     Array(P<Ty>, AnonConst),
1906     /// A raw pointer (`*const T` or `*mut T`).
1907     Ptr(MutTy),
1908     /// A reference (`&'a T` or `&'a mut T`).
1909     Rptr(Option<Lifetime>, MutTy),
1910     /// A bare function (e.g., `fn(usize) -> bool`).
1911     BareFn(P<BareFnTy>),
1912     /// The never type (`!`).
1913     Never,
1914     /// A tuple (`(A, B, C, D,...)`).
1915     Tup(Vec<P<Ty>>),
1916     /// A path (`module::module::...::Type`), optionally
1917     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1918     ///
1919     /// Type parameters are stored in the `Path` itself.
1920     Path(Option<QSelf>, Path),
1921     /// A trait object type `Bound1 + Bound2 + Bound3`
1922     /// where `Bound` is a trait or a lifetime.
1923     TraitObject(GenericBounds, TraitObjectSyntax),
1924     /// An `impl Bound1 + Bound2 + Bound3` type
1925     /// where `Bound` is a trait or a lifetime.
1926     ///
1927     /// The `NodeId` exists to prevent lowering from having to
1928     /// generate `NodeId`s on the fly, which would complicate
1929     /// the generation of opaque `type Foo = impl Trait` items significantly.
1930     ImplTrait(NodeId, GenericBounds),
1931     /// No-op; kept solely so that we can pretty-print faithfully.
1932     Paren(P<Ty>),
1933     /// Unused for now.
1934     Typeof(AnonConst),
1935     /// This means the type should be inferred instead of it having been
1936     /// specified. This can appear anywhere in a type.
1937     Infer,
1938     /// Inferred type of a `self` or `&self` argument in a method.
1939     ImplicitSelf,
1940     /// A macro in the type position.
1941     MacCall(MacCall),
1942     /// Placeholder for a kind that has failed to be defined.
1943     Err,
1944     /// Placeholder for a `va_list`.
1945     CVarArgs,
1946 }
1947
1948 impl TyKind {
1949     pub fn is_implicit_self(&self) -> bool {
1950         matches!(self, TyKind::ImplicitSelf)
1951     }
1952
1953     pub fn is_unit(&self) -> bool {
1954         matches!(self, TyKind::Tup(tys) if tys.is_empty())
1955     }
1956 }
1957
1958 /// Syntax used to declare a trait object.
1959 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1960 pub enum TraitObjectSyntax {
1961     Dyn,
1962     None,
1963 }
1964
1965 /// Inline assembly operand explicit register or register class.
1966 ///
1967 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1968 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1969 pub enum InlineAsmRegOrRegClass {
1970     Reg(Symbol),
1971     RegClass(Symbol),
1972 }
1973
1974 bitflags::bitflags! {
1975     #[derive(Encodable, Decodable, HashStable_Generic)]
1976     pub struct InlineAsmOptions: u8 {
1977         const PURE = 1 << 0;
1978         const NOMEM = 1 << 1;
1979         const READONLY = 1 << 2;
1980         const PRESERVES_FLAGS = 1 << 3;
1981         const NORETURN = 1 << 4;
1982         const NOSTACK = 1 << 5;
1983         const ATT_SYNTAX = 1 << 6;
1984     }
1985 }
1986
1987 #[derive(Clone, PartialEq, PartialOrd, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
1988 pub enum InlineAsmTemplatePiece {
1989     String(String),
1990     Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1991 }
1992
1993 impl fmt::Display for InlineAsmTemplatePiece {
1994     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1995         match self {
1996             Self::String(s) => {
1997                 for c in s.chars() {
1998                     match c {
1999                         '{' => f.write_str("{{")?,
2000                         '}' => f.write_str("}}")?,
2001                         _ => c.fmt(f)?,
2002                     }
2003                 }
2004                 Ok(())
2005             }
2006             Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2007                 write!(f, "{{{}:{}}}", operand_idx, modifier)
2008             }
2009             Self::Placeholder { operand_idx, modifier: None, .. } => {
2010                 write!(f, "{{{}}}", operand_idx)
2011             }
2012         }
2013     }
2014 }
2015
2016 impl InlineAsmTemplatePiece {
2017     /// Rebuilds the asm template string from its pieces.
2018     pub fn to_string(s: &[Self]) -> String {
2019         use fmt::Write;
2020         let mut out = String::new();
2021         for p in s.iter() {
2022             let _ = write!(out, "{}", p);
2023         }
2024         out
2025     }
2026 }
2027
2028 /// Inline assembly operand.
2029 ///
2030 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2031 #[derive(Clone, Encodable, Decodable, Debug)]
2032 pub enum InlineAsmOperand {
2033     In {
2034         reg: InlineAsmRegOrRegClass,
2035         expr: P<Expr>,
2036     },
2037     Out {
2038         reg: InlineAsmRegOrRegClass,
2039         late: bool,
2040         expr: Option<P<Expr>>,
2041     },
2042     InOut {
2043         reg: InlineAsmRegOrRegClass,
2044         late: bool,
2045         expr: P<Expr>,
2046     },
2047     SplitInOut {
2048         reg: InlineAsmRegOrRegClass,
2049         late: bool,
2050         in_expr: P<Expr>,
2051         out_expr: Option<P<Expr>>,
2052     },
2053     Const {
2054         expr: P<Expr>,
2055     },
2056     Sym {
2057         expr: P<Expr>,
2058     },
2059 }
2060
2061 /// Inline assembly.
2062 ///
2063 /// E.g., `asm!("NOP");`.
2064 #[derive(Clone, Encodable, Decodable, Debug)]
2065 pub struct InlineAsm {
2066     pub template: Vec<InlineAsmTemplatePiece>,
2067     pub operands: Vec<(InlineAsmOperand, Span)>,
2068     pub options: InlineAsmOptions,
2069     pub line_spans: Vec<Span>,
2070 }
2071
2072 /// Inline assembly dialect.
2073 ///
2074 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2075 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Hash, HashStable_Generic)]
2076 pub enum LlvmAsmDialect {
2077     Att,
2078     Intel,
2079 }
2080
2081 /// LLVM-style inline assembly.
2082 ///
2083 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2084 #[derive(Clone, Encodable, Decodable, Debug)]
2085 pub struct LlvmInlineAsmOutput {
2086     pub constraint: Symbol,
2087     pub expr: P<Expr>,
2088     pub is_rw: bool,
2089     pub is_indirect: bool,
2090 }
2091
2092 /// LLVM-style inline assembly.
2093 ///
2094 /// E.g., `llvm_asm!("NOP");`.
2095 #[derive(Clone, Encodable, Decodable, Debug)]
2096 pub struct LlvmInlineAsm {
2097     pub asm: Symbol,
2098     pub asm_str_style: StrStyle,
2099     pub outputs: Vec<LlvmInlineAsmOutput>,
2100     pub inputs: Vec<(Symbol, P<Expr>)>,
2101     pub clobbers: Vec<Symbol>,
2102     pub volatile: bool,
2103     pub alignstack: bool,
2104     pub dialect: LlvmAsmDialect,
2105 }
2106
2107 /// A parameter in a function header.
2108 ///
2109 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2110 #[derive(Clone, Encodable, Decodable, Debug)]
2111 pub struct Param {
2112     pub attrs: AttrVec,
2113     pub ty: P<Ty>,
2114     pub pat: P<Pat>,
2115     pub id: NodeId,
2116     pub span: Span,
2117     pub is_placeholder: bool,
2118 }
2119
2120 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2121 ///
2122 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2123 #[derive(Clone, Encodable, Decodable, Debug)]
2124 pub enum SelfKind {
2125     /// `self`, `mut self`
2126     Value(Mutability),
2127     /// `&'lt self`, `&'lt mut self`
2128     Region(Option<Lifetime>, Mutability),
2129     /// `self: TYPE`, `mut self: TYPE`
2130     Explicit(P<Ty>, Mutability),
2131 }
2132
2133 pub type ExplicitSelf = Spanned<SelfKind>;
2134
2135 impl Param {
2136     /// Attempts to cast parameter to `ExplicitSelf`.
2137     pub fn to_self(&self) -> Option<ExplicitSelf> {
2138         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2139             if ident.name == kw::SelfLower {
2140                 return match self.ty.kind {
2141                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2142                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2143                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2144                     }
2145                     _ => Some(respan(
2146                         self.pat.span.to(self.ty.span),
2147                         SelfKind::Explicit(self.ty.clone(), mutbl),
2148                     )),
2149                 };
2150             }
2151         }
2152         None
2153     }
2154
2155     /// Returns `true` if parameter is `self`.
2156     pub fn is_self(&self) -> bool {
2157         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2158             ident.name == kw::SelfLower
2159         } else {
2160             false
2161         }
2162     }
2163
2164     /// Builds a `Param` object from `ExplicitSelf`.
2165     pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2166         let span = eself.span.to(eself_ident.span);
2167         let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2168         let param = |mutbl, ty| Param {
2169             attrs,
2170             pat: P(Pat {
2171                 id: DUMMY_NODE_ID,
2172                 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2173                 span,
2174                 tokens: None,
2175             }),
2176             span,
2177             ty,
2178             id: DUMMY_NODE_ID,
2179             is_placeholder: false,
2180         };
2181         match eself.node {
2182             SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2183             SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2184             SelfKind::Region(lt, mutbl) => param(
2185                 Mutability::Not,
2186                 P(Ty {
2187                     id: DUMMY_NODE_ID,
2188                     kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2189                     span,
2190                     tokens: None,
2191                 }),
2192             ),
2193         }
2194     }
2195 }
2196
2197 /// A signature (not the body) of a function declaration.
2198 ///
2199 /// E.g., `fn foo(bar: baz)`.
2200 ///
2201 /// Please note that it's different from `FnHeader` structure
2202 /// which contains metadata about function safety, asyncness, constness and ABI.
2203 #[derive(Clone, Encodable, Decodable, Debug)]
2204 pub struct FnDecl {
2205     pub inputs: Vec<Param>,
2206     pub output: FnRetTy,
2207 }
2208
2209 impl FnDecl {
2210     pub fn get_self(&self) -> Option<ExplicitSelf> {
2211         self.inputs.get(0).and_then(Param::to_self)
2212     }
2213     pub fn has_self(&self) -> bool {
2214         self.inputs.get(0).map_or(false, Param::is_self)
2215     }
2216     pub fn c_variadic(&self) -> bool {
2217         self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2218     }
2219 }
2220
2221 /// Is the trait definition an auto trait?
2222 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2223 pub enum IsAuto {
2224     Yes,
2225     No,
2226 }
2227
2228 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2229 #[derive(HashStable_Generic)]
2230 pub enum Unsafe {
2231     Yes(Span),
2232     No,
2233 }
2234
2235 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2236 pub enum Async {
2237     Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2238     No,
2239 }
2240
2241 impl Async {
2242     pub fn is_async(self) -> bool {
2243         matches!(self, Async::Yes { .. })
2244     }
2245
2246     /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2247     pub fn opt_return_id(self) -> Option<NodeId> {
2248         match self {
2249             Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2250             Async::No => None,
2251         }
2252     }
2253 }
2254
2255 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2256 #[derive(HashStable_Generic)]
2257 pub enum Const {
2258     Yes(Span),
2259     No,
2260 }
2261
2262 /// Item defaultness.
2263 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2264 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2265 pub enum Defaultness {
2266     Default(Span),
2267     Final,
2268 }
2269
2270 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2271 pub enum ImplPolarity {
2272     /// `impl Trait for Type`
2273     Positive,
2274     /// `impl !Trait for Type`
2275     Negative(Span),
2276 }
2277
2278 impl fmt::Debug for ImplPolarity {
2279     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2280         match *self {
2281             ImplPolarity::Positive => "positive".fmt(f),
2282             ImplPolarity::Negative(_) => "negative".fmt(f),
2283         }
2284     }
2285 }
2286
2287 #[derive(Clone, Encodable, Decodable, Debug)]
2288 pub enum FnRetTy {
2289     /// Returns type is not specified.
2290     ///
2291     /// Functions default to `()` and closures default to inference.
2292     /// Span points to where return type would be inserted.
2293     Default(Span),
2294     /// Everything else.
2295     Ty(P<Ty>),
2296 }
2297
2298 impl FnRetTy {
2299     pub fn span(&self) -> Span {
2300         match *self {
2301             FnRetTy::Default(span) => span,
2302             FnRetTy::Ty(ref ty) => ty.span,
2303         }
2304     }
2305 }
2306
2307 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2308 pub enum Inline {
2309     Yes,
2310     No,
2311 }
2312
2313 /// Module item kind.
2314 #[derive(Clone, Encodable, Decodable, Debug)]
2315 pub enum ModKind {
2316     /// Module with inlined definition `mod foo { ... }`,
2317     /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2318     /// The inner span is from the first token past `{` to the last token until `}`,
2319     /// or from the first to the last token in the loaded file.
2320     Loaded(Vec<P<Item>>, Inline, Span),
2321     /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2322     Unloaded,
2323 }
2324
2325 /// Foreign module declaration.
2326 ///
2327 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2328 #[derive(Clone, Encodable, Decodable, Debug)]
2329 pub struct ForeignMod {
2330     /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2331     /// semantically by Rust.
2332     pub unsafety: Unsafe,
2333     pub abi: Option<StrLit>,
2334     pub items: Vec<P<ForeignItem>>,
2335 }
2336
2337 /// Global inline assembly.
2338 ///
2339 /// Also known as "module-level assembly" or "file-scoped assembly".
2340 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2341 pub struct GlobalAsm {
2342     pub asm: Symbol,
2343 }
2344
2345 #[derive(Clone, Encodable, Decodable, Debug)]
2346 pub struct EnumDef {
2347     pub variants: Vec<Variant>,
2348 }
2349 /// Enum variant.
2350 #[derive(Clone, Encodable, Decodable, Debug)]
2351 pub struct Variant {
2352     /// Attributes of the variant.
2353     pub attrs: Vec<Attribute>,
2354     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2355     pub id: NodeId,
2356     /// Span
2357     pub span: Span,
2358     /// The visibility of the variant. Syntactically accepted but not semantically.
2359     pub vis: Visibility,
2360     /// Name of the variant.
2361     pub ident: Ident,
2362
2363     /// Fields and constructor id of the variant.
2364     pub data: VariantData,
2365     /// Explicit discriminant, e.g., `Foo = 1`.
2366     pub disr_expr: Option<AnonConst>,
2367     /// Is a macro placeholder
2368     pub is_placeholder: bool,
2369 }
2370
2371 /// Part of `use` item to the right of its prefix.
2372 #[derive(Clone, Encodable, Decodable, Debug)]
2373 pub enum UseTreeKind {
2374     /// `use prefix` or `use prefix as rename`
2375     ///
2376     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2377     /// namespace.
2378     Simple(Option<Ident>, NodeId, NodeId),
2379     /// `use prefix::{...}`
2380     Nested(Vec<(UseTree, NodeId)>),
2381     /// `use prefix::*`
2382     Glob,
2383 }
2384
2385 /// A tree of paths sharing common prefixes.
2386 /// Used in `use` items both at top-level and inside of braces in import groups.
2387 #[derive(Clone, Encodable, Decodable, Debug)]
2388 pub struct UseTree {
2389     pub prefix: Path,
2390     pub kind: UseTreeKind,
2391     pub span: Span,
2392 }
2393
2394 impl UseTree {
2395     pub fn ident(&self) -> Ident {
2396         match self.kind {
2397             UseTreeKind::Simple(Some(rename), ..) => rename,
2398             UseTreeKind::Simple(None, ..) => {
2399                 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2400             }
2401             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2402         }
2403     }
2404 }
2405
2406 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2407 /// are contained as statements within items. These two cases need to be
2408 /// distinguished for pretty-printing.
2409 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2410 pub enum AttrStyle {
2411     Outer,
2412     Inner,
2413 }
2414
2415 rustc_index::newtype_index! {
2416     pub struct AttrId {
2417         ENCODABLE = custom
2418         DEBUG_FORMAT = "AttrId({})"
2419     }
2420 }
2421
2422 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2423     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2424         s.emit_unit()
2425     }
2426 }
2427
2428 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2429     fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2430         d.read_nil().map(|_| crate::attr::mk_attr_id())
2431     }
2432 }
2433
2434 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2435 pub struct AttrItem {
2436     pub path: Path,
2437     pub args: MacArgs,
2438     pub tokens: Option<LazyTokenStream>,
2439 }
2440
2441 /// A list of attributes.
2442 pub type AttrVec = ThinVec<Attribute>;
2443
2444 /// Metadata associated with an item.
2445 #[derive(Clone, Encodable, Decodable, Debug)]
2446 pub struct Attribute {
2447     pub kind: AttrKind,
2448     pub id: AttrId,
2449     /// Denotes if the attribute decorates the following construct (outer)
2450     /// or the construct this attribute is contained within (inner).
2451     pub style: AttrStyle,
2452     pub span: Span,
2453 }
2454
2455 #[derive(Clone, Encodable, Decodable, Debug)]
2456 pub enum AttrKind {
2457     /// A normal attribute.
2458     Normal(AttrItem, Option<LazyTokenStream>),
2459
2460     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2461     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2462     /// variant (which is much less compact and thus more expensive).
2463     DocComment(CommentKind, Symbol),
2464 }
2465
2466 /// `TraitRef`s appear in impls.
2467 ///
2468 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2469 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2470 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2471 /// same as the impl's `NodeId`).
2472 #[derive(Clone, Encodable, Decodable, Debug)]
2473 pub struct TraitRef {
2474     pub path: Path,
2475     pub ref_id: NodeId,
2476 }
2477
2478 #[derive(Clone, Encodable, Decodable, Debug)]
2479 pub struct PolyTraitRef {
2480     /// The `'a` in `<'a> Foo<&'a T>`.
2481     pub bound_generic_params: Vec<GenericParam>,
2482
2483     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2484     pub trait_ref: TraitRef,
2485
2486     pub span: Span,
2487 }
2488
2489 impl PolyTraitRef {
2490     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2491         PolyTraitRef {
2492             bound_generic_params: generic_params,
2493             trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2494             span,
2495         }
2496     }
2497 }
2498
2499 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2500 pub enum CrateSugar {
2501     /// Source is `pub(crate)`.
2502     PubCrate,
2503
2504     /// Source is (just) `crate`.
2505     JustCrate,
2506 }
2507
2508 #[derive(Clone, Encodable, Decodable, Debug)]
2509 pub struct Visibility {
2510     pub kind: VisibilityKind,
2511     pub span: Span,
2512     pub tokens: Option<LazyTokenStream>,
2513 }
2514
2515 #[derive(Clone, Encodable, Decodable, Debug)]
2516 pub enum VisibilityKind {
2517     Public,
2518     Crate(CrateSugar),
2519     Restricted { path: P<Path>, id: NodeId },
2520     Inherited,
2521 }
2522
2523 impl VisibilityKind {
2524     pub fn is_pub(&self) -> bool {
2525         matches!(self, VisibilityKind::Public)
2526     }
2527 }
2528
2529 /// Field definition in a struct, variant or union.
2530 ///
2531 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2532 #[derive(Clone, Encodable, Decodable, Debug)]
2533 pub struct FieldDef {
2534     pub attrs: Vec<Attribute>,
2535     pub id: NodeId,
2536     pub span: Span,
2537     pub vis: Visibility,
2538     pub ident: Option<Ident>,
2539
2540     pub ty: P<Ty>,
2541     pub is_placeholder: bool,
2542 }
2543
2544 /// Fields and constructor ids of enum variants and structs.
2545 #[derive(Clone, Encodable, Decodable, Debug)]
2546 pub enum VariantData {
2547     /// Struct variant.
2548     ///
2549     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2550     Struct(Vec<FieldDef>, bool),
2551     /// Tuple variant.
2552     ///
2553     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2554     Tuple(Vec<FieldDef>, NodeId),
2555     /// Unit variant.
2556     ///
2557     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2558     Unit(NodeId),
2559 }
2560
2561 impl VariantData {
2562     /// Return the fields of this variant.
2563     pub fn fields(&self) -> &[FieldDef] {
2564         match *self {
2565             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2566             _ => &[],
2567         }
2568     }
2569
2570     /// Return the `NodeId` of this variant's constructor, if it has one.
2571     pub fn ctor_id(&self) -> Option<NodeId> {
2572         match *self {
2573             VariantData::Struct(..) => None,
2574             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2575         }
2576     }
2577 }
2578
2579 /// An item definition.
2580 #[derive(Clone, Encodable, Decodable, Debug)]
2581 pub struct Item<K = ItemKind> {
2582     pub attrs: Vec<Attribute>,
2583     pub id: NodeId,
2584     pub span: Span,
2585     pub vis: Visibility,
2586     /// The name of the item.
2587     /// It might be a dummy name in case of anonymous items.
2588     pub ident: Ident,
2589
2590     pub kind: K,
2591
2592     /// Original tokens this item was parsed from. This isn't necessarily
2593     /// available for all items, although over time more and more items should
2594     /// have this be `Some`. Right now this is primarily used for procedural
2595     /// macros, notably custom attributes.
2596     ///
2597     /// Note that the tokens here do not include the outer attributes, but will
2598     /// include inner attributes.
2599     pub tokens: Option<LazyTokenStream>,
2600 }
2601
2602 impl Item {
2603     /// Return the span that encompasses the attributes.
2604     pub fn span_with_attributes(&self) -> Span {
2605         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2606     }
2607 }
2608
2609 impl<K: Into<ItemKind>> Item<K> {
2610     pub fn into_item(self) -> Item {
2611         let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2612         Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2613     }
2614 }
2615
2616 /// `extern` qualifier on a function item or function type.
2617 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2618 pub enum Extern {
2619     None,
2620     Implicit,
2621     Explicit(StrLit),
2622 }
2623
2624 impl Extern {
2625     pub fn from_abi(abi: Option<StrLit>) -> Extern {
2626         abi.map_or(Extern::Implicit, Extern::Explicit)
2627     }
2628 }
2629
2630 /// A function header.
2631 ///
2632 /// All the information between the visibility and the name of the function is
2633 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2634 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2635 pub struct FnHeader {
2636     pub unsafety: Unsafe,
2637     pub asyncness: Async,
2638     pub constness: Const,
2639     pub ext: Extern,
2640 }
2641
2642 impl FnHeader {
2643     /// Does this function header have any qualifiers or is it empty?
2644     pub fn has_qualifiers(&self) -> bool {
2645         let Self { unsafety, asyncness, constness, ext } = self;
2646         matches!(unsafety, Unsafe::Yes(_))
2647             || asyncness.is_async()
2648             || matches!(constness, Const::Yes(_))
2649             || !matches!(ext, Extern::None)
2650     }
2651 }
2652
2653 impl Default for FnHeader {
2654     fn default() -> FnHeader {
2655         FnHeader {
2656             unsafety: Unsafe::No,
2657             asyncness: Async::No,
2658             constness: Const::No,
2659             ext: Extern::None,
2660         }
2661     }
2662 }
2663
2664 #[derive(Clone, Encodable, Decodable, Debug)]
2665 pub struct TraitKind(
2666     pub IsAuto,
2667     pub Unsafe,
2668     pub Generics,
2669     pub GenericBounds,
2670     pub Vec<P<AssocItem>>,
2671 );
2672
2673 #[derive(Clone, Encodable, Decodable, Debug)]
2674 pub struct TyAliasKind(pub Defaultness, pub Generics, pub GenericBounds, pub Option<P<Ty>>);
2675
2676 #[derive(Clone, Encodable, Decodable, Debug)]
2677 pub struct ImplKind {
2678     pub unsafety: Unsafe,
2679     pub polarity: ImplPolarity,
2680     pub defaultness: Defaultness,
2681     pub constness: Const,
2682     pub generics: Generics,
2683
2684     /// The trait being implemented, if any.
2685     pub of_trait: Option<TraitRef>,
2686
2687     pub self_ty: P<Ty>,
2688     pub items: Vec<P<AssocItem>>,
2689 }
2690
2691 #[derive(Clone, Encodable, Decodable, Debug)]
2692 pub struct FnKind(pub Defaultness, pub FnSig, pub Generics, pub Option<P<Block>>);
2693
2694 #[derive(Clone, Encodable, Decodable, Debug)]
2695 pub enum ItemKind {
2696     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2697     ///
2698     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2699     ExternCrate(Option<Symbol>),
2700     /// A use declaration item (`use`).
2701     ///
2702     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2703     Use(UseTree),
2704     /// A static item (`static`).
2705     ///
2706     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2707     Static(P<Ty>, Mutability, Option<P<Expr>>),
2708     /// A constant item (`const`).
2709     ///
2710     /// E.g., `const FOO: i32 = 42;`.
2711     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2712     /// A function declaration (`fn`).
2713     ///
2714     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2715     Fn(Box<FnKind>),
2716     /// A module declaration (`mod`).
2717     ///
2718     /// E.g., `mod foo;` or `mod foo { .. }`.
2719     /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2720     /// semantically by Rust.
2721     Mod(Unsafe, ModKind),
2722     /// An external module (`extern`).
2723     ///
2724     /// E.g., `extern {}` or `extern "C" {}`.
2725     ForeignMod(ForeignMod),
2726     /// Module-level inline assembly (from `global_asm!()`).
2727     GlobalAsm(GlobalAsm),
2728     /// A type alias (`type`).
2729     ///
2730     /// E.g., `type Foo = Bar<u8>;`.
2731     TyAlias(Box<TyAliasKind>),
2732     /// An enum definition (`enum`).
2733     ///
2734     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2735     Enum(EnumDef, Generics),
2736     /// A struct definition (`struct`).
2737     ///
2738     /// E.g., `struct Foo<A> { x: A }`.
2739     Struct(VariantData, Generics),
2740     /// A union definition (`union`).
2741     ///
2742     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2743     Union(VariantData, Generics),
2744     /// A trait declaration (`trait`).
2745     ///
2746     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2747     Trait(Box<TraitKind>),
2748     /// Trait alias
2749     ///
2750     /// E.g., `trait Foo = Bar + Quux;`.
2751     TraitAlias(Generics, GenericBounds),
2752     /// An implementation.
2753     ///
2754     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2755     Impl(Box<ImplKind>),
2756     /// A macro invocation.
2757     ///
2758     /// E.g., `foo!(..)`.
2759     MacCall(MacCall),
2760
2761     /// A macro definition.
2762     MacroDef(MacroDef),
2763 }
2764
2765 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2766 rustc_data_structures::static_assert_size!(ItemKind, 112);
2767
2768 impl ItemKind {
2769     pub fn article(&self) -> &str {
2770         use ItemKind::*;
2771         match self {
2772             Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2773             | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2774             ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2775         }
2776     }
2777
2778     pub fn descr(&self) -> &str {
2779         match self {
2780             ItemKind::ExternCrate(..) => "extern crate",
2781             ItemKind::Use(..) => "`use` import",
2782             ItemKind::Static(..) => "static item",
2783             ItemKind::Const(..) => "constant item",
2784             ItemKind::Fn(..) => "function",
2785             ItemKind::Mod(..) => "module",
2786             ItemKind::ForeignMod(..) => "extern block",
2787             ItemKind::GlobalAsm(..) => "global asm item",
2788             ItemKind::TyAlias(..) => "type alias",
2789             ItemKind::Enum(..) => "enum",
2790             ItemKind::Struct(..) => "struct",
2791             ItemKind::Union(..) => "union",
2792             ItemKind::Trait(..) => "trait",
2793             ItemKind::TraitAlias(..) => "trait alias",
2794             ItemKind::MacCall(..) => "item macro invocation",
2795             ItemKind::MacroDef(..) => "macro definition",
2796             ItemKind::Impl { .. } => "implementation",
2797         }
2798     }
2799
2800     pub fn generics(&self) -> Option<&Generics> {
2801         match self {
2802             Self::Fn(box FnKind(_, _, generics, _))
2803             | Self::TyAlias(box TyAliasKind(_, generics, ..))
2804             | Self::Enum(_, generics)
2805             | Self::Struct(_, generics)
2806             | Self::Union(_, generics)
2807             | Self::Trait(box TraitKind(_, _, generics, ..))
2808             | Self::TraitAlias(generics, _)
2809             | Self::Impl(box ImplKind { generics, .. }) => Some(generics),
2810             _ => None,
2811         }
2812     }
2813 }
2814
2815 /// Represents associated items.
2816 /// These include items in `impl` and `trait` definitions.
2817 pub type AssocItem = Item<AssocItemKind>;
2818
2819 /// Represents associated item kinds.
2820 ///
2821 /// The term "provided" in the variants below refers to the item having a default
2822 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2823 /// In an implementation, all items must be provided.
2824 /// The `Option`s below denote the bodies, where `Some(_)`
2825 /// means "provided" and conversely `None` means "required".
2826 #[derive(Clone, Encodable, Decodable, Debug)]
2827 pub enum AssocItemKind {
2828     /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2829     /// If `def` is parsed, then the constant is provided, and otherwise required.
2830     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2831     /// An associated function.
2832     Fn(Box<FnKind>),
2833     /// An associated type.
2834     TyAlias(Box<TyAliasKind>),
2835     /// A macro expanding to associated items.
2836     MacCall(MacCall),
2837 }
2838
2839 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2840 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2841
2842 impl AssocItemKind {
2843     pub fn defaultness(&self) -> Defaultness {
2844         match *self {
2845             Self::Const(def, ..)
2846             | Self::Fn(box FnKind(def, ..))
2847             | Self::TyAlias(box TyAliasKind(def, ..)) => def,
2848             Self::MacCall(..) => Defaultness::Final,
2849         }
2850     }
2851 }
2852
2853 impl From<AssocItemKind> for ItemKind {
2854     fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2855         match assoc_item_kind {
2856             AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2857             AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2858             AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2859             AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2860         }
2861     }
2862 }
2863
2864 impl TryFrom<ItemKind> for AssocItemKind {
2865     type Error = ItemKind;
2866
2867     fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2868         Ok(match item_kind {
2869             ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2870             ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2871             ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2872             ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2873             _ => return Err(item_kind),
2874         })
2875     }
2876 }
2877
2878 /// An item in `extern` block.
2879 #[derive(Clone, Encodable, Decodable, Debug)]
2880 pub enum ForeignItemKind {
2881     /// A foreign static item (`static FOO: u8`).
2882     Static(P<Ty>, Mutability, Option<P<Expr>>),
2883     /// An foreign function.
2884     Fn(Box<FnKind>),
2885     /// An foreign type.
2886     TyAlias(Box<TyAliasKind>),
2887     /// A macro expanding to foreign items.
2888     MacCall(MacCall),
2889 }
2890
2891 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2892 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
2893
2894 impl From<ForeignItemKind> for ItemKind {
2895     fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2896         match foreign_item_kind {
2897             ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2898             ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2899             ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2900             ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2901         }
2902     }
2903 }
2904
2905 impl TryFrom<ItemKind> for ForeignItemKind {
2906     type Error = ItemKind;
2907
2908     fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2909         Ok(match item_kind {
2910             ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2911             ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
2912             ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
2913             ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2914             _ => return Err(item_kind),
2915         })
2916     }
2917 }
2918
2919 pub type ForeignItem = Item<ForeignItemKind>;