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    /// If this is a macro used for externally implementable items,
2113    /// it refers to an extern item which is its "target". This requires
2114    /// name resolution so can't just be an attribute, so we store it in this field.
2115    pub eii_extern_target: Option<EiiExternTarget>,
2116}
2117
2118#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
2119pub struct EiiExternTarget {
2120    /// path to the extern item we're targetting
2121    pub extern_item_path: Path,
2122    pub impl_unsafe: bool,
2123    pub span: Span,
2124}
2125
2126#[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
2127#[derive(HashStable_Generic, Walkable)]
2128pub enum StrStyle {
2129    /// A regular string, like `"foo"`.
2130    Cooked,
2131    /// A raw string, like `r##"foo"##`.
2132    ///
2133    /// The value is the number of `#` symbols used.
2134    Raw(u8),
2135}
2136
2137/// The kind of match expression
2138#[derive(Clone, Copy, Encodable, Decodable, Debug, PartialEq, Walkable)]
2139pub enum MatchKind {
2140    /// match expr { ... }
2141    Prefix,
2142    /// expr.match { ... }
2143    Postfix,
2144}
2145
2146/// The kind of yield expression
2147#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2148pub enum YieldKind {
2149    /// yield expr { ... }
2150    Prefix(Option<Box<Expr>>),
2151    /// expr.yield { ... }
2152    Postfix(Box<Expr>),
2153}
2154
2155impl YieldKind {
2156    /// Returns the expression inside the yield expression, if any.
2157    ///
2158    /// For postfix yields, this is guaranteed to be `Some`.
2159    pub const fn expr(&self) -> Option<&Box<Expr>> {
2160        match self {
2161            YieldKind::Prefix(expr) => expr.as_ref(),
2162            YieldKind::Postfix(expr) => Some(expr),
2163        }
2164    }
2165
2166    /// Returns a mutable reference to the expression being yielded, if any.
2167    pub const fn expr_mut(&mut self) -> Option<&mut Box<Expr>> {
2168        match self {
2169            YieldKind::Prefix(expr) => expr.as_mut(),
2170            YieldKind::Postfix(expr) => Some(expr),
2171        }
2172    }
2173
2174    /// Returns true if both yields are prefix or both are postfix.
2175    pub const fn same_kind(&self, other: &Self) -> bool {
2176        match (self, other) {
2177            (YieldKind::Prefix(_), YieldKind::Prefix(_)) => true,
2178            (YieldKind::Postfix(_), YieldKind::Postfix(_)) => true,
2179            _ => false,
2180        }
2181    }
2182}
2183
2184/// A literal in a meta item.
2185#[derive(Clone, Copy, Encodable, Decodable, Debug, HashStable_Generic)]
2186pub struct MetaItemLit {
2187    /// The original literal as written in the source code.
2188    pub symbol: Symbol,
2189    /// The original suffix as written in the source code.
2190    pub suffix: Option<Symbol>,
2191    /// The "semantic" representation of the literal lowered from the original tokens.
2192    /// Strings are unescaped, hexadecimal forms are eliminated, etc.
2193    pub kind: LitKind,
2194    pub span: Span,
2195}
2196
2197/// Similar to `MetaItemLit`, but restricted to string literals.
2198#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
2199pub struct StrLit {
2200    /// The original literal as written in source code.
2201    pub symbol: Symbol,
2202    /// The original suffix as written in source code.
2203    pub suffix: Option<Symbol>,
2204    /// The semantic (unescaped) representation of the literal.
2205    pub symbol_unescaped: Symbol,
2206    pub style: StrStyle,
2207    pub span: Span,
2208}
2209
2210impl StrLit {
2211    pub fn as_token_lit(&self) -> token::Lit {
2212        let token_kind = match self.style {
2213            StrStyle::Cooked => token::Str,
2214            StrStyle::Raw(n) => token::StrRaw(n),
2215        };
2216        token::Lit::new(token_kind, self.symbol, self.suffix)
2217    }
2218}
2219
2220/// Type of the integer literal based on provided suffix.
2221#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
2222#[derive(HashStable_Generic)]
2223pub enum LitIntType {
2224    /// e.g. `42_i32`.
2225    Signed(IntTy),
2226    /// e.g. `42_u32`.
2227    Unsigned(UintTy),
2228    /// e.g. `42`.
2229    Unsuffixed,
2230}
2231
2232/// Type of the float literal based on provided suffix.
2233#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
2234#[derive(HashStable_Generic)]
2235pub enum LitFloatType {
2236    /// A float literal with a suffix (`1f32` or `1E10f32`).
2237    Suffixed(FloatTy),
2238    /// A float literal without a suffix (`1.0 or 1.0E10`).
2239    Unsuffixed,
2240}
2241
2242/// This type is used within both `ast::MetaItemLit` and `hir::Lit`.
2243///
2244/// Note that the entire literal (including the suffix) is considered when
2245/// deciding the `LitKind`. This means that float literals like `1f32` are
2246/// classified by this type as `Float`. This is different to `token::LitKind`
2247/// which does *not* consider the suffix.
2248#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
2249pub enum LitKind {
2250    /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
2251    /// from the original token's symbol.
2252    Str(Symbol, StrStyle),
2253    /// A byte string (`b"foo"`). The symbol is unescaped, and so may differ
2254    /// from the original token's symbol.
2255    ByteStr(ByteSymbol, StrStyle),
2256    /// A C String (`c"foo"`). Guaranteed to only have `\0` at the end. The
2257    /// symbol is unescaped, and so may differ from the original token's
2258    /// symbol.
2259    CStr(ByteSymbol, StrStyle),
2260    /// A byte char (`b'f'`).
2261    Byte(u8),
2262    /// A character literal (`'a'`).
2263    Char(char),
2264    /// An integer literal (`1`).
2265    Int(Pu128, LitIntType),
2266    /// A float literal (`1.0`, `1f64` or `1E10f64`). The pre-suffix part is
2267    /// stored as a symbol rather than `f64` so that `LitKind` can impl `Eq`
2268    /// and `Hash`.
2269    Float(Symbol, LitFloatType),
2270    /// A boolean literal (`true`, `false`).
2271    Bool(bool),
2272    /// Placeholder for a literal that wasn't well-formed in some way.
2273    Err(ErrorGuaranteed),
2274}
2275
2276impl LitKind {
2277    pub fn str(&self) -> Option<Symbol> {
2278        match *self {
2279            LitKind::Str(s, _) => Some(s),
2280            _ => None,
2281        }
2282    }
2283
2284    /// Returns `true` if this literal is a string.
2285    pub fn is_str(&self) -> bool {
2286        matches!(self, LitKind::Str(..))
2287    }
2288
2289    /// Returns `true` if this literal is byte literal string.
2290    pub fn is_bytestr(&self) -> bool {
2291        matches!(self, LitKind::ByteStr(..))
2292    }
2293
2294    /// Returns `true` if this is a numeric literal.
2295    pub fn is_numeric(&self) -> bool {
2296        matches!(self, LitKind::Int(..) | LitKind::Float(..))
2297    }
2298
2299    /// Returns `true` if this literal has no suffix.
2300    /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
2301    pub fn is_unsuffixed(&self) -> bool {
2302        !self.is_suffixed()
2303    }
2304
2305    /// Returns `true` if this literal has a suffix.
2306    pub fn is_suffixed(&self) -> bool {
2307        match *self {
2308            // suffixed variants
2309            LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
2310            | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
2311            // unsuffixed variants
2312            LitKind::Str(..)
2313            | LitKind::ByteStr(..)
2314            | LitKind::CStr(..)
2315            | LitKind::Byte(..)
2316            | LitKind::Char(..)
2317            | LitKind::Int(_, LitIntType::Unsuffixed)
2318            | LitKind::Float(_, LitFloatType::Unsuffixed)
2319            | LitKind::Bool(..)
2320            | LitKind::Err(_) => false,
2321        }
2322    }
2323}
2324
2325// N.B., If you change this, you'll probably want to change the corresponding
2326// type structure in `middle/ty.rs` as well.
2327#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2328pub struct MutTy {
2329    pub ty: Box<Ty>,
2330    pub mutbl: Mutability,
2331}
2332
2333/// Represents a function's signature in a trait declaration,
2334/// trait implementation, or free function.
2335#[derive(Clone, Encodable, Decodable, Debug)]
2336pub struct FnSig {
2337    pub header: FnHeader,
2338    pub decl: Box<FnDecl>,
2339    pub span: Span,
2340}
2341
2342impl FnSig {
2343    /// Return a span encompassing the header, or where to insert it if empty.
2344    pub fn header_span(&self) -> Span {
2345        match self.header.ext {
2346            Extern::Implicit(span) | Extern::Explicit(_, span) => {
2347                return self.span.with_hi(span.hi());
2348            }
2349            Extern::None => {}
2350        }
2351
2352        match self.header.safety {
2353            Safety::Unsafe(span) | Safety::Safe(span) => return self.span.with_hi(span.hi()),
2354            Safety::Default => {}
2355        };
2356
2357        if let Some(coroutine_kind) = self.header.coroutine_kind {
2358            return self.span.with_hi(coroutine_kind.span().hi());
2359        }
2360
2361        if let Const::Yes(span) = self.header.constness {
2362            return self.span.with_hi(span.hi());
2363        }
2364
2365        self.span.shrink_to_lo()
2366    }
2367
2368    /// The span of the header's safety, or where to insert it if empty.
2369    pub fn safety_span(&self) -> Span {
2370        match self.header.safety {
2371            Safety::Unsafe(span) | Safety::Safe(span) => span,
2372            Safety::Default => {
2373                // Insert after the `coroutine_kind` if available.
2374                if let Some(extern_span) = self.header.ext.span() {
2375                    return extern_span.shrink_to_lo();
2376                }
2377
2378                // Insert right at the front of the signature.
2379                self.header_span().shrink_to_hi()
2380            }
2381        }
2382    }
2383
2384    /// The span of the header's extern, or where to insert it if empty.
2385    pub fn extern_span(&self) -> Span {
2386        self.header.ext.span().unwrap_or(self.safety_span().shrink_to_hi())
2387    }
2388}
2389
2390/// A constraint on an associated item.
2391///
2392/// ### Examples
2393///
2394/// * the `A = Ty` and `B = Ty` in `Trait<A = Ty, B = Ty>`
2395/// * the `G<Ty> = Ty` in `Trait<G<Ty> = Ty>`
2396/// * the `A: Bound` in `Trait<A: Bound>`
2397/// * the `RetTy` in `Trait(ArgTy, ArgTy) -> RetTy`
2398/// * the `C = { Ct }` in `Trait<C = { Ct }>` (feature `associated_const_equality`)
2399/// * the `f(..): Bound` in `Trait<f(..): Bound>` (feature `return_type_notation`)
2400#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2401pub struct AssocItemConstraint {
2402    pub id: NodeId,
2403    pub ident: Ident,
2404    pub gen_args: Option<GenericArgs>,
2405    pub kind: AssocItemConstraintKind,
2406    pub span: Span,
2407}
2408
2409#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2410pub enum Term {
2411    Ty(Box<Ty>),
2412    Const(AnonConst),
2413}
2414
2415impl From<Box<Ty>> for Term {
2416    fn from(v: Box<Ty>) -> Self {
2417        Term::Ty(v)
2418    }
2419}
2420
2421impl From<AnonConst> for Term {
2422    fn from(v: AnonConst) -> Self {
2423        Term::Const(v)
2424    }
2425}
2426
2427/// The kind of [associated item constraint][AssocItemConstraint].
2428#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2429pub enum AssocItemConstraintKind {
2430    /// An equality constraint for an associated item (e.g., `AssocTy = Ty` in `Trait<AssocTy = Ty>`).
2431    ///
2432    /// Also known as an *associated item binding* (we *bind* an associated item to a term).
2433    ///
2434    /// Furthermore, associated type equality constraints can also be referred to as *associated type
2435    /// bindings*. Similarly with associated const equality constraints and *associated const bindings*.
2436    Equality { term: Term },
2437    /// A bound on an associated type (e.g., `AssocTy: Bound` in `Trait<AssocTy: Bound>`).
2438    Bound {
2439        #[visitable(extra = BoundKind::Bound)]
2440        bounds: GenericBounds,
2441    },
2442}
2443
2444#[derive(Encodable, Decodable, Debug, Walkable)]
2445pub struct Ty {
2446    pub id: NodeId,
2447    pub kind: TyKind,
2448    pub span: Span,
2449    pub tokens: Option<LazyAttrTokenStream>,
2450}
2451
2452impl Clone for Ty {
2453    fn clone(&self) -> Self {
2454        ensure_sufficient_stack(|| Self {
2455            id: self.id,
2456            kind: self.kind.clone(),
2457            span: self.span,
2458            tokens: self.tokens.clone(),
2459        })
2460    }
2461}
2462
2463impl From<Box<Ty>> for Ty {
2464    fn from(value: Box<Ty>) -> Self {
2465        *value
2466    }
2467}
2468
2469impl Ty {
2470    pub fn peel_refs(&self) -> &Self {
2471        let mut final_ty = self;
2472        while let TyKind::Ref(_, MutTy { ty, .. }) | TyKind::Ptr(MutTy { ty, .. }) = &final_ty.kind
2473        {
2474            final_ty = ty;
2475        }
2476        final_ty
2477    }
2478
2479    pub fn is_maybe_parenthesised_infer(&self) -> bool {
2480        match &self.kind {
2481            TyKind::Infer => true,
2482            TyKind::Paren(inner) => inner.is_maybe_parenthesised_infer(),
2483            _ => false,
2484        }
2485    }
2486}
2487
2488#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2489pub struct FnPtrTy {
2490    pub safety: Safety,
2491    pub ext: Extern,
2492    pub generic_params: ThinVec<GenericParam>,
2493    pub decl: Box<FnDecl>,
2494    /// Span of the `[unsafe] [extern] fn(...) -> ...` part, i.e. everything
2495    /// after the generic params (if there are any, e.g. `for<'a>`).
2496    pub decl_span: Span,
2497}
2498
2499#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2500pub struct UnsafeBinderTy {
2501    pub generic_params: ThinVec<GenericParam>,
2502    pub inner_ty: Box<Ty>,
2503}
2504
2505/// The various kinds of type recognized by the compiler.
2506//
2507// Adding a new variant? Please update `test_ty` in `tests/ui/macros/stringify.rs`.
2508#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2509pub enum TyKind {
2510    /// A variable-length slice (`[T]`).
2511    Slice(Box<Ty>),
2512    /// A fixed length array (`[T; n]`).
2513    Array(Box<Ty>, AnonConst),
2514    /// A raw pointer (`*const T` or `*mut T`).
2515    Ptr(MutTy),
2516    /// A reference (`&'a T` or `&'a mut T`).
2517    Ref(#[visitable(extra = LifetimeCtxt::Ref)] Option<Lifetime>, MutTy),
2518    /// A pinned reference (`&'a pin const T` or `&'a pin mut T`).
2519    ///
2520    /// Desugars into `Pin<&'a T>` or `Pin<&'a mut T>`.
2521    PinnedRef(#[visitable(extra = LifetimeCtxt::Ref)] Option<Lifetime>, MutTy),
2522    /// A function pointer type (e.g., `fn(usize) -> bool`).
2523    FnPtr(Box<FnPtrTy>),
2524    /// An unsafe existential lifetime binder (e.g., `unsafe<'a> &'a ()`).
2525    UnsafeBinder(Box<UnsafeBinderTy>),
2526    /// The never type (`!`).
2527    Never,
2528    /// A tuple (`(A, B, C, D,...)`).
2529    Tup(ThinVec<Box<Ty>>),
2530    /// A path (`module::module::...::Type`), optionally
2531    /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2532    ///
2533    /// Type parameters are stored in the `Path` itself.
2534    Path(Option<Box<QSelf>>, Path),
2535    /// A trait object type `Bound1 + Bound2 + Bound3`
2536    /// where `Bound` is a trait or a lifetime.
2537    TraitObject(#[visitable(extra = BoundKind::TraitObject)] GenericBounds, TraitObjectSyntax),
2538    /// An `impl Bound1 + Bound2 + Bound3` type
2539    /// where `Bound` is a trait or a lifetime.
2540    ///
2541    /// The `NodeId` exists to prevent lowering from having to
2542    /// generate `NodeId`s on the fly, which would complicate
2543    /// the generation of opaque `type Foo = impl Trait` items significantly.
2544    ImplTrait(NodeId, #[visitable(extra = BoundKind::Impl)] GenericBounds),
2545    /// No-op; kept solely so that we can pretty-print faithfully.
2546    Paren(Box<Ty>),
2547    /// This means the type should be inferred instead of it having been
2548    /// specified. This can appear anywhere in a type.
2549    Infer,
2550    /// Inferred type of a `self` or `&self` argument in a method.
2551    ImplicitSelf,
2552    /// A macro in the type position.
2553    MacCall(Box<MacCall>),
2554    /// Placeholder for a `va_list`.
2555    CVarArgs,
2556    /// Pattern types like `pattern_type!(u32 is 1..=)`, which is the same as `NonZero<u32>`,
2557    /// just as part of the type system.
2558    Pat(Box<Ty>, Box<TyPat>),
2559    /// Sometimes we need a dummy value when no error has occurred.
2560    Dummy,
2561    /// Placeholder for a kind that has failed to be defined.
2562    Err(ErrorGuaranteed),
2563}
2564
2565impl TyKind {
2566    pub fn is_implicit_self(&self) -> bool {
2567        matches!(self, TyKind::ImplicitSelf)
2568    }
2569
2570    pub fn is_unit(&self) -> bool {
2571        matches!(self, TyKind::Tup(tys) if tys.is_empty())
2572    }
2573
2574    pub fn is_simple_path(&self) -> Option<Symbol> {
2575        if let TyKind::Path(None, Path { segments, .. }) = &self
2576            && let [segment] = &segments[..]
2577            && segment.args.is_none()
2578        {
2579            Some(segment.ident.name)
2580        } else {
2581            None
2582        }
2583    }
2584
2585    /// Returns `true` if this type is considered a scalar primitive (e.g.,
2586    /// `i32`, `u8`, `bool`, etc).
2587    ///
2588    /// This check is based on **symbol equality** and does **not** remove any
2589    /// path prefixes or references. If a type alias or shadowing is present
2590    /// (e.g., `type i32 = CustomType;`), this method will still return `true`
2591    /// for `i32`, even though it may not refer to the primitive type.
2592    pub fn maybe_scalar(&self) -> bool {
2593        let Some(ty_sym) = self.is_simple_path() else {
2594            // unit type
2595            return self.is_unit();
2596        };
2597        matches!(
2598            ty_sym,
2599            sym::i8
2600                | sym::i16
2601                | sym::i32
2602                | sym::i64
2603                | sym::i128
2604                | sym::u8
2605                | sym::u16
2606                | sym::u32
2607                | sym::u64
2608                | sym::u128
2609                | sym::f16
2610                | sym::f32
2611                | sym::f64
2612                | sym::f128
2613                | sym::char
2614                | sym::bool
2615        )
2616    }
2617}
2618
2619/// A pattern type pattern.
2620#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2621pub struct TyPat {
2622    pub id: NodeId,
2623    pub kind: TyPatKind,
2624    pub span: Span,
2625    pub tokens: Option<LazyAttrTokenStream>,
2626}
2627
2628/// All the different flavors of pattern that Rust recognizes.
2629//
2630// Adding a new variant? Please update `test_pat` in `tests/ui/macros/stringify.rs`.
2631#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2632pub enum TyPatKind {
2633    /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
2634    Range(Option<Box<AnonConst>>, Option<Box<AnonConst>>, Spanned<RangeEnd>),
2635
2636    /// A `!null` pattern for raw pointers.
2637    NotNull,
2638
2639    Or(ThinVec<TyPat>),
2640
2641    /// Placeholder for a pattern that wasn't syntactically well formed in some way.
2642    Err(ErrorGuaranteed),
2643}
2644
2645/// Syntax used to declare a trait object.
2646#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
2647#[repr(u8)]
2648pub enum TraitObjectSyntax {
2649    // SAFETY: When adding new variants make sure to update the `Tag` impl.
2650    Dyn = 0,
2651    None = 1,
2652}
2653
2654/// SAFETY: `TraitObjectSyntax` only has 3 data-less variants which means
2655/// it can be represented with a `u2`. We use `repr(u8)` to guarantee the
2656/// discriminants of the variants are no greater than `3`.
2657unsafe impl Tag for TraitObjectSyntax {
2658    const BITS: u32 = 2;
2659
2660    fn into_usize(self) -> usize {
2661        self as u8 as usize
2662    }
2663
2664    unsafe fn from_usize(tag: usize) -> Self {
2665        match tag {
2666            0 => TraitObjectSyntax::Dyn,
2667            1 => TraitObjectSyntax::None,
2668            _ => unreachable!(),
2669        }
2670    }
2671}
2672
2673#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2674pub enum PreciseCapturingArg {
2675    /// Lifetime parameter.
2676    Lifetime(#[visitable(extra = LifetimeCtxt::GenericArg)] Lifetime),
2677    /// Type or const parameter.
2678    Arg(Path, NodeId),
2679}
2680
2681/// Inline assembly operand explicit register or register class.
2682///
2683/// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2684#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
2685pub enum InlineAsmRegOrRegClass {
2686    Reg(Symbol),
2687    RegClass(Symbol),
2688}
2689
2690#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)]
2691pub struct InlineAsmOptions(u16);
2692bitflags::bitflags! {
2693    impl InlineAsmOptions: u16 {
2694        const PURE            = 1 << 0;
2695        const NOMEM           = 1 << 1;
2696        const READONLY        = 1 << 2;
2697        const PRESERVES_FLAGS = 1 << 3;
2698        const NORETURN        = 1 << 4;
2699        const NOSTACK         = 1 << 5;
2700        const ATT_SYNTAX      = 1 << 6;
2701        const RAW             = 1 << 7;
2702        const MAY_UNWIND      = 1 << 8;
2703    }
2704}
2705
2706impl InlineAsmOptions {
2707    pub const COUNT: usize = Self::all().bits().count_ones() as usize;
2708
2709    pub const GLOBAL_OPTIONS: Self = Self::ATT_SYNTAX.union(Self::RAW);
2710    pub const NAKED_OPTIONS: Self = Self::ATT_SYNTAX.union(Self::RAW);
2711
2712    pub fn human_readable_names(&self) -> Vec<&'static str> {
2713        let mut options = vec![];
2714
2715        if self.contains(InlineAsmOptions::PURE) {
2716            options.push("pure");
2717        }
2718        if self.contains(InlineAsmOptions::NOMEM) {
2719            options.push("nomem");
2720        }
2721        if self.contains(InlineAsmOptions::READONLY) {
2722            options.push("readonly");
2723        }
2724        if self.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2725            options.push("preserves_flags");
2726        }
2727        if self.contains(InlineAsmOptions::NORETURN) {
2728            options.push("noreturn");
2729        }
2730        if self.contains(InlineAsmOptions::NOSTACK) {
2731            options.push("nostack");
2732        }
2733        if self.contains(InlineAsmOptions::ATT_SYNTAX) {
2734            options.push("att_syntax");
2735        }
2736        if self.contains(InlineAsmOptions::RAW) {
2737            options.push("raw");
2738        }
2739        if self.contains(InlineAsmOptions::MAY_UNWIND) {
2740            options.push("may_unwind");
2741        }
2742
2743        options
2744    }
2745}
2746
2747impl std::fmt::Debug for InlineAsmOptions {
2748    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2749        bitflags::parser::to_writer(self, f)
2750    }
2751}
2752
2753#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic, Walkable)]
2754pub enum InlineAsmTemplatePiece {
2755    String(Cow<'static, str>),
2756    Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2757}
2758
2759impl fmt::Display for InlineAsmTemplatePiece {
2760    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2761        match self {
2762            Self::String(s) => {
2763                for c in s.chars() {
2764                    match c {
2765                        '{' => f.write_str("{{")?,
2766                        '}' => f.write_str("}}")?,
2767                        _ => c.fmt(f)?,
2768                    }
2769                }
2770                Ok(())
2771            }
2772            Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2773                write!(f, "{{{operand_idx}:{modifier}}}")
2774            }
2775            Self::Placeholder { operand_idx, modifier: None, .. } => {
2776                write!(f, "{{{operand_idx}}}")
2777            }
2778        }
2779    }
2780}
2781
2782impl InlineAsmTemplatePiece {
2783    /// Rebuilds the asm template string from its pieces.
2784    pub fn to_string(s: &[Self]) -> String {
2785        use fmt::Write;
2786        let mut out = String::new();
2787        for p in s.iter() {
2788            let _ = write!(out, "{p}");
2789        }
2790        out
2791    }
2792}
2793
2794/// Inline assembly symbol operands get their own AST node that is somewhat
2795/// similar to `AnonConst`.
2796///
2797/// The main difference is that we specifically don't assign it `DefId` in
2798/// `DefCollector`. Instead this is deferred until AST lowering where we
2799/// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2800/// depending on what the path resolves to.
2801#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2802pub struct InlineAsmSym {
2803    pub id: NodeId,
2804    pub qself: Option<Box<QSelf>>,
2805    pub path: Path,
2806}
2807
2808/// Inline assembly operand.
2809///
2810/// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2811#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2812pub enum InlineAsmOperand {
2813    In {
2814        reg: InlineAsmRegOrRegClass,
2815        expr: Box<Expr>,
2816    },
2817    Out {
2818        reg: InlineAsmRegOrRegClass,
2819        late: bool,
2820        expr: Option<Box<Expr>>,
2821    },
2822    InOut {
2823        reg: InlineAsmRegOrRegClass,
2824        late: bool,
2825        expr: Box<Expr>,
2826    },
2827    SplitInOut {
2828        reg: InlineAsmRegOrRegClass,
2829        late: bool,
2830        in_expr: Box<Expr>,
2831        out_expr: Option<Box<Expr>>,
2832    },
2833    Const {
2834        anon_const: AnonConst,
2835    },
2836    Sym {
2837        sym: InlineAsmSym,
2838    },
2839    Label {
2840        block: Box<Block>,
2841    },
2842}
2843
2844impl InlineAsmOperand {
2845    pub fn reg(&self) -> Option<&InlineAsmRegOrRegClass> {
2846        match self {
2847            Self::In { reg, .. }
2848            | Self::Out { reg, .. }
2849            | Self::InOut { reg, .. }
2850            | Self::SplitInOut { reg, .. } => Some(reg),
2851            Self::Const { .. } | Self::Sym { .. } | Self::Label { .. } => None,
2852        }
2853    }
2854}
2855
2856#[derive(Clone, Copy, Encodable, Decodable, Debug, HashStable_Generic, Walkable, PartialEq, Eq)]
2857pub enum AsmMacro {
2858    /// The `asm!` macro
2859    Asm,
2860    /// The `global_asm!` macro
2861    GlobalAsm,
2862    /// The `naked_asm!` macro
2863    NakedAsm,
2864}
2865
2866impl AsmMacro {
2867    pub const fn macro_name(self) -> &'static str {
2868        match self {
2869            AsmMacro::Asm => "asm",
2870            AsmMacro::GlobalAsm => "global_asm",
2871            AsmMacro::NakedAsm => "naked_asm",
2872        }
2873    }
2874
2875    pub const fn is_supported_option(self, option: InlineAsmOptions) -> bool {
2876        match self {
2877            AsmMacro::Asm => true,
2878            AsmMacro::GlobalAsm => InlineAsmOptions::GLOBAL_OPTIONS.contains(option),
2879            AsmMacro::NakedAsm => InlineAsmOptions::NAKED_OPTIONS.contains(option),
2880        }
2881    }
2882
2883    pub const fn diverges(self, options: InlineAsmOptions) -> bool {
2884        match self {
2885            AsmMacro::Asm => options.contains(InlineAsmOptions::NORETURN),
2886            AsmMacro::GlobalAsm => true,
2887            AsmMacro::NakedAsm => true,
2888        }
2889    }
2890}
2891
2892/// Inline assembly.
2893///
2894/// E.g., `asm!("NOP");`.
2895#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2896pub struct InlineAsm {
2897    pub asm_macro: AsmMacro,
2898    pub template: Vec<InlineAsmTemplatePiece>,
2899    pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2900    pub operands: Vec<(InlineAsmOperand, Span)>,
2901    pub clobber_abis: Vec<(Symbol, Span)>,
2902    #[visitable(ignore)]
2903    pub options: InlineAsmOptions,
2904    pub line_spans: Vec<Span>,
2905}
2906
2907/// A parameter in a function header.
2908///
2909/// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2910#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2911pub struct Param {
2912    pub attrs: AttrVec,
2913    pub ty: Box<Ty>,
2914    pub pat: Box<Pat>,
2915    pub id: NodeId,
2916    pub span: Span,
2917    pub is_placeholder: bool,
2918}
2919
2920/// Alternative representation for `Arg`s describing `self` parameter of methods.
2921///
2922/// E.g., `&mut self` as in `fn foo(&mut self)`.
2923#[derive(Clone, Encodable, Decodable, Debug)]
2924pub enum SelfKind {
2925    /// `self`, `mut self`
2926    Value(Mutability),
2927    /// `&'lt self`, `&'lt mut self`
2928    Region(Option<Lifetime>, Mutability),
2929    /// `&'lt pin const self`, `&'lt pin mut self`
2930    Pinned(Option<Lifetime>, Mutability),
2931    /// `self: TYPE`, `mut self: TYPE`
2932    Explicit(Box<Ty>, Mutability),
2933}
2934
2935impl SelfKind {
2936    pub fn to_ref_suggestion(&self) -> String {
2937        match self {
2938            SelfKind::Region(None, mutbl) => mutbl.ref_prefix_str().to_string(),
2939            SelfKind::Region(Some(lt), mutbl) => format!("&{lt} {}", mutbl.prefix_str()),
2940            SelfKind::Pinned(None, mutbl) => format!("&pin {}", mutbl.ptr_str()),
2941            SelfKind::Pinned(Some(lt), mutbl) => format!("&{lt} pin {}", mutbl.ptr_str()),
2942            SelfKind::Value(_) | SelfKind::Explicit(_, _) => {
2943                unreachable!("if we had an explicit self, we wouldn't be here")
2944            }
2945        }
2946    }
2947}
2948
2949pub type ExplicitSelf = Spanned<SelfKind>;
2950
2951impl Param {
2952    /// Attempts to cast parameter to `ExplicitSelf`.
2953    pub fn to_self(&self) -> Option<ExplicitSelf> {
2954        if let PatKind::Ident(BindingMode(ByRef::No, mutbl), ident, _) = self.pat.kind {
2955            if ident.name == kw::SelfLower {
2956                return match self.ty.kind {
2957                    TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2958                    TyKind::Ref(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2959                        Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2960                    }
2961                    TyKind::PinnedRef(lt, MutTy { ref ty, mutbl })
2962                        if ty.kind.is_implicit_self() =>
2963                    {
2964                        Some(respan(self.pat.span, SelfKind::Pinned(lt, mutbl)))
2965                    }
2966                    _ => Some(respan(
2967                        self.pat.span.to(self.ty.span),
2968                        SelfKind::Explicit(self.ty.clone(), mutbl),
2969                    )),
2970                };
2971            }
2972        }
2973        None
2974    }
2975
2976    /// Returns `true` if parameter is `self`.
2977    pub fn is_self(&self) -> bool {
2978        if let PatKind::Ident(_, ident, _) = self.pat.kind {
2979            ident.name == kw::SelfLower
2980        } else {
2981            false
2982        }
2983    }
2984
2985    /// Builds a `Param` object from `ExplicitSelf`.
2986    pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2987        let span = eself.span.to(eself_ident.span);
2988        let infer_ty = Box::new(Ty {
2989            id: DUMMY_NODE_ID,
2990            kind: TyKind::ImplicitSelf,
2991            span: eself_ident.span,
2992            tokens: None,
2993        });
2994        let (mutbl, ty) = match eself.node {
2995            SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2996            SelfKind::Value(mutbl) => (mutbl, infer_ty),
2997            SelfKind::Region(lt, mutbl) => (
2998                Mutability::Not,
2999                Box::new(Ty {
3000                    id: DUMMY_NODE_ID,
3001                    kind: TyKind::Ref(lt, MutTy { ty: infer_ty, mutbl }),
3002                    span,
3003                    tokens: None,
3004                }),
3005            ),
3006            SelfKind::Pinned(lt, mutbl) => (
3007                mutbl,
3008                Box::new(Ty {
3009                    id: DUMMY_NODE_ID,
3010                    kind: TyKind::PinnedRef(lt, MutTy { ty: infer_ty, mutbl }),
3011                    span,
3012                    tokens: None,
3013                }),
3014            ),
3015        };
3016        Param {
3017            attrs,
3018            pat: Box::new(Pat {
3019                id: DUMMY_NODE_ID,
3020                kind: PatKind::Ident(BindingMode(ByRef::No, mutbl), eself_ident, None),
3021                span,
3022                tokens: None,
3023            }),
3024            span,
3025            ty,
3026            id: DUMMY_NODE_ID,
3027            is_placeholder: false,
3028        }
3029    }
3030}
3031
3032/// A signature (not the body) of a function declaration.
3033///
3034/// E.g., `fn foo(bar: baz)`.
3035///
3036/// Please note that it's different from `FnHeader` structure
3037/// which contains metadata about function safety, asyncness, constness and ABI.
3038#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3039pub struct FnDecl {
3040    pub inputs: ThinVec<Param>,
3041    pub output: FnRetTy,
3042}
3043
3044impl FnDecl {
3045    pub fn has_self(&self) -> bool {
3046        self.inputs.get(0).is_some_and(Param::is_self)
3047    }
3048    pub fn c_variadic(&self) -> bool {
3049        self.inputs.last().is_some_and(|arg| matches!(arg.ty.kind, TyKind::CVarArgs))
3050    }
3051}
3052
3053/// Is the trait definition an auto trait?
3054#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
3055pub enum IsAuto {
3056    Yes,
3057    No,
3058}
3059
3060/// Safety of items.
3061#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
3062#[derive(HashStable_Generic, Walkable)]
3063pub enum Safety {
3064    /// `unsafe` an item is explicitly marked as `unsafe`.
3065    Unsafe(Span),
3066    /// `safe` an item is explicitly marked as `safe`.
3067    Safe(Span),
3068    /// Default means no value was provided, it will take a default value given the context in
3069    /// which is used.
3070    Default,
3071}
3072
3073/// Describes what kind of coroutine markers, if any, a function has.
3074///
3075/// Coroutine markers are things that cause the function to generate a coroutine, such as `async`,
3076/// which makes the function return `impl Future`, or `gen`, which makes the function return `impl
3077/// Iterator`.
3078#[derive(Copy, Clone, Encodable, Decodable, Debug, Walkable)]
3079pub enum CoroutineKind {
3080    /// `async`, which returns an `impl Future`.
3081    Async { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
3082    /// `gen`, which returns an `impl Iterator`.
3083    Gen { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
3084    /// `async gen`, which returns an `impl AsyncIterator`.
3085    AsyncGen { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
3086}
3087
3088impl CoroutineKind {
3089    pub fn span(self) -> Span {
3090        match self {
3091            CoroutineKind::Async { span, .. } => span,
3092            CoroutineKind::Gen { span, .. } => span,
3093            CoroutineKind::AsyncGen { span, .. } => span,
3094        }
3095    }
3096
3097    pub fn as_str(self) -> &'static str {
3098        match self {
3099            CoroutineKind::Async { .. } => "async",
3100            CoroutineKind::Gen { .. } => "gen",
3101            CoroutineKind::AsyncGen { .. } => "async gen",
3102        }
3103    }
3104
3105    pub fn closure_id(self) -> NodeId {
3106        match self {
3107            CoroutineKind::Async { closure_id, .. }
3108            | CoroutineKind::Gen { closure_id, .. }
3109            | CoroutineKind::AsyncGen { closure_id, .. } => closure_id,
3110        }
3111    }
3112
3113    /// In this case this is an `async` or `gen` return, the `NodeId` for the generated `impl Trait`
3114    /// item.
3115    pub fn return_id(self) -> (NodeId, Span) {
3116        match self {
3117            CoroutineKind::Async { return_impl_trait_id, span, .. }
3118            | CoroutineKind::Gen { return_impl_trait_id, span, .. }
3119            | CoroutineKind::AsyncGen { return_impl_trait_id, span, .. } => {
3120                (return_impl_trait_id, span)
3121            }
3122        }
3123    }
3124}
3125
3126#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
3127#[derive(HashStable_Generic, Walkable)]
3128pub enum Const {
3129    Yes(Span),
3130    No,
3131}
3132
3133/// Item defaultness.
3134/// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
3135#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
3136pub enum Defaultness {
3137    Default(Span),
3138    Final,
3139}
3140
3141#[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic, Walkable)]
3142pub enum ImplPolarity {
3143    /// `impl Trait for Type`
3144    Positive,
3145    /// `impl !Trait for Type`
3146    Negative(Span),
3147}
3148
3149impl fmt::Debug for ImplPolarity {
3150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3151        match *self {
3152            ImplPolarity::Positive => "positive".fmt(f),
3153            ImplPolarity::Negative(_) => "negative".fmt(f),
3154        }
3155    }
3156}
3157
3158/// The polarity of a trait bound.
3159#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash)]
3160#[derive(HashStable_Generic, Walkable)]
3161pub enum BoundPolarity {
3162    /// `Type: Trait`
3163    Positive,
3164    /// `Type: !Trait`
3165    Negative(Span),
3166    /// `Type: ?Trait`
3167    Maybe(Span),
3168}
3169
3170impl BoundPolarity {
3171    pub fn as_str(self) -> &'static str {
3172        match self {
3173            Self::Positive => "",
3174            Self::Negative(_) => "!",
3175            Self::Maybe(_) => "?",
3176        }
3177    }
3178}
3179
3180/// The constness of a trait bound.
3181#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash)]
3182#[derive(HashStable_Generic, Walkable)]
3183pub enum BoundConstness {
3184    /// `Type: Trait`
3185    Never,
3186    /// `Type: const Trait`
3187    Always(Span),
3188    /// `Type: [const] Trait`
3189    Maybe(Span),
3190}
3191
3192impl BoundConstness {
3193    pub fn as_str(self) -> &'static str {
3194        match self {
3195            Self::Never => "",
3196            Self::Always(_) => "const",
3197            Self::Maybe(_) => "[const]",
3198        }
3199    }
3200}
3201
3202/// The asyncness of a trait bound.
3203#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
3204#[derive(HashStable_Generic, Walkable)]
3205pub enum BoundAsyncness {
3206    /// `Type: Trait`
3207    Normal,
3208    /// `Type: async Trait`
3209    Async(Span),
3210}
3211
3212impl BoundAsyncness {
3213    pub fn as_str(self) -> &'static str {
3214        match self {
3215            Self::Normal => "",
3216            Self::Async(_) => "async",
3217        }
3218    }
3219}
3220
3221#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3222pub enum FnRetTy {
3223    /// Returns type is not specified.
3224    ///
3225    /// Functions default to `()` and closures default to inference.
3226    /// Span points to where return type would be inserted.
3227    Default(Span),
3228    /// Everything else.
3229    Ty(Box<Ty>),
3230}
3231
3232impl FnRetTy {
3233    pub fn span(&self) -> Span {
3234        match self {
3235            &FnRetTy::Default(span) => span,
3236            FnRetTy::Ty(ty) => ty.span,
3237        }
3238    }
3239}
3240
3241#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, Walkable)]
3242pub enum Inline {
3243    Yes,
3244    No { had_parse_error: Result<(), ErrorGuaranteed> },
3245}
3246
3247/// Module item kind.
3248#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3249pub enum ModKind {
3250    /// Module with inlined definition `mod foo { ... }`,
3251    /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
3252    /// The inner span is from the first token past `{` to the last token until `}`,
3253    /// or from the first to the last token in the loaded file.
3254    Loaded(ThinVec<Box<Item>>, Inline, ModSpans),
3255    /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
3256    Unloaded,
3257}
3258
3259#[derive(Copy, Clone, Encodable, Decodable, Debug, Default, Walkable)]
3260pub struct ModSpans {
3261    /// `inner_span` covers the body of the module; for a file module, its the whole file.
3262    /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
3263    pub inner_span: Span,
3264    pub inject_use_span: Span,
3265}
3266
3267/// Foreign module declaration.
3268///
3269/// E.g., `extern { .. }` or `extern "C" { .. }`.
3270#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3271pub struct ForeignMod {
3272    /// Span of the `extern` keyword.
3273    pub extern_span: Span,
3274    /// `unsafe` keyword accepted syntactically for macro DSLs, but not
3275    /// semantically by Rust.
3276    pub safety: Safety,
3277    pub abi: Option<StrLit>,
3278    pub items: ThinVec<Box<ForeignItem>>,
3279}
3280
3281#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3282pub struct EnumDef {
3283    pub variants: ThinVec<Variant>,
3284}
3285
3286/// Enum variant.
3287#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3288pub struct Variant {
3289    /// Attributes of the variant.
3290    pub attrs: AttrVec,
3291    /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
3292    pub id: NodeId,
3293    /// Span
3294    pub span: Span,
3295    /// The visibility of the variant. Syntactically accepted but not semantically.
3296    pub vis: Visibility,
3297    /// Name of the variant.
3298    pub ident: Ident,
3299
3300    /// Fields and constructor id of the variant.
3301    pub data: VariantData,
3302    /// Explicit discriminant, e.g., `Foo = 1`.
3303    pub disr_expr: Option<AnonConst>,
3304    /// Is a macro placeholder.
3305    pub is_placeholder: bool,
3306}
3307
3308/// Part of `use` item to the right of its prefix.
3309#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3310pub enum UseTreeKind {
3311    /// `use prefix` or `use prefix as rename`
3312    Simple(Option<Ident>),
3313    /// `use prefix::{...}`
3314    ///
3315    /// The span represents the braces of the nested group and all elements within:
3316    ///
3317    /// ```text
3318    /// use foo::{bar, baz};
3319    ///          ^^^^^^^^^^
3320    /// ```
3321    Nested { items: ThinVec<(UseTree, NodeId)>, span: Span },
3322    /// `use prefix::*`
3323    Glob,
3324}
3325
3326/// A tree of paths sharing common prefixes.
3327/// Used in `use` items both at top-level and inside of braces in import groups.
3328#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3329pub struct UseTree {
3330    pub prefix: Path,
3331    pub kind: UseTreeKind,
3332    pub span: Span,
3333}
3334
3335impl UseTree {
3336    pub fn ident(&self) -> Ident {
3337        match self.kind {
3338            UseTreeKind::Simple(Some(rename)) => rename,
3339            UseTreeKind::Simple(None) => {
3340                self.prefix.segments.last().expect("empty prefix in a simple import").ident
3341            }
3342            _ => panic!("`UseTree::ident` can only be used on a simple import"),
3343        }
3344    }
3345}
3346
3347/// Distinguishes between `Attribute`s that decorate items and Attributes that
3348/// are contained as statements within items. These two cases need to be
3349/// distinguished for pretty-printing.
3350#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic, Walkable)]
3351pub enum AttrStyle {
3352    Outer,
3353    Inner,
3354}
3355
3356/// A list of attributes.
3357pub type AttrVec = ThinVec<Attribute>;
3358
3359/// A syntax-level representation of an attribute.
3360#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3361pub struct Attribute {
3362    pub kind: AttrKind,
3363    pub id: AttrId,
3364    /// Denotes if the attribute decorates the following construct (outer)
3365    /// or the construct this attribute is contained within (inner).
3366    pub style: AttrStyle,
3367    pub span: Span,
3368}
3369
3370#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3371pub enum AttrKind {
3372    /// A normal attribute.
3373    Normal(Box<NormalAttr>),
3374
3375    /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
3376    /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
3377    /// variant (which is much less compact and thus more expensive).
3378    DocComment(CommentKind, Symbol),
3379}
3380
3381#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3382pub struct NormalAttr {
3383    pub item: AttrItem,
3384    // Tokens for the full attribute, e.g. `#[foo]`, `#![bar]`.
3385    pub tokens: Option<LazyAttrTokenStream>,
3386}
3387
3388impl NormalAttr {
3389    pub fn from_ident(ident: Ident) -> Self {
3390        Self {
3391            item: AttrItem {
3392                unsafety: Safety::Default,
3393                path: Path::from_ident(ident),
3394                args: AttrItemKind::Unparsed(AttrArgs::Empty),
3395                tokens: None,
3396            },
3397            tokens: None,
3398        }
3399    }
3400}
3401
3402#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3403pub struct AttrItem {
3404    pub unsafety: Safety,
3405    pub path: Path,
3406    pub args: AttrItemKind,
3407    // Tokens for the meta item, e.g. just the `foo` within `#[foo]` or `#![foo]`.
3408    pub tokens: Option<LazyAttrTokenStream>,
3409}
3410
3411/// Some attributes are stored in a parsed form, for performance reasons.
3412/// Their arguments don't have to be reparsed everytime they're used
3413#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3414pub enum AttrItemKind {
3415    Parsed(EarlyParsedAttribute),
3416    Unparsed(AttrArgs),
3417}
3418
3419impl AttrItemKind {
3420    pub fn unparsed(self) -> Option<AttrArgs> {
3421        match self {
3422            AttrItemKind::Unparsed(args) => Some(args),
3423            AttrItemKind::Parsed(_) => None,
3424        }
3425    }
3426
3427    pub fn unparsed_ref(&self) -> Option<&AttrArgs> {
3428        match self {
3429            AttrItemKind::Unparsed(args) => Some(args),
3430            AttrItemKind::Parsed(_) => None,
3431        }
3432    }
3433
3434    pub fn span(&self) -> Option<Span> {
3435        match self {
3436            AttrItemKind::Unparsed(args) => args.span(),
3437            AttrItemKind::Parsed(_) => None,
3438        }
3439    }
3440}
3441
3442/// Some attributes are stored in parsed form in the AST.
3443/// This is done for performance reasons, so the attributes don't need to be reparsed on every use.
3444///
3445/// Currently all early parsed attributes are excluded from pretty printing at rustc_ast_pretty::pprust::state::print_attribute_inline.
3446/// When adding new early parsed attributes, consider whether they should be pretty printed.
3447#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
3448pub enum EarlyParsedAttribute {
3449    CfgTrace(CfgEntry),
3450    CfgAttrTrace,
3451}
3452
3453impl AttrItem {
3454    pub fn is_valid_for_outer_style(&self) -> bool {
3455        self.path == sym::cfg_attr
3456            || self.path == sym::cfg
3457            || self.path == sym::forbid
3458            || self.path == sym::warn
3459            || self.path == sym::allow
3460            || self.path == sym::deny
3461    }
3462}
3463
3464/// `TraitRef`s appear in impls.
3465///
3466/// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
3467/// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
3468/// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
3469/// same as the impl's `NodeId`).
3470#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3471pub struct TraitRef {
3472    pub path: Path,
3473    pub ref_id: NodeId,
3474}
3475
3476/// Whether enclosing parentheses are present or not.
3477#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3478pub enum Parens {
3479    Yes,
3480    No,
3481}
3482
3483#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3484pub struct PolyTraitRef {
3485    /// The `'a` in `for<'a> Foo<&'a T>`.
3486    pub bound_generic_params: ThinVec<GenericParam>,
3487
3488    // Optional constness, asyncness, or polarity.
3489    pub modifiers: TraitBoundModifiers,
3490
3491    /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
3492    pub trait_ref: TraitRef,
3493
3494    pub span: Span,
3495
3496    /// When `Yes`, the first and last character of `span` are an opening
3497    /// and a closing paren respectively.
3498    pub parens: Parens,
3499}
3500
3501impl PolyTraitRef {
3502    pub fn new(
3503        generic_params: ThinVec<GenericParam>,
3504        path: Path,
3505        modifiers: TraitBoundModifiers,
3506        span: Span,
3507        parens: Parens,
3508    ) -> Self {
3509        PolyTraitRef {
3510            bound_generic_params: generic_params,
3511            modifiers,
3512            trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
3513            span,
3514            parens,
3515        }
3516    }
3517}
3518
3519#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3520pub struct Visibility {
3521    pub kind: VisibilityKind,
3522    pub span: Span,
3523    pub tokens: Option<LazyAttrTokenStream>,
3524}
3525
3526#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3527pub enum VisibilityKind {
3528    Public,
3529    Restricted { path: Box<Path>, id: NodeId, shorthand: bool },
3530    Inherited,
3531}
3532
3533impl VisibilityKind {
3534    pub fn is_pub(&self) -> bool {
3535        matches!(self, VisibilityKind::Public)
3536    }
3537}
3538
3539/// Field definition in a struct, variant or union.
3540///
3541/// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
3542#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3543pub struct FieldDef {
3544    pub attrs: AttrVec,
3545    pub id: NodeId,
3546    pub span: Span,
3547    pub vis: Visibility,
3548    pub safety: Safety,
3549    pub ident: Option<Ident>,
3550
3551    pub ty: Box<Ty>,
3552    pub default: Option<AnonConst>,
3553    pub is_placeholder: bool,
3554}
3555
3556/// Was parsing recovery performed?
3557#[derive(Copy, Clone, Debug, Encodable, Decodable, HashStable_Generic, Walkable)]
3558pub enum Recovered {
3559    No,
3560    Yes(ErrorGuaranteed),
3561}
3562
3563/// Fields and constructor ids of enum variants and structs.
3564#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3565pub enum VariantData {
3566    /// Struct variant.
3567    ///
3568    /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
3569    Struct { fields: ThinVec<FieldDef>, recovered: Recovered },
3570    /// Tuple variant.
3571    ///
3572    /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
3573    Tuple(ThinVec<FieldDef>, NodeId),
3574    /// Unit variant.
3575    ///
3576    /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
3577    Unit(NodeId),
3578}
3579
3580impl VariantData {
3581    /// Return the fields of this variant.
3582    pub fn fields(&self) -> &[FieldDef] {
3583        match self {
3584            VariantData::Struct { fields, .. } | VariantData::Tuple(fields, _) => fields,
3585            _ => &[],
3586        }
3587    }
3588
3589    /// Return the `NodeId` of this variant's constructor, if it has one.
3590    pub fn ctor_node_id(&self) -> Option<NodeId> {
3591        match *self {
3592            VariantData::Struct { .. } => None,
3593            VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
3594        }
3595    }
3596}
3597
3598/// An item definition.
3599#[derive(Clone, Encodable, Decodable, Debug)]
3600pub struct Item<K = ItemKind> {
3601    pub attrs: AttrVec,
3602    pub id: NodeId,
3603    pub span: Span,
3604    pub vis: Visibility,
3605
3606    pub kind: K,
3607
3608    /// Original tokens this item was parsed from. This isn't necessarily
3609    /// available for all items, although over time more and more items should
3610    /// have this be `Some`. Right now this is primarily used for procedural
3611    /// macros, notably custom attributes.
3612    ///
3613    /// Note that the tokens here do not include the outer attributes, but will
3614    /// include inner attributes.
3615    pub tokens: Option<LazyAttrTokenStream>,
3616}
3617
3618impl Item {
3619    /// Return the span that encompasses the attributes.
3620    pub fn span_with_attributes(&self) -> Span {
3621        self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
3622    }
3623
3624    pub fn opt_generics(&self) -> Option<&Generics> {
3625        match &self.kind {
3626            ItemKind::ExternCrate(..)
3627            | ItemKind::Use(_)
3628            | ItemKind::Mod(..)
3629            | ItemKind::ForeignMod(_)
3630            | ItemKind::GlobalAsm(_)
3631            | ItemKind::MacCall(_)
3632            | ItemKind::Delegation(_)
3633            | ItemKind::DelegationMac(_)
3634            | ItemKind::MacroDef(..) => None,
3635            ItemKind::Static(_) => None,
3636            ItemKind::Const(i) => Some(&i.generics),
3637            ItemKind::Fn(i) => Some(&i.generics),
3638            ItemKind::TyAlias(i) => Some(&i.generics),
3639            ItemKind::TraitAlias(i) => Some(&i.generics),
3640
3641            ItemKind::Enum(_, generics, _)
3642            | ItemKind::Struct(_, generics, _)
3643            | ItemKind::Union(_, generics, _) => Some(&generics),
3644            ItemKind::Trait(i) => Some(&i.generics),
3645            ItemKind::Impl(i) => Some(&i.generics),
3646        }
3647    }
3648}
3649
3650/// `extern` qualifier on a function item or function type.
3651#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
3652pub enum Extern {
3653    /// No explicit extern keyword was used.
3654    ///
3655    /// E.g. `fn foo() {}`.
3656    None,
3657    /// An explicit extern keyword was used, but with implicit ABI.
3658    ///
3659    /// E.g. `extern fn foo() {}`.
3660    ///
3661    /// This is just `extern "C"` (see `rustc_abi::ExternAbi::FALLBACK`).
3662    Implicit(Span),
3663    /// An explicit extern keyword was used with an explicit ABI.
3664    ///
3665    /// E.g. `extern "C" fn foo() {}`.
3666    Explicit(StrLit, Span),
3667}
3668
3669impl Extern {
3670    pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
3671        match abi {
3672            Some(name) => Extern::Explicit(name, span),
3673            None => Extern::Implicit(span),
3674        }
3675    }
3676
3677    pub fn span(self) -> Option<Span> {
3678        match self {
3679            Extern::None => None,
3680            Extern::Implicit(span) | Extern::Explicit(_, span) => Some(span),
3681        }
3682    }
3683}
3684
3685/// A function header.
3686///
3687/// All the information between the visibility and the name of the function is
3688/// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
3689#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
3690pub struct FnHeader {
3691    /// The `const` keyword, if any
3692    pub constness: Const,
3693    /// Whether this is `async`, `gen`, or nothing.
3694    pub coroutine_kind: Option<CoroutineKind>,
3695    /// Whether this is `unsafe`, or has a default safety.
3696    pub safety: Safety,
3697    /// The `extern` keyword and corresponding ABI string, if any.
3698    pub ext: Extern,
3699}
3700
3701impl FnHeader {
3702    /// Does this function header have any qualifiers or is it empty?
3703    pub fn has_qualifiers(&self) -> bool {
3704        let Self { safety, coroutine_kind, constness, ext } = self;
3705        matches!(safety, Safety::Unsafe(_))
3706            || coroutine_kind.is_some()
3707            || matches!(constness, Const::Yes(_))
3708            || !matches!(ext, Extern::None)
3709    }
3710}
3711
3712impl Default for FnHeader {
3713    fn default() -> FnHeader {
3714        FnHeader {
3715            safety: Safety::Default,
3716            coroutine_kind: None,
3717            constness: Const::No,
3718            ext: Extern::None,
3719        }
3720    }
3721}
3722
3723#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3724pub struct TraitAlias {
3725    pub constness: Const,
3726    pub ident: Ident,
3727    pub generics: Generics,
3728    #[visitable(extra = BoundKind::Bound)]
3729    pub bounds: GenericBounds,
3730}
3731
3732#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3733pub struct Trait {
3734    pub constness: Const,
3735    pub safety: Safety,
3736    pub is_auto: IsAuto,
3737    pub ident: Ident,
3738    pub generics: Generics,
3739    #[visitable(extra = BoundKind::SuperTraits)]
3740    pub bounds: GenericBounds,
3741    #[visitable(extra = AssocCtxt::Trait)]
3742    pub items: ThinVec<Box<AssocItem>>,
3743}
3744
3745#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3746pub struct TyAlias {
3747    pub defaultness: Defaultness,
3748    pub ident: Ident,
3749    pub generics: Generics,
3750    /// There are two locations for where clause on type aliases. This represents the second
3751    /// where clause, before the semicolon. The first where clause is stored inside `generics`.
3752    ///
3753    /// Take this example:
3754    /// ```ignore (only-for-syntax-highlight)
3755    /// trait Foo {
3756    ///   type Assoc<'a, 'b> where Self: 'a, Self: 'b;
3757    /// }
3758    /// impl Foo for () {
3759    ///   type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
3760    ///   //                 ^^^^^^^^^^^^^^ before where clause
3761    ///   //                                     ^^^^^^^^^^^^^^ after where clause
3762    /// }
3763    /// ```
3764    pub after_where_clause: WhereClause,
3765    #[visitable(extra = BoundKind::Bound)]
3766    pub bounds: GenericBounds,
3767    pub ty: Option<Box<Ty>>,
3768}
3769
3770#[derive(Clone, Encodable, Decodable, Debug)]
3771pub struct Impl {
3772    pub generics: Generics,
3773    pub constness: Const,
3774    pub of_trait: Option<Box<TraitImplHeader>>,
3775    pub self_ty: Box<Ty>,
3776    pub items: ThinVec<Box<AssocItem>>,
3777}
3778
3779#[derive(Clone, Encodable, Decodable, Debug)]
3780pub struct TraitImplHeader {
3781    pub defaultness: Defaultness,
3782    pub safety: Safety,
3783    pub polarity: ImplPolarity,
3784    pub trait_ref: TraitRef,
3785}
3786
3787#[derive(Clone, Encodable, Decodable, Debug, Default, Walkable)]
3788pub struct FnContract {
3789    /// Declarations of variables accessible both in the `requires` and
3790    /// `ensures` clauses.
3791    pub declarations: ThinVec<Stmt>,
3792    pub requires: Option<Box<Expr>>,
3793    pub ensures: Option<Box<Expr>>,
3794}
3795
3796#[derive(Clone, Encodable, Decodable, Debug)]
3797pub struct Fn {
3798    pub defaultness: Defaultness,
3799    pub ident: Ident,
3800    pub generics: Generics,
3801    pub sig: FnSig,
3802    pub contract: Option<Box<FnContract>>,
3803    pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
3804    pub body: Option<Box<Block>>,
3805
3806    /// This function is an implementation of an externally implementable item (EII).
3807    /// This means, there was an EII declared somewhere and this function is the
3808    /// implementation that should be run when the declaration is called.
3809    pub eii_impls: ThinVec<EiiImpl>,
3810}
3811
3812#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3813pub struct EiiImpl {
3814    pub node_id: NodeId,
3815    pub eii_macro_path: Path,
3816    pub impl_safety: Safety,
3817    pub span: Span,
3818    pub inner_span: Span,
3819    pub is_default: bool,
3820}
3821
3822#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3823pub struct Delegation {
3824    /// Path resolution id.
3825    pub id: NodeId,
3826    pub qself: Option<Box<QSelf>>,
3827    pub path: Path,
3828    pub ident: Ident,
3829    pub rename: Option<Ident>,
3830    pub body: Option<Box<Block>>,
3831    /// The item was expanded from a glob delegation item.
3832    pub from_glob: bool,
3833}
3834
3835#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3836pub struct DelegationMac {
3837    pub qself: Option<Box<QSelf>>,
3838    pub prefix: Path,
3839    // Some for list delegation, and None for glob delegation.
3840    pub suffixes: Option<ThinVec<(Ident, Option<Ident>)>>,
3841    pub body: Option<Box<Block>>,
3842}
3843
3844#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3845pub struct StaticItem {
3846    pub ident: Ident,
3847    pub ty: Box<Ty>,
3848    pub safety: Safety,
3849    pub mutability: Mutability,
3850    pub expr: Option<Box<Expr>>,
3851    pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
3852}
3853
3854#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3855pub struct ConstItem {
3856    pub defaultness: Defaultness,
3857    pub ident: Ident,
3858    pub generics: Generics,
3859    pub ty: Box<Ty>,
3860    pub rhs: Option<ConstItemRhs>,
3861    pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
3862}
3863
3864#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3865pub enum ConstItemRhs {
3866    TypeConst(AnonConst),
3867    Body(Box<Expr>),
3868}
3869
3870impl ConstItemRhs {
3871    pub fn span(&self) -> Span {
3872        self.expr().span
3873    }
3874
3875    pub fn expr(&self) -> &Expr {
3876        match self {
3877            ConstItemRhs::TypeConst(anon_const) => &anon_const.value,
3878            ConstItemRhs::Body(expr) => expr,
3879        }
3880    }
3881}
3882
3883// Adding a new variant? Please update `test_item` in `tests/ui/macros/stringify.rs`.
3884#[derive(Clone, Encodable, Decodable, Debug)]
3885pub enum ItemKind {
3886    /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
3887    ///
3888    /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3889    ExternCrate(Option<Symbol>, Ident),
3890    /// A use declaration item (`use`).
3891    ///
3892    /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
3893    Use(UseTree),
3894    /// A static item (`static`).
3895    ///
3896    /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
3897    Static(Box<StaticItem>),
3898    /// A constant item (`const`).
3899    ///
3900    /// E.g., `const FOO: i32 = 42;`.
3901    Const(Box<ConstItem>),
3902    /// A function declaration (`fn`).
3903    ///
3904    /// E.g., `fn foo(bar: usize) -> usize { .. }`.
3905    Fn(Box<Fn>),
3906    /// A module declaration (`mod`).
3907    ///
3908    /// E.g., `mod foo;` or `mod foo { .. }`.
3909    /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
3910    /// semantically by Rust.
3911    Mod(Safety, Ident, ModKind),
3912    /// An external module (`extern`).
3913    ///
3914    /// E.g., `extern {}` or `extern "C" {}`.
3915    ForeignMod(ForeignMod),
3916    /// Module-level inline assembly (from `global_asm!()`).
3917    GlobalAsm(Box<InlineAsm>),
3918    /// A type alias (`type`).
3919    ///
3920    /// E.g., `type Foo = Bar<u8>;`.
3921    TyAlias(Box<TyAlias>),
3922    /// An enum definition (`enum`).
3923    ///
3924    /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
3925    Enum(Ident, Generics, EnumDef),
3926    /// A struct definition (`struct`).
3927    ///
3928    /// E.g., `struct Foo<A> { x: A }`.
3929    Struct(Ident, Generics, VariantData),
3930    /// A union definition (`union`).
3931    ///
3932    /// E.g., `union Foo<A, B> { x: A, y: B }`.
3933    Union(Ident, Generics, VariantData),
3934    /// A trait declaration (`trait`).
3935    ///
3936    /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
3937    Trait(Box<Trait>),
3938    /// Trait alias.
3939    ///
3940    /// E.g., `trait Foo = Bar + Quux;`.
3941    TraitAlias(Box<TraitAlias>),
3942    /// An implementation.
3943    ///
3944    /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
3945    Impl(Impl),
3946    /// A macro invocation.
3947    ///
3948    /// E.g., `foo!(..)`.
3949    MacCall(Box<MacCall>),
3950    /// A macro definition.
3951    MacroDef(Ident, MacroDef),
3952    /// A single delegation item (`reuse`).
3953    ///
3954    /// E.g. `reuse <Type as Trait>::name { target_expr_template }`.
3955    Delegation(Box<Delegation>),
3956    /// A list or glob delegation item (`reuse prefix::{a, b, c}`, `reuse prefix::*`).
3957    /// Treated similarly to a macro call and expanded early.
3958    DelegationMac(Box<DelegationMac>),
3959}
3960
3961impl ItemKind {
3962    pub fn ident(&self) -> Option<Ident> {
3963        match *self {
3964            ItemKind::ExternCrate(_, ident)
3965            | ItemKind::Static(box StaticItem { ident, .. })
3966            | ItemKind::Const(box ConstItem { ident, .. })
3967            | ItemKind::Fn(box Fn { ident, .. })
3968            | ItemKind::Mod(_, ident, _)
3969            | ItemKind::TyAlias(box TyAlias { ident, .. })
3970            | ItemKind::Enum(ident, ..)
3971            | ItemKind::Struct(ident, ..)
3972            | ItemKind::Union(ident, ..)
3973            | ItemKind::Trait(box Trait { ident, .. })
3974            | ItemKind::TraitAlias(box TraitAlias { ident, .. })
3975            | ItemKind::MacroDef(ident, _)
3976            | ItemKind::Delegation(box Delegation { ident, .. }) => Some(ident),
3977
3978            ItemKind::Use(_)
3979            | ItemKind::ForeignMod(_)
3980            | ItemKind::GlobalAsm(_)
3981            | ItemKind::Impl(_)
3982            | ItemKind::MacCall(_)
3983            | ItemKind::DelegationMac(_) => None,
3984        }
3985    }
3986
3987    /// "a" or "an"
3988    pub fn article(&self) -> &'static str {
3989        use ItemKind::*;
3990        match self {
3991            Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
3992            | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..)
3993            | Delegation(..) | DelegationMac(..) => "a",
3994            ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
3995        }
3996    }
3997
3998    pub fn descr(&self) -> &'static str {
3999        match self {
4000            ItemKind::ExternCrate(..) => "extern crate",
4001            ItemKind::Use(..) => "`use` import",
4002            ItemKind::Static(..) => "static item",
4003            ItemKind::Const(..) => "constant item",
4004            ItemKind::Fn(..) => "function",
4005            ItemKind::Mod(..) => "module",
4006            ItemKind::ForeignMod(..) => "extern block",
4007            ItemKind::GlobalAsm(..) => "global asm item",
4008            ItemKind::TyAlias(..) => "type alias",
4009            ItemKind::Enum(..) => "enum",
4010            ItemKind::Struct(..) => "struct",
4011            ItemKind::Union(..) => "union",
4012            ItemKind::Trait(..) => "trait",
4013            ItemKind::TraitAlias(..) => "trait alias",
4014            ItemKind::MacCall(..) => "item macro invocation",
4015            ItemKind::MacroDef(..) => "macro definition",
4016            ItemKind::Impl { .. } => "implementation",
4017            ItemKind::Delegation(..) => "delegated function",
4018            ItemKind::DelegationMac(..) => "delegation",
4019        }
4020    }
4021
4022    pub fn generics(&self) -> Option<&Generics> {
4023        match self {
4024            Self::Fn(box Fn { generics, .. })
4025            | Self::TyAlias(box TyAlias { generics, .. })
4026            | Self::Const(box ConstItem { generics, .. })
4027            | Self::Enum(_, generics, _)
4028            | Self::Struct(_, generics, _)
4029            | Self::Union(_, generics, _)
4030            | Self::Trait(box Trait { generics, .. })
4031            | Self::TraitAlias(box TraitAlias { generics, .. })
4032            | Self::Impl(Impl { generics, .. }) => Some(generics),
4033            _ => None,
4034        }
4035    }
4036}
4037
4038/// Represents associated items.
4039/// These include items in `impl` and `trait` definitions.
4040pub type AssocItem = Item<AssocItemKind>;
4041
4042/// Represents associated item kinds.
4043///
4044/// The term "provided" in the variants below refers to the item having a default
4045/// definition / body. Meanwhile, a "required" item lacks a definition / body.
4046/// In an implementation, all items must be provided.
4047/// The `Option`s below denote the bodies, where `Some(_)`
4048/// means "provided" and conversely `None` means "required".
4049#[derive(Clone, Encodable, Decodable, Debug)]
4050pub enum AssocItemKind {
4051    /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
4052    /// If `def` is parsed, then the constant is provided, and otherwise required.
4053    Const(Box<ConstItem>),
4054    /// An associated function.
4055    Fn(Box<Fn>),
4056    /// An associated type.
4057    Type(Box<TyAlias>),
4058    /// A macro expanding to associated items.
4059    MacCall(Box<MacCall>),
4060    /// An associated delegation item.
4061    Delegation(Box<Delegation>),
4062    /// An associated list or glob delegation item.
4063    DelegationMac(Box<DelegationMac>),
4064}
4065
4066impl AssocItemKind {
4067    pub fn ident(&self) -> Option<Ident> {
4068        match *self {
4069            AssocItemKind::Const(box ConstItem { ident, .. })
4070            | AssocItemKind::Fn(box Fn { ident, .. })
4071            | AssocItemKind::Type(box TyAlias { ident, .. })
4072            | AssocItemKind::Delegation(box Delegation { ident, .. }) => Some(ident),
4073
4074            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(_) => None,
4075        }
4076    }
4077
4078    pub fn defaultness(&self) -> Defaultness {
4079        match *self {
4080            Self::Const(box ConstItem { defaultness, .. })
4081            | Self::Fn(box Fn { defaultness, .. })
4082            | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
4083            Self::MacCall(..) | Self::Delegation(..) | Self::DelegationMac(..) => {
4084                Defaultness::Final
4085            }
4086        }
4087    }
4088}
4089
4090impl From<AssocItemKind> for ItemKind {
4091    fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
4092        match assoc_item_kind {
4093            AssocItemKind::Const(item) => ItemKind::Const(item),
4094            AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
4095            AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
4096            AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
4097            AssocItemKind::Delegation(delegation) => ItemKind::Delegation(delegation),
4098            AssocItemKind::DelegationMac(delegation) => ItemKind::DelegationMac(delegation),
4099        }
4100    }
4101}
4102
4103impl TryFrom<ItemKind> for AssocItemKind {
4104    type Error = ItemKind;
4105
4106    fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
4107        Ok(match item_kind {
4108            ItemKind::Const(item) => AssocItemKind::Const(item),
4109            ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
4110            ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
4111            ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
4112            ItemKind::Delegation(d) => AssocItemKind::Delegation(d),
4113            ItemKind::DelegationMac(d) => AssocItemKind::DelegationMac(d),
4114            _ => return Err(item_kind),
4115        })
4116    }
4117}
4118
4119/// An item in `extern` block.
4120#[derive(Clone, Encodable, Decodable, Debug)]
4121pub enum ForeignItemKind {
4122    /// A foreign static item (`static FOO: u8`).
4123    Static(Box<StaticItem>),
4124    /// A foreign function.
4125    Fn(Box<Fn>),
4126    /// A foreign type.
4127    TyAlias(Box<TyAlias>),
4128    /// A macro expanding to foreign items.
4129    MacCall(Box<MacCall>),
4130}
4131
4132impl ForeignItemKind {
4133    pub fn ident(&self) -> Option<Ident> {
4134        match *self {
4135            ForeignItemKind::Static(box StaticItem { ident, .. })
4136            | ForeignItemKind::Fn(box Fn { ident, .. })
4137            | ForeignItemKind::TyAlias(box TyAlias { ident, .. }) => Some(ident),
4138
4139            ForeignItemKind::MacCall(_) => None,
4140        }
4141    }
4142}
4143
4144impl From<ForeignItemKind> for ItemKind {
4145    fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
4146        match foreign_item_kind {
4147            ForeignItemKind::Static(box static_foreign_item) => {
4148                ItemKind::Static(Box::new(static_foreign_item))
4149            }
4150            ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
4151            ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
4152            ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
4153        }
4154    }
4155}
4156
4157impl TryFrom<ItemKind> for ForeignItemKind {
4158    type Error = ItemKind;
4159
4160    fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
4161        Ok(match item_kind {
4162            ItemKind::Static(box static_item) => ForeignItemKind::Static(Box::new(static_item)),
4163            ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
4164            ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
4165            ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
4166            _ => return Err(item_kind),
4167        })
4168    }
4169}
4170
4171pub type ForeignItem = Item<ForeignItemKind>;
4172
4173// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
4174#[cfg(target_pointer_width = "64")]
4175mod size_asserts {
4176    use rustc_data_structures::static_assert_size;
4177
4178    use super::*;
4179    // tidy-alphabetical-start
4180    static_assert_size!(AssocItem, 80);
4181    static_assert_size!(AssocItemKind, 16);
4182    static_assert_size!(Attribute, 32);
4183    static_assert_size!(Block, 32);
4184    static_assert_size!(Expr, 72);
4185    static_assert_size!(ExprKind, 40);
4186    static_assert_size!(Fn, 192);
4187    static_assert_size!(ForeignItem, 80);
4188    static_assert_size!(ForeignItemKind, 16);
4189    static_assert_size!(GenericArg, 24);
4190    static_assert_size!(GenericBound, 88);
4191    static_assert_size!(Generics, 40);
4192    static_assert_size!(Impl, 80);
4193    static_assert_size!(Item, 152);
4194    static_assert_size!(ItemKind, 88);
4195    static_assert_size!(LitKind, 24);
4196    static_assert_size!(Local, 96);
4197    static_assert_size!(MetaItemLit, 40);
4198    static_assert_size!(Param, 40);
4199    static_assert_size!(Pat, 80);
4200    static_assert_size!(PatKind, 56);
4201    static_assert_size!(Path, 24);
4202    static_assert_size!(PathSegment, 24);
4203    static_assert_size!(Stmt, 32);
4204    static_assert_size!(StmtKind, 16);
4205    static_assert_size!(TraitImplHeader, 72);
4206    static_assert_size!(Ty, 64);
4207    static_assert_size!(TyKind, 40);
4208    // tidy-alphabetical-end
4209}