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