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