rustc_ast/
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//! - [`MetaItemLit`] and [`LitKind`]: Literal expressions.
17//! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`]: Macro definition and invocation.
18//! - [`Attribute`]: Metadata associated with item.
19//! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
20
21use std::borrow::Cow;
22use std::sync::Arc;
23use std::{cmp, fmt};
24
25pub use GenericArgs::*;
26pub use UnsafeSource::*;
27pub use rustc_ast_ir::{Movability, Mutability, Pinnedness};
28use rustc_data_structures::packed::Pu128;
29use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30use rustc_data_structures::stack::ensure_sufficient_stack;
31use rustc_data_structures::tagged_ptr::Tag;
32use rustc_macros::{Decodable, Encodable, HashStable_Generic};
33pub use rustc_span::AttrId;
34use rustc_span::source_map::{Spanned, respan};
35use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
36use thin_vec::{ThinVec, thin_vec};
37
38pub use crate::format::*;
39use crate::ptr::P;
40use crate::token::{self, CommentKind, Delimiter};
41use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream};
42use crate::util::parser::{ExprPrecedence, Fixity};
43
44/// A "Label" is an identifier of some point in sources,
45/// e.g. in the following code:
46///
47/// ```rust
48/// 'outer: loop {
49///     break 'outer;
50/// }
51/// ```
52///
53/// `'outer` is a label.
54#[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
55pub struct Label {
56    pub ident: Ident,
57}
58
59impl fmt::Debug for Label {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write!(f, "label({:?})", self.ident)
62    }
63}
64
65/// A "Lifetime" is an annotation of the scope in which variable
66/// can be used, e.g. `'a` in `&'a i32`.
67#[derive(Clone, Encodable, Decodable, Copy, PartialEq, Eq, Hash)]
68pub struct Lifetime {
69    pub id: NodeId,
70    pub ident: Ident,
71}
72
73impl fmt::Debug for Lifetime {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        write!(f, "lifetime({}: {})", self.id, self)
76    }
77}
78
79impl fmt::Display for Lifetime {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(f, "{}", self.ident.name)
82    }
83}
84
85/// A "Path" is essentially Rust's notion of a name.
86///
87/// It's represented as a sequence of identifiers,
88/// along with a bunch of supporting information.
89///
90/// E.g., `std::cmp::PartialEq`.
91#[derive(Clone, Encodable, Decodable, Debug)]
92pub struct Path {
93    pub span: Span,
94    /// The segments in the path: the things separated by `::`.
95    /// Global paths begin with `kw::PathRoot`.
96    pub segments: ThinVec<PathSegment>,
97    pub tokens: Option<LazyAttrTokenStream>,
98}
99
100impl PartialEq<Symbol> for Path {
101    #[inline]
102    fn eq(&self, symbol: &Symbol) -> bool {
103        matches!(&self.segments[..], [segment] if segment.ident.name == *symbol)
104    }
105}
106
107impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
108    fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
109        self.segments.len().hash_stable(hcx, hasher);
110        for segment in &self.segments {
111            segment.ident.hash_stable(hcx, hasher);
112        }
113    }
114}
115
116impl Path {
117    /// Convert a span and an identifier to the corresponding
118    /// one-segment path.
119    pub fn from_ident(ident: Ident) -> Path {
120        Path { segments: thin_vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
121    }
122
123    pub fn is_global(&self) -> bool {
124        self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
125    }
126
127    /// Check if this path is potentially a trivial const arg, i.e., one that can _potentially_
128    /// be represented without an anon const in the HIR.
129    ///
130    /// If `allow_mgca_arg` is true (as should be the case in most situations when
131    /// `#![feature(min_generic_const_args)]` is enabled), then this always returns true
132    /// because all paths are valid.
133    ///
134    /// Otherwise, it returns true iff the path has exactly one segment, and it has no generic args
135    /// (i.e., it is _potentially_ a const parameter).
136    #[tracing::instrument(level = "debug", ret)]
137    pub fn is_potential_trivial_const_arg(&self, allow_mgca_arg: bool) -> bool {
138        allow_mgca_arg
139            || self.segments.len() == 1 && self.segments.iter().all(|seg| seg.args.is_none())
140    }
141}
142
143/// A segment of a path: an identifier, an optional lifetime, and a set of types.
144///
145/// E.g., `std`, `String` or `Box<T>`.
146#[derive(Clone, Encodable, Decodable, Debug)]
147pub struct PathSegment {
148    /// The identifier portion of this path segment.
149    pub ident: Ident,
150
151    pub id: NodeId,
152
153    /// Type/lifetime parameters attached to this path. They come in
154    /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
155    /// `None` means that no parameter list is supplied (`Path`),
156    /// `Some` means that parameter list is supplied (`Path<X, Y>`)
157    /// but it can be empty (`Path<>`).
158    /// `P` is used as a size optimization for the common case with no parameters.
159    pub args: Option<P<GenericArgs>>,
160}
161
162impl PathSegment {
163    pub fn from_ident(ident: Ident) -> Self {
164        PathSegment { ident, id: DUMMY_NODE_ID, args: None }
165    }
166
167    pub fn path_root(span: Span) -> Self {
168        PathSegment::from_ident(Ident::new(kw::PathRoot, span))
169    }
170
171    pub fn span(&self) -> Span {
172        match &self.args {
173            Some(args) => self.ident.span.to(args.span()),
174            None => self.ident.span,
175        }
176    }
177}
178
179/// The generic arguments and associated item constraints of a path segment.
180///
181/// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
182#[derive(Clone, Encodable, Decodable, Debug)]
183pub enum GenericArgs {
184    /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
185    AngleBracketed(AngleBracketedArgs),
186    /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
187    Parenthesized(ParenthesizedArgs),
188    /// `(..)` in return type notation.
189    ParenthesizedElided(Span),
190}
191
192impl GenericArgs {
193    pub fn is_angle_bracketed(&self) -> bool {
194        matches!(self, AngleBracketed(..))
195    }
196
197    pub fn span(&self) -> Span {
198        match self {
199            AngleBracketed(data) => data.span,
200            Parenthesized(data) => data.span,
201            ParenthesizedElided(span) => *span,
202        }
203    }
204}
205
206/// Concrete argument in the sequence of generic args.
207#[derive(Clone, Encodable, Decodable, Debug)]
208pub enum GenericArg {
209    /// `'a` in `Foo<'a>`.
210    Lifetime(Lifetime),
211    /// `Bar` in `Foo<Bar>`.
212    Type(P<Ty>),
213    /// `1` in `Foo<1>`.
214    Const(AnonConst),
215}
216
217impl GenericArg {
218    pub fn span(&self) -> Span {
219        match self {
220            GenericArg::Lifetime(lt) => lt.ident.span,
221            GenericArg::Type(ty) => ty.span,
222            GenericArg::Const(ct) => ct.value.span,
223        }
224    }
225}
226
227/// A path like `Foo<'a, T>`.
228#[derive(Clone, Encodable, Decodable, Debug, Default)]
229pub struct AngleBracketedArgs {
230    /// The overall span.
231    pub span: Span,
232    /// The comma separated parts in the `<...>`.
233    pub args: ThinVec<AngleBracketedArg>,
234}
235
236/// Either an argument for a generic parameter or a constraint on an associated item.
237#[derive(Clone, Encodable, Decodable, Debug)]
238pub enum AngleBracketedArg {
239    /// A generic argument for a generic parameter.
240    Arg(GenericArg),
241    /// A constraint on an associated item.
242    Constraint(AssocItemConstraint),
243}
244
245impl AngleBracketedArg {
246    pub fn span(&self) -> Span {
247        match self {
248            AngleBracketedArg::Arg(arg) => arg.span(),
249            AngleBracketedArg::Constraint(constraint) => constraint.span,
250        }
251    }
252}
253
254impl From<AngleBracketedArgs> for P<GenericArgs> {
255    fn from(val: AngleBracketedArgs) -> Self {
256        P(GenericArgs::AngleBracketed(val))
257    }
258}
259
260impl From<ParenthesizedArgs> for P<GenericArgs> {
261    fn from(val: ParenthesizedArgs) -> Self {
262        P(GenericArgs::Parenthesized(val))
263    }
264}
265
266/// A path like `Foo(A, B) -> C`.
267#[derive(Clone, Encodable, Decodable, Debug)]
268pub struct ParenthesizedArgs {
269    /// ```text
270    /// Foo(A, B) -> C
271    /// ^^^^^^^^^^^^^^
272    /// ```
273    pub span: Span,
274
275    /// `(A, B)`
276    pub inputs: ThinVec<P<Ty>>,
277
278    /// ```text
279    /// Foo(A, B) -> C
280    ///    ^^^^^^
281    /// ```
282    pub inputs_span: Span,
283
284    /// `C`
285    pub output: FnRetTy,
286}
287
288impl ParenthesizedArgs {
289    pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
290        let args = self
291            .inputs
292            .iter()
293            .cloned()
294            .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
295            .collect();
296        AngleBracketedArgs { span: self.inputs_span, args }
297    }
298}
299
300use crate::AstDeref;
301pub use crate::node_id::{CRATE_NODE_ID, DUMMY_NODE_ID, NodeId};
302
303/// Modifiers on a trait bound like `~const`, `?` and `!`.
304#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
305pub struct TraitBoundModifiers {
306    pub constness: BoundConstness,
307    pub asyncness: BoundAsyncness,
308    pub polarity: BoundPolarity,
309}
310
311impl TraitBoundModifiers {
312    pub const NONE: Self = Self {
313        constness: BoundConstness::Never,
314        asyncness: BoundAsyncness::Normal,
315        polarity: BoundPolarity::Positive,
316    };
317}
318
319#[derive(Clone, Encodable, Decodable, Debug)]
320pub enum GenericBound {
321    Trait(PolyTraitRef),
322    Outlives(Lifetime),
323    /// Precise capturing syntax: `impl Sized + use<'a>`
324    Use(ThinVec<PreciseCapturingArg>, Span),
325}
326
327impl GenericBound {
328    pub fn span(&self) -> Span {
329        match self {
330            GenericBound::Trait(t, ..) => t.span,
331            GenericBound::Outlives(l) => l.ident.span,
332            GenericBound::Use(_, span) => *span,
333        }
334    }
335}
336
337pub type GenericBounds = Vec<GenericBound>;
338
339/// Specifies the enforced ordering for generic parameters. In the future,
340/// if we wanted to relax this order, we could override `PartialEq` and
341/// `PartialOrd`, to allow the kinds to be unordered.
342#[derive(Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
343pub enum ParamKindOrd {
344    Lifetime,
345    TypeOrConst,
346}
347
348impl fmt::Display for ParamKindOrd {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        match self {
351            ParamKindOrd::Lifetime => "lifetime".fmt(f),
352            ParamKindOrd::TypeOrConst => "type and const".fmt(f),
353        }
354    }
355}
356
357#[derive(Clone, Encodable, Decodable, Debug)]
358pub enum GenericParamKind {
359    /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
360    Lifetime,
361    Type {
362        default: Option<P<Ty>>,
363    },
364    Const {
365        ty: P<Ty>,
366        /// Span of the `const` keyword.
367        kw_span: Span,
368        /// Optional default value for the const generic param.
369        default: Option<AnonConst>,
370    },
371}
372
373#[derive(Clone, Encodable, Decodable, Debug)]
374pub struct GenericParam {
375    pub id: NodeId,
376    pub ident: Ident,
377    pub attrs: AttrVec,
378    pub bounds: GenericBounds,
379    pub is_placeholder: bool,
380    pub kind: GenericParamKind,
381    pub colon_span: Option<Span>,
382}
383
384impl GenericParam {
385    pub fn span(&self) -> Span {
386        match &self.kind {
387            GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
388                self.ident.span
389            }
390            GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
391            GenericParamKind::Const { kw_span, default: Some(default), .. } => {
392                kw_span.to(default.value.span)
393            }
394            GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
395        }
396    }
397}
398
399/// Represents lifetime, type and const parameters attached to a declaration of
400/// a function, enum, trait, etc.
401#[derive(Clone, Encodable, Decodable, Debug, Default)]
402pub struct Generics {
403    pub params: ThinVec<GenericParam>,
404    pub where_clause: WhereClause,
405    pub span: Span,
406}
407
408/// A where-clause in a definition.
409#[derive(Clone, Encodable, Decodable, Debug, Default)]
410pub struct WhereClause {
411    /// `true` if we ate a `where` token.
412    ///
413    /// This can happen if we parsed no predicates, e.g., `struct Foo where {}`.
414    /// This allows us to pretty-print accurately and provide correct suggestion diagnostics.
415    pub has_where_token: bool,
416    pub predicates: ThinVec<WherePredicate>,
417    pub span: Span,
418}
419
420impl WhereClause {
421    pub fn is_empty(&self) -> bool {
422        !self.has_where_token && self.predicates.is_empty()
423    }
424}
425
426/// A single predicate in a where-clause.
427#[derive(Clone, Encodable, Decodable, Debug)]
428pub struct WherePredicate {
429    pub attrs: AttrVec,
430    pub kind: WherePredicateKind,
431    pub id: NodeId,
432    pub span: Span,
433    pub is_placeholder: bool,
434}
435
436/// Predicate kind in where-clause.
437#[derive(Clone, Encodable, Decodable, Debug)]
438pub enum WherePredicateKind {
439    /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
440    BoundPredicate(WhereBoundPredicate),
441    /// A lifetime predicate (e.g., `'a: 'b + 'c`).
442    RegionPredicate(WhereRegionPredicate),
443    /// An equality predicate (unsupported).
444    EqPredicate(WhereEqPredicate),
445}
446
447/// A type bound.
448///
449/// E.g., `for<'c> Foo: Send + Clone + 'c`.
450#[derive(Clone, Encodable, Decodable, Debug)]
451pub struct WhereBoundPredicate {
452    /// Any generics from a `for` binding.
453    pub bound_generic_params: ThinVec<GenericParam>,
454    /// The type being bounded.
455    pub bounded_ty: P<Ty>,
456    /// Trait and lifetime bounds (`Clone + Send + 'static`).
457    pub bounds: GenericBounds,
458}
459
460/// A lifetime predicate.
461///
462/// E.g., `'a: 'b + 'c`.
463#[derive(Clone, Encodable, Decodable, Debug)]
464pub struct WhereRegionPredicate {
465    pub lifetime: Lifetime,
466    pub bounds: GenericBounds,
467}
468
469/// An equality predicate (unsupported).
470///
471/// E.g., `T = int`.
472#[derive(Clone, Encodable, Decodable, Debug)]
473pub struct WhereEqPredicate {
474    pub lhs_ty: P<Ty>,
475    pub rhs_ty: P<Ty>,
476}
477
478#[derive(Clone, Encodable, Decodable, Debug)]
479pub struct Crate {
480    pub attrs: AttrVec,
481    pub items: ThinVec<P<Item>>,
482    pub spans: ModSpans,
483    /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
484    /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
485    pub id: NodeId,
486    pub is_placeholder: bool,
487}
488
489/// A semantic representation of a meta item. A meta item is a slightly
490/// restricted form of an attribute -- it can only contain expressions in
491/// certain leaf positions, rather than arbitrary token streams -- that is used
492/// for most built-in attributes.
493///
494/// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
495#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
496pub struct MetaItem {
497    pub unsafety: Safety,
498    pub path: Path,
499    pub kind: MetaItemKind,
500    pub span: Span,
501}
502
503/// The meta item kind, containing the data after the initial path.
504#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
505pub enum MetaItemKind {
506    /// Word meta item.
507    ///
508    /// E.g., `#[test]`, which lacks any arguments after `test`.
509    Word,
510
511    /// List meta item.
512    ///
513    /// E.g., `#[derive(..)]`, where the field represents the `..`.
514    List(ThinVec<MetaItemInner>),
515
516    /// Name value meta item.
517    ///
518    /// E.g., `#[feature = "foo"]`, where the field represents the `"foo"`.
519    NameValue(MetaItemLit),
520}
521
522/// Values inside meta item lists.
523///
524/// E.g., each of `Clone`, `Copy` in `#[derive(Clone, Copy)]`.
525#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
526pub enum MetaItemInner {
527    /// A full MetaItem, for recursive meta items.
528    MetaItem(MetaItem),
529
530    /// A literal.
531    ///
532    /// E.g., `"foo"`, `64`, `true`.
533    Lit(MetaItemLit),
534}
535
536/// A block (`{ .. }`).
537///
538/// E.g., `{ .. }` as in `fn foo() { .. }`.
539#[derive(Clone, Encodable, Decodable, Debug)]
540pub struct Block {
541    /// The statements in the block.
542    pub stmts: ThinVec<Stmt>,
543    pub id: NodeId,
544    /// Distinguishes between `unsafe { ... }` and `{ ... }`.
545    pub rules: BlockCheckMode,
546    pub span: Span,
547    pub tokens: Option<LazyAttrTokenStream>,
548    /// The following *isn't* a parse error, but will cause multiple errors in following stages.
549    /// ```compile_fail
550    /// let x = {
551    ///     foo: var
552    /// };
553    /// ```
554    /// #34255
555    pub could_be_bare_literal: bool,
556}
557
558/// A match pattern.
559///
560/// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
561#[derive(Clone, Encodable, Decodable, Debug)]
562pub struct Pat {
563    pub id: NodeId,
564    pub kind: PatKind,
565    pub span: Span,
566    pub tokens: Option<LazyAttrTokenStream>,
567}
568
569impl Pat {
570    /// Attempt reparsing the pattern as a type.
571    /// This is intended for use by diagnostics.
572    pub fn to_ty(&self) -> Option<P<Ty>> {
573        let kind = match &self.kind {
574            // In a type expression `_` is an inference variable.
575            PatKind::Wild => TyKind::Infer,
576            // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
577            PatKind::Ident(BindingMode::NONE, ident, None) => {
578                TyKind::Path(None, Path::from_ident(*ident))
579            }
580            PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
581            PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
582            // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
583            PatKind::Ref(pat, mutbl) => {
584                pat.to_ty().map(|ty| TyKind::Ref(None, MutTy { ty, mutbl: *mutbl }))?
585            }
586            // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
587            // when `P` can be reparsed as a type `T`.
588            PatKind::Slice(pats) if let [pat] = pats.as_slice() => {
589                pat.to_ty().map(TyKind::Slice)?
590            }
591            // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
592            // assuming `T0` to `Tn` are all syntactically valid as types.
593            PatKind::Tuple(pats) => {
594                let mut tys = ThinVec::with_capacity(pats.len());
595                // FIXME(#48994) - could just be collected into an Option<Vec>
596                for pat in pats {
597                    tys.push(pat.to_ty()?);
598                }
599                TyKind::Tup(tys)
600            }
601            _ => return None,
602        };
603
604        Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
605    }
606
607    /// Walk top-down and call `it` in each place where a pattern occurs
608    /// starting with the root pattern `walk` is called on. If `it` returns
609    /// false then we will descend no further but siblings will be processed.
610    pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
611        if !it(self) {
612            return;
613        }
614
615        match &self.kind {
616            // Walk into the pattern associated with `Ident` (if any).
617            PatKind::Ident(_, _, Some(p)) => p.walk(it),
618
619            // Walk into each field of struct.
620            PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
621
622            // Sequence of patterns.
623            PatKind::TupleStruct(_, _, s)
624            | PatKind::Tuple(s)
625            | PatKind::Slice(s)
626            | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
627
628            // Trivial wrappers over inner patterns.
629            PatKind::Box(s)
630            | PatKind::Deref(s)
631            | PatKind::Ref(s, _)
632            | PatKind::Paren(s)
633            | PatKind::Guard(s, _) => s.walk(it),
634
635            // These patterns do not contain subpatterns, skip.
636            PatKind::Wild
637            | PatKind::Rest
638            | PatKind::Never
639            | PatKind::Expr(_)
640            | PatKind::Range(..)
641            | PatKind::Ident(..)
642            | PatKind::Path(..)
643            | PatKind::MacCall(_)
644            | PatKind::Err(_) => {}
645        }
646    }
647
648    /// Is this a `..` pattern?
649    pub fn is_rest(&self) -> bool {
650        matches!(self.kind, PatKind::Rest)
651    }
652
653    /// Whether this could be a never pattern, taking into account that a macro invocation can
654    /// return a never pattern. Used to inform errors during parsing.
655    pub fn could_be_never_pattern(&self) -> bool {
656        let mut could_be_never_pattern = false;
657        self.walk(&mut |pat| match &pat.kind {
658            PatKind::Never | PatKind::MacCall(_) => {
659                could_be_never_pattern = true;
660                false
661            }
662            PatKind::Or(s) => {
663                could_be_never_pattern = s.iter().all(|p| p.could_be_never_pattern());
664                false
665            }
666            _ => true,
667        });
668        could_be_never_pattern
669    }
670
671    /// Whether this contains a `!` pattern. This in particular means that a feature gate error will
672    /// be raised if the feature is off. Used to avoid gating the feature twice.
673    pub fn contains_never_pattern(&self) -> bool {
674        let mut contains_never_pattern = false;
675        self.walk(&mut |pat| {
676            if matches!(pat.kind, PatKind::Never) {
677                contains_never_pattern = true;
678            }
679            true
680        });
681        contains_never_pattern
682    }
683
684    /// Return a name suitable for diagnostics.
685    pub fn descr(&self) -> Option<String> {
686        match &self.kind {
687            PatKind::Wild => Some("_".to_string()),
688            PatKind::Ident(BindingMode::NONE, ident, None) => Some(format!("{ident}")),
689            PatKind::Ref(pat, mutbl) => pat.descr().map(|d| format!("&{}{d}", mutbl.prefix_str())),
690            _ => None,
691        }
692    }
693}
694
695/// A single field in a struct pattern.
696///
697/// Patterns like the fields of `Foo { x, ref y, ref mut z }`
698/// are treated the same as `x: x, y: ref y, z: ref mut z`,
699/// except when `is_shorthand` is true.
700#[derive(Clone, Encodable, Decodable, Debug)]
701pub struct PatField {
702    /// The identifier for the field.
703    pub ident: Ident,
704    /// The pattern the field is destructured to.
705    pub pat: P<Pat>,
706    pub is_shorthand: bool,
707    pub attrs: AttrVec,
708    pub id: NodeId,
709    pub span: Span,
710    pub is_placeholder: bool,
711}
712
713#[derive(Clone, Copy, Debug, Eq, PartialEq)]
714#[derive(Encodable, Decodable, HashStable_Generic)]
715pub enum ByRef {
716    Yes(Mutability),
717    No,
718}
719
720impl ByRef {
721    #[must_use]
722    pub fn cap_ref_mutability(mut self, mutbl: Mutability) -> Self {
723        if let ByRef::Yes(old_mutbl) = &mut self {
724            *old_mutbl = cmp::min(*old_mutbl, mutbl);
725        }
726        self
727    }
728}
729
730/// The mode of a binding (`mut`, `ref mut`, etc).
731/// Used for both the explicit binding annotations given in the HIR for a binding
732/// and the final binding mode that we infer after type inference/match ergonomics.
733/// `.0` is the by-reference mode (`ref`, `ref mut`, or by value),
734/// `.1` is the mutability of the binding.
735#[derive(Clone, Copy, Debug, Eq, PartialEq)]
736#[derive(Encodable, Decodable, HashStable_Generic)]
737pub struct BindingMode(pub ByRef, pub Mutability);
738
739impl BindingMode {
740    pub const NONE: Self = Self(ByRef::No, Mutability::Not);
741    pub const REF: Self = Self(ByRef::Yes(Mutability::Not), Mutability::Not);
742    pub const MUT: Self = Self(ByRef::No, Mutability::Mut);
743    pub const REF_MUT: Self = Self(ByRef::Yes(Mutability::Mut), Mutability::Not);
744    pub const MUT_REF: Self = Self(ByRef::Yes(Mutability::Not), Mutability::Mut);
745    pub const MUT_REF_MUT: Self = Self(ByRef::Yes(Mutability::Mut), Mutability::Mut);
746
747    pub fn prefix_str(self) -> &'static str {
748        match self {
749            Self::NONE => "",
750            Self::REF => "ref ",
751            Self::MUT => "mut ",
752            Self::REF_MUT => "ref mut ",
753            Self::MUT_REF => "mut ref ",
754            Self::MUT_REF_MUT => "mut ref mut ",
755        }
756    }
757}
758
759#[derive(Clone, Encodable, Decodable, Debug)]
760pub enum RangeEnd {
761    /// `..=` or `...`
762    Included(RangeSyntax),
763    /// `..`
764    Excluded,
765}
766
767#[derive(Clone, Encodable, Decodable, Debug)]
768pub enum RangeSyntax {
769    /// `...`
770    DotDotDot,
771    /// `..=`
772    DotDotEq,
773}
774
775/// All the different flavors of pattern that Rust recognizes.
776//
777// Adding a new variant? Please update `test_pat` in `tests/ui/macros/stringify.rs`.
778#[derive(Clone, Encodable, Decodable, Debug)]
779pub enum PatKind {
780    /// Represents a wildcard pattern (`_`).
781    Wild,
782
783    /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
784    /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
785    /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
786    /// during name resolution.
787    Ident(BindingMode, Ident, Option<P<Pat>>),
788
789    /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
790    Struct(Option<P<QSelf>>, Path, ThinVec<PatField>, PatFieldsRest),
791
792    /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
793    TupleStruct(Option<P<QSelf>>, Path, ThinVec<P<Pat>>),
794
795    /// An or-pattern `A | B | C`.
796    /// Invariant: `pats.len() >= 2`.
797    Or(ThinVec<P<Pat>>),
798
799    /// A possibly qualified path pattern.
800    /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
801    /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
802    /// only legally refer to associated constants.
803    Path(Option<P<QSelf>>, Path),
804
805    /// A tuple pattern (`(a, b)`).
806    Tuple(ThinVec<P<Pat>>),
807
808    /// A `box` pattern.
809    Box(P<Pat>),
810
811    /// A `deref` pattern (currently `deref!()` macro-based syntax).
812    Deref(P<Pat>),
813
814    /// A reference pattern (e.g., `&mut (a, b)`).
815    Ref(P<Pat>, Mutability),
816
817    /// A literal, const block or path.
818    Expr(P<Expr>),
819
820    /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
821    Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
822
823    /// A slice pattern `[a, b, c]`.
824    Slice(ThinVec<P<Pat>>),
825
826    /// A rest pattern `..`.
827    ///
828    /// Syntactically it is valid anywhere.
829    ///
830    /// Semantically however, it only has meaning immediately inside:
831    /// - a slice pattern: `[a, .., b]`,
832    /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
833    /// - a tuple pattern: `(a, .., b)`,
834    /// - a tuple struct/variant pattern: `$path(a, .., b)`.
835    ///
836    /// In all of these cases, an additional restriction applies,
837    /// only one rest pattern may occur in the pattern sequences.
838    Rest,
839
840    // A never pattern `!`.
841    Never,
842
843    /// A guard pattern (e.g., `x if guard(x)`).
844    Guard(P<Pat>, P<Expr>),
845
846    /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
847    Paren(P<Pat>),
848
849    /// A macro pattern; pre-expansion.
850    MacCall(P<MacCall>),
851
852    /// Placeholder for a pattern that wasn't syntactically well formed in some way.
853    Err(ErrorGuaranteed),
854}
855
856/// Whether the `..` is present in a struct fields pattern.
857#[derive(Clone, Copy, Encodable, Decodable, Debug, PartialEq)]
858pub enum PatFieldsRest {
859    /// `module::StructName { field, ..}`
860    Rest,
861    /// `module::StructName { field, syntax error }`
862    Recovered(ErrorGuaranteed),
863    /// `module::StructName { field }`
864    None,
865}
866
867/// The kind of borrow in an `AddrOf` expression,
868/// e.g., `&place` or `&raw const place`.
869#[derive(Clone, Copy, PartialEq, Eq, Debug)]
870#[derive(Encodable, Decodable, HashStable_Generic)]
871pub enum BorrowKind {
872    /// A normal borrow, `&$expr` or `&mut $expr`.
873    /// The resulting type is either `&'a T` or `&'a mut T`
874    /// where `T = typeof($expr)` and `'a` is some lifetime.
875    Ref,
876    /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
877    /// The resulting type is either `*const T` or `*mut T`
878    /// where `T = typeof($expr)`.
879    Raw,
880}
881
882#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
883pub enum BinOpKind {
884    /// The `+` operator (addition)
885    Add,
886    /// The `-` operator (subtraction)
887    Sub,
888    /// The `*` operator (multiplication)
889    Mul,
890    /// The `/` operator (division)
891    Div,
892    /// The `%` operator (modulus)
893    Rem,
894    /// The `&&` operator (logical and)
895    And,
896    /// The `||` operator (logical or)
897    Or,
898    /// The `^` operator (bitwise xor)
899    BitXor,
900    /// The `&` operator (bitwise and)
901    BitAnd,
902    /// The `|` operator (bitwise or)
903    BitOr,
904    /// The `<<` operator (shift left)
905    Shl,
906    /// The `>>` operator (shift right)
907    Shr,
908    /// The `==` operator (equality)
909    Eq,
910    /// The `<` operator (less than)
911    Lt,
912    /// The `<=` operator (less than or equal to)
913    Le,
914    /// The `!=` operator (not equal to)
915    Ne,
916    /// The `>=` operator (greater than or equal to)
917    Ge,
918    /// The `>` operator (greater than)
919    Gt,
920}
921
922impl BinOpKind {
923    pub fn as_str(&self) -> &'static str {
924        use BinOpKind::*;
925        match self {
926            Add => "+",
927            Sub => "-",
928            Mul => "*",
929            Div => "/",
930            Rem => "%",
931            And => "&&",
932            Or => "||",
933            BitXor => "^",
934            BitAnd => "&",
935            BitOr => "|",
936            Shl => "<<",
937            Shr => ">>",
938            Eq => "==",
939            Lt => "<",
940            Le => "<=",
941            Ne => "!=",
942            Ge => ">=",
943            Gt => ">",
944        }
945    }
946
947    pub fn is_lazy(&self) -> bool {
948        matches!(self, BinOpKind::And | BinOpKind::Or)
949    }
950
951    pub fn precedence(&self) -> ExprPrecedence {
952        use BinOpKind::*;
953        match *self {
954            Mul | Div | Rem => ExprPrecedence::Product,
955            Add | Sub => ExprPrecedence::Sum,
956            Shl | Shr => ExprPrecedence::Shift,
957            BitAnd => ExprPrecedence::BitAnd,
958            BitXor => ExprPrecedence::BitXor,
959            BitOr => ExprPrecedence::BitOr,
960            Lt | Gt | Le | Ge | Eq | Ne => ExprPrecedence::Compare,
961            And => ExprPrecedence::LAnd,
962            Or => ExprPrecedence::LOr,
963        }
964    }
965
966    pub fn fixity(&self) -> Fixity {
967        use BinOpKind::*;
968        match self {
969            Eq | Ne | Lt | Le | Gt | Ge => Fixity::None,
970            Add | Sub | Mul | Div | Rem | And | Or | BitXor | BitAnd | BitOr | Shl | Shr => {
971                Fixity::Left
972            }
973        }
974    }
975
976    pub fn is_comparison(self) -> bool {
977        use BinOpKind::*;
978        match self {
979            Eq | Ne | Lt | Le | Gt | Ge => true,
980            Add | Sub | Mul | Div | Rem | And | Or | BitXor | BitAnd | BitOr | Shl | Shr => false,
981        }
982    }
983
984    /// Returns `true` if the binary operator takes its arguments by value.
985    pub fn is_by_value(self) -> bool {
986        !self.is_comparison()
987    }
988}
989
990pub type BinOp = Spanned<BinOpKind>;
991
992/// Unary operator.
993///
994/// Note that `&data` is not an operator, it's an `AddrOf` expression.
995#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
996pub enum UnOp {
997    /// The `*` operator for dereferencing
998    Deref,
999    /// The `!` operator for logical inversion
1000    Not,
1001    /// The `-` operator for negation
1002    Neg,
1003}
1004
1005impl UnOp {
1006    pub fn as_str(&self) -> &'static str {
1007        match self {
1008            UnOp::Deref => "*",
1009            UnOp::Not => "!",
1010            UnOp::Neg => "-",
1011        }
1012    }
1013
1014    /// Returns `true` if the unary operator takes its argument by value.
1015    pub fn is_by_value(self) -> bool {
1016        matches!(self, Self::Neg | Self::Not)
1017    }
1018}
1019
1020/// A statement. No `attrs` or `tokens` fields because each `StmtKind` variant
1021/// contains an AST node with those fields. (Except for `StmtKind::Empty`,
1022/// which never has attrs or tokens)
1023#[derive(Clone, Encodable, Decodable, Debug)]
1024pub struct Stmt {
1025    pub id: NodeId,
1026    pub kind: StmtKind,
1027    pub span: Span,
1028}
1029
1030impl Stmt {
1031    pub fn has_trailing_semicolon(&self) -> bool {
1032        match &self.kind {
1033            StmtKind::Semi(_) => true,
1034            StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
1035            _ => false,
1036        }
1037    }
1038
1039    /// Converts a parsed `Stmt` to a `Stmt` with
1040    /// a trailing semicolon.
1041    ///
1042    /// This only modifies the parsed AST struct, not the attached
1043    /// `LazyAttrTokenStream`. The parser is responsible for calling
1044    /// `ToAttrTokenStream::add_trailing_semi` when there is actually
1045    /// a semicolon in the tokenstream.
1046    pub fn add_trailing_semicolon(mut self) -> Self {
1047        self.kind = match self.kind {
1048            StmtKind::Expr(expr) => StmtKind::Semi(expr),
1049            StmtKind::MacCall(mac) => {
1050                StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
1051                    MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
1052                }))
1053            }
1054            kind => kind,
1055        };
1056
1057        self
1058    }
1059
1060    pub fn is_item(&self) -> bool {
1061        matches!(self.kind, StmtKind::Item(_))
1062    }
1063
1064    pub fn is_expr(&self) -> bool {
1065        matches!(self.kind, StmtKind::Expr(_))
1066    }
1067}
1068
1069// Adding a new variant? Please update `test_stmt` in `tests/ui/macros/stringify.rs`.
1070#[derive(Clone, Encodable, Decodable, Debug)]
1071pub enum StmtKind {
1072    /// A local (let) binding.
1073    Let(P<Local>),
1074    /// An item definition.
1075    Item(P<Item>),
1076    /// Expr without trailing semi-colon.
1077    Expr(P<Expr>),
1078    /// Expr with a trailing semi-colon.
1079    Semi(P<Expr>),
1080    /// Just a trailing semi-colon.
1081    Empty,
1082    /// Macro.
1083    MacCall(P<MacCallStmt>),
1084}
1085
1086#[derive(Clone, Encodable, Decodable, Debug)]
1087pub struct MacCallStmt {
1088    pub mac: P<MacCall>,
1089    pub style: MacStmtStyle,
1090    pub attrs: AttrVec,
1091    pub tokens: Option<LazyAttrTokenStream>,
1092}
1093
1094#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1095pub enum MacStmtStyle {
1096    /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1097    /// `foo!(...);`, `foo![...];`).
1098    Semicolon,
1099    /// The macro statement had braces (e.g., `foo! { ... }`).
1100    Braces,
1101    /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1102    /// `foo!(...)`). All of these will end up being converted into macro
1103    /// expressions.
1104    NoBraces,
1105}
1106
1107/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1108#[derive(Clone, Encodable, Decodable, Debug)]
1109pub struct Local {
1110    pub id: NodeId,
1111    pub pat: P<Pat>,
1112    pub ty: Option<P<Ty>>,
1113    pub kind: LocalKind,
1114    pub span: Span,
1115    pub colon_sp: Option<Span>,
1116    pub attrs: AttrVec,
1117    pub tokens: Option<LazyAttrTokenStream>,
1118}
1119
1120#[derive(Clone, Encodable, Decodable, Debug)]
1121pub enum LocalKind {
1122    /// Local declaration.
1123    /// Example: `let x;`
1124    Decl,
1125    /// Local declaration with an initializer.
1126    /// Example: `let x = y;`
1127    Init(P<Expr>),
1128    /// Local declaration with an initializer and an `else` clause.
1129    /// Example: `let Some(x) = y else { return };`
1130    InitElse(P<Expr>, P<Block>),
1131}
1132
1133impl LocalKind {
1134    pub fn init(&self) -> Option<&Expr> {
1135        match self {
1136            Self::Decl => None,
1137            Self::Init(i) | Self::InitElse(i, _) => Some(i),
1138        }
1139    }
1140
1141    pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1142        match self {
1143            Self::Decl => None,
1144            Self::Init(init) => Some((init, None)),
1145            Self::InitElse(init, els) => Some((init, Some(els))),
1146        }
1147    }
1148}
1149
1150/// An arm of a 'match'.
1151///
1152/// E.g., `0..=10 => { println!("match!") }` as in
1153///
1154/// ```
1155/// match 123 {
1156///     0..=10 => { println!("match!") },
1157///     _ => { println!("no match!") },
1158/// }
1159/// ```
1160#[derive(Clone, Encodable, Decodable, Debug)]
1161pub struct Arm {
1162    pub attrs: AttrVec,
1163    /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`.
1164    pub pat: P<Pat>,
1165    /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`.
1166    pub guard: Option<P<Expr>>,
1167    /// Match arm body. Omitted if the pattern is a never pattern.
1168    pub body: Option<P<Expr>>,
1169    pub span: Span,
1170    pub id: NodeId,
1171    pub is_placeholder: bool,
1172}
1173
1174/// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1175#[derive(Clone, Encodable, Decodable, Debug)]
1176pub struct ExprField {
1177    pub attrs: AttrVec,
1178    pub id: NodeId,
1179    pub span: Span,
1180    pub ident: Ident,
1181    pub expr: P<Expr>,
1182    pub is_shorthand: bool,
1183    pub is_placeholder: bool,
1184}
1185
1186#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1187pub enum BlockCheckMode {
1188    Default,
1189    Unsafe(UnsafeSource),
1190}
1191
1192#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1193pub enum UnsafeSource {
1194    CompilerGenerated,
1195    UserProvided,
1196}
1197
1198/// A constant (expression) that's not an item or associated item,
1199/// but needs its own `DefId` for type-checking, const-eval, etc.
1200/// These are usually found nested inside types (e.g., array lengths)
1201/// or expressions (e.g., repeat counts), and also used to define
1202/// explicit discriminant values for enum variants.
1203#[derive(Clone, Encodable, Decodable, Debug)]
1204pub struct AnonConst {
1205    pub id: NodeId,
1206    pub value: P<Expr>,
1207}
1208
1209/// An expression.
1210#[derive(Clone, Encodable, Decodable, Debug)]
1211pub struct Expr {
1212    pub id: NodeId,
1213    pub kind: ExprKind,
1214    pub span: Span,
1215    pub attrs: AttrVec,
1216    pub tokens: Option<LazyAttrTokenStream>,
1217}
1218
1219impl Expr {
1220    /// Check if this expression is potentially a trivial const arg, i.e., one that can _potentially_
1221    /// be represented without an anon const in the HIR.
1222    ///
1223    /// This will unwrap at most one block level (curly braces). After that, if the expression
1224    /// is a path, it mostly dispatches to [`Path::is_potential_trivial_const_arg`].
1225    /// See there for more info about `allow_mgca_arg`.
1226    ///
1227    /// The only additional thing to note is that when `allow_mgca_arg` is false, this function
1228    /// will only allow paths with no qself, before dispatching to the `Path` function of
1229    /// the same name.
1230    ///
1231    /// Does not ensure that the path resolves to a const param/item, the caller should check this.
1232    /// This also does not consider macros, so it's only correct after macro-expansion.
1233    pub fn is_potential_trivial_const_arg(&self, allow_mgca_arg: bool) -> bool {
1234        let this = self.maybe_unwrap_block();
1235        if allow_mgca_arg {
1236            matches!(this.kind, ExprKind::Path(..))
1237        } else {
1238            if let ExprKind::Path(None, path) = &this.kind
1239                && path.is_potential_trivial_const_arg(allow_mgca_arg)
1240            {
1241                true
1242            } else {
1243                false
1244            }
1245        }
1246    }
1247
1248    /// Returns an expression with (when possible) *one* outter brace removed
1249    pub fn maybe_unwrap_block(&self) -> &Expr {
1250        if let ExprKind::Block(block, None) = &self.kind
1251            && let [stmt] = block.stmts.as_slice()
1252            && let StmtKind::Expr(expr) = &stmt.kind
1253        {
1254            expr
1255        } else {
1256            self
1257        }
1258    }
1259
1260    /// Determines whether this expression is a macro call optionally wrapped in braces . If
1261    /// `already_stripped_block` is set then we do not attempt to peel off a layer of braces.
1262    ///
1263    /// Returns the [`NodeId`] of the macro call and whether a layer of braces has been peeled
1264    /// either before, or part of, this function.
1265    pub fn optionally_braced_mac_call(
1266        &self,
1267        already_stripped_block: bool,
1268    ) -> Option<(bool, NodeId)> {
1269        match &self.kind {
1270            ExprKind::Block(block, None)
1271                if let [stmt] = &*block.stmts
1272                    && !already_stripped_block =>
1273            {
1274                match &stmt.kind {
1275                    StmtKind::MacCall(_) => Some((true, stmt.id)),
1276                    StmtKind::Expr(expr) if let ExprKind::MacCall(_) = &expr.kind => {
1277                        Some((true, expr.id))
1278                    }
1279                    _ => None,
1280                }
1281            }
1282            ExprKind::MacCall(_) => Some((already_stripped_block, self.id)),
1283            _ => None,
1284        }
1285    }
1286
1287    pub fn to_bound(&self) -> Option<GenericBound> {
1288        match &self.kind {
1289            ExprKind::Path(None, path) => Some(GenericBound::Trait(PolyTraitRef::new(
1290                ThinVec::new(),
1291                path.clone(),
1292                TraitBoundModifiers::NONE,
1293                self.span,
1294            ))),
1295            _ => None,
1296        }
1297    }
1298
1299    pub fn peel_parens(&self) -> &Expr {
1300        let mut expr = self;
1301        while let ExprKind::Paren(inner) = &expr.kind {
1302            expr = inner;
1303        }
1304        expr
1305    }
1306
1307    pub fn peel_parens_and_refs(&self) -> &Expr {
1308        let mut expr = self;
1309        while let ExprKind::Paren(inner) | ExprKind::AddrOf(BorrowKind::Ref, _, inner) = &expr.kind
1310        {
1311            expr = inner;
1312        }
1313        expr
1314    }
1315
1316    /// Attempts to reparse as `Ty` (for diagnostic purposes).
1317    pub fn to_ty(&self) -> Option<P<Ty>> {
1318        let kind = match &self.kind {
1319            // Trivial conversions.
1320            ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1321            ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1322
1323            ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1324
1325            ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1326                expr.to_ty().map(|ty| TyKind::Ref(None, MutTy { ty, mutbl: *mutbl }))?
1327            }
1328
1329            ExprKind::Repeat(expr, expr_len) => {
1330                expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1331            }
1332
1333            ExprKind::Array(exprs) if let [expr] = exprs.as_slice() => {
1334                expr.to_ty().map(TyKind::Slice)?
1335            }
1336
1337            ExprKind::Tup(exprs) => {
1338                let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<ThinVec<_>>>()?;
1339                TyKind::Tup(tys)
1340            }
1341
1342            // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1343            // then type of result is trait object.
1344            // Otherwise we don't assume the result type.
1345            ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1346                if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1347                    TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1348                } else {
1349                    return None;
1350                }
1351            }
1352
1353            ExprKind::Underscore => TyKind::Infer,
1354
1355            // This expression doesn't look like a type syntactically.
1356            _ => return None,
1357        };
1358
1359        Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1360    }
1361
1362    pub fn precedence(&self) -> ExprPrecedence {
1363        match &self.kind {
1364            ExprKind::Closure(closure) => {
1365                match closure.fn_decl.output {
1366                    FnRetTy::Default(_) => ExprPrecedence::Jump,
1367                    FnRetTy::Ty(_) => ExprPrecedence::Unambiguous,
1368                }
1369            }
1370
1371            ExprKind::Break(..)
1372            | ExprKind::Ret(..)
1373            | ExprKind::Yield(..)
1374            | ExprKind::Yeet(..)
1375            | ExprKind::Become(..) => ExprPrecedence::Jump,
1376
1377            // `Range` claims to have higher precedence than `Assign`, but `x .. x = x` fails to
1378            // parse, instead of parsing as `(x .. x) = x`. Giving `Range` a lower precedence
1379            // ensures that `pprust` will add parentheses in the right places to get the desired
1380            // parse.
1381            ExprKind::Range(..) => ExprPrecedence::Range,
1382
1383            // Binop-like expr kinds, handled by `AssocOp`.
1384            ExprKind::Binary(op, ..) => op.node.precedence(),
1385            ExprKind::Cast(..) => ExprPrecedence::Cast,
1386
1387            ExprKind::Assign(..) |
1388            ExprKind::AssignOp(..) => ExprPrecedence::Assign,
1389
1390            // Unary, prefix
1391            ExprKind::AddrOf(..)
1392            // Here `let pats = expr` has `let pats =` as a "unary" prefix of `expr`.
1393            // However, this is not exactly right. When `let _ = a` is the LHS of a binop we
1394            // need parens sometimes. E.g. we can print `(let _ = a) && b` as `let _ = a && b`
1395            // but we need to print `(let _ = a) < b` as-is with parens.
1396            | ExprKind::Let(..)
1397            | ExprKind::Unary(..) => ExprPrecedence::Prefix,
1398
1399            // Never need parens
1400            ExprKind::Array(_)
1401            | ExprKind::Await(..)
1402            | ExprKind::Use(..)
1403            | ExprKind::Block(..)
1404            | ExprKind::Call(..)
1405            | ExprKind::ConstBlock(_)
1406            | ExprKind::Continue(..)
1407            | ExprKind::Field(..)
1408            | ExprKind::ForLoop { .. }
1409            | ExprKind::FormatArgs(..)
1410            | ExprKind::Gen(..)
1411            | ExprKind::If(..)
1412            | ExprKind::IncludedBytes(..)
1413            | ExprKind::Index(..)
1414            | ExprKind::InlineAsm(..)
1415            | ExprKind::Lit(_)
1416            | ExprKind::Loop(..)
1417            | ExprKind::MacCall(..)
1418            | ExprKind::Match(..)
1419            | ExprKind::MethodCall(..)
1420            | ExprKind::OffsetOf(..)
1421            | ExprKind::Paren(..)
1422            | ExprKind::Path(..)
1423            | ExprKind::Repeat(..)
1424            | ExprKind::Struct(..)
1425            | ExprKind::Try(..)
1426            | ExprKind::TryBlock(..)
1427            | ExprKind::Tup(_)
1428            | ExprKind::Type(..)
1429            | ExprKind::Underscore
1430            | ExprKind::UnsafeBinderCast(..)
1431            | ExprKind::While(..)
1432            | ExprKind::Err(_)
1433            | ExprKind::Dummy => ExprPrecedence::Unambiguous,
1434        }
1435    }
1436
1437    /// To a first-order approximation, is this a pattern?
1438    pub fn is_approximately_pattern(&self) -> bool {
1439        matches!(
1440            &self.peel_parens().kind,
1441            ExprKind::Array(_)
1442                | ExprKind::Call(_, _)
1443                | ExprKind::Tup(_)
1444                | ExprKind::Lit(_)
1445                | ExprKind::Range(_, _, _)
1446                | ExprKind::Underscore
1447                | ExprKind::Path(_, _)
1448                | ExprKind::Struct(_)
1449        )
1450    }
1451}
1452
1453#[derive(Clone, Encodable, Decodable, Debug)]
1454pub struct Closure {
1455    pub binder: ClosureBinder,
1456    pub capture_clause: CaptureBy,
1457    pub constness: Const,
1458    pub coroutine_kind: Option<CoroutineKind>,
1459    pub movability: Movability,
1460    pub fn_decl: P<FnDecl>,
1461    pub body: P<Expr>,
1462    /// The span of the declaration block: 'move |...| -> ...'
1463    pub fn_decl_span: Span,
1464    /// The span of the argument block `|...|`
1465    pub fn_arg_span: Span,
1466}
1467
1468/// Limit types of a range (inclusive or exclusive).
1469#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1470pub enum RangeLimits {
1471    /// Inclusive at the beginning, exclusive at the end.
1472    HalfOpen,
1473    /// Inclusive at the beginning and end.
1474    Closed,
1475}
1476
1477impl RangeLimits {
1478    pub fn as_str(&self) -> &'static str {
1479        match self {
1480            RangeLimits::HalfOpen => "..",
1481            RangeLimits::Closed => "..=",
1482        }
1483    }
1484}
1485
1486/// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1487#[derive(Clone, Encodable, Decodable, Debug)]
1488pub struct MethodCall {
1489    /// The method name and its generic arguments, e.g. `foo::<Bar, Baz>`.
1490    pub seg: PathSegment,
1491    /// The receiver, e.g. `x`.
1492    pub receiver: P<Expr>,
1493    /// The arguments, e.g. `a, b, c`.
1494    pub args: ThinVec<P<Expr>>,
1495    /// The span of the function, without the dot and receiver e.g. `foo::<Bar,
1496    /// Baz>(a, b, c)`.
1497    pub span: Span,
1498}
1499
1500#[derive(Clone, Encodable, Decodable, Debug)]
1501pub enum StructRest {
1502    /// `..x`.
1503    Base(P<Expr>),
1504    /// `..`.
1505    Rest(Span),
1506    /// No trailing `..` or expression.
1507    None,
1508}
1509
1510#[derive(Clone, Encodable, Decodable, Debug)]
1511pub struct StructExpr {
1512    pub qself: Option<P<QSelf>>,
1513    pub path: Path,
1514    pub fields: ThinVec<ExprField>,
1515    pub rest: StructRest,
1516}
1517
1518// Adding a new variant? Please update `test_expr` in `tests/ui/macros/stringify.rs`.
1519#[derive(Clone, Encodable, Decodable, Debug)]
1520pub enum ExprKind {
1521    /// An array (e.g, `[a, b, c, d]`).
1522    Array(ThinVec<P<Expr>>),
1523    /// Allow anonymous constants from an inline `const` block.
1524    ConstBlock(AnonConst),
1525    /// A function call.
1526    ///
1527    /// The first field resolves to the function itself,
1528    /// and the second field is the list of arguments.
1529    /// This also represents calling the constructor of
1530    /// tuple-like ADTs such as tuple structs and enum variants.
1531    Call(P<Expr>, ThinVec<P<Expr>>),
1532    /// A method call (e.g., `x.foo::<Bar, Baz>(a, b, c)`).
1533    MethodCall(Box<MethodCall>),
1534    /// A tuple (e.g., `(a, b, c, d)`).
1535    Tup(ThinVec<P<Expr>>),
1536    /// A binary operation (e.g., `a + b`, `a * b`).
1537    Binary(BinOp, P<Expr>, P<Expr>),
1538    /// A unary operation (e.g., `!x`, `*x`).
1539    Unary(UnOp, P<Expr>),
1540    /// A literal (e.g., `1`, `"foo"`).
1541    Lit(token::Lit),
1542    /// A cast (e.g., `foo as f64`).
1543    Cast(P<Expr>, P<Ty>),
1544    /// A type ascription (e.g., `builtin # type_ascribe(42, usize)`).
1545    ///
1546    /// Usually not written directly in user code but
1547    /// indirectly via the macro `type_ascribe!(...)`.
1548    Type(P<Expr>, P<Ty>),
1549    /// A `let pat = expr` expression that is only semantically allowed in the condition
1550    /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1551    ///
1552    /// `Span` represents the whole `let pat = expr` statement.
1553    Let(P<Pat>, P<Expr>, Span, Recovered),
1554    /// An `if` block, with an optional `else` block.
1555    ///
1556    /// `if expr { block } else { expr }`
1557    If(P<Expr>, P<Block>, Option<P<Expr>>),
1558    /// A while loop, with an optional label.
1559    ///
1560    /// `'label: while expr { block }`
1561    While(P<Expr>, P<Block>, Option<Label>),
1562    /// A `for` loop, with an optional label.
1563    ///
1564    /// `'label: for await? pat in iter { block }`
1565    ///
1566    /// This is desugared to a combination of `loop` and `match` expressions.
1567    ForLoop {
1568        pat: P<Pat>,
1569        iter: P<Expr>,
1570        body: P<Block>,
1571        label: Option<Label>,
1572        kind: ForLoopKind,
1573    },
1574    /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1575    ///
1576    /// `'label: loop { block }`
1577    Loop(P<Block>, Option<Label>, Span),
1578    /// A `match` block.
1579    Match(P<Expr>, ThinVec<Arm>, MatchKind),
1580    /// A closure (e.g., `move |a, b, c| a + b + c`).
1581    Closure(Box<Closure>),
1582    /// A block (`'label: { ... }`).
1583    Block(P<Block>, Option<Label>),
1584    /// An `async` block (`async move { ... }`),
1585    /// or a `gen` block (`gen move { ... }`).
1586    ///
1587    /// The span is the "decl", which is the header before the body `{ }`
1588    /// including the `asyng`/`gen` keywords and possibly `move`.
1589    Gen(CaptureBy, P<Block>, GenBlockKind, Span),
1590    /// An await expression (`my_future.await`). Span is of await keyword.
1591    Await(P<Expr>, Span),
1592    /// A use expression (`x.use`). Span is of use keyword.
1593    Use(P<Expr>, Span),
1594
1595    /// A try block (`try { ... }`).
1596    TryBlock(P<Block>),
1597
1598    /// An assignment (`a = foo()`).
1599    /// The `Span` argument is the span of the `=` token.
1600    Assign(P<Expr>, P<Expr>, Span),
1601    /// An assignment with an operator.
1602    ///
1603    /// E.g., `a += 1`.
1604    AssignOp(BinOp, P<Expr>, P<Expr>),
1605    /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1606    Field(P<Expr>, Ident),
1607    /// An indexing operation (e.g., `foo[2]`).
1608    /// The span represents the span of the `[2]`, including brackets.
1609    Index(P<Expr>, P<Expr>, Span),
1610    /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1611    Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1612    /// An underscore, used in destructuring assignment to ignore a value.
1613    Underscore,
1614
1615    /// Variable reference, possibly containing `::` and/or type
1616    /// parameters (e.g., `foo::bar::<baz>`).
1617    ///
1618    /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1619    Path(Option<P<QSelf>>, Path),
1620
1621    /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1622    AddrOf(BorrowKind, Mutability, P<Expr>),
1623    /// A `break`, with an optional label to break, and an optional expression.
1624    Break(Option<Label>, Option<P<Expr>>),
1625    /// A `continue`, with an optional label.
1626    Continue(Option<Label>),
1627    /// A `return`, with an optional value to be returned.
1628    Ret(Option<P<Expr>>),
1629
1630    /// Output of the `asm!()` macro.
1631    InlineAsm(P<InlineAsm>),
1632
1633    /// An `offset_of` expression (e.g., `builtin # offset_of(Struct, field)`).
1634    ///
1635    /// Usually not written directly in user code but
1636    /// indirectly via the macro `core::mem::offset_of!(...)`.
1637    OffsetOf(P<Ty>, P<[Ident]>),
1638
1639    /// A macro invocation; pre-expansion.
1640    MacCall(P<MacCall>),
1641
1642    /// A struct literal expression.
1643    ///
1644    /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1645    Struct(P<StructExpr>),
1646
1647    /// An array literal constructed from one repeated element.
1648    ///
1649    /// E.g., `[1; 5]`. The expression is the element to be
1650    /// repeated; the constant is the number of times to repeat it.
1651    Repeat(P<Expr>, AnonConst),
1652
1653    /// No-op: used solely so we can pretty-print faithfully.
1654    Paren(P<Expr>),
1655
1656    /// A try expression (`expr?`).
1657    Try(P<Expr>),
1658
1659    /// A `yield`, with an optional value to be yielded.
1660    Yield(YieldKind),
1661
1662    /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1663    /// with an optional value to be returned.
1664    Yeet(Option<P<Expr>>),
1665
1666    /// A tail call return, with the value to be returned.
1667    ///
1668    /// While `.0` must be a function call, we check this later, after parsing.
1669    Become(P<Expr>),
1670
1671    /// Bytes included via `include_bytes!`
1672    /// Added for optimization purposes to avoid the need to escape
1673    /// large binary blobs - should always behave like [`ExprKind::Lit`]
1674    /// with a `ByteStr` literal.
1675    IncludedBytes(Arc<[u8]>),
1676
1677    /// A `format_args!()` expression.
1678    FormatArgs(P<FormatArgs>),
1679
1680    UnsafeBinderCast(UnsafeBinderCastKind, P<Expr>, Option<P<Ty>>),
1681
1682    /// Placeholder for an expression that wasn't syntactically well formed in some way.
1683    Err(ErrorGuaranteed),
1684
1685    /// Acts as a null expression. Lowering it will always emit a bug.
1686    Dummy,
1687}
1688
1689/// Used to differentiate between `for` loops and `for await` loops.
1690#[derive(Clone, Copy, Encodable, Decodable, Debug, PartialEq, Eq)]
1691pub enum ForLoopKind {
1692    For,
1693    ForAwait,
1694}
1695
1696/// Used to differentiate between `async {}` blocks and `gen {}` blocks.
1697#[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq)]
1698pub enum GenBlockKind {
1699    Async,
1700    Gen,
1701    AsyncGen,
1702}
1703
1704impl fmt::Display for GenBlockKind {
1705    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1706        self.modifier().fmt(f)
1707    }
1708}
1709
1710impl GenBlockKind {
1711    pub fn modifier(&self) -> &'static str {
1712        match self {
1713            GenBlockKind::Async => "async",
1714            GenBlockKind::Gen => "gen",
1715            GenBlockKind::AsyncGen => "async gen",
1716        }
1717    }
1718}
1719
1720/// Whether we're unwrapping or wrapping an unsafe binder
1721#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1722#[derive(Encodable, Decodable, HashStable_Generic)]
1723pub enum UnsafeBinderCastKind {
1724    // e.g. `&i32` -> `unsafe<'a> &'a i32`
1725    Wrap,
1726    // e.g. `unsafe<'a> &'a i32` -> `&i32`
1727    Unwrap,
1728}
1729
1730/// The explicit `Self` type in a "qualified path". The actual
1731/// path, including the trait and the associated item, is stored
1732/// separately. `position` represents the index of the associated
1733/// item qualified with this `Self` type.
1734///
1735/// ```ignore (only-for-syntax-highlight)
1736/// <Vec<T> as a::b::Trait>::AssociatedItem
1737///  ^~~~~     ~~~~~~~~~~~~~~^
1738///  ty        position = 3
1739///
1740/// <Vec<T>>::AssociatedItem
1741///  ^~~~~    ^
1742///  ty       position = 0
1743/// ```
1744#[derive(Clone, Encodable, Decodable, Debug)]
1745pub struct QSelf {
1746    pub ty: P<Ty>,
1747
1748    /// The span of `a::b::Trait` in a path like `<Vec<T> as
1749    /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1750    /// 0`, this is an empty span.
1751    pub path_span: Span,
1752    pub position: usize,
1753}
1754
1755/// A capture clause used in closures and `async` blocks.
1756#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1757pub enum CaptureBy {
1758    /// `move |x| y + x`.
1759    Value {
1760        /// The span of the `move` keyword.
1761        move_kw: Span,
1762    },
1763    /// `move` or `use` keywords were not specified.
1764    Ref,
1765    /// `use |x| y + x`.
1766    ///
1767    /// Note that if you have a regular closure like `|| x.use`, this will *not* result
1768    /// in a `Use` capture. Instead, the `ExprUseVisitor` will look at the type
1769    /// of `x` and treat `x.use` as either a copy/clone/move as appropriate.
1770    Use {
1771        /// The span of the `use` keyword.
1772        use_kw: Span,
1773    },
1774}
1775
1776/// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1777#[derive(Clone, Encodable, Decodable, Debug)]
1778pub enum ClosureBinder {
1779    /// The binder is not present, all closure lifetimes are inferred.
1780    NotPresent,
1781    /// The binder is present.
1782    For {
1783        /// Span of the whole `for<>` clause
1784        ///
1785        /// ```text
1786        /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1787        /// ^^^^^^^^^^^ -- this
1788        /// ```
1789        span: Span,
1790
1791        /// Lifetimes in the `for<>` closure
1792        ///
1793        /// ```text
1794        /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1795        ///     ^^^^^^ -- this
1796        /// ```
1797        generic_params: ThinVec<GenericParam>,
1798    },
1799}
1800
1801/// Represents a macro invocation. The `path` indicates which macro
1802/// is being invoked, and the `args` are arguments passed to it.
1803#[derive(Clone, Encodable, Decodable, Debug)]
1804pub struct MacCall {
1805    pub path: Path,
1806    pub args: P<DelimArgs>,
1807}
1808
1809impl MacCall {
1810    pub fn span(&self) -> Span {
1811        self.path.span.to(self.args.dspan.entire())
1812    }
1813}
1814
1815/// Arguments passed to an attribute macro.
1816#[derive(Clone, Encodable, Decodable, Debug)]
1817pub enum AttrArgs {
1818    /// No arguments: `#[attr]`.
1819    Empty,
1820    /// Delimited arguments: `#[attr()/[]/{}]`.
1821    Delimited(DelimArgs),
1822    /// Arguments of a key-value attribute: `#[attr = "value"]`.
1823    Eq {
1824        /// Span of the `=` token.
1825        eq_span: Span,
1826        expr: P<Expr>,
1827    },
1828}
1829
1830impl AttrArgs {
1831    pub fn span(&self) -> Option<Span> {
1832        match self {
1833            AttrArgs::Empty => None,
1834            AttrArgs::Delimited(args) => Some(args.dspan.entire()),
1835            AttrArgs::Eq { eq_span, expr } => Some(eq_span.to(expr.span)),
1836        }
1837    }
1838
1839    /// Tokens inside the delimiters or after `=`.
1840    /// Proc macros see these tokens, for example.
1841    pub fn inner_tokens(&self) -> TokenStream {
1842        match self {
1843            AttrArgs::Empty => TokenStream::default(),
1844            AttrArgs::Delimited(args) => args.tokens.clone(),
1845            AttrArgs::Eq { expr, .. } => TokenStream::from_ast(expr),
1846        }
1847    }
1848}
1849
1850/// Delimited arguments, as used in `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1851#[derive(Clone, Encodable, Decodable, Debug)]
1852pub struct DelimArgs {
1853    pub dspan: DelimSpan,
1854    pub delim: Delimiter, // Note: `Delimiter::Invisible` never occurs
1855    pub tokens: TokenStream,
1856}
1857
1858impl DelimArgs {
1859    /// Whether a macro with these arguments needs a semicolon
1860    /// when used as a standalone item or statement.
1861    pub fn need_semicolon(&self) -> bool {
1862        !matches!(self, DelimArgs { delim: Delimiter::Brace, .. })
1863    }
1864}
1865
1866impl<CTX> HashStable<CTX> for DelimArgs
1867where
1868    CTX: crate::HashStableContext,
1869{
1870    fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1871        let DelimArgs { dspan, delim, tokens } = self;
1872        dspan.hash_stable(ctx, hasher);
1873        delim.hash_stable(ctx, hasher);
1874        tokens.hash_stable(ctx, hasher);
1875    }
1876}
1877
1878/// Represents a macro definition.
1879#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1880pub struct MacroDef {
1881    pub body: P<DelimArgs>,
1882    /// `true` if macro was defined with `macro_rules`.
1883    pub macro_rules: bool,
1884}
1885
1886#[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1887#[derive(HashStable_Generic)]
1888pub enum StrStyle {
1889    /// A regular string, like `"foo"`.
1890    Cooked,
1891    /// A raw string, like `r##"foo"##`.
1892    ///
1893    /// The value is the number of `#` symbols used.
1894    Raw(u8),
1895}
1896
1897/// The kind of match expression
1898#[derive(Clone, Copy, Encodable, Decodable, Debug, PartialEq)]
1899pub enum MatchKind {
1900    /// match expr { ... }
1901    Prefix,
1902    /// expr.match { ... }
1903    Postfix,
1904}
1905
1906/// The kind of yield expression
1907#[derive(Clone, Encodable, Decodable, Debug)]
1908pub enum YieldKind {
1909    /// yield expr { ... }
1910    Prefix(Option<P<Expr>>),
1911    /// expr.yield { ... }
1912    Postfix(P<Expr>),
1913}
1914
1915impl YieldKind {
1916    /// Returns the expression inside the yield expression, if any.
1917    ///
1918    /// For postfix yields, this is guaranteed to be `Some`.
1919    pub const fn expr(&self) -> Option<&P<Expr>> {
1920        match self {
1921            YieldKind::Prefix(expr) => expr.as_ref(),
1922            YieldKind::Postfix(expr) => Some(expr),
1923        }
1924    }
1925
1926    /// Returns a mutable reference to the expression being yielded, if any.
1927    pub const fn expr_mut(&mut self) -> Option<&mut P<Expr>> {
1928        match self {
1929            YieldKind::Prefix(expr) => expr.as_mut(),
1930            YieldKind::Postfix(expr) => Some(expr),
1931        }
1932    }
1933
1934    /// Returns true if both yields are prefix or both are postfix.
1935    pub const fn same_kind(&self, other: &Self) -> bool {
1936        match (self, other) {
1937            (YieldKind::Prefix(_), YieldKind::Prefix(_)) => true,
1938            (YieldKind::Postfix(_), YieldKind::Postfix(_)) => true,
1939            _ => false,
1940        }
1941    }
1942}
1943
1944/// A literal in a meta item.
1945#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1946pub struct MetaItemLit {
1947    /// The original literal as written in the source code.
1948    pub symbol: Symbol,
1949    /// The original suffix as written in the source code.
1950    pub suffix: Option<Symbol>,
1951    /// The "semantic" representation of the literal lowered from the original tokens.
1952    /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1953    pub kind: LitKind,
1954    pub span: Span,
1955}
1956
1957/// Similar to `MetaItemLit`, but restricted to string literals.
1958#[derive(Clone, Copy, Encodable, Decodable, Debug)]
1959pub struct StrLit {
1960    /// The original literal as written in source code.
1961    pub symbol: Symbol,
1962    /// The original suffix as written in source code.
1963    pub suffix: Option<Symbol>,
1964    /// The semantic (unescaped) representation of the literal.
1965    pub symbol_unescaped: Symbol,
1966    pub style: StrStyle,
1967    pub span: Span,
1968}
1969
1970impl StrLit {
1971    pub fn as_token_lit(&self) -> token::Lit {
1972        let token_kind = match self.style {
1973            StrStyle::Cooked => token::Str,
1974            StrStyle::Raw(n) => token::StrRaw(n),
1975        };
1976        token::Lit::new(token_kind, self.symbol, self.suffix)
1977    }
1978}
1979
1980/// Type of the integer literal based on provided suffix.
1981#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1982#[derive(HashStable_Generic)]
1983pub enum LitIntType {
1984    /// e.g. `42_i32`.
1985    Signed(IntTy),
1986    /// e.g. `42_u32`.
1987    Unsigned(UintTy),
1988    /// e.g. `42`.
1989    Unsuffixed,
1990}
1991
1992/// Type of the float literal based on provided suffix.
1993#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1994#[derive(HashStable_Generic)]
1995pub enum LitFloatType {
1996    /// A float literal with a suffix (`1f32` or `1E10f32`).
1997    Suffixed(FloatTy),
1998    /// A float literal without a suffix (`1.0 or 1.0E10`).
1999    Unsuffixed,
2000}
2001
2002/// This type is used within both `ast::MetaItemLit` and `hir::Lit`.
2003///
2004/// Note that the entire literal (including the suffix) is considered when
2005/// deciding the `LitKind`. This means that float literals like `1f32` are
2006/// classified by this type as `Float`. This is different to `token::LitKind`
2007/// which does *not* consider the suffix.
2008#[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
2009pub enum LitKind {
2010    /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
2011    /// from the original token's symbol.
2012    Str(Symbol, StrStyle),
2013    /// A byte string (`b"foo"`). Not stored as a symbol because it might be
2014    /// non-utf8, and symbols only allow utf8 strings.
2015    ByteStr(Arc<[u8]>, StrStyle),
2016    /// A C String (`c"foo"`). Guaranteed to only have `\0` at the end.
2017    CStr(Arc<[u8]>, StrStyle),
2018    /// A byte char (`b'f'`).
2019    Byte(u8),
2020    /// A character literal (`'a'`).
2021    Char(char),
2022    /// An integer literal (`1`).
2023    Int(Pu128, LitIntType),
2024    /// A float literal (`1.0`, `1f64` or `1E10f64`). The pre-suffix part is
2025    /// stored as a symbol rather than `f64` so that `LitKind` can impl `Eq`
2026    /// and `Hash`.
2027    Float(Symbol, LitFloatType),
2028    /// A boolean literal (`true`, `false`).
2029    Bool(bool),
2030    /// Placeholder for a literal that wasn't well-formed in some way.
2031    Err(ErrorGuaranteed),
2032}
2033
2034impl LitKind {
2035    pub fn str(&self) -> Option<Symbol> {
2036        match *self {
2037            LitKind::Str(s, _) => Some(s),
2038            _ => None,
2039        }
2040    }
2041
2042    /// Returns `true` if this literal is a string.
2043    pub fn is_str(&self) -> bool {
2044        matches!(self, LitKind::Str(..))
2045    }
2046
2047    /// Returns `true` if this literal is byte literal string.
2048    pub fn is_bytestr(&self) -> bool {
2049        matches!(self, LitKind::ByteStr(..))
2050    }
2051
2052    /// Returns `true` if this is a numeric literal.
2053    pub fn is_numeric(&self) -> bool {
2054        matches!(self, LitKind::Int(..) | LitKind::Float(..))
2055    }
2056
2057    /// Returns `true` if this literal has no suffix.
2058    /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
2059    pub fn is_unsuffixed(&self) -> bool {
2060        !self.is_suffixed()
2061    }
2062
2063    /// Returns `true` if this literal has a suffix.
2064    pub fn is_suffixed(&self) -> bool {
2065        match *self {
2066            // suffixed variants
2067            LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
2068            | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
2069            // unsuffixed variants
2070            LitKind::Str(..)
2071            | LitKind::ByteStr(..)
2072            | LitKind::CStr(..)
2073            | LitKind::Byte(..)
2074            | LitKind::Char(..)
2075            | LitKind::Int(_, LitIntType::Unsuffixed)
2076            | LitKind::Float(_, LitFloatType::Unsuffixed)
2077            | LitKind::Bool(..)
2078            | LitKind::Err(_) => false,
2079        }
2080    }
2081}
2082
2083// N.B., If you change this, you'll probably want to change the corresponding
2084// type structure in `middle/ty.rs` as well.
2085#[derive(Clone, Encodable, Decodable, Debug)]
2086pub struct MutTy {
2087    pub ty: P<Ty>,
2088    pub mutbl: Mutability,
2089}
2090
2091/// Represents a function's signature in a trait declaration,
2092/// trait implementation, or free function.
2093#[derive(Clone, Encodable, Decodable, Debug)]
2094pub struct FnSig {
2095    pub header: FnHeader,
2096    pub decl: P<FnDecl>,
2097    pub span: Span,
2098}
2099
2100#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2101#[derive(Encodable, Decodable, HashStable_Generic)]
2102pub enum FloatTy {
2103    F16,
2104    F32,
2105    F64,
2106    F128,
2107}
2108
2109impl FloatTy {
2110    pub fn name_str(self) -> &'static str {
2111        match self {
2112            FloatTy::F16 => "f16",
2113            FloatTy::F32 => "f32",
2114            FloatTy::F64 => "f64",
2115            FloatTy::F128 => "f128",
2116        }
2117    }
2118
2119    pub fn name(self) -> Symbol {
2120        match self {
2121            FloatTy::F16 => sym::f16,
2122            FloatTy::F32 => sym::f32,
2123            FloatTy::F64 => sym::f64,
2124            FloatTy::F128 => sym::f128,
2125        }
2126    }
2127}
2128
2129#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2130#[derive(Encodable, Decodable, HashStable_Generic)]
2131pub enum IntTy {
2132    Isize,
2133    I8,
2134    I16,
2135    I32,
2136    I64,
2137    I128,
2138}
2139
2140impl IntTy {
2141    pub fn name_str(&self) -> &'static str {
2142        match *self {
2143            IntTy::Isize => "isize",
2144            IntTy::I8 => "i8",
2145            IntTy::I16 => "i16",
2146            IntTy::I32 => "i32",
2147            IntTy::I64 => "i64",
2148            IntTy::I128 => "i128",
2149        }
2150    }
2151
2152    pub fn name(&self) -> Symbol {
2153        match *self {
2154            IntTy::Isize => sym::isize,
2155            IntTy::I8 => sym::i8,
2156            IntTy::I16 => sym::i16,
2157            IntTy::I32 => sym::i32,
2158            IntTy::I64 => sym::i64,
2159            IntTy::I128 => sym::i128,
2160        }
2161    }
2162}
2163
2164#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
2165#[derive(Encodable, Decodable, HashStable_Generic)]
2166pub enum UintTy {
2167    Usize,
2168    U8,
2169    U16,
2170    U32,
2171    U64,
2172    U128,
2173}
2174
2175impl UintTy {
2176    pub fn name_str(&self) -> &'static str {
2177        match *self {
2178            UintTy::Usize => "usize",
2179            UintTy::U8 => "u8",
2180            UintTy::U16 => "u16",
2181            UintTy::U32 => "u32",
2182            UintTy::U64 => "u64",
2183            UintTy::U128 => "u128",
2184        }
2185    }
2186
2187    pub fn name(&self) -> Symbol {
2188        match *self {
2189            UintTy::Usize => sym::usize,
2190            UintTy::U8 => sym::u8,
2191            UintTy::U16 => sym::u16,
2192            UintTy::U32 => sym::u32,
2193            UintTy::U64 => sym::u64,
2194            UintTy::U128 => sym::u128,
2195        }
2196    }
2197}
2198
2199/// A constraint on an associated item.
2200///
2201/// ### Examples
2202///
2203/// * the `A = Ty` and `B = Ty` in `Trait<A = Ty, B = Ty>`
2204/// * the `G<Ty> = Ty` in `Trait<G<Ty> = Ty>`
2205/// * the `A: Bound` in `Trait<A: Bound>`
2206/// * the `RetTy` in `Trait(ArgTy, ArgTy) -> RetTy`
2207/// * the `C = { Ct }` in `Trait<C = { Ct }>` (feature `associated_const_equality`)
2208/// * the `f(..): Bound` in `Trait<f(..): Bound>` (feature `return_type_notation`)
2209#[derive(Clone, Encodable, Decodable, Debug)]
2210pub struct AssocItemConstraint {
2211    pub id: NodeId,
2212    pub ident: Ident,
2213    pub gen_args: Option<GenericArgs>,
2214    pub kind: AssocItemConstraintKind,
2215    pub span: Span,
2216}
2217
2218#[derive(Clone, Encodable, Decodable, Debug)]
2219pub enum Term {
2220    Ty(P<Ty>),
2221    Const(AnonConst),
2222}
2223
2224impl From<P<Ty>> for Term {
2225    fn from(v: P<Ty>) -> Self {
2226        Term::Ty(v)
2227    }
2228}
2229
2230impl From<AnonConst> for Term {
2231    fn from(v: AnonConst) -> Self {
2232        Term::Const(v)
2233    }
2234}
2235
2236/// The kind of [associated item constraint][AssocItemConstraint].
2237#[derive(Clone, Encodable, Decodable, Debug)]
2238pub enum AssocItemConstraintKind {
2239    /// An equality constraint for an associated item (e.g., `AssocTy = Ty` in `Trait<AssocTy = Ty>`).
2240    ///
2241    /// Also known as an *associated item binding* (we *bind* an associated item to a term).
2242    ///
2243    /// Furthermore, associated type equality constraints can also be referred to as *associated type
2244    /// bindings*. Similarly with associated const equality constraints and *associated const bindings*.
2245    Equality { term: Term },
2246    /// A bound on an associated type (e.g., `AssocTy: Bound` in `Trait<AssocTy: Bound>`).
2247    Bound { bounds: GenericBounds },
2248}
2249
2250#[derive(Encodable, Decodable, Debug)]
2251pub struct Ty {
2252    pub id: NodeId,
2253    pub kind: TyKind,
2254    pub span: Span,
2255    pub tokens: Option<LazyAttrTokenStream>,
2256}
2257
2258impl Clone for Ty {
2259    fn clone(&self) -> Self {
2260        ensure_sufficient_stack(|| Self {
2261            id: self.id,
2262            kind: self.kind.clone(),
2263            span: self.span,
2264            tokens: self.tokens.clone(),
2265        })
2266    }
2267}
2268
2269impl Ty {
2270    pub fn peel_refs(&self) -> &Self {
2271        let mut final_ty = self;
2272        while let TyKind::Ref(_, MutTy { ty, .. }) | TyKind::Ptr(MutTy { ty, .. }) = &final_ty.kind
2273        {
2274            final_ty = ty;
2275        }
2276        final_ty
2277    }
2278
2279    pub fn is_maybe_parenthesised_infer(&self) -> bool {
2280        match &self.kind {
2281            TyKind::Infer => true,
2282            TyKind::Paren(inner) => inner.ast_deref().is_maybe_parenthesised_infer(),
2283            _ => false,
2284        }
2285    }
2286}
2287
2288#[derive(Clone, Encodable, Decodable, Debug)]
2289pub struct BareFnTy {
2290    pub safety: Safety,
2291    pub ext: Extern,
2292    pub generic_params: ThinVec<GenericParam>,
2293    pub decl: P<FnDecl>,
2294    /// Span of the `[unsafe] [extern] fn(...) -> ...` part, i.e. everything
2295    /// after the generic params (if there are any, e.g. `for<'a>`).
2296    pub decl_span: Span,
2297}
2298
2299#[derive(Clone, Encodable, Decodable, Debug)]
2300pub struct UnsafeBinderTy {
2301    pub generic_params: ThinVec<GenericParam>,
2302    pub inner_ty: P<Ty>,
2303}
2304
2305/// The various kinds of type recognized by the compiler.
2306//
2307// Adding a new variant? Please update `test_ty` in `tests/ui/macros/stringify.rs`.
2308#[derive(Clone, Encodable, Decodable, Debug)]
2309pub enum TyKind {
2310    /// A variable-length slice (`[T]`).
2311    Slice(P<Ty>),
2312    /// A fixed length array (`[T; n]`).
2313    Array(P<Ty>, AnonConst),
2314    /// A raw pointer (`*const T` or `*mut T`).
2315    Ptr(MutTy),
2316    /// A reference (`&'a T` or `&'a mut T`).
2317    Ref(Option<Lifetime>, MutTy),
2318    /// A pinned reference (`&'a pin const T` or `&'a pin mut T`).
2319    ///
2320    /// Desugars into `Pin<&'a T>` or `Pin<&'a mut T>`.
2321    PinnedRef(Option<Lifetime>, MutTy),
2322    /// A bare function (e.g., `fn(usize) -> bool`).
2323    BareFn(P<BareFnTy>),
2324    /// An unsafe existential lifetime binder (e.g., `unsafe<'a> &'a ()`).
2325    UnsafeBinder(P<UnsafeBinderTy>),
2326    /// The never type (`!`).
2327    Never,
2328    /// A tuple (`(A, B, C, D,...)`).
2329    Tup(ThinVec<P<Ty>>),
2330    /// A path (`module::module::...::Type`), optionally
2331    /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2332    ///
2333    /// Type parameters are stored in the `Path` itself.
2334    Path(Option<P<QSelf>>, Path),
2335    /// A trait object type `Bound1 + Bound2 + Bound3`
2336    /// where `Bound` is a trait or a lifetime.
2337    TraitObject(GenericBounds, TraitObjectSyntax),
2338    /// An `impl Bound1 + Bound2 + Bound3` type
2339    /// where `Bound` is a trait or a lifetime.
2340    ///
2341    /// The `NodeId` exists to prevent lowering from having to
2342    /// generate `NodeId`s on the fly, which would complicate
2343    /// the generation of opaque `type Foo = impl Trait` items significantly.
2344    ImplTrait(NodeId, GenericBounds),
2345    /// No-op; kept solely so that we can pretty-print faithfully.
2346    Paren(P<Ty>),
2347    /// Unused for now.
2348    Typeof(AnonConst),
2349    /// This means the type should be inferred instead of it having been
2350    /// specified. This can appear anywhere in a type.
2351    Infer,
2352    /// Inferred type of a `self` or `&self` argument in a method.
2353    ImplicitSelf,
2354    /// A macro in the type position.
2355    MacCall(P<MacCall>),
2356    /// Placeholder for a `va_list`.
2357    CVarArgs,
2358    /// Pattern types like `pattern_type!(u32 is 1..=)`, which is the same as `NonZero<u32>`,
2359    /// just as part of the type system.
2360    Pat(P<Ty>, P<TyPat>),
2361    /// Sometimes we need a dummy value when no error has occurred.
2362    Dummy,
2363    /// Placeholder for a kind that has failed to be defined.
2364    Err(ErrorGuaranteed),
2365}
2366
2367impl TyKind {
2368    pub fn is_implicit_self(&self) -> bool {
2369        matches!(self, TyKind::ImplicitSelf)
2370    }
2371
2372    pub fn is_unit(&self) -> bool {
2373        matches!(self, TyKind::Tup(tys) if tys.is_empty())
2374    }
2375
2376    pub fn is_simple_path(&self) -> Option<Symbol> {
2377        if let TyKind::Path(None, Path { segments, .. }) = &self
2378            && let [segment] = &segments[..]
2379            && segment.args.is_none()
2380        {
2381            Some(segment.ident.name)
2382        } else {
2383            None
2384        }
2385    }
2386}
2387
2388/// A pattern type pattern.
2389#[derive(Clone, Encodable, Decodable, Debug)]
2390pub struct TyPat {
2391    pub id: NodeId,
2392    pub kind: TyPatKind,
2393    pub span: Span,
2394    pub tokens: Option<LazyAttrTokenStream>,
2395}
2396
2397/// All the different flavors of pattern that Rust recognizes.
2398//
2399// Adding a new variant? Please update `test_pat` in `tests/ui/macros/stringify.rs`.
2400#[derive(Clone, Encodable, Decodable, Debug)]
2401pub enum TyPatKind {
2402    /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
2403    Range(Option<P<AnonConst>>, Option<P<AnonConst>>, Spanned<RangeEnd>),
2404
2405    /// Placeholder for a pattern that wasn't syntactically well formed in some way.
2406    Err(ErrorGuaranteed),
2407}
2408
2409/// Syntax used to declare a trait object.
2410#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2411#[repr(u8)]
2412pub enum TraitObjectSyntax {
2413    // SAFETY: When adding new variants make sure to update the `Tag` impl.
2414    Dyn = 0,
2415    DynStar = 1,
2416    None = 2,
2417}
2418
2419/// SAFETY: `TraitObjectSyntax` only has 3 data-less variants which means
2420/// it can be represented with a `u2`. We use `repr(u8)` to guarantee the
2421/// discriminants of the variants are no greater than `3`.
2422unsafe impl Tag for TraitObjectSyntax {
2423    const BITS: u32 = 2;
2424
2425    fn into_usize(self) -> usize {
2426        self as u8 as usize
2427    }
2428
2429    unsafe fn from_usize(tag: usize) -> Self {
2430        match tag {
2431            0 => TraitObjectSyntax::Dyn,
2432            1 => TraitObjectSyntax::DynStar,
2433            2 => TraitObjectSyntax::None,
2434            _ => unreachable!(),
2435        }
2436    }
2437}
2438
2439#[derive(Clone, Encodable, Decodable, Debug)]
2440pub enum PreciseCapturingArg {
2441    /// Lifetime parameter.
2442    Lifetime(Lifetime),
2443    /// Type or const parameter.
2444    Arg(Path, NodeId),
2445}
2446
2447/// Inline assembly operand explicit register or register class.
2448///
2449/// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2450#[derive(Clone, Copy, Encodable, Decodable, Debug)]
2451pub enum InlineAsmRegOrRegClass {
2452    Reg(Symbol),
2453    RegClass(Symbol),
2454}
2455
2456#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)]
2457pub struct InlineAsmOptions(u16);
2458bitflags::bitflags! {
2459    impl InlineAsmOptions: u16 {
2460        const PURE            = 1 << 0;
2461        const NOMEM           = 1 << 1;
2462        const READONLY        = 1 << 2;
2463        const PRESERVES_FLAGS = 1 << 3;
2464        const NORETURN        = 1 << 4;
2465        const NOSTACK         = 1 << 5;
2466        const ATT_SYNTAX      = 1 << 6;
2467        const RAW             = 1 << 7;
2468        const MAY_UNWIND      = 1 << 8;
2469    }
2470}
2471
2472impl InlineAsmOptions {
2473    pub const COUNT: usize = Self::all().bits().count_ones() as usize;
2474
2475    pub const GLOBAL_OPTIONS: Self = Self::ATT_SYNTAX.union(Self::RAW);
2476    pub const NAKED_OPTIONS: Self = Self::ATT_SYNTAX.union(Self::RAW);
2477
2478    pub fn human_readable_names(&self) -> Vec<&'static str> {
2479        let mut options = vec![];
2480
2481        if self.contains(InlineAsmOptions::PURE) {
2482            options.push("pure");
2483        }
2484        if self.contains(InlineAsmOptions::NOMEM) {
2485            options.push("nomem");
2486        }
2487        if self.contains(InlineAsmOptions::READONLY) {
2488            options.push("readonly");
2489        }
2490        if self.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2491            options.push("preserves_flags");
2492        }
2493        if self.contains(InlineAsmOptions::NORETURN) {
2494            options.push("noreturn");
2495        }
2496        if self.contains(InlineAsmOptions::NOSTACK) {
2497            options.push("nostack");
2498        }
2499        if self.contains(InlineAsmOptions::ATT_SYNTAX) {
2500            options.push("att_syntax");
2501        }
2502        if self.contains(InlineAsmOptions::RAW) {
2503            options.push("raw");
2504        }
2505        if self.contains(InlineAsmOptions::MAY_UNWIND) {
2506            options.push("may_unwind");
2507        }
2508
2509        options
2510    }
2511}
2512
2513impl std::fmt::Debug for InlineAsmOptions {
2514    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2515        bitflags::parser::to_writer(self, f)
2516    }
2517}
2518
2519#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2520pub enum InlineAsmTemplatePiece {
2521    String(Cow<'static, str>),
2522    Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2523}
2524
2525impl fmt::Display for InlineAsmTemplatePiece {
2526    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2527        match self {
2528            Self::String(s) => {
2529                for c in s.chars() {
2530                    match c {
2531                        '{' => f.write_str("{{")?,
2532                        '}' => f.write_str("}}")?,
2533                        _ => c.fmt(f)?,
2534                    }
2535                }
2536                Ok(())
2537            }
2538            Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2539                write!(f, "{{{operand_idx}:{modifier}}}")
2540            }
2541            Self::Placeholder { operand_idx, modifier: None, .. } => {
2542                write!(f, "{{{operand_idx}}}")
2543            }
2544        }
2545    }
2546}
2547
2548impl InlineAsmTemplatePiece {
2549    /// Rebuilds the asm template string from its pieces.
2550    pub fn to_string(s: &[Self]) -> String {
2551        use fmt::Write;
2552        let mut out = String::new();
2553        for p in s.iter() {
2554            let _ = write!(out, "{p}");
2555        }
2556        out
2557    }
2558}
2559
2560/// Inline assembly symbol operands get their own AST node that is somewhat
2561/// similar to `AnonConst`.
2562///
2563/// The main difference is that we specifically don't assign it `DefId` in
2564/// `DefCollector`. Instead this is deferred until AST lowering where we
2565/// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2566/// depending on what the path resolves to.
2567#[derive(Clone, Encodable, Decodable, Debug)]
2568pub struct InlineAsmSym {
2569    pub id: NodeId,
2570    pub qself: Option<P<QSelf>>,
2571    pub path: Path,
2572}
2573
2574/// Inline assembly operand.
2575///
2576/// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2577#[derive(Clone, Encodable, Decodable, Debug)]
2578pub enum InlineAsmOperand {
2579    In {
2580        reg: InlineAsmRegOrRegClass,
2581        expr: P<Expr>,
2582    },
2583    Out {
2584        reg: InlineAsmRegOrRegClass,
2585        late: bool,
2586        expr: Option<P<Expr>>,
2587    },
2588    InOut {
2589        reg: InlineAsmRegOrRegClass,
2590        late: bool,
2591        expr: P<Expr>,
2592    },
2593    SplitInOut {
2594        reg: InlineAsmRegOrRegClass,
2595        late: bool,
2596        in_expr: P<Expr>,
2597        out_expr: Option<P<Expr>>,
2598    },
2599    Const {
2600        anon_const: AnonConst,
2601    },
2602    Sym {
2603        sym: InlineAsmSym,
2604    },
2605    Label {
2606        block: P<Block>,
2607    },
2608}
2609
2610impl InlineAsmOperand {
2611    pub fn reg(&self) -> Option<&InlineAsmRegOrRegClass> {
2612        match self {
2613            Self::In { reg, .. }
2614            | Self::Out { reg, .. }
2615            | Self::InOut { reg, .. }
2616            | Self::SplitInOut { reg, .. } => Some(reg),
2617            Self::Const { .. } | Self::Sym { .. } | Self::Label { .. } => None,
2618        }
2619    }
2620}
2621
2622#[derive(Clone, Copy, Encodable, Decodable, Debug, HashStable_Generic)]
2623pub enum AsmMacro {
2624    /// The `asm!` macro
2625    Asm,
2626    /// The `global_asm!` macro
2627    GlobalAsm,
2628    /// The `naked_asm!` macro
2629    NakedAsm,
2630}
2631
2632impl AsmMacro {
2633    pub const fn macro_name(self) -> &'static str {
2634        match self {
2635            AsmMacro::Asm => "asm",
2636            AsmMacro::GlobalAsm => "global_asm",
2637            AsmMacro::NakedAsm => "naked_asm",
2638        }
2639    }
2640
2641    pub const fn is_supported_option(self, option: InlineAsmOptions) -> bool {
2642        match self {
2643            AsmMacro::Asm => true,
2644            AsmMacro::GlobalAsm => InlineAsmOptions::GLOBAL_OPTIONS.contains(option),
2645            AsmMacro::NakedAsm => InlineAsmOptions::NAKED_OPTIONS.contains(option),
2646        }
2647    }
2648
2649    pub const fn diverges(self, options: InlineAsmOptions) -> bool {
2650        match self {
2651            AsmMacro::Asm => options.contains(InlineAsmOptions::NORETURN),
2652            AsmMacro::GlobalAsm => true,
2653            AsmMacro::NakedAsm => true,
2654        }
2655    }
2656}
2657
2658/// Inline assembly.
2659///
2660/// E.g., `asm!("NOP");`.
2661#[derive(Clone, Encodable, Decodable, Debug)]
2662pub struct InlineAsm {
2663    pub asm_macro: AsmMacro,
2664    pub template: Vec<InlineAsmTemplatePiece>,
2665    pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2666    pub operands: Vec<(InlineAsmOperand, Span)>,
2667    pub clobber_abis: Vec<(Symbol, Span)>,
2668    pub options: InlineAsmOptions,
2669    pub line_spans: Vec<Span>,
2670}
2671
2672/// A parameter in a function header.
2673///
2674/// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2675#[derive(Clone, Encodable, Decodable, Debug)]
2676pub struct Param {
2677    pub attrs: AttrVec,
2678    pub ty: P<Ty>,
2679    pub pat: P<Pat>,
2680    pub id: NodeId,
2681    pub span: Span,
2682    pub is_placeholder: bool,
2683}
2684
2685/// Alternative representation for `Arg`s describing `self` parameter of methods.
2686///
2687/// E.g., `&mut self` as in `fn foo(&mut self)`.
2688#[derive(Clone, Encodable, Decodable, Debug)]
2689pub enum SelfKind {
2690    /// `self`, `mut self`
2691    Value(Mutability),
2692    /// `&'lt self`, `&'lt mut self`
2693    Region(Option<Lifetime>, Mutability),
2694    /// `&'lt pin const self`, `&'lt pin mut self`
2695    Pinned(Option<Lifetime>, Mutability),
2696    /// `self: TYPE`, `mut self: TYPE`
2697    Explicit(P<Ty>, Mutability),
2698}
2699
2700impl SelfKind {
2701    pub fn to_ref_suggestion(&self) -> String {
2702        match self {
2703            SelfKind::Region(None, mutbl) => mutbl.ref_prefix_str().to_string(),
2704            SelfKind::Region(Some(lt), mutbl) => format!("&{lt} {}", mutbl.prefix_str()),
2705            SelfKind::Pinned(None, mutbl) => format!("&pin {}", mutbl.ptr_str()),
2706            SelfKind::Pinned(Some(lt), mutbl) => format!("&{lt} pin {}", mutbl.ptr_str()),
2707            SelfKind::Value(_) | SelfKind::Explicit(_, _) => {
2708                unreachable!("if we had an explicit self, we wouldn't be here")
2709            }
2710        }
2711    }
2712}
2713
2714pub type ExplicitSelf = Spanned<SelfKind>;
2715
2716impl Param {
2717    /// Attempts to cast parameter to `ExplicitSelf`.
2718    pub fn to_self(&self) -> Option<ExplicitSelf> {
2719        if let PatKind::Ident(BindingMode(ByRef::No, mutbl), ident, _) = self.pat.kind {
2720            if ident.name == kw::SelfLower {
2721                return match self.ty.kind {
2722                    TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2723                    TyKind::Ref(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2724                        Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2725                    }
2726                    TyKind::PinnedRef(lt, MutTy { ref ty, mutbl })
2727                        if ty.kind.is_implicit_self() =>
2728                    {
2729                        Some(respan(self.pat.span, SelfKind::Pinned(lt, mutbl)))
2730                    }
2731                    _ => Some(respan(
2732                        self.pat.span.to(self.ty.span),
2733                        SelfKind::Explicit(self.ty.clone(), mutbl),
2734                    )),
2735                };
2736            }
2737        }
2738        None
2739    }
2740
2741    /// Returns `true` if parameter is `self`.
2742    pub fn is_self(&self) -> bool {
2743        if let PatKind::Ident(_, ident, _) = self.pat.kind {
2744            ident.name == kw::SelfLower
2745        } else {
2746            false
2747        }
2748    }
2749
2750    /// Builds a `Param` object from `ExplicitSelf`.
2751    pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2752        let span = eself.span.to(eself_ident.span);
2753        let infer_ty = P(Ty {
2754            id: DUMMY_NODE_ID,
2755            kind: TyKind::ImplicitSelf,
2756            span: eself_ident.span,
2757            tokens: None,
2758        });
2759        let (mutbl, ty) = match eself.node {
2760            SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2761            SelfKind::Value(mutbl) => (mutbl, infer_ty),
2762            SelfKind::Region(lt, mutbl) => (
2763                Mutability::Not,
2764                P(Ty {
2765                    id: DUMMY_NODE_ID,
2766                    kind: TyKind::Ref(lt, MutTy { ty: infer_ty, mutbl }),
2767                    span,
2768                    tokens: None,
2769                }),
2770            ),
2771            SelfKind::Pinned(lt, mutbl) => (
2772                mutbl,
2773                P(Ty {
2774                    id: DUMMY_NODE_ID,
2775                    kind: TyKind::PinnedRef(lt, MutTy { ty: infer_ty, mutbl }),
2776                    span,
2777                    tokens: None,
2778                }),
2779            ),
2780        };
2781        Param {
2782            attrs,
2783            pat: P(Pat {
2784                id: DUMMY_NODE_ID,
2785                kind: PatKind::Ident(BindingMode(ByRef::No, mutbl), eself_ident, None),
2786                span,
2787                tokens: None,
2788            }),
2789            span,
2790            ty,
2791            id: DUMMY_NODE_ID,
2792            is_placeholder: false,
2793        }
2794    }
2795}
2796
2797/// A signature (not the body) of a function declaration.
2798///
2799/// E.g., `fn foo(bar: baz)`.
2800///
2801/// Please note that it's different from `FnHeader` structure
2802/// which contains metadata about function safety, asyncness, constness and ABI.
2803#[derive(Clone, Encodable, Decodable, Debug)]
2804pub struct FnDecl {
2805    pub inputs: ThinVec<Param>,
2806    pub output: FnRetTy,
2807}
2808
2809impl FnDecl {
2810    pub fn has_self(&self) -> bool {
2811        self.inputs.get(0).is_some_and(Param::is_self)
2812    }
2813    pub fn c_variadic(&self) -> bool {
2814        self.inputs.last().is_some_and(|arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2815    }
2816}
2817
2818/// Is the trait definition an auto trait?
2819#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2820pub enum IsAuto {
2821    Yes,
2822    No,
2823}
2824
2825/// Safety of items.
2826#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2827#[derive(HashStable_Generic)]
2828pub enum Safety {
2829    /// `unsafe` an item is explicitly marked as `unsafe`.
2830    Unsafe(Span),
2831    /// `safe` an item is explicitly marked as `safe`.
2832    Safe(Span),
2833    /// Default means no value was provided, it will take a default value given the context in
2834    /// which is used.
2835    Default,
2836}
2837
2838/// Describes what kind of coroutine markers, if any, a function has.
2839///
2840/// Coroutine markers are things that cause the function to generate a coroutine, such as `async`,
2841/// which makes the function return `impl Future`, or `gen`, which makes the function return `impl
2842/// Iterator`.
2843#[derive(Copy, Clone, Encodable, Decodable, Debug)]
2844pub enum CoroutineKind {
2845    /// `async`, which returns an `impl Future`.
2846    Async { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2847    /// `gen`, which returns an `impl Iterator`.
2848    Gen { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2849    /// `async gen`, which returns an `impl AsyncIterator`.
2850    AsyncGen { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2851}
2852
2853impl CoroutineKind {
2854    pub fn span(self) -> Span {
2855        match self {
2856            CoroutineKind::Async { span, .. } => span,
2857            CoroutineKind::Gen { span, .. } => span,
2858            CoroutineKind::AsyncGen { span, .. } => span,
2859        }
2860    }
2861
2862    pub fn as_str(self) -> &'static str {
2863        match self {
2864            CoroutineKind::Async { .. } => "async",
2865            CoroutineKind::Gen { .. } => "gen",
2866            CoroutineKind::AsyncGen { .. } => "async gen",
2867        }
2868    }
2869
2870    pub fn closure_id(self) -> NodeId {
2871        match self {
2872            CoroutineKind::Async { closure_id, .. }
2873            | CoroutineKind::Gen { closure_id, .. }
2874            | CoroutineKind::AsyncGen { closure_id, .. } => closure_id,
2875        }
2876    }
2877
2878    /// In this case this is an `async` or `gen` return, the `NodeId` for the generated `impl Trait`
2879    /// item.
2880    pub fn return_id(self) -> (NodeId, Span) {
2881        match self {
2882            CoroutineKind::Async { return_impl_trait_id, span, .. }
2883            | CoroutineKind::Gen { return_impl_trait_id, span, .. }
2884            | CoroutineKind::AsyncGen { return_impl_trait_id, span, .. } => {
2885                (return_impl_trait_id, span)
2886            }
2887        }
2888    }
2889}
2890
2891#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2892#[derive(HashStable_Generic)]
2893pub enum Const {
2894    Yes(Span),
2895    No,
2896}
2897
2898/// Item defaultness.
2899/// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2900#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2901pub enum Defaultness {
2902    Default(Span),
2903    Final,
2904}
2905
2906#[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2907pub enum ImplPolarity {
2908    /// `impl Trait for Type`
2909    Positive,
2910    /// `impl !Trait for Type`
2911    Negative(Span),
2912}
2913
2914impl fmt::Debug for ImplPolarity {
2915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2916        match *self {
2917            ImplPolarity::Positive => "positive".fmt(f),
2918            ImplPolarity::Negative(_) => "negative".fmt(f),
2919        }
2920    }
2921}
2922
2923/// The polarity of a trait bound.
2924#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash)]
2925#[derive(HashStable_Generic)]
2926pub enum BoundPolarity {
2927    /// `Type: Trait`
2928    Positive,
2929    /// `Type: !Trait`
2930    Negative(Span),
2931    /// `Type: ?Trait`
2932    Maybe(Span),
2933}
2934
2935impl BoundPolarity {
2936    pub fn as_str(self) -> &'static str {
2937        match self {
2938            Self::Positive => "",
2939            Self::Negative(_) => "!",
2940            Self::Maybe(_) => "?",
2941        }
2942    }
2943}
2944
2945/// The constness of a trait bound.
2946#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash)]
2947#[derive(HashStable_Generic)]
2948pub enum BoundConstness {
2949    /// `Type: Trait`
2950    Never,
2951    /// `Type: const Trait`
2952    Always(Span),
2953    /// `Type: ~const Trait`
2954    Maybe(Span),
2955}
2956
2957impl BoundConstness {
2958    pub fn as_str(self) -> &'static str {
2959        match self {
2960            Self::Never => "",
2961            Self::Always(_) => "const",
2962            Self::Maybe(_) => "~const",
2963        }
2964    }
2965}
2966
2967/// The asyncness of a trait bound.
2968#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
2969#[derive(HashStable_Generic)]
2970pub enum BoundAsyncness {
2971    /// `Type: Trait`
2972    Normal,
2973    /// `Type: async Trait`
2974    Async(Span),
2975}
2976
2977impl BoundAsyncness {
2978    pub fn as_str(self) -> &'static str {
2979        match self {
2980            Self::Normal => "",
2981            Self::Async(_) => "async",
2982        }
2983    }
2984}
2985
2986#[derive(Clone, Encodable, Decodable, Debug)]
2987pub enum FnRetTy {
2988    /// Returns type is not specified.
2989    ///
2990    /// Functions default to `()` and closures default to inference.
2991    /// Span points to where return type would be inserted.
2992    Default(Span),
2993    /// Everything else.
2994    Ty(P<Ty>),
2995}
2996
2997impl FnRetTy {
2998    pub fn span(&self) -> Span {
2999        match self {
3000            &FnRetTy::Default(span) => span,
3001            FnRetTy::Ty(ty) => ty.span,
3002        }
3003    }
3004}
3005
3006#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
3007pub enum Inline {
3008    Yes,
3009    No,
3010}
3011
3012/// Module item kind.
3013#[derive(Clone, Encodable, Decodable, Debug)]
3014pub enum ModKind {
3015    /// Module with inlined definition `mod foo { ... }`,
3016    /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
3017    /// The inner span is from the first token past `{` to the last token until `}`,
3018    /// or from the first to the last token in the loaded file.
3019    Loaded(ThinVec<P<Item>>, Inline, ModSpans, Result<(), ErrorGuaranteed>),
3020    /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
3021    Unloaded,
3022}
3023
3024#[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
3025pub struct ModSpans {
3026    /// `inner_span` covers the body of the module; for a file module, its the whole file.
3027    /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
3028    pub inner_span: Span,
3029    pub inject_use_span: Span,
3030}
3031
3032/// Foreign module declaration.
3033///
3034/// E.g., `extern { .. }` or `extern "C" { .. }`.
3035#[derive(Clone, Encodable, Decodable, Debug)]
3036pub struct ForeignMod {
3037    /// Span of the `extern` keyword.
3038    pub extern_span: Span,
3039    /// `unsafe` keyword accepted syntactically for macro DSLs, but not
3040    /// semantically by Rust.
3041    pub safety: Safety,
3042    pub abi: Option<StrLit>,
3043    pub items: ThinVec<P<ForeignItem>>,
3044}
3045
3046#[derive(Clone, Encodable, Decodable, Debug)]
3047pub struct EnumDef {
3048    pub variants: ThinVec<Variant>,
3049}
3050/// Enum variant.
3051#[derive(Clone, Encodable, Decodable, Debug)]
3052pub struct Variant {
3053    /// Attributes of the variant.
3054    pub attrs: AttrVec,
3055    /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
3056    pub id: NodeId,
3057    /// Span
3058    pub span: Span,
3059    /// The visibility of the variant. Syntactically accepted but not semantically.
3060    pub vis: Visibility,
3061    /// Name of the variant.
3062    pub ident: Ident,
3063
3064    /// Fields and constructor id of the variant.
3065    pub data: VariantData,
3066    /// Explicit discriminant, e.g., `Foo = 1`.
3067    pub disr_expr: Option<AnonConst>,
3068    /// Is a macro placeholder.
3069    pub is_placeholder: bool,
3070}
3071
3072/// Part of `use` item to the right of its prefix.
3073#[derive(Clone, Encodable, Decodable, Debug)]
3074pub enum UseTreeKind {
3075    /// `use prefix` or `use prefix as rename`
3076    Simple(Option<Ident>),
3077    /// `use prefix::{...}`
3078    ///
3079    /// The span represents the braces of the nested group and all elements within:
3080    ///
3081    /// ```text
3082    /// use foo::{bar, baz};
3083    ///          ^^^^^^^^^^
3084    /// ```
3085    Nested { items: ThinVec<(UseTree, NodeId)>, span: Span },
3086    /// `use prefix::*`
3087    Glob,
3088}
3089
3090/// A tree of paths sharing common prefixes.
3091/// Used in `use` items both at top-level and inside of braces in import groups.
3092#[derive(Clone, Encodable, Decodable, Debug)]
3093pub struct UseTree {
3094    pub prefix: Path,
3095    pub kind: UseTreeKind,
3096    pub span: Span,
3097}
3098
3099impl UseTree {
3100    pub fn ident(&self) -> Ident {
3101        match self.kind {
3102            UseTreeKind::Simple(Some(rename)) => rename,
3103            UseTreeKind::Simple(None) => {
3104                self.prefix.segments.last().expect("empty prefix in a simple import").ident
3105            }
3106            _ => panic!("`UseTree::ident` can only be used on a simple import"),
3107        }
3108    }
3109}
3110
3111/// Distinguishes between `Attribute`s that decorate items and Attributes that
3112/// are contained as statements within items. These two cases need to be
3113/// distinguished for pretty-printing.
3114#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
3115pub enum AttrStyle {
3116    Outer,
3117    Inner,
3118}
3119
3120/// A list of attributes.
3121pub type AttrVec = ThinVec<Attribute>;
3122
3123/// A syntax-level representation of an attribute.
3124#[derive(Clone, Encodable, Decodable, Debug)]
3125pub struct Attribute {
3126    pub kind: AttrKind,
3127    pub id: AttrId,
3128    /// Denotes if the attribute decorates the following construct (outer)
3129    /// or the construct this attribute is contained within (inner).
3130    pub style: AttrStyle,
3131    pub span: Span,
3132}
3133
3134#[derive(Clone, Encodable, Decodable, Debug)]
3135pub enum AttrKind {
3136    /// A normal attribute.
3137    Normal(P<NormalAttr>),
3138
3139    /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
3140    /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
3141    /// variant (which is much less compact and thus more expensive).
3142    DocComment(CommentKind, Symbol),
3143}
3144
3145#[derive(Clone, Encodable, Decodable, Debug)]
3146pub struct NormalAttr {
3147    pub item: AttrItem,
3148    // Tokens for the full attribute, e.g. `#[foo]`, `#![bar]`.
3149    pub tokens: Option<LazyAttrTokenStream>,
3150}
3151
3152impl NormalAttr {
3153    pub fn from_ident(ident: Ident) -> Self {
3154        Self {
3155            item: AttrItem {
3156                unsafety: Safety::Default,
3157                path: Path::from_ident(ident),
3158                args: AttrArgs::Empty,
3159                tokens: None,
3160            },
3161            tokens: None,
3162        }
3163    }
3164}
3165
3166#[derive(Clone, Encodable, Decodable, Debug)]
3167pub struct AttrItem {
3168    pub unsafety: Safety,
3169    pub path: Path,
3170    pub args: AttrArgs,
3171    // Tokens for the meta item, e.g. just the `foo` within `#[foo]` or `#![foo]`.
3172    pub tokens: Option<LazyAttrTokenStream>,
3173}
3174
3175impl AttrItem {
3176    pub fn is_valid_for_outer_style(&self) -> bool {
3177        self.path == sym::cfg_attr
3178            || self.path == sym::cfg
3179            || self.path == sym::forbid
3180            || self.path == sym::warn
3181            || self.path == sym::allow
3182            || self.path == sym::deny
3183    }
3184}
3185
3186/// `TraitRef`s appear in impls.
3187///
3188/// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
3189/// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
3190/// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
3191/// same as the impl's `NodeId`).
3192#[derive(Clone, Encodable, Decodable, Debug)]
3193pub struct TraitRef {
3194    pub path: Path,
3195    pub ref_id: NodeId,
3196}
3197
3198#[derive(Clone, Encodable, Decodable, Debug)]
3199pub struct PolyTraitRef {
3200    /// The `'a` in `for<'a> Foo<&'a T>`.
3201    pub bound_generic_params: ThinVec<GenericParam>,
3202
3203    // Optional constness, asyncness, or polarity.
3204    pub modifiers: TraitBoundModifiers,
3205
3206    /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
3207    pub trait_ref: TraitRef,
3208
3209    pub span: Span,
3210}
3211
3212impl PolyTraitRef {
3213    pub fn new(
3214        generic_params: ThinVec<GenericParam>,
3215        path: Path,
3216        modifiers: TraitBoundModifiers,
3217        span: Span,
3218    ) -> Self {
3219        PolyTraitRef {
3220            bound_generic_params: generic_params,
3221            modifiers,
3222            trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
3223            span,
3224        }
3225    }
3226}
3227
3228#[derive(Clone, Encodable, Decodable, Debug)]
3229pub struct Visibility {
3230    pub kind: VisibilityKind,
3231    pub span: Span,
3232    pub tokens: Option<LazyAttrTokenStream>,
3233}
3234
3235#[derive(Clone, Encodable, Decodable, Debug)]
3236pub enum VisibilityKind {
3237    Public,
3238    Restricted { path: P<Path>, id: NodeId, shorthand: bool },
3239    Inherited,
3240}
3241
3242impl VisibilityKind {
3243    pub fn is_pub(&self) -> bool {
3244        matches!(self, VisibilityKind::Public)
3245    }
3246}
3247
3248/// Field definition in a struct, variant or union.
3249///
3250/// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
3251#[derive(Clone, Encodable, Decodable, Debug)]
3252pub struct FieldDef {
3253    pub attrs: AttrVec,
3254    pub id: NodeId,
3255    pub span: Span,
3256    pub vis: Visibility,
3257    pub safety: Safety,
3258    pub ident: Option<Ident>,
3259
3260    pub ty: P<Ty>,
3261    pub default: Option<AnonConst>,
3262    pub is_placeholder: bool,
3263}
3264
3265/// Was parsing recovery performed?
3266#[derive(Copy, Clone, Debug, Encodable, Decodable, HashStable_Generic)]
3267pub enum Recovered {
3268    No,
3269    Yes(ErrorGuaranteed),
3270}
3271
3272/// Fields and constructor ids of enum variants and structs.
3273#[derive(Clone, Encodable, Decodable, Debug)]
3274pub enum VariantData {
3275    /// Struct variant.
3276    ///
3277    /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
3278    Struct { fields: ThinVec<FieldDef>, recovered: Recovered },
3279    /// Tuple variant.
3280    ///
3281    /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
3282    Tuple(ThinVec<FieldDef>, NodeId),
3283    /// Unit variant.
3284    ///
3285    /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
3286    Unit(NodeId),
3287}
3288
3289impl VariantData {
3290    /// Return the fields of this variant.
3291    pub fn fields(&self) -> &[FieldDef] {
3292        match self {
3293            VariantData::Struct { fields, .. } | VariantData::Tuple(fields, _) => fields,
3294            _ => &[],
3295        }
3296    }
3297
3298    /// Return the `NodeId` of this variant's constructor, if it has one.
3299    pub fn ctor_node_id(&self) -> Option<NodeId> {
3300        match *self {
3301            VariantData::Struct { .. } => None,
3302            VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
3303        }
3304    }
3305}
3306
3307/// An item definition.
3308#[derive(Clone, Encodable, Decodable, Debug)]
3309pub struct Item<K = ItemKind> {
3310    pub attrs: AttrVec,
3311    pub id: NodeId,
3312    pub span: Span,
3313    pub vis: Visibility,
3314    /// The name of the item.
3315    /// It might be a dummy name in case of anonymous items.
3316    pub ident: Ident,
3317
3318    pub kind: K,
3319
3320    /// Original tokens this item was parsed from. This isn't necessarily
3321    /// available for all items, although over time more and more items should
3322    /// have this be `Some`. Right now this is primarily used for procedural
3323    /// macros, notably custom attributes.
3324    ///
3325    /// Note that the tokens here do not include the outer attributes, but will
3326    /// include inner attributes.
3327    pub tokens: Option<LazyAttrTokenStream>,
3328}
3329
3330impl Item {
3331    /// Return the span that encompasses the attributes.
3332    pub fn span_with_attributes(&self) -> Span {
3333        self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
3334    }
3335
3336    pub fn opt_generics(&self) -> Option<&Generics> {
3337        match &self.kind {
3338            ItemKind::ExternCrate(_)
3339            | ItemKind::Use(_)
3340            | ItemKind::Mod(_, _)
3341            | ItemKind::ForeignMod(_)
3342            | ItemKind::GlobalAsm(_)
3343            | ItemKind::MacCall(_)
3344            | ItemKind::Delegation(_)
3345            | ItemKind::DelegationMac(_)
3346            | ItemKind::MacroDef(_) => None,
3347            ItemKind::Static(_) => None,
3348            ItemKind::Const(i) => Some(&i.generics),
3349            ItemKind::Fn(i) => Some(&i.generics),
3350            ItemKind::TyAlias(i) => Some(&i.generics),
3351            ItemKind::TraitAlias(generics, _)
3352            | ItemKind::Enum(_, generics)
3353            | ItemKind::Struct(_, generics)
3354            | ItemKind::Union(_, generics) => Some(&generics),
3355            ItemKind::Trait(i) => Some(&i.generics),
3356            ItemKind::Impl(i) => Some(&i.generics),
3357        }
3358    }
3359}
3360
3361/// `extern` qualifier on a function item or function type.
3362#[derive(Clone, Copy, Encodable, Decodable, Debug)]
3363pub enum Extern {
3364    /// No explicit extern keyword was used.
3365    ///
3366    /// E.g. `fn foo() {}`.
3367    None,
3368    /// An explicit extern keyword was used, but with implicit ABI.
3369    ///
3370    /// E.g. `extern fn foo() {}`.
3371    ///
3372    /// This is just `extern "C"` (see `rustc_abi::ExternAbi::FALLBACK`).
3373    Implicit(Span),
3374    /// An explicit extern keyword was used with an explicit ABI.
3375    ///
3376    /// E.g. `extern "C" fn foo() {}`.
3377    Explicit(StrLit, Span),
3378}
3379
3380impl Extern {
3381    pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
3382        match abi {
3383            Some(name) => Extern::Explicit(name, span),
3384            None => Extern::Implicit(span),
3385        }
3386    }
3387}
3388
3389/// A function header.
3390///
3391/// All the information between the visibility and the name of the function is
3392/// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
3393#[derive(Clone, Copy, Encodable, Decodable, Debug)]
3394pub struct FnHeader {
3395    /// Whether this is `unsafe`, or has a default safety.
3396    pub safety: Safety,
3397    /// Whether this is `async`, `gen`, or nothing.
3398    pub coroutine_kind: Option<CoroutineKind>,
3399    /// The `const` keyword, if any
3400    pub constness: Const,
3401    /// The `extern` keyword and corresponding ABI string, if any.
3402    pub ext: Extern,
3403}
3404
3405impl FnHeader {
3406    /// Does this function header have any qualifiers or is it empty?
3407    pub fn has_qualifiers(&self) -> bool {
3408        let Self { safety, coroutine_kind, constness, ext } = self;
3409        matches!(safety, Safety::Unsafe(_))
3410            || coroutine_kind.is_some()
3411            || matches!(constness, Const::Yes(_))
3412            || !matches!(ext, Extern::None)
3413    }
3414}
3415
3416impl Default for FnHeader {
3417    fn default() -> FnHeader {
3418        FnHeader {
3419            safety: Safety::Default,
3420            coroutine_kind: None,
3421            constness: Const::No,
3422            ext: Extern::None,
3423        }
3424    }
3425}
3426
3427#[derive(Clone, Encodable, Decodable, Debug)]
3428pub struct Trait {
3429    pub safety: Safety,
3430    pub is_auto: IsAuto,
3431    pub generics: Generics,
3432    pub bounds: GenericBounds,
3433    pub items: ThinVec<P<AssocItem>>,
3434}
3435
3436/// The location of a where clause on a `TyAlias` (`Span`) and whether there was
3437/// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
3438/// are two locations for where clause on type aliases, but their predicates
3439/// are concatenated together.
3440///
3441/// Take this example:
3442/// ```ignore (only-for-syntax-highlight)
3443/// trait Foo {
3444///   type Assoc<'a, 'b> where Self: 'a, Self: 'b;
3445/// }
3446/// impl Foo for () {
3447///   type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
3448///   //                 ^^^^^^^^^^^^^^ first where clause
3449///   //                                     ^^^^^^^^^^^^^^ second where clause
3450/// }
3451/// ```
3452///
3453/// If there is no where clause, then this is `false` with `DUMMY_SP`.
3454#[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
3455pub struct TyAliasWhereClause {
3456    pub has_where_token: bool,
3457    pub span: Span,
3458}
3459
3460/// The span information for the two where clauses on a `TyAlias`.
3461#[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
3462pub struct TyAliasWhereClauses {
3463    /// Before the equals sign.
3464    pub before: TyAliasWhereClause,
3465    /// After the equals sign.
3466    pub after: TyAliasWhereClause,
3467    /// The index in `TyAlias.generics.where_clause.predicates` that would split
3468    /// into predicates from the where clause before the equals sign and the ones
3469    /// from the where clause after the equals sign.
3470    pub split: usize,
3471}
3472
3473#[derive(Clone, Encodable, Decodable, Debug)]
3474pub struct TyAlias {
3475    pub defaultness: Defaultness,
3476    pub generics: Generics,
3477    pub where_clauses: TyAliasWhereClauses,
3478    pub bounds: GenericBounds,
3479    pub ty: Option<P<Ty>>,
3480}
3481
3482#[derive(Clone, Encodable, Decodable, Debug)]
3483pub struct Impl {
3484    pub defaultness: Defaultness,
3485    pub safety: Safety,
3486    pub generics: Generics,
3487    pub constness: Const,
3488    pub polarity: ImplPolarity,
3489    /// The trait being implemented, if any.
3490    pub of_trait: Option<TraitRef>,
3491    pub self_ty: P<Ty>,
3492    pub items: ThinVec<P<AssocItem>>,
3493}
3494
3495#[derive(Clone, Encodable, Decodable, Debug, Default)]
3496pub struct FnContract {
3497    pub requires: Option<P<Expr>>,
3498    pub ensures: Option<P<Expr>>,
3499}
3500
3501#[derive(Clone, Encodable, Decodable, Debug)]
3502pub struct Fn {
3503    pub defaultness: Defaultness,
3504    pub generics: Generics,
3505    pub sig: FnSig,
3506    pub contract: Option<P<FnContract>>,
3507    pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
3508    pub body: Option<P<Block>>,
3509}
3510
3511#[derive(Clone, Encodable, Decodable, Debug)]
3512pub struct Delegation {
3513    /// Path resolution id.
3514    pub id: NodeId,
3515    pub qself: Option<P<QSelf>>,
3516    pub path: Path,
3517    pub rename: Option<Ident>,
3518    pub body: Option<P<Block>>,
3519    /// The item was expanded from a glob delegation item.
3520    pub from_glob: bool,
3521}
3522
3523#[derive(Clone, Encodable, Decodable, Debug)]
3524pub struct DelegationMac {
3525    pub qself: Option<P<QSelf>>,
3526    pub prefix: Path,
3527    // Some for list delegation, and None for glob delegation.
3528    pub suffixes: Option<ThinVec<(Ident, Option<Ident>)>>,
3529    pub body: Option<P<Block>>,
3530}
3531
3532#[derive(Clone, Encodable, Decodable, Debug)]
3533pub struct StaticItem {
3534    pub ty: P<Ty>,
3535    pub safety: Safety,
3536    pub mutability: Mutability,
3537    pub expr: Option<P<Expr>>,
3538}
3539
3540#[derive(Clone, Encodable, Decodable, Debug)]
3541pub struct ConstItem {
3542    pub defaultness: Defaultness,
3543    pub generics: Generics,
3544    pub ty: P<Ty>,
3545    pub expr: Option<P<Expr>>,
3546}
3547
3548// Adding a new variant? Please update `test_item` in `tests/ui/macros/stringify.rs`.
3549#[derive(Clone, Encodable, Decodable, Debug)]
3550pub enum ItemKind {
3551    /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
3552    ///
3553    /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3554    ExternCrate(Option<Symbol>),
3555    /// A use declaration item (`use`).
3556    ///
3557    /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
3558    Use(UseTree),
3559    /// A static item (`static`).
3560    ///
3561    /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
3562    Static(Box<StaticItem>),
3563    /// A constant item (`const`).
3564    ///
3565    /// E.g., `const FOO: i32 = 42;`.
3566    Const(Box<ConstItem>),
3567    /// A function declaration (`fn`).
3568    ///
3569    /// E.g., `fn foo(bar: usize) -> usize { .. }`.
3570    Fn(Box<Fn>),
3571    /// A module declaration (`mod`).
3572    ///
3573    /// E.g., `mod foo;` or `mod foo { .. }`.
3574    /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
3575    /// semantically by Rust.
3576    Mod(Safety, ModKind),
3577    /// An external module (`extern`).
3578    ///
3579    /// E.g., `extern {}` or `extern "C" {}`.
3580    ForeignMod(ForeignMod),
3581    /// Module-level inline assembly (from `global_asm!()`).
3582    GlobalAsm(Box<InlineAsm>),
3583    /// A type alias (`type`).
3584    ///
3585    /// E.g., `type Foo = Bar<u8>;`.
3586    TyAlias(Box<TyAlias>),
3587    /// An enum definition (`enum`).
3588    ///
3589    /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
3590    Enum(EnumDef, Generics),
3591    /// A struct definition (`struct`).
3592    ///
3593    /// E.g., `struct Foo<A> { x: A }`.
3594    Struct(VariantData, Generics),
3595    /// A union definition (`union`).
3596    ///
3597    /// E.g., `union Foo<A, B> { x: A, y: B }`.
3598    Union(VariantData, Generics),
3599    /// A trait declaration (`trait`).
3600    ///
3601    /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
3602    Trait(Box<Trait>),
3603    /// Trait alias.
3604    ///
3605    /// E.g., `trait Foo = Bar + Quux;`.
3606    TraitAlias(Generics, GenericBounds),
3607    /// An implementation.
3608    ///
3609    /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
3610    Impl(Box<Impl>),
3611    /// A macro invocation.
3612    ///
3613    /// E.g., `foo!(..)`.
3614    MacCall(P<MacCall>),
3615
3616    /// A macro definition.
3617    MacroDef(MacroDef),
3618
3619    /// A single delegation item (`reuse`).
3620    ///
3621    /// E.g. `reuse <Type as Trait>::name { target_expr_template }`.
3622    Delegation(Box<Delegation>),
3623    /// A list or glob delegation item (`reuse prefix::{a, b, c}`, `reuse prefix::*`).
3624    /// Treated similarly to a macro call and expanded early.
3625    DelegationMac(Box<DelegationMac>),
3626}
3627
3628impl ItemKind {
3629    /// "a" or "an"
3630    pub fn article(&self) -> &'static str {
3631        use ItemKind::*;
3632        match self {
3633            Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
3634            | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..)
3635            | Delegation(..) | DelegationMac(..) => "a",
3636            ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
3637        }
3638    }
3639
3640    pub fn descr(&self) -> &'static str {
3641        match self {
3642            ItemKind::ExternCrate(..) => "extern crate",
3643            ItemKind::Use(..) => "`use` import",
3644            ItemKind::Static(..) => "static item",
3645            ItemKind::Const(..) => "constant item",
3646            ItemKind::Fn(..) => "function",
3647            ItemKind::Mod(..) => "module",
3648            ItemKind::ForeignMod(..) => "extern block",
3649            ItemKind::GlobalAsm(..) => "global asm item",
3650            ItemKind::TyAlias(..) => "type alias",
3651            ItemKind::Enum(..) => "enum",
3652            ItemKind::Struct(..) => "struct",
3653            ItemKind::Union(..) => "union",
3654            ItemKind::Trait(..) => "trait",
3655            ItemKind::TraitAlias(..) => "trait alias",
3656            ItemKind::MacCall(..) => "item macro invocation",
3657            ItemKind::MacroDef(..) => "macro definition",
3658            ItemKind::Impl { .. } => "implementation",
3659            ItemKind::Delegation(..) => "delegated function",
3660            ItemKind::DelegationMac(..) => "delegation",
3661        }
3662    }
3663
3664    pub fn generics(&self) -> Option<&Generics> {
3665        match self {
3666            Self::Fn(box Fn { generics, .. })
3667            | Self::TyAlias(box TyAlias { generics, .. })
3668            | Self::Const(box ConstItem { generics, .. })
3669            | Self::Enum(_, generics)
3670            | Self::Struct(_, generics)
3671            | Self::Union(_, generics)
3672            | Self::Trait(box Trait { generics, .. })
3673            | Self::TraitAlias(generics, _)
3674            | Self::Impl(box Impl { generics, .. }) => Some(generics),
3675            _ => None,
3676        }
3677    }
3678}
3679
3680/// Represents associated items.
3681/// These include items in `impl` and `trait` definitions.
3682pub type AssocItem = Item<AssocItemKind>;
3683
3684/// Represents associated item kinds.
3685///
3686/// The term "provided" in the variants below refers to the item having a default
3687/// definition / body. Meanwhile, a "required" item lacks a definition / body.
3688/// In an implementation, all items must be provided.
3689/// The `Option`s below denote the bodies, where `Some(_)`
3690/// means "provided" and conversely `None` means "required".
3691#[derive(Clone, Encodable, Decodable, Debug)]
3692pub enum AssocItemKind {
3693    /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
3694    /// If `def` is parsed, then the constant is provided, and otherwise required.
3695    Const(Box<ConstItem>),
3696    /// An associated function.
3697    Fn(Box<Fn>),
3698    /// An associated type.
3699    Type(Box<TyAlias>),
3700    /// A macro expanding to associated items.
3701    MacCall(P<MacCall>),
3702    /// An associated delegation item.
3703    Delegation(Box<Delegation>),
3704    /// An associated list or glob delegation item.
3705    DelegationMac(Box<DelegationMac>),
3706}
3707
3708impl AssocItemKind {
3709    pub fn defaultness(&self) -> Defaultness {
3710        match *self {
3711            Self::Const(box ConstItem { defaultness, .. })
3712            | Self::Fn(box Fn { defaultness, .. })
3713            | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
3714            Self::MacCall(..) | Self::Delegation(..) | Self::DelegationMac(..) => {
3715                Defaultness::Final
3716            }
3717        }
3718    }
3719}
3720
3721impl From<AssocItemKind> for ItemKind {
3722    fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
3723        match assoc_item_kind {
3724            AssocItemKind::Const(item) => ItemKind::Const(item),
3725            AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3726            AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3727            AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
3728            AssocItemKind::Delegation(delegation) => ItemKind::Delegation(delegation),
3729            AssocItemKind::DelegationMac(delegation) => ItemKind::DelegationMac(delegation),
3730        }
3731    }
3732}
3733
3734impl TryFrom<ItemKind> for AssocItemKind {
3735    type Error = ItemKind;
3736
3737    fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
3738        Ok(match item_kind {
3739            ItemKind::Const(item) => AssocItemKind::Const(item),
3740            ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
3741            ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
3742            ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
3743            ItemKind::Delegation(d) => AssocItemKind::Delegation(d),
3744            ItemKind::DelegationMac(d) => AssocItemKind::DelegationMac(d),
3745            _ => return Err(item_kind),
3746        })
3747    }
3748}
3749
3750/// An item in `extern` block.
3751#[derive(Clone, Encodable, Decodable, Debug)]
3752pub enum ForeignItemKind {
3753    /// A foreign static item (`static FOO: u8`).
3754    Static(Box<StaticItem>),
3755    /// An foreign function.
3756    Fn(Box<Fn>),
3757    /// An foreign type.
3758    TyAlias(Box<TyAlias>),
3759    /// A macro expanding to foreign items.
3760    MacCall(P<MacCall>),
3761}
3762
3763impl From<ForeignItemKind> for ItemKind {
3764    fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3765        match foreign_item_kind {
3766            ForeignItemKind::Static(box static_foreign_item) => {
3767                ItemKind::Static(Box::new(static_foreign_item))
3768            }
3769            ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3770            ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3771            ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3772        }
3773    }
3774}
3775
3776impl TryFrom<ItemKind> for ForeignItemKind {
3777    type Error = ItemKind;
3778
3779    fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3780        Ok(match item_kind {
3781            ItemKind::Static(box static_item) => ForeignItemKind::Static(Box::new(static_item)),
3782            ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3783            ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3784            ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3785            _ => return Err(item_kind),
3786        })
3787    }
3788}
3789
3790pub type ForeignItem = Item<ForeignItemKind>;
3791
3792// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3793#[cfg(target_pointer_width = "64")]
3794mod size_asserts {
3795    use rustc_data_structures::static_assert_size;
3796
3797    use super::*;
3798    // tidy-alphabetical-start
3799    static_assert_size!(AssocItem, 88);
3800    static_assert_size!(AssocItemKind, 16);
3801    static_assert_size!(Attribute, 32);
3802    static_assert_size!(Block, 32);
3803    static_assert_size!(Expr, 72);
3804    static_assert_size!(ExprKind, 40);
3805    static_assert_size!(Fn, 176);
3806    static_assert_size!(ForeignItem, 88);
3807    static_assert_size!(ForeignItemKind, 16);
3808    static_assert_size!(GenericArg, 24);
3809    static_assert_size!(GenericBound, 88);
3810    static_assert_size!(Generics, 40);
3811    static_assert_size!(Impl, 136);
3812    static_assert_size!(Item, 136);
3813    static_assert_size!(ItemKind, 64);
3814    static_assert_size!(LitKind, 24);
3815    static_assert_size!(Local, 80);
3816    static_assert_size!(MetaItemLit, 40);
3817    static_assert_size!(Param, 40);
3818    static_assert_size!(Pat, 72);
3819    static_assert_size!(Path, 24);
3820    static_assert_size!(PathSegment, 24);
3821    static_assert_size!(PatKind, 48);
3822    static_assert_size!(Stmt, 32);
3823    static_assert_size!(StmtKind, 16);
3824    static_assert_size!(Ty, 64);
3825    static_assert_size!(TyKind, 40);
3826    // tidy-alphabetical-end
3827}