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