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