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