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