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