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