rustc_hir/
hir.rs

1// ignore-tidy-filelength
2use std::borrow::Cow;
3use std::fmt;
4
5use rustc_abi::ExternAbi;
6use rustc_ast::attr::AttributeExt;
7use rustc_ast::token::DocFragmentKind;
8use rustc_ast::util::parser::ExprPrecedence;
9use rustc_ast::{
10    self as ast, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitIntType,
11    LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind, join_path_idents,
12};
13pub use rustc_ast::{
14    AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
15    BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
16    MetaItemInner, MetaItemLit, Movability, Mutability, Pinnedness, UnOp,
17};
18use rustc_data_structures::fingerprint::Fingerprint;
19use rustc_data_structures::sorted_map::SortedMap;
20use rustc_data_structures::tagged_ptr::TaggedRef;
21use rustc_error_messages::{DiagArgValue, IntoDiagArg};
22use rustc_index::IndexVec;
23use rustc_macros::{Decodable, Encodable, HashStable_Generic};
24use rustc_span::def_id::LocalDefId;
25use rustc_span::source_map::Spanned;
26use rustc_span::{
27    BytePos, DUMMY_SP, DesugaringKind, ErrorGuaranteed, Ident, Span, Symbol, kw, sym,
28};
29use rustc_target::asm::InlineAsmRegOrRegClass;
30use smallvec::SmallVec;
31use thin_vec::ThinVec;
32use tracing::debug;
33
34use crate::attrs::AttributeKind;
35use crate::def::{CtorKind, DefKind, MacroKinds, PerNS, Res};
36use crate::def_id::{DefId, LocalDefIdMap};
37pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId};
38use crate::intravisit::{FnKind, VisitorExt};
39use crate::lints::DelayedLints;
40
41#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
42pub enum AngleBrackets {
43    /// E.g. `Path`.
44    Missing,
45    /// E.g. `Path<>`.
46    Empty,
47    /// E.g. `Path<T>`.
48    Full,
49}
50
51#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
52pub enum LifetimeSource {
53    /// E.g. `&Type`, `&'_ Type`, `&'a Type`, `&mut Type`, `&'_ mut Type`, `&'a mut Type`
54    Reference,
55
56    /// E.g. `ContainsLifetime`, `ContainsLifetime<>`, `ContainsLifetime<'_>`,
57    /// `ContainsLifetime<'a>`
58    Path { angle_brackets: AngleBrackets },
59
60    /// E.g. `impl Trait + '_`, `impl Trait + 'a`
61    OutlivesBound,
62
63    /// E.g. `impl Trait + use<'_>`, `impl Trait + use<'a>`
64    PreciseCapturing,
65
66    /// Other usages which have not yet been categorized. Feel free to
67    /// add new sources that you find useful.
68    ///
69    /// Some non-exhaustive examples:
70    /// - `where T: 'a`
71    /// - `fn(_: dyn Trait + 'a)`
72    Other,
73}
74
75#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
76pub enum LifetimeSyntax {
77    /// E.g. `&Type`, `ContainsLifetime`
78    Implicit,
79
80    /// E.g. `&'_ Type`, `ContainsLifetime<'_>`, `impl Trait + '_`, `impl Trait + use<'_>`
81    ExplicitAnonymous,
82
83    /// E.g. `&'a Type`, `ContainsLifetime<'a>`, `impl Trait + 'a`, `impl Trait + use<'a>`
84    ExplicitBound,
85}
86
87impl From<Ident> for LifetimeSyntax {
88    fn from(ident: Ident) -> Self {
89        let name = ident.name;
90
91        if name == sym::empty {
92            unreachable!("A lifetime name should never be empty");
93        } else if name == kw::UnderscoreLifetime {
94            LifetimeSyntax::ExplicitAnonymous
95        } else {
96            debug_assert!(name.as_str().starts_with('\''));
97            LifetimeSyntax::ExplicitBound
98        }
99    }
100}
101
102/// A lifetime. The valid field combinations are non-obvious and not all
103/// combinations are possible. The following example shows some of
104/// them. See also the comments on `LifetimeKind` and `LifetimeSource`.
105///
106/// ```
107/// #[repr(C)]
108/// struct S<'a>(&'a u32);       // res=Param, name='a, source=Reference, syntax=ExplicitBound
109/// unsafe extern "C" {
110///     fn f1(s: S);             // res=Param, name='_, source=Path, syntax=Implicit
111///     fn f2(s: S<'_>);         // res=Param, name='_, source=Path, syntax=ExplicitAnonymous
112///     fn f3<'a>(s: S<'a>);     // res=Param, name='a, source=Path, syntax=ExplicitBound
113/// }
114///
115/// struct St<'a> { x: &'a u32 } // res=Param, name='a, source=Reference, syntax=ExplicitBound
116/// fn f() {
117///     _ = St { x: &0 };        // res=Infer, name='_, source=Path, syntax=Implicit
118///     _ = St::<'_> { x: &0 };  // res=Infer, name='_, source=Path, syntax=ExplicitAnonymous
119/// }
120///
121/// struct Name<'a>(&'a str);    // res=Param,  name='a, source=Reference, syntax=ExplicitBound
122/// const A: Name = Name("a");   // res=Static, name='_, source=Path, syntax=Implicit
123/// const B: &str = "";          // res=Static, name='_, source=Reference, syntax=Implicit
124/// static C: &'_ str = "";      // res=Static, name='_, source=Reference, syntax=ExplicitAnonymous
125/// static D: &'static str = ""; // res=Static, name='static, source=Reference, syntax=ExplicitBound
126///
127/// trait Tr {}
128/// fn tr(_: Box<dyn Tr>) {}     // res=ImplicitObjectLifetimeDefault, name='_, source=Other, syntax=Implicit
129///
130/// fn capture_outlives<'a>() ->
131///     impl FnOnce() + 'a       // res=Param, ident='a, source=OutlivesBound, syntax=ExplicitBound
132/// {
133///     || {}
134/// }
135///
136/// fn capture_precise<'a>() ->
137///     impl FnOnce() + use<'a>  // res=Param, ident='a, source=PreciseCapturing, syntax=ExplicitBound
138/// {
139///     || {}
140/// }
141///
142/// // (commented out because these cases trigger errors)
143/// // struct S1<'a>(&'a str);   // res=Param, name='a, source=Reference, syntax=ExplicitBound
144/// // struct S2(S1);            // res=Error, name='_, source=Path, syntax=Implicit
145/// // struct S3(S1<'_>);        // res=Error, name='_, source=Path, syntax=ExplicitAnonymous
146/// // struct S4(S1<'a>);        // res=Error, name='a, source=Path, syntax=ExplicitBound
147/// ```
148///
149/// Some combinations that cannot occur are `LifetimeSyntax::Implicit` with
150/// `LifetimeSource::OutlivesBound` or `LifetimeSource::PreciseCapturing`
151/// — there's no way to "elide" these lifetimes.
152#[derive(Debug, Copy, Clone, HashStable_Generic)]
153// Raise the alignment to at least 4 bytes.
154// This is relied on in other parts of the compiler (for pointer tagging):
155// <https://github.com/rust-lang/rust/blob/ce5fdd7d42aba9a2925692e11af2bd39cf37798a/compiler/rustc_data_structures/src/tagged_ptr.rs#L163>
156// Removing this `repr(4)` will cause the compiler to not build on platforms
157// like `m68k` Linux, where the alignment of u32 and usize is only 2.
158// Since `repr(align)` may only raise alignment, this has no effect on
159// platforms where the alignment is already sufficient.
160#[repr(align(4))]
161pub struct Lifetime {
162    #[stable_hasher(ignore)]
163    pub hir_id: HirId,
164
165    /// Either a named lifetime definition (e.g. `'a`, `'static`) or an
166    /// anonymous lifetime (`'_`, either explicitly written, or inserted for
167    /// things like `&type`).
168    pub ident: Ident,
169
170    /// Semantics of this lifetime.
171    pub kind: LifetimeKind,
172
173    /// The context in which the lifetime occurred. See `Lifetime::suggestion`
174    /// for example use.
175    pub source: LifetimeSource,
176
177    /// The syntax that the user used to declare this lifetime. See
178    /// `Lifetime::suggestion` for example use.
179    pub syntax: LifetimeSyntax,
180}
181
182#[derive(Debug, Copy, Clone, HashStable_Generic)]
183pub enum ParamName {
184    /// Some user-given name like `T` or `'x`.
185    Plain(Ident),
186
187    /// Indicates an illegal name was given and an error has been
188    /// reported (so we should squelch other derived errors).
189    ///
190    /// Occurs when, e.g., `'_` is used in the wrong place, or a
191    /// lifetime name is duplicated.
192    Error(Ident),
193
194    /// Synthetic name generated when user elided a lifetime in an impl header.
195    ///
196    /// E.g., the lifetimes in cases like these:
197    /// ```ignore (fragment)
198    /// impl Foo for &u32
199    /// impl Foo<'_> for u32
200    /// ```
201    /// in that case, we rewrite to
202    /// ```ignore (fragment)
203    /// impl<'f> Foo for &'f u32
204    /// impl<'f> Foo<'f> for u32
205    /// ```
206    /// where `'f` is something like `Fresh(0)`. The indices are
207    /// unique per impl, but not necessarily continuous.
208    Fresh,
209}
210
211impl ParamName {
212    pub fn ident(&self) -> Ident {
213        match *self {
214            ParamName::Plain(ident) | ParamName::Error(ident) => ident,
215            ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
216        }
217    }
218}
219
220#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
221pub enum LifetimeKind {
222    /// User-given names or fresh (synthetic) names.
223    Param(LocalDefId),
224
225    /// Implicit lifetime in a context like `dyn Foo`. This is
226    /// distinguished from implicit lifetimes elsewhere because the
227    /// lifetime that they default to must appear elsewhere within the
228    /// enclosing type. This means that, in an `impl Trait` context, we
229    /// don't have to create a parameter for them. That is, `impl
230    /// Trait<Item = &u32>` expands to an opaque type like `type
231    /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
232    /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
233    /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
234    /// that surrounding code knows not to create a lifetime
235    /// parameter.
236    ImplicitObjectLifetimeDefault,
237
238    /// Indicates an error during lowering (usually `'_` in wrong place)
239    /// that was already reported.
240    Error,
241
242    /// User wrote an anonymous lifetime, either `'_` or nothing (which gets
243    /// converted to `'_`). The semantics of this lifetime should be inferred
244    /// by typechecking code.
245    Infer,
246
247    /// User wrote `'static` or nothing (which gets converted to `'_`).
248    Static,
249}
250
251impl LifetimeKind {
252    fn is_elided(&self) -> bool {
253        match self {
254            LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true,
255
256            // It might seem surprising that `Fresh` counts as not *elided*
257            // -- but this is because, as far as the code in the compiler is
258            // concerned -- `Fresh` variants act equivalently to "some fresh name".
259            // They correspond to early-bound regions on an impl, in other words.
260            LifetimeKind::Error | LifetimeKind::Param(..) | LifetimeKind::Static => false,
261        }
262    }
263}
264
265impl fmt::Display for Lifetime {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        self.ident.name.fmt(f)
268    }
269}
270
271impl Lifetime {
272    pub fn new(
273        hir_id: HirId,
274        ident: Ident,
275        kind: LifetimeKind,
276        source: LifetimeSource,
277        syntax: LifetimeSyntax,
278    ) -> Lifetime {
279        let lifetime = Lifetime { hir_id, ident, kind, source, syntax };
280
281        // Sanity check: elided lifetimes form a strict subset of anonymous lifetimes.
282        #[cfg(debug_assertions)]
283        match (lifetime.is_elided(), lifetime.is_anonymous()) {
284            (false, false) => {} // e.g. `'a`
285            (false, true) => {}  // e.g. explicit `'_`
286            (true, true) => {}   // e.g. `&x`
287            (true, false) => panic!("bad Lifetime"),
288        }
289
290        lifetime
291    }
292
293    pub fn is_elided(&self) -> bool {
294        self.kind.is_elided()
295    }
296
297    pub fn is_anonymous(&self) -> bool {
298        self.ident.name == kw::UnderscoreLifetime
299    }
300
301    pub fn is_implicit(&self) -> bool {
302        matches!(self.syntax, LifetimeSyntax::Implicit)
303    }
304
305    pub fn is_static(&self) -> bool {
306        self.kind == LifetimeKind::Static
307    }
308
309    pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
310        use LifetimeSource::*;
311        use LifetimeSyntax::*;
312
313        debug_assert!(new_lifetime.starts_with('\''));
314
315        match (self.syntax, self.source) {
316            // The user wrote `'a` or `'_`.
317            (ExplicitBound | ExplicitAnonymous, _) => (self.ident.span, format!("{new_lifetime}")),
318
319            // The user wrote `Path<T>`, and omitted the `'_,`.
320            (Implicit, Path { angle_brackets: AngleBrackets::Full }) => {
321                (self.ident.span, format!("{new_lifetime}, "))
322            }
323
324            // The user wrote `Path<>`, and omitted the `'_`..
325            (Implicit, Path { angle_brackets: AngleBrackets::Empty }) => {
326                (self.ident.span, format!("{new_lifetime}"))
327            }
328
329            // The user wrote `Path` and omitted the `<'_>`.
330            (Implicit, Path { angle_brackets: AngleBrackets::Missing }) => {
331                (self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
332            }
333
334            // The user wrote `&type` or `&mut type`.
335            (Implicit, Reference) => (self.ident.span, format!("{new_lifetime} ")),
336
337            (Implicit, source) => {
338                unreachable!("can't suggest for a implicit lifetime of {source:?}")
339            }
340        }
341    }
342}
343
344/// A `Path` is essentially Rust's notion of a name; for instance,
345/// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
346/// along with a bunch of supporting information.
347#[derive(Debug, Clone, Copy, HashStable_Generic)]
348pub struct Path<'hir, R = Res> {
349    pub span: Span,
350    /// The resolution for the path.
351    pub res: R,
352    /// The segments in the path: the things separated by `::`.
353    pub segments: &'hir [PathSegment<'hir>],
354}
355
356/// Up to three resolutions for type, value and macro namespaces.
357pub type UsePath<'hir> = Path<'hir, PerNS<Option<Res>>>;
358
359impl Path<'_> {
360    pub fn is_global(&self) -> bool {
361        self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
362    }
363}
364
365/// A segment of a path: an identifier, an optional lifetime, and a set of
366/// types.
367#[derive(Debug, Clone, Copy, HashStable_Generic)]
368pub struct PathSegment<'hir> {
369    /// The identifier portion of this path segment.
370    pub ident: Ident,
371    #[stable_hasher(ignore)]
372    pub hir_id: HirId,
373    pub res: Res,
374
375    /// Type/lifetime parameters attached to this path. They come in
376    /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
377    /// this is more than just simple syntactic sugar; the use of
378    /// parens affects the region binding rules, so we preserve the
379    /// distinction.
380    pub args: Option<&'hir GenericArgs<'hir>>,
381
382    /// Whether to infer remaining type parameters, if any.
383    /// This only applies to expression and pattern paths, and
384    /// out of those only the segments with no type parameters
385    /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
386    pub infer_args: bool,
387}
388
389impl<'hir> PathSegment<'hir> {
390    /// Converts an identifier to the corresponding segment.
391    pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
392        PathSegment { ident, hir_id, res, infer_args: true, args: None }
393    }
394
395    pub fn invalid() -> Self {
396        Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
397    }
398
399    pub fn args(&self) -> &GenericArgs<'hir> {
400        if let Some(ref args) = self.args {
401            args
402        } else {
403            const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
404            DUMMY
405        }
406    }
407}
408
409#[derive(Clone, Copy, Debug, HashStable_Generic)]
410pub enum ConstItemRhs<'hir> {
411    Body(BodyId),
412    TypeConst(&'hir ConstArg<'hir>),
413}
414
415impl<'hir> ConstItemRhs<'hir> {
416    pub fn hir_id(&self) -> HirId {
417        match self {
418            ConstItemRhs::Body(body_id) => body_id.hir_id,
419            ConstItemRhs::TypeConst(ct_arg) => ct_arg.hir_id,
420        }
421    }
422
423    pub fn span<'tcx>(&self, tcx: impl crate::intravisit::HirTyCtxt<'tcx>) -> Span {
424        match self {
425            ConstItemRhs::Body(body_id) => tcx.hir_body(*body_id).value.span,
426            ConstItemRhs::TypeConst(ct_arg) => ct_arg.span(),
427        }
428    }
429}
430
431/// A constant that enters the type system, used for arguments to const generics (e.g. array lengths).
432///
433/// These are distinct from [`AnonConst`] as anon consts in the type system are not allowed
434/// to use any generic parameters, therefore we must represent `N` differently. Additionally
435/// future designs for supporting generic parameters in const arguments will likely not use
436/// an anon const based design.
437///
438/// So, `ConstArg` (specifically, [`ConstArgKind`]) distinguishes between const args
439/// that are [just paths](ConstArgKind::Path) (currently just bare const params)
440/// versus const args that are literals or have arbitrary computations (e.g., `{ 1 + 3 }`).
441///
442/// For an explanation of the `Unambig` generic parameter see the dev-guide:
443/// <https://rustc-dev-guide.rust-lang.org/ambig-unambig-ty-and-consts.html>
444#[derive(Clone, Copy, Debug, HashStable_Generic)]
445#[repr(C)]
446pub struct ConstArg<'hir, Unambig = ()> {
447    #[stable_hasher(ignore)]
448    pub hir_id: HirId,
449    pub kind: ConstArgKind<'hir, Unambig>,
450}
451
452impl<'hir> ConstArg<'hir, AmbigArg> {
453    /// Converts a `ConstArg` in an ambiguous position to one in an unambiguous position.
454    ///
455    /// Functions accepting unambiguous consts may expect the [`ConstArgKind::Infer`] variant
456    /// to be used. Care should be taken to separately handle infer consts when calling this
457    /// function as it cannot be handled by downstream code making use of the returned const.
458    ///
459    /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or
460    /// specifically matching on [`GenericArg::Infer`] when handling generic arguments.
461    ///
462    /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer]
463    pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
464        // SAFETY: `ConstArg` is `repr(C)` and `ConstArgKind` is marked `repr(u8)` so that the
465        // layout is the same across different ZST type arguments.
466        let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
467        unsafe { &*ptr }
468    }
469}
470
471impl<'hir> ConstArg<'hir> {
472    /// Converts a `ConstArg` in an unambiguous position to one in an ambiguous position. This is
473    /// fallible as the [`ConstArgKind::Infer`] variant is not present in ambiguous positions.
474    ///
475    /// Functions accepting ambiguous consts will not handle the [`ConstArgKind::Infer`] variant, if
476    /// infer consts are relevant to you then care should be taken to handle them separately.
477    pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
478        if let ConstArgKind::Infer(_, ()) = self.kind {
479            return None;
480        }
481
482        // SAFETY: `ConstArg` is `repr(C)` and `ConstArgKind` is marked `repr(u8)` so that the layout is
483        // the same across different ZST type arguments. We also asserted that the `self` is
484        // not a `ConstArgKind::Infer` so there is no risk of transmuting a `()` to `AmbigArg`.
485        let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
486        Some(unsafe { &*ptr })
487    }
488}
489
490impl<'hir, Unambig> ConstArg<'hir, Unambig> {
491    pub fn anon_const_hir_id(&self) -> Option<HirId> {
492        match self.kind {
493            ConstArgKind::Anon(ac) => Some(ac.hir_id),
494            _ => None,
495        }
496    }
497
498    pub fn span(&self) -> Span {
499        match self.kind {
500            ConstArgKind::Struct(path, _) => path.span(),
501            ConstArgKind::Path(path) => path.span(),
502            ConstArgKind::TupleCall(path, _) => path.span(),
503            ConstArgKind::Anon(anon) => anon.span,
504            ConstArgKind::Error(span, _) => span,
505            ConstArgKind::Infer(span, _) => span,
506        }
507    }
508}
509
510/// See [`ConstArg`].
511#[derive(Clone, Copy, Debug, HashStable_Generic)]
512#[repr(u8, C)]
513pub enum ConstArgKind<'hir, Unambig = ()> {
514    /// **Note:** Currently this is only used for bare const params
515    /// (`N` where `fn foo<const N: usize>(...)`),
516    /// not paths to any const (`N` where `const N: usize = ...`).
517    ///
518    /// However, in the future, we'll be using it for all of those.
519    Path(QPath<'hir>),
520    Anon(&'hir AnonConst),
521    /// Represents construction of struct/struct variants
522    Struct(QPath<'hir>, &'hir [&'hir ConstArgExprField<'hir>]),
523    /// Tuple constructor variant
524    TupleCall(QPath<'hir>, &'hir [&'hir ConstArg<'hir>]),
525    /// Error const
526    Error(Span, ErrorGuaranteed),
527    /// This variant is not always used to represent inference consts, sometimes
528    /// [`GenericArg::Infer`] is used instead.
529    Infer(Span, Unambig),
530}
531
532#[derive(Clone, Copy, Debug, HashStable_Generic)]
533pub struct ConstArgExprField<'hir> {
534    pub hir_id: HirId,
535    pub span: Span,
536    pub field: Ident,
537    pub expr: &'hir ConstArg<'hir>,
538}
539
540#[derive(Clone, Copy, Debug, HashStable_Generic)]
541pub struct InferArg {
542    #[stable_hasher(ignore)]
543    pub hir_id: HirId,
544    pub span: Span,
545}
546
547impl InferArg {
548    pub fn to_ty(&self) -> Ty<'static> {
549        Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
550    }
551}
552
553#[derive(Debug, Clone, Copy, HashStable_Generic)]
554pub enum GenericArg<'hir> {
555    Lifetime(&'hir Lifetime),
556    Type(&'hir Ty<'hir, AmbigArg>),
557    Const(&'hir ConstArg<'hir, AmbigArg>),
558    /// Inference variables in [`GenericArg`] are always represented by
559    /// `GenericArg::Infer` instead of the `Infer` variants on [`TyKind`] and
560    /// [`ConstArgKind`] as it is not clear until hir ty lowering whether a
561    /// `_` argument is a type or const argument.
562    ///
563    /// However, some builtin types' generic arguments are represented by [`TyKind`]
564    /// without a [`GenericArg`], instead directly storing a [`Ty`] or [`ConstArg`]. In
565    /// such cases they *are* represented by the `Infer` variants on [`TyKind`] and
566    /// [`ConstArgKind`] as it is not ambiguous whether the argument is a type or const.
567    Infer(InferArg),
568}
569
570impl GenericArg<'_> {
571    pub fn span(&self) -> Span {
572        match self {
573            GenericArg::Lifetime(l) => l.ident.span,
574            GenericArg::Type(t) => t.span,
575            GenericArg::Const(c) => c.span(),
576            GenericArg::Infer(i) => i.span,
577        }
578    }
579
580    pub fn hir_id(&self) -> HirId {
581        match self {
582            GenericArg::Lifetime(l) => l.hir_id,
583            GenericArg::Type(t) => t.hir_id,
584            GenericArg::Const(c) => c.hir_id,
585            GenericArg::Infer(i) => i.hir_id,
586        }
587    }
588
589    pub fn descr(&self) -> &'static str {
590        match self {
591            GenericArg::Lifetime(_) => "lifetime",
592            GenericArg::Type(_) => "type",
593            GenericArg::Const(_) => "constant",
594            GenericArg::Infer(_) => "placeholder",
595        }
596    }
597
598    pub fn to_ord(&self) -> ast::ParamKindOrd {
599        match self {
600            GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
601            GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
602                ast::ParamKindOrd::TypeOrConst
603            }
604        }
605    }
606
607    pub fn is_ty_or_const(&self) -> bool {
608        match self {
609            GenericArg::Lifetime(_) => false,
610            GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
611        }
612    }
613}
614
615/// The generic arguments and associated item constraints of a path segment.
616#[derive(Debug, Clone, Copy, HashStable_Generic)]
617pub struct GenericArgs<'hir> {
618    /// The generic arguments for this path segment.
619    pub args: &'hir [GenericArg<'hir>],
620    /// The associated item constraints for this path segment.
621    pub constraints: &'hir [AssocItemConstraint<'hir>],
622    /// Whether the arguments were written in parenthesized form (e.g., `Fn(T) -> U`).
623    ///
624    /// This is required mostly for pretty-printing and diagnostics,
625    /// but also for changing lifetime elision rules to be "function-like".
626    pub parenthesized: GenericArgsParentheses,
627    /// The span encompassing the arguments, constraints and the surrounding brackets (`<>` or `()`).
628    ///
629    /// For example:
630    ///
631    /// ```ignore (illustrative)
632    ///       Foo<A, B, AssocTy = D>           Fn(T, U, V) -> W
633    ///          ^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^
634    /// ```
635    ///
636    /// Note that this may be:
637    /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
638    /// - dummy, if this was generated during desugaring
639    pub span_ext: Span,
640}
641
642impl<'hir> GenericArgs<'hir> {
643    pub const fn none() -> Self {
644        Self {
645            args: &[],
646            constraints: &[],
647            parenthesized: GenericArgsParentheses::No,
648            span_ext: DUMMY_SP,
649        }
650    }
651
652    /// Obtain the list of input types and the output type if the generic arguments are parenthesized.
653    ///
654    /// Returns the `Ty0, Ty1, ...` and the `RetTy` in `Trait(Ty0, Ty1, ...) -> RetTy`.
655    /// Panics if the parenthesized arguments have an incorrect form (this shouldn't happen).
656    pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
657        if self.parenthesized != GenericArgsParentheses::ParenSugar {
658            return None;
659        }
660
661        let inputs = self
662            .args
663            .iter()
664            .find_map(|arg| {
665                let GenericArg::Type(ty) = arg else { return None };
666                let TyKind::Tup(tys) = &ty.kind else { return None };
667                Some(tys)
668            })
669            .unwrap();
670
671        Some((inputs, self.paren_sugar_output_inner()))
672    }
673
674    /// Obtain the output type if the generic arguments are parenthesized.
675    ///
676    /// Returns the `RetTy` in `Trait(Ty0, Ty1, ...) -> RetTy`.
677    /// Panics if the parenthesized arguments have an incorrect form (this shouldn't happen).
678    pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
679        (self.parenthesized == GenericArgsParentheses::ParenSugar)
680            .then(|| self.paren_sugar_output_inner())
681    }
682
683    fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
684        let [constraint] = self.constraints.try_into().unwrap();
685        debug_assert_eq!(constraint.ident.name, sym::Output);
686        constraint.ty().unwrap()
687    }
688
689    pub fn has_err(&self) -> Option<ErrorGuaranteed> {
690        self.args
691            .iter()
692            .find_map(|arg| {
693                let GenericArg::Type(ty) = arg else { return None };
694                let TyKind::Err(guar) = ty.kind else { return None };
695                Some(guar)
696            })
697            .or_else(|| {
698                self.constraints.iter().find_map(|constraint| {
699                    let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
700                    Some(guar)
701                })
702            })
703    }
704
705    #[inline]
706    pub fn num_lifetime_params(&self) -> usize {
707        self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
708    }
709
710    #[inline]
711    pub fn has_lifetime_params(&self) -> bool {
712        self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
713    }
714
715    #[inline]
716    /// This function returns the number of type and const generic params.
717    /// It should only be used for diagnostics.
718    pub fn num_generic_params(&self) -> usize {
719        self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
720    }
721
722    /// The span encompassing the arguments and constraints[^1] inside the surrounding brackets.
723    ///
724    /// Returns `None` if the span is empty (i.e., no brackets) or dummy.
725    ///
726    /// [^1]: Unless of the form `-> Ty` (see [`GenericArgsParentheses`]).
727    pub fn span(&self) -> Option<Span> {
728        let span_ext = self.span_ext()?;
729        Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
730    }
731
732    /// Returns span encompassing arguments and their surrounding `<>` or `()`
733    pub fn span_ext(&self) -> Option<Span> {
734        Some(self.span_ext).filter(|span| !span.is_empty())
735    }
736
737    pub fn is_empty(&self) -> bool {
738        self.args.is_empty()
739    }
740}
741
742#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)]
743pub enum GenericArgsParentheses {
744    No,
745    /// Bounds for `feature(return_type_notation)`, like `T: Trait<method(..): Send>`,
746    /// where the args are explicitly elided with `..`
747    ReturnTypeNotation,
748    /// parenthesized function-family traits, like `T: Fn(u32) -> i32`
749    ParenSugar,
750}
751
752/// The modifiers on a trait bound.
753#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
754pub struct TraitBoundModifiers {
755    pub constness: BoundConstness,
756    pub polarity: BoundPolarity,
757}
758
759impl TraitBoundModifiers {
760    pub const NONE: Self =
761        TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
762}
763
764#[derive(Clone, Copy, Debug, HashStable_Generic)]
765pub enum GenericBound<'hir> {
766    Trait(PolyTraitRef<'hir>),
767    Outlives(&'hir Lifetime),
768    Use(&'hir [PreciseCapturingArg<'hir>], Span),
769}
770
771impl GenericBound<'_> {
772    pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
773        match self {
774            GenericBound::Trait(data) => Some(&data.trait_ref),
775            _ => None,
776        }
777    }
778
779    pub fn span(&self) -> Span {
780        match self {
781            GenericBound::Trait(t, ..) => t.span,
782            GenericBound::Outlives(l) => l.ident.span,
783            GenericBound::Use(_, span) => *span,
784        }
785    }
786}
787
788pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
789
790#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, Debug)]
791pub enum MissingLifetimeKind {
792    /// An explicit `'_`.
793    Underscore,
794    /// An elided lifetime `&' ty`.
795    Ampersand,
796    /// An elided lifetime in brackets with written brackets.
797    Comma,
798    /// An elided lifetime with elided brackets.
799    Brackets,
800}
801
802#[derive(Copy, Clone, Debug, HashStable_Generic)]
803pub enum LifetimeParamKind {
804    // Indicates that the lifetime definition was explicitly declared (e.g., in
805    // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
806    Explicit,
807
808    // Indication that the lifetime was elided (e.g., in both cases in
809    // `fn foo(x: &u8) -> &'_ u8 { x }`).
810    Elided(MissingLifetimeKind),
811
812    // Indication that the lifetime name was somehow in error.
813    Error,
814}
815
816#[derive(Debug, Clone, Copy, HashStable_Generic)]
817pub enum GenericParamKind<'hir> {
818    /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
819    Lifetime {
820        kind: LifetimeParamKind,
821    },
822    Type {
823        default: Option<&'hir Ty<'hir>>,
824        synthetic: bool,
825    },
826    Const {
827        ty: &'hir Ty<'hir>,
828        /// Optional default value for the const generic param
829        default: Option<&'hir ConstArg<'hir>>,
830    },
831}
832
833#[derive(Debug, Clone, Copy, HashStable_Generic)]
834pub struct GenericParam<'hir> {
835    #[stable_hasher(ignore)]
836    pub hir_id: HirId,
837    pub def_id: LocalDefId,
838    pub name: ParamName,
839    pub span: Span,
840    pub pure_wrt_drop: bool,
841    pub kind: GenericParamKind<'hir>,
842    pub colon_span: Option<Span>,
843    pub source: GenericParamSource,
844}
845
846impl<'hir> GenericParam<'hir> {
847    /// Synthetic type-parameters are inserted after normal ones.
848    /// In order for normal parameters to be able to refer to synthetic ones,
849    /// scans them first.
850    pub fn is_impl_trait(&self) -> bool {
851        matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
852    }
853
854    /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
855    ///
856    /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
857    pub fn is_elided_lifetime(&self) -> bool {
858        matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
859    }
860}
861
862/// Records where the generic parameter originated from.
863///
864/// This can either be from an item's generics, in which case it's typically
865/// early-bound (but can be a late-bound lifetime in functions, for example),
866/// or from a `for<...>` binder, in which case it's late-bound (and notably,
867/// does not show up in the parent item's generics).
868#[derive(Debug, Clone, Copy, HashStable_Generic)]
869pub enum GenericParamSource {
870    // Early or late-bound parameters defined on an item
871    Generics,
872    // Late-bound parameters defined via a `for<...>`
873    Binder,
874}
875
876#[derive(Default)]
877pub struct GenericParamCount {
878    pub lifetimes: usize,
879    pub types: usize,
880    pub consts: usize,
881    pub infer: usize,
882}
883
884/// Represents lifetimes and type parameters attached to a declaration
885/// of a function, enum, trait, etc.
886#[derive(Debug, Clone, Copy, HashStable_Generic)]
887pub struct Generics<'hir> {
888    pub params: &'hir [GenericParam<'hir>],
889    pub predicates: &'hir [WherePredicate<'hir>],
890    pub has_where_clause_predicates: bool,
891    pub where_clause_span: Span,
892    pub span: Span,
893}
894
895impl<'hir> Generics<'hir> {
896    pub const fn empty() -> &'hir Generics<'hir> {
897        const NOPE: Generics<'_> = Generics {
898            params: &[],
899            predicates: &[],
900            has_where_clause_predicates: false,
901            where_clause_span: DUMMY_SP,
902            span: DUMMY_SP,
903        };
904        &NOPE
905    }
906
907    pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
908        self.params.iter().find(|&param| name == param.name.ident().name)
909    }
910
911    /// If there are generic parameters, return where to introduce a new one.
912    pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
913        if let Some(first) = self.params.first()
914            && self.span.contains(first.span)
915        {
916            // `fn foo<A>(t: impl Trait)`
917            //         ^ suggest `'a, ` here
918            Some(first.span.shrink_to_lo())
919        } else {
920            None
921        }
922    }
923
924    /// If there are generic parameters, return where to introduce a new one.
925    pub fn span_for_param_suggestion(&self) -> Option<Span> {
926        self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
927            // `fn foo<A>(t: impl Trait)`
928            //          ^ suggest `, T: Trait` here
929            self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
930        })
931    }
932
933    /// `Span` where further predicates would be suggested, accounting for trailing commas, like
934    ///  in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
935    pub fn tail_span_for_predicate_suggestion(&self) -> Span {
936        let end = self.where_clause_span.shrink_to_hi();
937        if self.has_where_clause_predicates {
938            self.predicates
939                .iter()
940                .rfind(|&p| p.kind.in_where_clause())
941                .map_or(end, |p| p.span)
942                .shrink_to_hi()
943                .to(end)
944        } else {
945            end
946        }
947    }
948
949    pub fn add_where_or_trailing_comma(&self) -> &'static str {
950        if self.has_where_clause_predicates {
951            ","
952        } else if self.where_clause_span.is_empty() {
953            " where"
954        } else {
955            // No where clause predicates, but we have `where` token
956            ""
957        }
958    }
959
960    pub fn bounds_for_param(
961        &self,
962        param_def_id: LocalDefId,
963    ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
964        self.predicates.iter().filter_map(move |pred| match pred.kind {
965            WherePredicateKind::BoundPredicate(bp)
966                if bp.is_param_bound(param_def_id.to_def_id()) =>
967            {
968                Some(bp)
969            }
970            _ => None,
971        })
972    }
973
974    pub fn outlives_for_param(
975        &self,
976        param_def_id: LocalDefId,
977    ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
978        self.predicates.iter().filter_map(move |pred| match pred.kind {
979            WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
980            _ => None,
981        })
982    }
983
984    /// Returns a suggestable empty span right after the "final" bound of the generic parameter.
985    ///
986    /// If that bound needs to be wrapped in parentheses to avoid ambiguity with
987    /// subsequent bounds, it also returns an empty span for an open parenthesis
988    /// as the second component.
989    ///
990    /// E.g., adding `+ 'static` after `Fn() -> dyn Future<Output = ()>` or
991    /// `Fn() -> &'static dyn Debug` requires parentheses:
992    /// `Fn() -> (dyn Future<Output = ()>) + 'static` and
993    /// `Fn() -> &'static (dyn Debug) + 'static`, respectively.
994    pub fn bounds_span_for_suggestions(
995        &self,
996        param_def_id: LocalDefId,
997    ) -> Option<(Span, Option<Span>)> {
998        self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
999            |bound| {
1000                let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
1001                    && let [.., segment] = trait_ref.path.segments
1002                    && let Some(ret_ty) = segment.args().paren_sugar_output()
1003                    && let ret_ty = ret_ty.peel_refs()
1004                    && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
1005                    && let TraitObjectSyntax::Dyn = tagged_ptr.tag()
1006                    && ret_ty.span.can_be_used_for_suggestions()
1007                {
1008                    Some(ret_ty.span)
1009                } else {
1010                    None
1011                };
1012
1013                span_for_parentheses.map_or_else(
1014                    || {
1015                        // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1016                        // as we use this method to get a span appropriate for suggestions.
1017                        let bs = bound.span();
1018                        bs.can_be_used_for_suggestions().then(|| (bs.shrink_to_hi(), None))
1019                    },
1020                    |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
1021                )
1022            },
1023        )
1024    }
1025
1026    pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
1027        let predicate = &self.predicates[pos];
1028        let span = predicate.span;
1029
1030        if !predicate.kind.in_where_clause() {
1031            // <T: ?Sized, U>
1032            //   ^^^^^^^^
1033            return span;
1034        }
1035
1036        // We need to find out which comma to remove.
1037        if pos < self.predicates.len() - 1 {
1038            let next_pred = &self.predicates[pos + 1];
1039            if next_pred.kind.in_where_clause() {
1040                // where T: ?Sized, Foo: Bar,
1041                //       ^^^^^^^^^^^
1042                return span.until(next_pred.span);
1043            }
1044        }
1045
1046        if pos > 0 {
1047            let prev_pred = &self.predicates[pos - 1];
1048            if prev_pred.kind.in_where_clause() {
1049                // where Foo: Bar, T: ?Sized,
1050                //               ^^^^^^^^^^^
1051                return prev_pred.span.shrink_to_hi().to(span);
1052            }
1053        }
1054
1055        // This is the only predicate in the where clause.
1056        // where T: ?Sized
1057        // ^^^^^^^^^^^^^^^
1058        self.where_clause_span
1059    }
1060
1061    pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
1062        let predicate = &self.predicates[predicate_pos];
1063        let bounds = predicate.kind.bounds();
1064
1065        if bounds.len() == 1 {
1066            return self.span_for_predicate_removal(predicate_pos);
1067        }
1068
1069        let bound_span = bounds[bound_pos].span();
1070        if bound_pos < bounds.len() - 1 {
1071            // If there's another bound after the current bound
1072            // include the following '+' e.g.:
1073            //
1074            //  `T: Foo + CurrentBound + Bar`
1075            //            ^^^^^^^^^^^^^^^
1076            bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
1077        } else {
1078            // If the current bound is the last bound
1079            // include the preceding '+' E.g.:
1080            //
1081            //  `T: Foo + Bar + CurrentBound`
1082            //               ^^^^^^^^^^^^^^^
1083            bound_span.with_lo(bounds[bound_pos - 1].span().hi())
1084        }
1085    }
1086}
1087
1088/// A single predicate in a where-clause.
1089#[derive(Debug, Clone, Copy, HashStable_Generic)]
1090pub struct WherePredicate<'hir> {
1091    #[stable_hasher(ignore)]
1092    pub hir_id: HirId,
1093    pub span: Span,
1094    pub kind: &'hir WherePredicateKind<'hir>,
1095}
1096
1097/// The kind of a single predicate in a where-clause.
1098#[derive(Debug, Clone, Copy, HashStable_Generic)]
1099pub enum WherePredicateKind<'hir> {
1100    /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
1101    BoundPredicate(WhereBoundPredicate<'hir>),
1102    /// A lifetime predicate (e.g., `'a: 'b + 'c`).
1103    RegionPredicate(WhereRegionPredicate<'hir>),
1104    /// An equality predicate (unsupported).
1105    EqPredicate(WhereEqPredicate<'hir>),
1106}
1107
1108impl<'hir> WherePredicateKind<'hir> {
1109    pub fn in_where_clause(&self) -> bool {
1110        match self {
1111            WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
1112            WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
1113            WherePredicateKind::EqPredicate(_) => false,
1114        }
1115    }
1116
1117    pub fn bounds(&self) -> GenericBounds<'hir> {
1118        match self {
1119            WherePredicateKind::BoundPredicate(p) => p.bounds,
1120            WherePredicateKind::RegionPredicate(p) => p.bounds,
1121            WherePredicateKind::EqPredicate(_) => &[],
1122        }
1123    }
1124}
1125
1126#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
1127pub enum PredicateOrigin {
1128    WhereClause,
1129    GenericParam,
1130    ImplTrait,
1131}
1132
1133/// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
1134#[derive(Debug, Clone, Copy, HashStable_Generic)]
1135pub struct WhereBoundPredicate<'hir> {
1136    /// Origin of the predicate.
1137    pub origin: PredicateOrigin,
1138    /// Any generics from a `for` binding.
1139    pub bound_generic_params: &'hir [GenericParam<'hir>],
1140    /// The type being bounded.
1141    pub bounded_ty: &'hir Ty<'hir>,
1142    /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
1143    pub bounds: GenericBounds<'hir>,
1144}
1145
1146impl<'hir> WhereBoundPredicate<'hir> {
1147    /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
1148    pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
1149        self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
1150    }
1151}
1152
1153/// A lifetime predicate (e.g., `'a: 'b + 'c`).
1154#[derive(Debug, Clone, Copy, HashStable_Generic)]
1155pub struct WhereRegionPredicate<'hir> {
1156    pub in_where_clause: bool,
1157    pub lifetime: &'hir Lifetime,
1158    pub bounds: GenericBounds<'hir>,
1159}
1160
1161impl<'hir> WhereRegionPredicate<'hir> {
1162    /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
1163    fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
1164        self.lifetime.kind == LifetimeKind::Param(param_def_id)
1165    }
1166}
1167
1168/// An equality predicate (e.g., `T = int`); currently unsupported.
1169#[derive(Debug, Clone, Copy, HashStable_Generic)]
1170pub struct WhereEqPredicate<'hir> {
1171    pub lhs_ty: &'hir Ty<'hir>,
1172    pub rhs_ty: &'hir Ty<'hir>,
1173}
1174
1175/// HIR node coupled with its parent's id in the same HIR owner.
1176///
1177/// The parent is trash when the node is a HIR owner.
1178#[derive(Clone, Copy, Debug)]
1179pub struct ParentedNode<'tcx> {
1180    pub parent: ItemLocalId,
1181    pub node: Node<'tcx>,
1182}
1183
1184/// Arguments passed to an attribute macro.
1185#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1186pub enum AttrArgs {
1187    /// No arguments: `#[attr]`.
1188    Empty,
1189    /// Delimited arguments: `#[attr()/[]/{}]`.
1190    Delimited(DelimArgs),
1191    /// Arguments of a key-value attribute: `#[attr = "value"]`.
1192    Eq {
1193        /// Span of the `=` token.
1194        eq_span: Span,
1195        /// The "value".
1196        expr: MetaItemLit,
1197    },
1198}
1199
1200#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1201pub struct AttrPath {
1202    pub segments: Box<[Symbol]>,
1203    pub span: Span,
1204}
1205
1206impl IntoDiagArg for AttrPath {
1207    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> DiagArgValue {
1208        self.to_string().into_diag_arg(path)
1209    }
1210}
1211
1212impl AttrPath {
1213    pub fn from_ast(path: &ast::Path, lower_span: impl Copy + Fn(Span) -> Span) -> Self {
1214        AttrPath {
1215            segments: path
1216                .segments
1217                .iter()
1218                .map(|i| i.ident.name)
1219                .collect::<Vec<_>>()
1220                .into_boxed_slice(),
1221            span: lower_span(path.span),
1222        }
1223    }
1224}
1225
1226impl fmt::Display for AttrPath {
1227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1228        write!(
1229            f,
1230            "{}",
1231            join_path_idents(self.segments.iter().map(|i| Ident { name: *i, span: DUMMY_SP }))
1232        )
1233    }
1234}
1235
1236#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1237pub struct AttrItem {
1238    // Not lowered to hir::Path because we have no NodeId to resolve to.
1239    pub path: AttrPath,
1240    pub args: AttrArgs,
1241    pub id: HashIgnoredAttrId,
1242    /// Denotes if the attribute decorates the following construct (outer)
1243    /// or the construct this attribute is contained within (inner).
1244    pub style: AttrStyle,
1245    /// Span of the entire attribute
1246    pub span: Span,
1247}
1248
1249/// The derived implementation of [`HashStable_Generic`] on [`Attribute`]s shouldn't hash
1250/// [`AttrId`]s. By wrapping them in this, we make sure we never do.
1251#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1252pub struct HashIgnoredAttrId {
1253    pub attr_id: AttrId,
1254}
1255
1256#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1257pub enum Attribute {
1258    /// A parsed built-in attribute.
1259    ///
1260    /// Each attribute has a span connected to it. However, you must be somewhat careful using it.
1261    /// That's because sometimes we merge multiple attributes together, like when an item has
1262    /// multiple `repr` attributes. In this case the span might not be very useful.
1263    Parsed(AttributeKind),
1264
1265    /// An attribute that could not be parsed, out of a token-like representation.
1266    /// This is the case for custom tool attributes.
1267    Unparsed(Box<AttrItem>),
1268}
1269
1270impl Attribute {
1271    pub fn get_normal_item(&self) -> &AttrItem {
1272        match &self {
1273            Attribute::Unparsed(normal) => &normal,
1274            _ => panic!("unexpected parsed attribute"),
1275        }
1276    }
1277
1278    pub fn unwrap_normal_item(self) -> AttrItem {
1279        match self {
1280            Attribute::Unparsed(normal) => *normal,
1281            _ => panic!("unexpected parsed attribute"),
1282        }
1283    }
1284
1285    pub fn value_lit(&self) -> Option<&MetaItemLit> {
1286        match &self {
1287            Attribute::Unparsed(n) => match n.as_ref() {
1288                AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1289                _ => None,
1290            },
1291            _ => None,
1292        }
1293    }
1294
1295    pub fn is_parsed_attr(&self) -> bool {
1296        match self {
1297            Attribute::Parsed(_) => true,
1298            Attribute::Unparsed(_) => false,
1299        }
1300    }
1301}
1302
1303impl AttributeExt for Attribute {
1304    #[inline]
1305    fn id(&self) -> AttrId {
1306        match &self {
1307            Attribute::Unparsed(u) => u.id.attr_id,
1308            _ => panic!(),
1309        }
1310    }
1311
1312    #[inline]
1313    fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1314        match &self {
1315            Attribute::Unparsed(n) => match n.as_ref() {
1316                AttrItem { args: AttrArgs::Delimited(d), .. } => {
1317                    ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1318                }
1319                _ => None,
1320            },
1321            _ => None,
1322        }
1323    }
1324
1325    #[inline]
1326    fn value_str(&self) -> Option<Symbol> {
1327        self.value_lit().and_then(|x| x.value_str())
1328    }
1329
1330    #[inline]
1331    fn value_span(&self) -> Option<Span> {
1332        self.value_lit().map(|i| i.span)
1333    }
1334
1335    /// For a single-segment attribute, returns its name; otherwise, returns `None`.
1336    #[inline]
1337    fn name(&self) -> Option<Symbol> {
1338        match &self {
1339            Attribute::Unparsed(n) => {
1340                if let [ident] = n.path.segments.as_ref() {
1341                    Some(*ident)
1342                } else {
1343                    None
1344                }
1345            }
1346            _ => None,
1347        }
1348    }
1349
1350    #[inline]
1351    fn path_matches(&self, name: &[Symbol]) -> bool {
1352        match &self {
1353            Attribute::Unparsed(n) => n.path.segments.iter().eq(name),
1354            _ => false,
1355        }
1356    }
1357
1358    #[inline]
1359    fn is_doc_comment(&self) -> Option<Span> {
1360        if let Attribute::Parsed(AttributeKind::DocComment { span, .. }) = self {
1361            Some(*span)
1362        } else {
1363            None
1364        }
1365    }
1366
1367    #[inline]
1368    fn span(&self) -> Span {
1369        match &self {
1370            Attribute::Unparsed(u) => u.span,
1371            // FIXME: should not be needed anymore when all attrs are parsed
1372            Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1373            Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1374            Attribute::Parsed(AttributeKind::CfgTrace(cfgs)) => cfgs[0].1,
1375            a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1376        }
1377    }
1378
1379    #[inline]
1380    fn is_word(&self) -> bool {
1381        match &self {
1382            Attribute::Unparsed(n) => {
1383                matches!(n.args, AttrArgs::Empty)
1384            }
1385            _ => false,
1386        }
1387    }
1388
1389    #[inline]
1390    fn symbol_path(&self) -> Option<SmallVec<[Symbol; 1]>> {
1391        match &self {
1392            Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1393            _ => None,
1394        }
1395    }
1396
1397    fn path_span(&self) -> Option<Span> {
1398        match &self {
1399            Attribute::Unparsed(attr) => Some(attr.path.span),
1400            Attribute::Parsed(_) => None,
1401        }
1402    }
1403
1404    #[inline]
1405    fn doc_str(&self) -> Option<Symbol> {
1406        match &self {
1407            Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1408            _ => None,
1409        }
1410    }
1411
1412    fn is_automatically_derived_attr(&self) -> bool {
1413        matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)))
1414    }
1415
1416    #[inline]
1417    fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)> {
1418        match &self {
1419            Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1420                Some((*comment, *kind))
1421            }
1422            _ => None,
1423        }
1424    }
1425
1426    fn doc_resolution_scope(&self) -> Option<AttrStyle> {
1427        match self {
1428            Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
1429            Attribute::Unparsed(attr) if self.has_name(sym::doc) && self.value_str().is_some() => {
1430                Some(attr.style)
1431            }
1432            _ => None,
1433        }
1434    }
1435
1436    fn is_proc_macro_attr(&self) -> bool {
1437        matches!(
1438            self,
1439            Attribute::Parsed(
1440                AttributeKind::ProcMacro(..)
1441                    | AttributeKind::ProcMacroAttribute(..)
1442                    | AttributeKind::ProcMacroDerive { .. }
1443            )
1444        )
1445    }
1446
1447    fn is_doc_hidden(&self) -> bool {
1448        matches!(self, Attribute::Parsed(AttributeKind::Doc(d)) if d.hidden.is_some())
1449    }
1450
1451    fn is_doc_keyword_or_attribute(&self) -> bool {
1452        matches!(self, Attribute::Parsed(AttributeKind::Doc(d)) if d.attribute.is_some() || d.keyword.is_some())
1453    }
1454}
1455
1456// FIXME(fn_delegation): use function delegation instead of manually forwarding
1457impl Attribute {
1458    #[inline]
1459    pub fn id(&self) -> AttrId {
1460        AttributeExt::id(self)
1461    }
1462
1463    #[inline]
1464    pub fn name(&self) -> Option<Symbol> {
1465        AttributeExt::name(self)
1466    }
1467
1468    #[inline]
1469    pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1470        AttributeExt::meta_item_list(self)
1471    }
1472
1473    #[inline]
1474    pub fn value_str(&self) -> Option<Symbol> {
1475        AttributeExt::value_str(self)
1476    }
1477
1478    #[inline]
1479    pub fn value_span(&self) -> Option<Span> {
1480        AttributeExt::value_span(self)
1481    }
1482
1483    #[inline]
1484    pub fn path_matches(&self, name: &[Symbol]) -> bool {
1485        AttributeExt::path_matches(self, name)
1486    }
1487
1488    #[inline]
1489    pub fn is_doc_comment(&self) -> Option<Span> {
1490        AttributeExt::is_doc_comment(self)
1491    }
1492
1493    #[inline]
1494    pub fn has_name(&self, name: Symbol) -> bool {
1495        AttributeExt::has_name(self, name)
1496    }
1497
1498    #[inline]
1499    pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1500        AttributeExt::has_any_name(self, names)
1501    }
1502
1503    #[inline]
1504    pub fn span(&self) -> Span {
1505        AttributeExt::span(self)
1506    }
1507
1508    #[inline]
1509    pub fn is_word(&self) -> bool {
1510        AttributeExt::is_word(self)
1511    }
1512
1513    #[inline]
1514    pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1515        AttributeExt::path(self)
1516    }
1517
1518    #[inline]
1519    pub fn doc_str(&self) -> Option<Symbol> {
1520        AttributeExt::doc_str(self)
1521    }
1522
1523    #[inline]
1524    pub fn is_proc_macro_attr(&self) -> bool {
1525        AttributeExt::is_proc_macro_attr(self)
1526    }
1527
1528    #[inline]
1529    pub fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)> {
1530        AttributeExt::doc_str_and_fragment_kind(self)
1531    }
1532}
1533
1534/// Attributes owned by a HIR owner.
1535#[derive(Debug)]
1536pub struct AttributeMap<'tcx> {
1537    pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1538    /// Preprocessed `#[define_opaque]` attribute.
1539    pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1540    // Only present when the crate hash is needed.
1541    pub opt_hash: Option<Fingerprint>,
1542}
1543
1544impl<'tcx> AttributeMap<'tcx> {
1545    pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1546        map: SortedMap::new(),
1547        opt_hash: Some(Fingerprint::ZERO),
1548        define_opaque: None,
1549    };
1550
1551    #[inline]
1552    pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1553        self.map.get(&id).copied().unwrap_or(&[])
1554    }
1555}
1556
1557/// Map of all HIR nodes inside the current owner.
1558/// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
1559/// The HIR tree, including bodies, is pre-hashed.
1560pub struct OwnerNodes<'tcx> {
1561    /// Pre-computed hash of the full HIR. Used in the crate hash. Only present
1562    /// when incr. comp. is enabled.
1563    pub opt_hash_including_bodies: Option<Fingerprint>,
1564    /// Full HIR for the current owner.
1565    // The zeroth node's parent should never be accessed: the owner's parent is computed by the
1566    // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
1567    // used.
1568    pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1569    /// Content of local bodies.
1570    pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1571}
1572
1573impl<'tcx> OwnerNodes<'tcx> {
1574    pub fn node(&self) -> OwnerNode<'tcx> {
1575        // Indexing must ensure it is an OwnerNode.
1576        self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1577    }
1578}
1579
1580impl fmt::Debug for OwnerNodes<'_> {
1581    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582        f.debug_struct("OwnerNodes")
1583            // Do not print all the pointers to all the nodes, as it would be unreadable.
1584            .field("node", &self.nodes[ItemLocalId::ZERO])
1585            .field(
1586                "parents",
1587                &fmt::from_fn(|f| {
1588                    f.debug_list()
1589                        .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1590                            fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1591                        }))
1592                        .finish()
1593                }),
1594            )
1595            .field("bodies", &self.bodies)
1596            .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1597            .finish()
1598    }
1599}
1600
1601/// Full information resulting from lowering an AST node.
1602#[derive(Debug, HashStable_Generic)]
1603pub struct OwnerInfo<'hir> {
1604    /// Contents of the HIR.
1605    pub nodes: OwnerNodes<'hir>,
1606    /// Map from each nested owner to its parent's local id.
1607    pub parenting: LocalDefIdMap<ItemLocalId>,
1608    /// Collected attributes of the HIR nodes.
1609    pub attrs: AttributeMap<'hir>,
1610    /// Map indicating what traits are in scope for places where this
1611    /// is relevant; generated by resolve.
1612    pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1613
1614    /// Lints delayed during ast lowering to be emitted
1615    /// after hir has completely built
1616    pub delayed_lints: DelayedLints,
1617}
1618
1619impl<'tcx> OwnerInfo<'tcx> {
1620    #[inline]
1621    pub fn node(&self) -> OwnerNode<'tcx> {
1622        self.nodes.node()
1623    }
1624}
1625
1626#[derive(Copy, Clone, Debug, HashStable_Generic)]
1627pub enum MaybeOwner<'tcx> {
1628    Owner(&'tcx OwnerInfo<'tcx>),
1629    NonOwner(HirId),
1630    /// Used as a placeholder for unused LocalDefId.
1631    Phantom,
1632}
1633
1634impl<'tcx> MaybeOwner<'tcx> {
1635    pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1636        match self {
1637            MaybeOwner::Owner(i) => Some(i),
1638            MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1639        }
1640    }
1641
1642    pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1643        self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1644    }
1645}
1646
1647/// The top-level data structure that stores the entire contents of
1648/// the crate currently being compiled.
1649///
1650/// For more details, see the [rustc dev guide].
1651///
1652/// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
1653#[derive(Debug)]
1654pub struct Crate<'hir> {
1655    pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1656    // Only present when incr. comp. is enabled.
1657    pub opt_hir_hash: Option<Fingerprint>,
1658}
1659
1660#[derive(Debug, Clone, Copy, HashStable_Generic)]
1661pub struct Closure<'hir> {
1662    pub def_id: LocalDefId,
1663    pub binder: ClosureBinder,
1664    pub constness: Constness,
1665    pub capture_clause: CaptureBy,
1666    pub bound_generic_params: &'hir [GenericParam<'hir>],
1667    pub fn_decl: &'hir FnDecl<'hir>,
1668    pub body: BodyId,
1669    /// The span of the declaration block: 'move |...| -> ...'
1670    pub fn_decl_span: Span,
1671    /// The span of the argument block `|...|`
1672    pub fn_arg_span: Option<Span>,
1673    pub kind: ClosureKind,
1674}
1675
1676#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1677pub enum ClosureKind {
1678    /// This is a plain closure expression.
1679    Closure,
1680    /// This is a coroutine expression -- i.e. a closure expression in which
1681    /// we've found a `yield`. These can arise either from "plain" coroutine
1682    ///  usage (e.g. `let x = || { yield (); }`) or from a desugared expression
1683    /// (e.g. `async` and `gen` blocks).
1684    Coroutine(CoroutineKind),
1685    /// This is a coroutine-closure, which is a special sugared closure that
1686    /// returns one of the sugared coroutine (`async`/`gen`/`async gen`). It
1687    /// additionally allows capturing the coroutine's upvars by ref, and therefore
1688    /// needs to be specially treated during analysis and borrowck.
1689    CoroutineClosure(CoroutineDesugaring),
1690}
1691
1692/// A block of statements `{ .. }`, which may have a label (in this case the
1693/// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
1694/// the `rules` being anything but `DefaultBlock`.
1695#[derive(Debug, Clone, Copy, HashStable_Generic)]
1696pub struct Block<'hir> {
1697    /// Statements in a block.
1698    pub stmts: &'hir [Stmt<'hir>],
1699    /// An expression at the end of the block
1700    /// without a semicolon, if any.
1701    pub expr: Option<&'hir Expr<'hir>>,
1702    #[stable_hasher(ignore)]
1703    pub hir_id: HirId,
1704    /// Distinguishes between `unsafe { ... }` and `{ ... }`.
1705    pub rules: BlockCheckMode,
1706    /// The span includes the curly braces `{` and `}` around the block.
1707    pub span: Span,
1708    /// If true, then there may exist `break 'a` values that aim to
1709    /// break out of this block early.
1710    /// Used by `'label: {}` blocks and by `try {}` blocks.
1711    pub targeted_by_break: bool,
1712}
1713
1714impl<'hir> Block<'hir> {
1715    pub fn innermost_block(&self) -> &Block<'hir> {
1716        let mut block = self;
1717        while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1718            block = inner_block;
1719        }
1720        block
1721    }
1722}
1723
1724#[derive(Debug, Clone, Copy, HashStable_Generic)]
1725pub struct TyPat<'hir> {
1726    #[stable_hasher(ignore)]
1727    pub hir_id: HirId,
1728    pub kind: TyPatKind<'hir>,
1729    pub span: Span,
1730}
1731
1732#[derive(Debug, Clone, Copy, HashStable_Generic)]
1733pub struct Pat<'hir> {
1734    #[stable_hasher(ignore)]
1735    pub hir_id: HirId,
1736    pub kind: PatKind<'hir>,
1737    pub span: Span,
1738    /// Whether to use default binding modes.
1739    /// At present, this is false only for destructuring assignment.
1740    pub default_binding_modes: bool,
1741}
1742
1743impl<'hir> Pat<'hir> {
1744    fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1745        if !it(self) {
1746            return false;
1747        }
1748
1749        use PatKind::*;
1750        match self.kind {
1751            Missing => unreachable!(),
1752            Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1753            Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => {
1754                s.walk_short_(it)
1755            }
1756            Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1757            TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1758            Slice(before, slice, after) => {
1759                before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1760            }
1761        }
1762    }
1763
1764    /// Walk the pattern in left-to-right order,
1765    /// short circuiting (with `.all(..)`) if `false` is returned.
1766    ///
1767    /// Note that when visiting e.g. `Tuple(ps)`,
1768    /// if visiting `ps[0]` returns `false`,
1769    /// then `ps[1]` will not be visited.
1770    pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1771        self.walk_short_(&mut it)
1772    }
1773
1774    fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1775        if !it(self) {
1776            return;
1777        }
1778
1779        use PatKind::*;
1780        match self.kind {
1781            Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1782            Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1783            Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1784            TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1785            Slice(before, slice, after) => {
1786                before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1787            }
1788        }
1789    }
1790
1791    /// Walk the pattern in left-to-right order.
1792    ///
1793    /// If `it(pat)` returns `false`, the children are not visited.
1794    pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1795        self.walk_(&mut it)
1796    }
1797
1798    /// Walk the pattern in left-to-right order.
1799    ///
1800    /// If you always want to recurse, prefer this method over `walk`.
1801    pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1802        self.walk(|p| {
1803            it(p);
1804            true
1805        })
1806    }
1807
1808    /// Whether this a never pattern.
1809    pub fn is_never_pattern(&self) -> bool {
1810        let mut is_never_pattern = false;
1811        self.walk(|pat| match &pat.kind {
1812            PatKind::Never => {
1813                is_never_pattern = true;
1814                false
1815            }
1816            PatKind::Or(s) => {
1817                is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1818                false
1819            }
1820            _ => true,
1821        });
1822        is_never_pattern
1823    }
1824
1825    /// Whether this pattern constitutes a read of value of the scrutinee that
1826    /// it is matching against. This is used to determine whether we should
1827    /// perform `NeverToAny` coercions.
1828    ///
1829    /// See [`expr_guaranteed_to_constitute_read_for_never`][m] for the nuances of
1830    /// what happens when this returns true.
1831    ///
1832    /// [m]: ../../rustc_middle/ty/struct.TyCtxt.html#method.expr_guaranteed_to_constitute_read_for_never
1833    pub fn is_guaranteed_to_constitute_read_for_never(&self) -> bool {
1834        match self.kind {
1835            // Does not constitute a read.
1836            PatKind::Wild => false,
1837
1838            // The guard cannot affect if we make a read or not (it runs after the inner pattern
1839            // has matched), therefore it's irrelevant.
1840            PatKind::Guard(pat, _) => pat.is_guaranteed_to_constitute_read_for_never(),
1841
1842            // This is unnecessarily restrictive when the pattern that doesn't
1843            // constitute a read is unreachable.
1844            //
1845            // For example `match *never_ptr { value => {}, _ => {} }` or
1846            // `match *never_ptr { _ if false => {}, value => {} }`.
1847            //
1848            // It is however fine to be restrictive here; only returning `true`
1849            // can lead to unsoundness.
1850            PatKind::Or(subpats) => {
1851                subpats.iter().all(|pat| pat.is_guaranteed_to_constitute_read_for_never())
1852            }
1853
1854            // Does constitute a read, since it is equivalent to a discriminant read.
1855            PatKind::Never => true,
1856
1857            // All of these constitute a read, or match on something that isn't `!`,
1858            // which would require a `NeverToAny` coercion.
1859            PatKind::Missing
1860            | PatKind::Binding(_, _, _, _)
1861            | PatKind::Struct(_, _, _)
1862            | PatKind::TupleStruct(_, _, _)
1863            | PatKind::Tuple(_, _)
1864            | PatKind::Box(_)
1865            | PatKind::Ref(_, _, _)
1866            | PatKind::Deref(_)
1867            | PatKind::Expr(_)
1868            | PatKind::Range(_, _, _)
1869            | PatKind::Slice(_, _, _)
1870            | PatKind::Err(_) => true,
1871        }
1872    }
1873}
1874
1875/// A single field in a struct pattern.
1876///
1877/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1878/// are treated the same as` x: x, y: ref y, z: ref mut z`,
1879/// except `is_shorthand` is true.
1880#[derive(Debug, Clone, Copy, HashStable_Generic)]
1881pub struct PatField<'hir> {
1882    #[stable_hasher(ignore)]
1883    pub hir_id: HirId,
1884    /// The identifier for the field.
1885    pub ident: Ident,
1886    /// The pattern the field is destructured to.
1887    pub pat: &'hir Pat<'hir>,
1888    pub is_shorthand: bool,
1889    pub span: Span,
1890}
1891
1892#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1893pub enum RangeEnd {
1894    Included,
1895    Excluded,
1896}
1897
1898impl fmt::Display for RangeEnd {
1899    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1900        f.write_str(match self {
1901            RangeEnd::Included => "..=",
1902            RangeEnd::Excluded => "..",
1903        })
1904    }
1905}
1906
1907// Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1908// this type only takes up 4 bytes, at the cost of being restricted to a
1909// maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1910#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1911pub struct DotDotPos(u32);
1912
1913impl DotDotPos {
1914    /// Panics if n >= u32::MAX.
1915    pub fn new(n: Option<usize>) -> Self {
1916        match n {
1917            Some(n) => {
1918                assert!(n < u32::MAX as usize);
1919                Self(n as u32)
1920            }
1921            None => Self(u32::MAX),
1922        }
1923    }
1924
1925    pub fn as_opt_usize(&self) -> Option<usize> {
1926        if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1927    }
1928}
1929
1930impl fmt::Debug for DotDotPos {
1931    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1932        self.as_opt_usize().fmt(f)
1933    }
1934}
1935
1936#[derive(Debug, Clone, Copy, HashStable_Generic)]
1937pub struct PatExpr<'hir> {
1938    #[stable_hasher(ignore)]
1939    pub hir_id: HirId,
1940    pub span: Span,
1941    pub kind: PatExprKind<'hir>,
1942}
1943
1944#[derive(Debug, Clone, Copy, HashStable_Generic)]
1945pub enum PatExprKind<'hir> {
1946    Lit {
1947        lit: Lit,
1948        // FIXME: move this into `Lit` and handle negated literal expressions
1949        // once instead of matching on unop neg expressions everywhere.
1950        negated: bool,
1951    },
1952    /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1953    Path(QPath<'hir>),
1954}
1955
1956#[derive(Debug, Clone, Copy, HashStable_Generic)]
1957pub enum TyPatKind<'hir> {
1958    /// A range pattern (e.g., `1..=2` or `1..2`).
1959    Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1960
1961    /// A pattern that excludes null pointers
1962    NotNull,
1963
1964    /// A list of patterns where only one needs to be satisfied
1965    Or(&'hir [TyPat<'hir>]),
1966
1967    /// A placeholder for a pattern that wasn't well formed in some way.
1968    Err(ErrorGuaranteed),
1969}
1970
1971#[derive(Debug, Clone, Copy, HashStable_Generic)]
1972pub enum PatKind<'hir> {
1973    /// A missing pattern, e.g. for an anonymous param in a bare fn like `fn f(u32)`.
1974    Missing,
1975
1976    /// Represents a wildcard pattern (i.e., `_`).
1977    Wild,
1978
1979    /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1980    /// The `HirId` is the canonical ID for the variable being bound,
1981    /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1982    /// which is the pattern ID of the first `x`.
1983    ///
1984    /// The `BindingMode` is what's provided by the user, before match
1985    /// ergonomics are applied. For the binding mode actually in use,
1986    /// see [`TypeckResults::extract_binding_mode`].
1987    ///
1988    /// [`TypeckResults::extract_binding_mode`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.extract_binding_mode
1989    Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1990
1991    /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1992    /// The `Option` contains the span of a possible `..`.
1993    Struct(QPath<'hir>, &'hir [PatField<'hir>], Option<Span>),
1994
1995    /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1996    /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1997    /// `0 <= position <= subpats.len()`
1998    TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1999
2000    /// An or-pattern `A | B | C`.
2001    /// Invariant: `pats.len() >= 2`.
2002    Or(&'hir [Pat<'hir>]),
2003
2004    /// A never pattern `!`.
2005    Never,
2006
2007    /// A tuple pattern (e.g., `(a, b)`).
2008    /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
2009    /// `0 <= position <= subpats.len()`
2010    Tuple(&'hir [Pat<'hir>], DotDotPos),
2011
2012    /// A `box` pattern.
2013    Box(&'hir Pat<'hir>),
2014
2015    /// A `deref` pattern (currently `deref!()` macro-based syntax).
2016    Deref(&'hir Pat<'hir>),
2017
2018    /// A reference pattern (e.g., `&mut (a, b)`).
2019    Ref(&'hir Pat<'hir>, Pinnedness, Mutability),
2020
2021    /// A literal, const block or path.
2022    Expr(&'hir PatExpr<'hir>),
2023
2024    /// A guard pattern (e.g., `x if guard(x)`).
2025    Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
2026
2027    /// A range pattern (e.g., `1..=2` or `1..2`).
2028    Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
2029
2030    /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
2031    ///
2032    /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
2033    /// If `slice` exists, then `after` can be non-empty.
2034    ///
2035    /// The representation for e.g., `[a, b, .., c, d]` is:
2036    /// ```ignore (illustrative)
2037    /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
2038    /// ```
2039    Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
2040
2041    /// A placeholder for a pattern that wasn't well formed in some way.
2042    Err(ErrorGuaranteed),
2043}
2044
2045/// A statement.
2046#[derive(Debug, Clone, Copy, HashStable_Generic)]
2047pub struct Stmt<'hir> {
2048    #[stable_hasher(ignore)]
2049    pub hir_id: HirId,
2050    pub kind: StmtKind<'hir>,
2051    pub span: Span,
2052}
2053
2054/// The contents of a statement.
2055#[derive(Debug, Clone, Copy, HashStable_Generic)]
2056pub enum StmtKind<'hir> {
2057    /// A local (`let`) binding.
2058    Let(&'hir LetStmt<'hir>),
2059
2060    /// An item binding.
2061    Item(ItemId),
2062
2063    /// An expression without a trailing semi-colon (must have unit type).
2064    Expr(&'hir Expr<'hir>),
2065
2066    /// An expression with a trailing semi-colon (may have any type).
2067    Semi(&'hir Expr<'hir>),
2068}
2069
2070/// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
2071#[derive(Debug, Clone, Copy, HashStable_Generic)]
2072pub struct LetStmt<'hir> {
2073    /// Span of `super` in `super let`.
2074    pub super_: Option<Span>,
2075    pub pat: &'hir Pat<'hir>,
2076    /// Type annotation, if any (otherwise the type will be inferred).
2077    pub ty: Option<&'hir Ty<'hir>>,
2078    /// Initializer expression to set the value, if any.
2079    pub init: Option<&'hir Expr<'hir>>,
2080    /// Else block for a `let...else` binding.
2081    pub els: Option<&'hir Block<'hir>>,
2082    #[stable_hasher(ignore)]
2083    pub hir_id: HirId,
2084    pub span: Span,
2085    /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
2086    /// desugaring, or `AssignDesugar` if it is the result of a complex
2087    /// assignment desugaring. Otherwise will be `Normal`.
2088    pub source: LocalSource,
2089}
2090
2091/// Represents a single arm of a `match` expression, e.g.
2092/// `<pat> (if <guard>) => <body>`.
2093#[derive(Debug, Clone, Copy, HashStable_Generic)]
2094pub struct Arm<'hir> {
2095    #[stable_hasher(ignore)]
2096    pub hir_id: HirId,
2097    pub span: Span,
2098    /// If this pattern and the optional guard matches, then `body` is evaluated.
2099    pub pat: &'hir Pat<'hir>,
2100    /// Optional guard clause.
2101    pub guard: Option<&'hir Expr<'hir>>,
2102    /// The expression the arm evaluates to if this arm matches.
2103    pub body: &'hir Expr<'hir>,
2104}
2105
2106/// Represents a `let <pat>[: <ty>] = <expr>` expression (not a [`LetStmt`]), occurring in an `if-let`
2107/// or `let-else`, evaluating to a boolean. Typically the pattern is refutable.
2108///
2109/// In an `if let`, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of
2110/// the desugaring to if-let. Only let-else supports the type annotation at present.
2111#[derive(Debug, Clone, Copy, HashStable_Generic)]
2112pub struct LetExpr<'hir> {
2113    pub span: Span,
2114    pub pat: &'hir Pat<'hir>,
2115    pub ty: Option<&'hir Ty<'hir>>,
2116    pub init: &'hir Expr<'hir>,
2117    /// `Recovered::Yes` when this let expressions is not in a syntactically valid location.
2118    /// Used to prevent building MIR in such situations.
2119    pub recovered: ast::Recovered,
2120}
2121
2122#[derive(Debug, Clone, Copy, HashStable_Generic)]
2123pub struct ExprField<'hir> {
2124    #[stable_hasher(ignore)]
2125    pub hir_id: HirId,
2126    pub ident: Ident,
2127    pub expr: &'hir Expr<'hir>,
2128    pub span: Span,
2129    pub is_shorthand: bool,
2130}
2131
2132#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2133pub enum BlockCheckMode {
2134    DefaultBlock,
2135    UnsafeBlock(UnsafeSource),
2136}
2137
2138#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2139pub enum UnsafeSource {
2140    CompilerGenerated,
2141    UserProvided,
2142}
2143
2144#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
2145pub struct BodyId {
2146    pub hir_id: HirId,
2147}
2148
2149/// The body of a function, closure, or constant value. In the case of
2150/// a function, the body contains not only the function body itself
2151/// (which is an expression), but also the argument patterns, since
2152/// those are something that the caller doesn't really care about.
2153///
2154/// # Examples
2155///
2156/// ```
2157/// fn foo((x, y): (u32, u32)) -> u32 {
2158///     x + y
2159/// }
2160/// ```
2161///
2162/// Here, the `Body` associated with `foo()` would contain:
2163///
2164/// - an `params` array containing the `(x, y)` pattern
2165/// - a `value` containing the `x + y` expression (maybe wrapped in a block)
2166/// - `coroutine_kind` would be `None`
2167///
2168/// All bodies have an **owner**, which can be accessed via the HIR
2169/// map using `body_owner_def_id()`.
2170#[derive(Debug, Clone, Copy, HashStable_Generic)]
2171pub struct Body<'hir> {
2172    pub params: &'hir [Param<'hir>],
2173    pub value: &'hir Expr<'hir>,
2174}
2175
2176impl<'hir> Body<'hir> {
2177    pub fn id(&self) -> BodyId {
2178        BodyId { hir_id: self.value.hir_id }
2179    }
2180}
2181
2182/// The type of source expression that caused this coroutine to be created.
2183#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2184pub enum CoroutineKind {
2185    /// A coroutine that comes from a desugaring.
2186    Desugared(CoroutineDesugaring, CoroutineSource),
2187
2188    /// A coroutine literal created via a `yield` inside a closure.
2189    Coroutine(Movability),
2190}
2191
2192impl CoroutineKind {
2193    pub fn movability(self) -> Movability {
2194        match self {
2195            CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2196            | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2197            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2198            CoroutineKind::Coroutine(mov) => mov,
2199        }
2200    }
2201
2202    pub fn is_fn_like(self) -> bool {
2203        matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2204    }
2205
2206    pub fn to_plural_string(&self) -> String {
2207        match self {
2208            CoroutineKind::Desugared(d, CoroutineSource::Fn) => format!("{d:#}fn bodies"),
2209            CoroutineKind::Desugared(d, CoroutineSource::Block) => format!("{d:#}blocks"),
2210            CoroutineKind::Desugared(d, CoroutineSource::Closure) => format!("{d:#}closure bodies"),
2211            CoroutineKind::Coroutine(_) => "coroutines".to_string(),
2212        }
2213    }
2214}
2215
2216impl fmt::Display for CoroutineKind {
2217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2218        match self {
2219            CoroutineKind::Desugared(d, k) => {
2220                d.fmt(f)?;
2221                k.fmt(f)
2222            }
2223            CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2224        }
2225    }
2226}
2227
2228/// In the case of a coroutine created as part of an async/gen construct,
2229/// which kind of async/gen construct caused it to be created?
2230///
2231/// This helps error messages but is also used to drive coercions in
2232/// type-checking (see #60424).
2233#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
2234pub enum CoroutineSource {
2235    /// An explicit `async`/`gen` block written by the user.
2236    Block,
2237
2238    /// An explicit `async`/`gen` closure written by the user.
2239    Closure,
2240
2241    /// The `async`/`gen` block generated as the body of an async/gen function.
2242    Fn,
2243}
2244
2245impl fmt::Display for CoroutineSource {
2246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2247        match self {
2248            CoroutineSource::Block => "block",
2249            CoroutineSource::Closure => "closure body",
2250            CoroutineSource::Fn => "fn body",
2251        }
2252        .fmt(f)
2253    }
2254}
2255
2256#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2257pub enum CoroutineDesugaring {
2258    /// An explicit `async` block or the body of an `async` function.
2259    Async,
2260
2261    /// An explicit `gen` block or the body of a `gen` function.
2262    Gen,
2263
2264    /// An explicit `async gen` block or the body of an `async gen` function,
2265    /// which is able to both `yield` and `.await`.
2266    AsyncGen,
2267}
2268
2269impl fmt::Display for CoroutineDesugaring {
2270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2271        match self {
2272            CoroutineDesugaring::Async => {
2273                if f.alternate() {
2274                    f.write_str("`async` ")?;
2275                } else {
2276                    f.write_str("async ")?
2277                }
2278            }
2279            CoroutineDesugaring::Gen => {
2280                if f.alternate() {
2281                    f.write_str("`gen` ")?;
2282                } else {
2283                    f.write_str("gen ")?
2284                }
2285            }
2286            CoroutineDesugaring::AsyncGen => {
2287                if f.alternate() {
2288                    f.write_str("`async gen` ")?;
2289                } else {
2290                    f.write_str("async gen ")?
2291                }
2292            }
2293        }
2294
2295        Ok(())
2296    }
2297}
2298
2299#[derive(Copy, Clone, Debug)]
2300pub enum BodyOwnerKind {
2301    /// Functions and methods.
2302    Fn,
2303
2304    /// Closures
2305    Closure,
2306
2307    /// Constants and associated constants, also including inline constants.
2308    Const { inline: bool },
2309
2310    /// Initializer of a `static` item.
2311    Static(Mutability),
2312
2313    /// Fake body for a global asm to store its const-like value types.
2314    GlobalAsm,
2315}
2316
2317impl BodyOwnerKind {
2318    pub fn is_fn_or_closure(self) -> bool {
2319        match self {
2320            BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2321            BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2322                false
2323            }
2324        }
2325    }
2326}
2327
2328/// The kind of an item that requires const-checking.
2329#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2330pub enum ConstContext {
2331    /// A `const fn`.
2332    ConstFn,
2333
2334    /// A `static` or `static mut`.
2335    Static(Mutability),
2336
2337    /// A `const`, associated `const`, or other const context.
2338    ///
2339    /// Other contexts include:
2340    /// - Array length expressions
2341    /// - Enum discriminants
2342    /// - Const generics
2343    ///
2344    /// For the most part, other contexts are treated just like a regular `const`, so they are
2345    /// lumped into the same category.
2346    Const { inline: bool },
2347}
2348
2349impl ConstContext {
2350    /// A description of this const context that can appear between backticks in an error message.
2351    ///
2352    /// E.g. `const` or `static mut`.
2353    pub fn keyword_name(self) -> &'static str {
2354        match self {
2355            Self::Const { .. } => "const",
2356            Self::Static(Mutability::Not) => "static",
2357            Self::Static(Mutability::Mut) => "static mut",
2358            Self::ConstFn => "const fn",
2359        }
2360    }
2361}
2362
2363/// A colloquial, trivially pluralizable description of this const context for use in error
2364/// messages.
2365impl fmt::Display for ConstContext {
2366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2367        match *self {
2368            Self::Const { .. } => write!(f, "constant"),
2369            Self::Static(_) => write!(f, "static"),
2370            Self::ConstFn => write!(f, "constant function"),
2371        }
2372    }
2373}
2374
2375impl IntoDiagArg for ConstContext {
2376    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
2377        DiagArgValue::Str(Cow::Borrowed(match self {
2378            ConstContext::ConstFn => "const_fn",
2379            ConstContext::Static(_) => "static",
2380            ConstContext::Const { .. } => "const",
2381        }))
2382    }
2383}
2384
2385/// A literal.
2386pub type Lit = Spanned<LitKind>;
2387
2388/// A constant (expression) that's not an item or associated item,
2389/// but needs its own `DefId` for type-checking, const-eval, etc.
2390/// These are usually found nested inside types (e.g., array lengths)
2391/// or expressions (e.g., repeat counts), and also used to define
2392/// explicit discriminant values for enum variants.
2393///
2394/// You can check if this anon const is a default in a const param
2395/// `const N: usize = { ... }` with `tcx.hir_opt_const_param_default_param_def_id(..)`
2396#[derive(Copy, Clone, Debug, HashStable_Generic)]
2397pub struct AnonConst {
2398    #[stable_hasher(ignore)]
2399    pub hir_id: HirId,
2400    pub def_id: LocalDefId,
2401    pub body: BodyId,
2402    pub span: Span,
2403}
2404
2405/// An inline constant expression `const { something }`.
2406#[derive(Copy, Clone, Debug, HashStable_Generic)]
2407pub struct ConstBlock {
2408    #[stable_hasher(ignore)]
2409    pub hir_id: HirId,
2410    pub def_id: LocalDefId,
2411    pub body: BodyId,
2412}
2413
2414/// An expression.
2415///
2416/// For more details, see the [rust lang reference].
2417/// Note that the reference does not document nightly-only features.
2418/// There may be also slight differences in the names and representation of AST nodes between
2419/// the compiler and the reference.
2420///
2421/// [rust lang reference]: https://doc.rust-lang.org/reference/expressions.html
2422#[derive(Debug, Clone, Copy, HashStable_Generic)]
2423pub struct Expr<'hir> {
2424    #[stable_hasher(ignore)]
2425    pub hir_id: HirId,
2426    pub kind: ExprKind<'hir>,
2427    pub span: Span,
2428}
2429
2430impl Expr<'_> {
2431    pub fn precedence(&self, has_attr: &dyn Fn(HirId) -> bool) -> ExprPrecedence {
2432        let prefix_attrs_precedence = || -> ExprPrecedence {
2433            if has_attr(self.hir_id) { ExprPrecedence::Prefix } else { ExprPrecedence::Unambiguous }
2434        };
2435
2436        match &self.kind {
2437            ExprKind::Closure(closure) => {
2438                match closure.fn_decl.output {
2439                    FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2440                    FnRetTy::Return(_) => prefix_attrs_precedence(),
2441                }
2442            }
2443
2444            ExprKind::Break(..)
2445            | ExprKind::Ret(..)
2446            | ExprKind::Yield(..)
2447            | ExprKind::Become(..) => ExprPrecedence::Jump,
2448
2449            // Binop-like expr kinds, handled by `AssocOp`.
2450            ExprKind::Binary(op, ..) => op.node.precedence(),
2451            ExprKind::Cast(..) => ExprPrecedence::Cast,
2452
2453            ExprKind::Assign(..) |
2454            ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2455
2456            // Unary, prefix
2457            ExprKind::AddrOf(..)
2458            // Here `let pats = expr` has `let pats =` as a "unary" prefix of `expr`.
2459            // However, this is not exactly right. When `let _ = a` is the LHS of a binop we
2460            // need parens sometimes. E.g. we can print `(let _ = a) && b` as `let _ = a && b`
2461            // but we need to print `(let _ = a) < b` as-is with parens.
2462            | ExprKind::Let(..)
2463            | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2464
2465            // Need parens if and only if there are prefix attributes.
2466            ExprKind::Array(_)
2467            | ExprKind::Block(..)
2468            | ExprKind::Call(..)
2469            | ExprKind::ConstBlock(_)
2470            | ExprKind::Continue(..)
2471            | ExprKind::Field(..)
2472            | ExprKind::If(..)
2473            | ExprKind::Index(..)
2474            | ExprKind::InlineAsm(..)
2475            | ExprKind::Lit(_)
2476            | ExprKind::Loop(..)
2477            | ExprKind::Match(..)
2478            | ExprKind::MethodCall(..)
2479            | ExprKind::OffsetOf(..)
2480            | ExprKind::Path(..)
2481            | ExprKind::Repeat(..)
2482            | ExprKind::Struct(..)
2483            | ExprKind::Tup(_)
2484            | ExprKind::Type(..)
2485            | ExprKind::UnsafeBinderCast(..)
2486            | ExprKind::Use(..)
2487            | ExprKind::Err(_) => prefix_attrs_precedence(),
2488
2489            ExprKind::DropTemps(expr, ..) => expr.precedence(has_attr),
2490        }
2491    }
2492
2493    /// Whether this looks like a place expr, without checking for deref
2494    /// adjustments.
2495    /// This will return `true` in some potentially surprising cases such as
2496    /// `CONSTANT.field`.
2497    pub fn is_syntactic_place_expr(&self) -> bool {
2498        self.is_place_expr(|_| true)
2499    }
2500
2501    /// Whether this is a place expression.
2502    ///
2503    /// `allow_projections_from` should return `true` if indexing a field or index expression based
2504    /// on the given expression should be considered a place expression.
2505    pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2506        match self.kind {
2507            ExprKind::Path(QPath::Resolved(_, ref path)) => {
2508                matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2509            }
2510
2511            // Type ascription inherits its place expression kind from its
2512            // operand. See:
2513            // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
2514            ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2515
2516            // Unsafe binder cast preserves place-ness of the sub-expression.
2517            ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2518
2519            ExprKind::Unary(UnOp::Deref, _) => true,
2520
2521            ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2522                allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2523            }
2524
2525            // Suppress errors for bad expressions.
2526            ExprKind::Err(_guar)
2527            | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2528
2529            // Partially qualified paths in expressions can only legally
2530            // refer to associated items which are always rvalues.
2531            ExprKind::Path(QPath::TypeRelative(..))
2532            | ExprKind::Call(..)
2533            | ExprKind::MethodCall(..)
2534            | ExprKind::Use(..)
2535            | ExprKind::Struct(..)
2536            | ExprKind::Tup(..)
2537            | ExprKind::If(..)
2538            | ExprKind::Match(..)
2539            | ExprKind::Closure { .. }
2540            | ExprKind::Block(..)
2541            | ExprKind::Repeat(..)
2542            | ExprKind::Array(..)
2543            | ExprKind::Break(..)
2544            | ExprKind::Continue(..)
2545            | ExprKind::Ret(..)
2546            | ExprKind::Become(..)
2547            | ExprKind::Let(..)
2548            | ExprKind::Loop(..)
2549            | ExprKind::Assign(..)
2550            | ExprKind::InlineAsm(..)
2551            | ExprKind::OffsetOf(..)
2552            | ExprKind::AssignOp(..)
2553            | ExprKind::Lit(_)
2554            | ExprKind::ConstBlock(..)
2555            | ExprKind::Unary(..)
2556            | ExprKind::AddrOf(..)
2557            | ExprKind::Binary(..)
2558            | ExprKind::Yield(..)
2559            | ExprKind::Cast(..)
2560            | ExprKind::DropTemps(..) => false,
2561        }
2562    }
2563
2564    /// If this is a desugared range expression,
2565    /// returns the span of the range without desugaring context.
2566    pub fn range_span(&self) -> Option<Span> {
2567        is_range_literal(self).then(|| self.span.parent_callsite().unwrap())
2568    }
2569
2570    /// Check if expression is an integer literal that can be used
2571    /// where `usize` is expected.
2572    pub fn is_size_lit(&self) -> bool {
2573        matches!(
2574            self.kind,
2575            ExprKind::Lit(Lit {
2576                node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2577                ..
2578            })
2579        )
2580    }
2581
2582    /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
2583    /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
2584    /// silent, only signaling the ownership system. By doing this, suggestions that check the
2585    /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
2586    /// beyond remembering to call this function before doing analysis on it.
2587    pub fn peel_drop_temps(&self) -> &Self {
2588        let mut expr = self;
2589        while let ExprKind::DropTemps(inner) = &expr.kind {
2590            expr = inner;
2591        }
2592        expr
2593    }
2594
2595    pub fn peel_blocks(&self) -> &Self {
2596        let mut expr = self;
2597        while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2598            expr = inner;
2599        }
2600        expr
2601    }
2602
2603    pub fn peel_borrows(&self) -> &Self {
2604        let mut expr = self;
2605        while let ExprKind::AddrOf(.., inner) = &expr.kind {
2606            expr = inner;
2607        }
2608        expr
2609    }
2610
2611    pub fn can_have_side_effects(&self) -> bool {
2612        match self.peel_drop_temps().kind {
2613            ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2614                false
2615            }
2616            ExprKind::Type(base, _)
2617            | ExprKind::Unary(_, base)
2618            | ExprKind::Field(base, _)
2619            | ExprKind::Index(base, _, _)
2620            | ExprKind::AddrOf(.., base)
2621            | ExprKind::Cast(base, _)
2622            | ExprKind::UnsafeBinderCast(_, base, _) => {
2623                // This isn't exactly true for `Index` and all `Unary`, but we are using this
2624                // method exclusively for diagnostics and there's a *cultural* pressure against
2625                // them being used only for its side-effects.
2626                base.can_have_side_effects()
2627            }
2628            ExprKind::Struct(_, fields, init) => {
2629                let init_side_effects = match init {
2630                    StructTailExpr::Base(init) => init.can_have_side_effects(),
2631                    StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2632                };
2633                fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2634                    || init_side_effects
2635            }
2636
2637            ExprKind::Array(args)
2638            | ExprKind::Tup(args)
2639            | ExprKind::Call(
2640                Expr {
2641                    kind:
2642                        ExprKind::Path(QPath::Resolved(
2643                            None,
2644                            Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2645                        )),
2646                    ..
2647                },
2648                args,
2649            ) => args.iter().any(|arg| arg.can_have_side_effects()),
2650            ExprKind::If(..)
2651            | ExprKind::Match(..)
2652            | ExprKind::MethodCall(..)
2653            | ExprKind::Call(..)
2654            | ExprKind::Closure { .. }
2655            | ExprKind::Block(..)
2656            | ExprKind::Repeat(..)
2657            | ExprKind::Break(..)
2658            | ExprKind::Continue(..)
2659            | ExprKind::Ret(..)
2660            | ExprKind::Become(..)
2661            | ExprKind::Let(..)
2662            | ExprKind::Loop(..)
2663            | ExprKind::Assign(..)
2664            | ExprKind::InlineAsm(..)
2665            | ExprKind::AssignOp(..)
2666            | ExprKind::ConstBlock(..)
2667            | ExprKind::Binary(..)
2668            | ExprKind::Yield(..)
2669            | ExprKind::DropTemps(..)
2670            | ExprKind::Err(_) => true,
2671        }
2672    }
2673
2674    /// To a first-order approximation, is this a pattern?
2675    pub fn is_approximately_pattern(&self) -> bool {
2676        match &self.kind {
2677            ExprKind::Array(_)
2678            | ExprKind::Call(..)
2679            | ExprKind::Tup(_)
2680            | ExprKind::Lit(_)
2681            | ExprKind::Path(_)
2682            | ExprKind::Struct(..) => true,
2683            _ => false,
2684        }
2685    }
2686
2687    /// Whether this and the `other` expression are the same for purposes of an indexing operation.
2688    ///
2689    /// This is only used for diagnostics to see if we have things like `foo[i]` where `foo` is
2690    /// borrowed multiple times with `i`.
2691    pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2692        match (self.kind, other.kind) {
2693            (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2694            (
2695                ExprKind::Path(QPath::Resolved(None, path1)),
2696                ExprKind::Path(QPath::Resolved(None, path2)),
2697            ) => path1.res == path2.res,
2698            (
2699                ExprKind::Struct(
2700                    &QPath::Resolved(None, &Path { res: Res::Def(_, path1_def_id), .. }),
2701                    args1,
2702                    StructTailExpr::None,
2703                ),
2704                ExprKind::Struct(
2705                    &QPath::Resolved(None, &Path { res: Res::Def(_, path2_def_id), .. }),
2706                    args2,
2707                    StructTailExpr::None,
2708                ),
2709            ) => {
2710                path2_def_id == path1_def_id
2711                    && is_range_literal(self)
2712                    && is_range_literal(other)
2713                    && std::iter::zip(args1, args2)
2714                        .all(|(a, b)| a.expr.equivalent_for_indexing(b.expr))
2715            }
2716            _ => false,
2717        }
2718    }
2719
2720    pub fn method_ident(&self) -> Option<Ident> {
2721        match self.kind {
2722            ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2723            ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2724            _ => None,
2725        }
2726    }
2727}
2728
2729/// Checks if the specified expression is a built-in range literal.
2730/// (See: `LoweringContext::lower_expr()`).
2731pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2732    if let ExprKind::Struct(QPath::Resolved(None, path), _, StructTailExpr::None) = expr.kind
2733        && let [.., segment] = path.segments
2734        && let sym::RangeFrom
2735        | sym::RangeFull
2736        | sym::Range
2737        | sym::RangeToInclusive
2738        | sym::RangeTo
2739        | sym::RangeFromCopy
2740        | sym::RangeCopy
2741        | sym::RangeInclusiveCopy
2742        | sym::RangeToInclusiveCopy = segment.ident.name
2743        && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2744    {
2745        true
2746    } else if let ExprKind::Call(func, _) = &expr.kind
2747        && let ExprKind::Path(QPath::Resolved(None, path)) = func.kind
2748        && let [.., segment] = path.segments
2749        && let sym::range_inclusive_new = segment.ident.name
2750        && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2751    {
2752        true
2753    } else {
2754        false
2755    }
2756}
2757
2758/// Checks if the specified expression needs parentheses for prefix
2759/// or postfix suggestions to be valid.
2760/// For example, `a + b` requires parentheses to suggest `&(a + b)`,
2761/// but just `a` does not.
2762/// Similarly, `(a + b).c()` also requires parentheses.
2763/// This should not be used for other types of suggestions.
2764pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2765    match expr.kind {
2766        // parenthesize if needed (Issue #46756)
2767        ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2768        // parenthesize borrows of range literals (Issue #54505)
2769        _ if is_range_literal(expr) => true,
2770        _ => false,
2771    }
2772}
2773
2774#[derive(Debug, Clone, Copy, HashStable_Generic)]
2775pub enum ExprKind<'hir> {
2776    /// Allow anonymous constants from an inline `const` block
2777    ConstBlock(ConstBlock),
2778    /// An array (e.g., `[a, b, c, d]`).
2779    Array(&'hir [Expr<'hir>]),
2780    /// A function call.
2781    ///
2782    /// The first field resolves to the function itself (usually an `ExprKind::Path`),
2783    /// and the second field is the list of arguments.
2784    /// This also represents calling the constructor of
2785    /// tuple-like ADTs such as tuple structs and enum variants.
2786    Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2787    /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
2788    ///
2789    /// The `PathSegment` represents the method name and its generic arguments
2790    /// (within the angle brackets).
2791    /// The `&Expr` is the expression that evaluates
2792    /// to the object on which the method is being called on (the receiver),
2793    /// and the `&[Expr]` is the rest of the arguments.
2794    /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
2795    /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
2796    /// The final `Span` represents the span of the function and arguments
2797    /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
2798    ///
2799    /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
2800    /// the `hir_id` of the `MethodCall` node itself.
2801    ///
2802    /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
2803    MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2804    /// An use expression (e.g., `var.use`).
2805    Use(&'hir Expr<'hir>, Span),
2806    /// A tuple (e.g., `(a, b, c, d)`).
2807    Tup(&'hir [Expr<'hir>]),
2808    /// A binary operation (e.g., `a + b`, `a * b`).
2809    Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2810    /// A unary operation (e.g., `!x`, `*x`).
2811    Unary(UnOp, &'hir Expr<'hir>),
2812    /// A literal (e.g., `1`, `"foo"`).
2813    Lit(Lit),
2814    /// A cast (e.g., `foo as f64`).
2815    Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2816    /// A type ascription (e.g., `x: Foo`). See RFC 3307.
2817    Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2818    /// Wraps the expression in a terminating scope.
2819    /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
2820    ///
2821    /// This construct only exists to tweak the drop order in AST lowering.
2822    /// An example of that is the desugaring of `for` loops.
2823    DropTemps(&'hir Expr<'hir>),
2824    /// A `let $pat = $expr` expression.
2825    ///
2826    /// These are not [`LetStmt`] and only occur as expressions.
2827    /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
2828    Let(&'hir LetExpr<'hir>),
2829    /// An `if` block, with an optional else block.
2830    ///
2831    /// I.e., `if <expr> { <expr> } else { <expr> }`.
2832    ///
2833    /// The "then" expr is always `ExprKind::Block`. If present, the "else" expr is always
2834    /// `ExprKind::Block` (for `else`) or `ExprKind::If` (for `else if`).
2835    /// Note that using an `Expr` instead of a `Block` for the "then" part is intentional,
2836    /// as it simplifies the type coercion machinery.
2837    If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2838    /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
2839    ///
2840    /// I.e., `'label: loop { <block> }`.
2841    ///
2842    /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
2843    Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2844    /// A `match` block, with a source that indicates whether or not it is
2845    /// the result of a desugaring, and if so, which kind.
2846    Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2847    /// A closure (e.g., `move |a, b, c| {a + b + c}`).
2848    ///
2849    /// The `Span` is the argument block `|...|`.
2850    ///
2851    /// This may also be a coroutine literal or an `async block` as indicated by the
2852    /// `Option<Movability>`.
2853    Closure(&'hir Closure<'hir>),
2854    /// A block (e.g., `'label: { ... }`).
2855    Block(&'hir Block<'hir>, Option<Label>),
2856
2857    /// An assignment (e.g., `a = foo()`).
2858    Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2859    /// An assignment with an operator.
2860    ///
2861    /// E.g., `a += 1`.
2862    AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2863    /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
2864    Field(&'hir Expr<'hir>, Ident),
2865    /// An indexing operation (`foo[2]`).
2866    /// Similar to [`ExprKind::MethodCall`], the final `Span` represents the span of the brackets
2867    /// and index.
2868    Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2869
2870    /// Path to a definition, possibly containing lifetime or type parameters.
2871    Path(QPath<'hir>),
2872
2873    /// A referencing operation (i.e., `&a` or `&mut a`).
2874    AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2875    /// A `break`, with an optional label to break.
2876    Break(Destination, Option<&'hir Expr<'hir>>),
2877    /// A `continue`, with an optional label.
2878    Continue(Destination),
2879    /// A `return`, with an optional value to be returned.
2880    Ret(Option<&'hir Expr<'hir>>),
2881    /// A `become`, with the value to be returned.
2882    Become(&'hir Expr<'hir>),
2883
2884    /// Inline assembly (from `asm!`), with its outputs and inputs.
2885    InlineAsm(&'hir InlineAsm<'hir>),
2886
2887    /// Field offset (`offset_of!`)
2888    OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2889
2890    /// A struct or struct-like variant literal expression.
2891    ///
2892    /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2893    /// where `base` is the `Option<Expr>`.
2894    Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2895
2896    /// An array literal constructed from one repeated element.
2897    ///
2898    /// E.g., `[1; 5]`. The first expression is the element
2899    /// to be repeated; the second is the number of times to repeat it.
2900    Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2901
2902    /// A suspension point for coroutines (i.e., `yield <expr>`).
2903    Yield(&'hir Expr<'hir>, YieldSource),
2904
2905    /// Operators which can be used to interconvert `unsafe` binder types.
2906    /// e.g. `unsafe<'a> &'a i32` <=> `&i32`.
2907    UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2908
2909    /// A placeholder for an expression that wasn't syntactically well formed in some way.
2910    Err(rustc_span::ErrorGuaranteed),
2911}
2912
2913#[derive(Debug, Clone, Copy, HashStable_Generic)]
2914pub enum StructTailExpr<'hir> {
2915    /// A struct expression where all the fields are explicitly enumerated: `Foo { a, b }`.
2916    None,
2917    /// A struct expression with a "base", an expression of the same type as the outer struct that
2918    /// will be used to populate any fields not explicitly mentioned: `Foo { ..base }`
2919    Base(&'hir Expr<'hir>),
2920    /// A struct expression with a `..` tail but no "base" expression. The values from the struct
2921    /// fields' default values will be used to populate any fields not explicitly mentioned:
2922    /// `Foo { .. }`.
2923    DefaultFields(Span),
2924}
2925
2926/// Represents an optionally `Self`-qualified value/type path or associated extension.
2927///
2928/// To resolve the path to a `DefId`, call [`qpath_res`].
2929///
2930/// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2931#[derive(Debug, Clone, Copy, HashStable_Generic)]
2932pub enum QPath<'hir> {
2933    /// Path to a definition, optionally "fully-qualified" with a `Self`
2934    /// type, if the path points to an associated item in a trait.
2935    ///
2936    /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2937    /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2938    /// even though they both have the same two-segment `Clone::clone` `Path`.
2939    Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2940
2941    /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2942    /// Will be resolved by type-checking to an associated item.
2943    ///
2944    /// UFCS source paths can desugar into this, with `Vec::new` turning into
2945    /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2946    /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2947    TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2948}
2949
2950impl<'hir> QPath<'hir> {
2951    /// Returns the span of this `QPath`.
2952    pub fn span(&self) -> Span {
2953        match *self {
2954            QPath::Resolved(_, path) => path.span,
2955            QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2956        }
2957    }
2958
2959    /// Returns the span of the qself of this `QPath`. For example, `()` in
2960    /// `<() as Trait>::method`.
2961    pub fn qself_span(&self) -> Span {
2962        match *self {
2963            QPath::Resolved(_, path) => path.span,
2964            QPath::TypeRelative(qself, _) => qself.span,
2965        }
2966    }
2967}
2968
2969/// Hints at the original code for a let statement.
2970#[derive(Copy, Clone, Debug, HashStable_Generic)]
2971pub enum LocalSource {
2972    /// A `match _ { .. }`.
2973    Normal,
2974    /// When lowering async functions, we create locals within the `async move` so that
2975    /// all parameters are dropped after the future is polled.
2976    ///
2977    /// ```ignore (pseudo-Rust)
2978    /// async fn foo(<pattern> @ x: Type) {
2979    ///     async move {
2980    ///         let <pattern> = x;
2981    ///     }
2982    /// }
2983    /// ```
2984    AsyncFn,
2985    /// A desugared `<expr>.await`.
2986    AwaitDesugar,
2987    /// A desugared `expr = expr`, where the LHS is a tuple, struct, array or underscore expression.
2988    AssignDesugar,
2989    /// A contract `#[ensures(..)]` attribute injects a let binding for the check that runs at point of return.
2990    Contract,
2991}
2992
2993/// Hints at the original code for a `match _ { .. }`.
2994#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2995pub enum MatchSource {
2996    /// A `match _ { .. }`.
2997    Normal,
2998    /// A `expr.match { .. }`.
2999    Postfix,
3000    /// A desugared `for _ in _ { .. }` loop.
3001    ForLoopDesugar,
3002    /// A desugared `?` operator.
3003    TryDesugar(HirId),
3004    /// A desugared `<expr>.await`.
3005    AwaitDesugar,
3006    /// A desugared `format_args!()`.
3007    FormatArgs,
3008}
3009
3010impl MatchSource {
3011    #[inline]
3012    pub const fn name(self) -> &'static str {
3013        use MatchSource::*;
3014        match self {
3015            Normal => "match",
3016            Postfix => ".match",
3017            ForLoopDesugar => "for",
3018            TryDesugar(_) => "?",
3019            AwaitDesugar => ".await",
3020            FormatArgs => "format_args!()",
3021        }
3022    }
3023}
3024
3025/// The loop type that yielded an `ExprKind::Loop`.
3026#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3027pub enum LoopSource {
3028    /// A `loop { .. }` loop.
3029    Loop,
3030    /// A `while _ { .. }` loop.
3031    While,
3032    /// A `for _ in _ { .. }` loop.
3033    ForLoop,
3034}
3035
3036impl LoopSource {
3037    pub fn name(self) -> &'static str {
3038        match self {
3039            LoopSource::Loop => "loop",
3040            LoopSource::While => "while",
3041            LoopSource::ForLoop => "for",
3042        }
3043    }
3044}
3045
3046#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
3047pub enum LoopIdError {
3048    OutsideLoopScope,
3049    UnlabeledCfInWhileCondition,
3050    UnresolvedLabel,
3051}
3052
3053impl fmt::Display for LoopIdError {
3054    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3055        f.write_str(match self {
3056            LoopIdError::OutsideLoopScope => "not inside loop scope",
3057            LoopIdError::UnlabeledCfInWhileCondition => {
3058                "unlabeled control flow (break or continue) in while condition"
3059            }
3060            LoopIdError::UnresolvedLabel => "label not found",
3061        })
3062    }
3063}
3064
3065#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
3066pub struct Destination {
3067    /// This is `Some(_)` iff there is an explicit user-specified 'label
3068    pub label: Option<Label>,
3069
3070    /// These errors are caught and then reported during the diagnostics pass in
3071    /// `librustc_passes/loops.rs`
3072    pub target_id: Result<HirId, LoopIdError>,
3073}
3074
3075/// The yield kind that caused an `ExprKind::Yield`.
3076#[derive(Copy, Clone, Debug, HashStable_Generic)]
3077pub enum YieldSource {
3078    /// An `<expr>.await`.
3079    Await { expr: Option<HirId> },
3080    /// A plain `yield`.
3081    Yield,
3082}
3083
3084impl fmt::Display for YieldSource {
3085    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3086        f.write_str(match self {
3087            YieldSource::Await { .. } => "`await`",
3088            YieldSource::Yield => "`yield`",
3089        })
3090    }
3091}
3092
3093// N.B., if you change this, you'll probably want to change the corresponding
3094// type structure in middle/ty.rs as well.
3095#[derive(Debug, Clone, Copy, HashStable_Generic)]
3096pub struct MutTy<'hir> {
3097    pub ty: &'hir Ty<'hir>,
3098    pub mutbl: Mutability,
3099}
3100
3101/// Represents a function's signature in a trait declaration,
3102/// trait implementation, or a free function.
3103#[derive(Debug, Clone, Copy, HashStable_Generic)]
3104pub struct FnSig<'hir> {
3105    pub header: FnHeader,
3106    pub decl: &'hir FnDecl<'hir>,
3107    pub span: Span,
3108}
3109
3110// The bodies for items are stored "out of line", in a separate
3111// hashmap in the `Crate`. Here we just record the hir-id of the item
3112// so it can fetched later.
3113#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3114pub struct TraitItemId {
3115    pub owner_id: OwnerId,
3116}
3117
3118impl TraitItemId {
3119    #[inline]
3120    pub fn hir_id(&self) -> HirId {
3121        // Items are always HIR owners.
3122        HirId::make_owner(self.owner_id.def_id)
3123    }
3124}
3125
3126/// Represents an item declaration within a trait declaration,
3127/// possibly including a default implementation. A trait item is
3128/// either required (meaning it doesn't have an implementation, just a
3129/// signature) or provided (meaning it has a default implementation).
3130#[derive(Debug, Clone, Copy, HashStable_Generic)]
3131pub struct TraitItem<'hir> {
3132    pub ident: Ident,
3133    pub owner_id: OwnerId,
3134    pub generics: &'hir Generics<'hir>,
3135    pub kind: TraitItemKind<'hir>,
3136    pub span: Span,
3137    pub defaultness: Defaultness,
3138    pub has_delayed_lints: bool,
3139}
3140
3141macro_rules! expect_methods_self_kind {
3142    ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3143        $(
3144            #[track_caller]
3145            pub fn $name(&self) -> $ret_ty {
3146                let $pat = &self.kind else { expect_failed(stringify!($name), self) };
3147                $ret_val
3148            }
3149        )*
3150    }
3151}
3152
3153macro_rules! expect_methods_self {
3154    ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3155        $(
3156            #[track_caller]
3157            pub fn $name(&self) -> $ret_ty {
3158                let $pat = self else { expect_failed(stringify!($name), self) };
3159                $ret_val
3160            }
3161        )*
3162    }
3163}
3164
3165#[track_caller]
3166fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3167    panic!("{ident}: found {found:?}")
3168}
3169
3170impl<'hir> TraitItem<'hir> {
3171    #[inline]
3172    pub fn hir_id(&self) -> HirId {
3173        // Items are always HIR owners.
3174        HirId::make_owner(self.owner_id.def_id)
3175    }
3176
3177    pub fn trait_item_id(&self) -> TraitItemId {
3178        TraitItemId { owner_id: self.owner_id }
3179    }
3180
3181    expect_methods_self_kind! {
3182        expect_const, (&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3183            TraitItemKind::Const(ty, rhs), (ty, *rhs);
3184
3185        expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3186            TraitItemKind::Fn(ty, trfn), (ty, trfn);
3187
3188        expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3189            TraitItemKind::Type(bounds, ty), (bounds, *ty);
3190    }
3191}
3192
3193/// Represents a trait method's body (or just argument names).
3194#[derive(Debug, Clone, Copy, HashStable_Generic)]
3195pub enum TraitFn<'hir> {
3196    /// No default body in the trait, just a signature.
3197    Required(&'hir [Option<Ident>]),
3198
3199    /// Both signature and body are provided in the trait.
3200    Provided(BodyId),
3201}
3202
3203/// Represents a trait method or associated constant or type
3204#[derive(Debug, Clone, Copy, HashStable_Generic)]
3205pub enum TraitItemKind<'hir> {
3206    /// An associated constant with an optional value (otherwise `impl`s must contain a value).
3207    Const(&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3208    /// An associated function with an optional body.
3209    Fn(FnSig<'hir>, TraitFn<'hir>),
3210    /// An associated type with (possibly empty) bounds and optional concrete
3211    /// type.
3212    Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3213}
3214
3215// The bodies for items are stored "out of line", in a separate
3216// hashmap in the `Crate`. Here we just record the hir-id of the item
3217// so it can fetched later.
3218#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3219pub struct ImplItemId {
3220    pub owner_id: OwnerId,
3221}
3222
3223impl ImplItemId {
3224    #[inline]
3225    pub fn hir_id(&self) -> HirId {
3226        // Items are always HIR owners.
3227        HirId::make_owner(self.owner_id.def_id)
3228    }
3229}
3230
3231/// Represents an associated item within an impl block.
3232///
3233/// Refer to [`Impl`] for an impl block declaration.
3234#[derive(Debug, Clone, Copy, HashStable_Generic)]
3235pub struct ImplItem<'hir> {
3236    pub ident: Ident,
3237    pub owner_id: OwnerId,
3238    pub generics: &'hir Generics<'hir>,
3239    pub kind: ImplItemKind<'hir>,
3240    pub impl_kind: ImplItemImplKind,
3241    pub span: Span,
3242    pub has_delayed_lints: bool,
3243}
3244
3245#[derive(Debug, Clone, Copy, HashStable_Generic)]
3246pub enum ImplItemImplKind {
3247    Inherent {
3248        vis_span: Span,
3249    },
3250    Trait {
3251        defaultness: Defaultness,
3252        /// Item in the trait that this item implements
3253        trait_item_def_id: Result<DefId, ErrorGuaranteed>,
3254    },
3255}
3256
3257impl<'hir> ImplItem<'hir> {
3258    #[inline]
3259    pub fn hir_id(&self) -> HirId {
3260        // Items are always HIR owners.
3261        HirId::make_owner(self.owner_id.def_id)
3262    }
3263
3264    pub fn impl_item_id(&self) -> ImplItemId {
3265        ImplItemId { owner_id: self.owner_id }
3266    }
3267
3268    pub fn vis_span(&self) -> Option<Span> {
3269        match self.impl_kind {
3270            ImplItemImplKind::Trait { .. } => None,
3271            ImplItemImplKind::Inherent { vis_span, .. } => Some(vis_span),
3272        }
3273    }
3274
3275    expect_methods_self_kind! {
3276        expect_const, (&'hir Ty<'hir>, ConstItemRhs<'hir>), ImplItemKind::Const(ty, rhs), (ty, *rhs);
3277        expect_fn,    (&FnSig<'hir>, BodyId),               ImplItemKind::Fn(ty, body),   (ty, *body);
3278        expect_type,  &'hir Ty<'hir>,                       ImplItemKind::Type(ty),       ty;
3279    }
3280}
3281
3282/// Represents various kinds of content within an `impl`.
3283#[derive(Debug, Clone, Copy, HashStable_Generic)]
3284pub enum ImplItemKind<'hir> {
3285    /// An associated constant of the given type, set to the constant result
3286    /// of the expression.
3287    Const(&'hir Ty<'hir>, ConstItemRhs<'hir>),
3288    /// An associated function implementation with the given signature and body.
3289    Fn(FnSig<'hir>, BodyId),
3290    /// An associated type.
3291    Type(&'hir Ty<'hir>),
3292}
3293
3294/// A constraint on an associated item.
3295///
3296/// ### Examples
3297///
3298/// * the `A = Ty` and `B = Ty` in `Trait<A = Ty, B = Ty>`
3299/// * the `G<Ty> = Ty` in `Trait<G<Ty> = Ty>`
3300/// * the `A: Bound` in `Trait<A: Bound>`
3301/// * the `RetTy` in `Trait(ArgTy, ArgTy) -> RetTy`
3302/// * the `C = { Ct }` in `Trait<C = { Ct }>` (feature `associated_const_equality`)
3303/// * the `f(..): Bound` in `Trait<f(..): Bound>` (feature `return_type_notation`)
3304#[derive(Debug, Clone, Copy, HashStable_Generic)]
3305pub struct AssocItemConstraint<'hir> {
3306    #[stable_hasher(ignore)]
3307    pub hir_id: HirId,
3308    pub ident: Ident,
3309    pub gen_args: &'hir GenericArgs<'hir>,
3310    pub kind: AssocItemConstraintKind<'hir>,
3311    pub span: Span,
3312}
3313
3314impl<'hir> AssocItemConstraint<'hir> {
3315    /// Obtain the type on the RHS of an assoc ty equality constraint if applicable.
3316    pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3317        match self.kind {
3318            AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3319            _ => None,
3320        }
3321    }
3322
3323    /// Obtain the const on the RHS of an assoc const equality constraint if applicable.
3324    pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3325        match self.kind {
3326            AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3327            _ => None,
3328        }
3329    }
3330}
3331
3332#[derive(Debug, Clone, Copy, HashStable_Generic)]
3333pub enum Term<'hir> {
3334    Ty(&'hir Ty<'hir>),
3335    Const(&'hir ConstArg<'hir>),
3336}
3337
3338impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3339    fn from(ty: &'hir Ty<'hir>) -> Self {
3340        Term::Ty(ty)
3341    }
3342}
3343
3344impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3345    fn from(c: &'hir ConstArg<'hir>) -> Self {
3346        Term::Const(c)
3347    }
3348}
3349
3350/// The kind of [associated item constraint][AssocItemConstraint].
3351#[derive(Debug, Clone, Copy, HashStable_Generic)]
3352pub enum AssocItemConstraintKind<'hir> {
3353    /// An equality constraint for an associated item (e.g., `AssocTy = Ty` in `Trait<AssocTy = Ty>`).
3354    ///
3355    /// Also known as an *associated item binding* (we *bind* an associated item to a term).
3356    ///
3357    /// Furthermore, associated type equality constraints can also be referred to as *associated type
3358    /// bindings*. Similarly with associated const equality constraints and *associated const bindings*.
3359    Equality { term: Term<'hir> },
3360    /// A bound on an associated type (e.g., `AssocTy: Bound` in `Trait<AssocTy: Bound>`).
3361    Bound { bounds: &'hir [GenericBound<'hir>] },
3362}
3363
3364impl<'hir> AssocItemConstraintKind<'hir> {
3365    pub fn descr(&self) -> &'static str {
3366        match self {
3367            AssocItemConstraintKind::Equality { .. } => "binding",
3368            AssocItemConstraintKind::Bound { .. } => "constraint",
3369        }
3370    }
3371}
3372
3373/// An uninhabited enum used to make `Infer` variants on [`Ty`] and [`ConstArg`] be
3374/// unreachable. Zero-Variant enums are guaranteed to have the same layout as the never
3375/// type.
3376#[derive(Debug, Clone, Copy, HashStable_Generic)]
3377pub enum AmbigArg {}
3378
3379/// Represents a type in the `HIR`.
3380///
3381/// For an explanation of the `Unambig` generic parameter see the dev-guide:
3382/// <https://rustc-dev-guide.rust-lang.org/ambig-unambig-ty-and-consts.html>
3383#[derive(Debug, Clone, Copy, HashStable_Generic)]
3384#[repr(C)]
3385pub struct Ty<'hir, Unambig = ()> {
3386    #[stable_hasher(ignore)]
3387    pub hir_id: HirId,
3388    pub span: Span,
3389    pub kind: TyKind<'hir, Unambig>,
3390}
3391
3392impl<'hir> Ty<'hir, AmbigArg> {
3393    /// Converts a `Ty` in an ambiguous position to one in an unambiguous position.
3394    ///
3395    /// Functions accepting an unambiguous types may expect the [`TyKind::Infer`] variant
3396    /// to be used. Care should be taken to separately handle infer types when calling this
3397    /// function as it cannot be handled by downstream code making use of the returned ty.
3398    ///
3399    /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or
3400    /// specifically matching on [`GenericArg::Infer`] when handling generic arguments.
3401    ///
3402    /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer]
3403    pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3404        // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is
3405        // the same across different ZST type arguments.
3406        let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3407        unsafe { &*ptr }
3408    }
3409}
3410
3411impl<'hir> Ty<'hir> {
3412    /// Converts a `Ty` in an unambiguous position to one in an ambiguous position. This is
3413    /// fallible as the [`TyKind::Infer`] variant is not present in ambiguous positions.
3414    ///
3415    /// Functions accepting ambiguous types will not handle the [`TyKind::Infer`] variant, if
3416    /// infer types are relevant to you then care should be taken to handle them separately.
3417    pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3418        if let TyKind::Infer(()) = self.kind {
3419            return None;
3420        }
3421
3422        // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is
3423        // the same across different ZST type arguments. We also asserted that the `self` is
3424        // not a `TyKind::Infer` so there is no risk of transmuting a `()` to `AmbigArg`.
3425        let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3426        Some(unsafe { &*ptr })
3427    }
3428}
3429
3430impl<'hir> Ty<'hir, AmbigArg> {
3431    pub fn peel_refs(&self) -> &Ty<'hir> {
3432        let mut final_ty = self.as_unambig_ty();
3433        while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3434            final_ty = ty;
3435        }
3436        final_ty
3437    }
3438}
3439
3440impl<'hir> Ty<'hir> {
3441    pub fn peel_refs(&self) -> &Self {
3442        let mut final_ty = self;
3443        while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3444            final_ty = ty;
3445        }
3446        final_ty
3447    }
3448
3449    /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
3450    pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3451        let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3452            return None;
3453        };
3454        let [segment] = &path.segments else {
3455            return None;
3456        };
3457        match path.res {
3458            Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3459                Some((def_id, segment.ident))
3460            }
3461            _ => None,
3462        }
3463    }
3464
3465    pub fn find_self_aliases(&self) -> Vec<Span> {
3466        use crate::intravisit::Visitor;
3467        struct MyVisitor(Vec<Span>);
3468        impl<'v> Visitor<'v> for MyVisitor {
3469            fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3470                if matches!(
3471                    &t.kind,
3472                    TyKind::Path(QPath::Resolved(
3473                        _,
3474                        Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3475                    ))
3476                ) {
3477                    self.0.push(t.span);
3478                    return;
3479                }
3480                crate::intravisit::walk_ty(self, t);
3481            }
3482        }
3483
3484        let mut my_visitor = MyVisitor(vec![]);
3485        my_visitor.visit_ty_unambig(self);
3486        my_visitor.0
3487    }
3488
3489    /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
3490    /// use inference to provide suggestions for the appropriate type if possible.
3491    pub fn is_suggestable_infer_ty(&self) -> bool {
3492        fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3493            generic_args.iter().any(|arg| match arg {
3494                GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3495                GenericArg::Infer(_) => true,
3496                _ => false,
3497            })
3498        }
3499        debug!(?self);
3500        match &self.kind {
3501            TyKind::Infer(()) => true,
3502            TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3503            TyKind::Array(ty, length) => {
3504                ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3505            }
3506            TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3507            TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3508            TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3509                ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3510            }
3511            TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3512                ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3513                    || segments
3514                        .iter()
3515                        .any(|segment| are_suggestable_generic_args(segment.args().args))
3516            }
3517            _ => false,
3518        }
3519    }
3520}
3521
3522/// Not represented directly in the AST; referred to by name through a `ty_path`.
3523#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3524pub enum PrimTy {
3525    Int(IntTy),
3526    Uint(UintTy),
3527    Float(FloatTy),
3528    Str,
3529    Bool,
3530    Char,
3531}
3532
3533impl PrimTy {
3534    /// All of the primitive types
3535    pub const ALL: [Self; 19] = [
3536        // any changes here should also be reflected in `PrimTy::from_name`
3537        Self::Int(IntTy::I8),
3538        Self::Int(IntTy::I16),
3539        Self::Int(IntTy::I32),
3540        Self::Int(IntTy::I64),
3541        Self::Int(IntTy::I128),
3542        Self::Int(IntTy::Isize),
3543        Self::Uint(UintTy::U8),
3544        Self::Uint(UintTy::U16),
3545        Self::Uint(UintTy::U32),
3546        Self::Uint(UintTy::U64),
3547        Self::Uint(UintTy::U128),
3548        Self::Uint(UintTy::Usize),
3549        Self::Float(FloatTy::F16),
3550        Self::Float(FloatTy::F32),
3551        Self::Float(FloatTy::F64),
3552        Self::Float(FloatTy::F128),
3553        Self::Bool,
3554        Self::Char,
3555        Self::Str,
3556    ];
3557
3558    /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
3559    ///
3560    /// Used by clippy.
3561    pub fn name_str(self) -> &'static str {
3562        match self {
3563            PrimTy::Int(i) => i.name_str(),
3564            PrimTy::Uint(u) => u.name_str(),
3565            PrimTy::Float(f) => f.name_str(),
3566            PrimTy::Str => "str",
3567            PrimTy::Bool => "bool",
3568            PrimTy::Char => "char",
3569        }
3570    }
3571
3572    pub fn name(self) -> Symbol {
3573        match self {
3574            PrimTy::Int(i) => i.name(),
3575            PrimTy::Uint(u) => u.name(),
3576            PrimTy::Float(f) => f.name(),
3577            PrimTy::Str => sym::str,
3578            PrimTy::Bool => sym::bool,
3579            PrimTy::Char => sym::char,
3580        }
3581    }
3582
3583    /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
3584    /// Returns `None` if no matching type is found.
3585    pub fn from_name(name: Symbol) -> Option<Self> {
3586        let ty = match name {
3587            // any changes here should also be reflected in `PrimTy::ALL`
3588            sym::i8 => Self::Int(IntTy::I8),
3589            sym::i16 => Self::Int(IntTy::I16),
3590            sym::i32 => Self::Int(IntTy::I32),
3591            sym::i64 => Self::Int(IntTy::I64),
3592            sym::i128 => Self::Int(IntTy::I128),
3593            sym::isize => Self::Int(IntTy::Isize),
3594            sym::u8 => Self::Uint(UintTy::U8),
3595            sym::u16 => Self::Uint(UintTy::U16),
3596            sym::u32 => Self::Uint(UintTy::U32),
3597            sym::u64 => Self::Uint(UintTy::U64),
3598            sym::u128 => Self::Uint(UintTy::U128),
3599            sym::usize => Self::Uint(UintTy::Usize),
3600            sym::f16 => Self::Float(FloatTy::F16),
3601            sym::f32 => Self::Float(FloatTy::F32),
3602            sym::f64 => Self::Float(FloatTy::F64),
3603            sym::f128 => Self::Float(FloatTy::F128),
3604            sym::bool => Self::Bool,
3605            sym::char => Self::Char,
3606            sym::str => Self::Str,
3607            _ => return None,
3608        };
3609        Some(ty)
3610    }
3611}
3612
3613#[derive(Debug, Clone, Copy, HashStable_Generic)]
3614pub struct FnPtrTy<'hir> {
3615    pub safety: Safety,
3616    pub abi: ExternAbi,
3617    pub generic_params: &'hir [GenericParam<'hir>],
3618    pub decl: &'hir FnDecl<'hir>,
3619    // `Option` because bare fn parameter identifiers are optional. We also end up
3620    // with `None` in some error cases, e.g. invalid parameter patterns.
3621    pub param_idents: &'hir [Option<Ident>],
3622}
3623
3624#[derive(Debug, Clone, Copy, HashStable_Generic)]
3625pub struct UnsafeBinderTy<'hir> {
3626    pub generic_params: &'hir [GenericParam<'hir>],
3627    pub inner_ty: &'hir Ty<'hir>,
3628}
3629
3630#[derive(Debug, Clone, Copy, HashStable_Generic)]
3631pub struct OpaqueTy<'hir> {
3632    #[stable_hasher(ignore)]
3633    pub hir_id: HirId,
3634    pub def_id: LocalDefId,
3635    pub bounds: GenericBounds<'hir>,
3636    pub origin: OpaqueTyOrigin<LocalDefId>,
3637    pub span: Span,
3638}
3639
3640#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3641pub enum PreciseCapturingArgKind<T, U> {
3642    Lifetime(T),
3643    /// Non-lifetime argument (type or const)
3644    Param(U),
3645}
3646
3647pub type PreciseCapturingArg<'hir> =
3648    PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3649
3650impl PreciseCapturingArg<'_> {
3651    pub fn hir_id(self) -> HirId {
3652        match self {
3653            PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3654            PreciseCapturingArg::Param(param) => param.hir_id,
3655        }
3656    }
3657
3658    pub fn name(self) -> Symbol {
3659        match self {
3660            PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3661            PreciseCapturingArg::Param(param) => param.ident.name,
3662        }
3663    }
3664}
3665
3666/// We need to have a [`Node`] for the [`HirId`] that we attach the type/const param
3667/// resolution to. Lifetimes don't have this problem, and for them, it's actually
3668/// kind of detrimental to use a custom node type versus just using [`Lifetime`],
3669/// since resolve_bound_vars operates on `Lifetime`s.
3670#[derive(Debug, Clone, Copy, HashStable_Generic)]
3671pub struct PreciseCapturingNonLifetimeArg {
3672    #[stable_hasher(ignore)]
3673    pub hir_id: HirId,
3674    pub ident: Ident,
3675    pub res: Res,
3676}
3677
3678#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3679#[derive(HashStable_Generic, Encodable, Decodable)]
3680pub enum RpitContext {
3681    Trait,
3682    TraitImpl,
3683}
3684
3685/// From whence the opaque type came.
3686#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3687#[derive(HashStable_Generic, Encodable, Decodable)]
3688pub enum OpaqueTyOrigin<D> {
3689    /// `-> impl Trait`
3690    FnReturn {
3691        /// The defining function.
3692        parent: D,
3693        // Whether this is an RPITIT (return position impl trait in trait)
3694        in_trait_or_impl: Option<RpitContext>,
3695    },
3696    /// `async fn`
3697    AsyncFn {
3698        /// The defining function.
3699        parent: D,
3700        // Whether this is an AFIT (async fn in trait)
3701        in_trait_or_impl: Option<RpitContext>,
3702    },
3703    /// type aliases: `type Foo = impl Trait;`
3704    TyAlias {
3705        /// The type alias or associated type parent of the TAIT/ATPIT
3706        parent: D,
3707        /// associated types in impl blocks for traits.
3708        in_assoc_ty: bool,
3709    },
3710}
3711
3712#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3713pub enum InferDelegationKind {
3714    Input(usize),
3715    Output,
3716}
3717
3718/// The various kinds of types recognized by the compiler.
3719///
3720/// For an explanation of the `Unambig` generic parameter see the dev-guide:
3721/// <https://rustc-dev-guide.rust-lang.org/ambig-unambig-ty-and-consts.html>
3722// SAFETY: `repr(u8)` is required so that `TyKind<()>` and `TyKind<!>` are layout compatible
3723#[repr(u8, C)]
3724#[derive(Debug, Clone, Copy, HashStable_Generic)]
3725pub enum TyKind<'hir, Unambig = ()> {
3726    /// Actual type should be inherited from `DefId` signature
3727    InferDelegation(DefId, InferDelegationKind),
3728    /// A variable length slice (i.e., `[T]`).
3729    Slice(&'hir Ty<'hir>),
3730    /// A fixed length array (i.e., `[T; n]`).
3731    Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3732    /// A raw pointer (i.e., `*const T` or `*mut T`).
3733    Ptr(MutTy<'hir>),
3734    /// A reference (i.e., `&'a T` or `&'a mut T`).
3735    Ref(&'hir Lifetime, MutTy<'hir>),
3736    /// A function pointer (e.g., `fn(usize) -> bool`).
3737    FnPtr(&'hir FnPtrTy<'hir>),
3738    /// An unsafe binder type (e.g. `unsafe<'a> Foo<'a>`).
3739    UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3740    /// The never type (`!`).
3741    Never,
3742    /// A tuple (`(A, B, C, D, ...)`).
3743    Tup(&'hir [Ty<'hir>]),
3744    /// A path to a type definition (`module::module::...::Type`), or an
3745    /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
3746    ///
3747    /// Type parameters may be stored in each `PathSegment`.
3748    Path(QPath<'hir>),
3749    /// An opaque type definition itself. This is only used for `impl Trait`.
3750    OpaqueDef(&'hir OpaqueTy<'hir>),
3751    /// A trait ascription type, which is `impl Trait` within a local binding.
3752    TraitAscription(GenericBounds<'hir>),
3753    /// A trait object type `Bound1 + Bound2 + Bound3`
3754    /// where `Bound` is a trait or a lifetime.
3755    ///
3756    /// We use pointer tagging to represent a `&'hir Lifetime` and `TraitObjectSyntax` pair
3757    /// as otherwise this type being `repr(C)` would result in `TyKind` increasing in size.
3758    TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3759    /// Placeholder for a type that has failed to be defined.
3760    Err(rustc_span::ErrorGuaranteed),
3761    /// Pattern types (`pattern_type!(u32 is 1..)`)
3762    Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3763    /// `TyKind::Infer` means the type should be inferred instead of it having been
3764    /// specified. This can appear anywhere in a type.
3765    ///
3766    /// This variant is not always used to represent inference types, sometimes
3767    /// [`GenericArg::Infer`] is used instead.
3768    Infer(Unambig),
3769}
3770
3771#[derive(Debug, Clone, Copy, HashStable_Generic)]
3772pub enum InlineAsmOperand<'hir> {
3773    In {
3774        reg: InlineAsmRegOrRegClass,
3775        expr: &'hir Expr<'hir>,
3776    },
3777    Out {
3778        reg: InlineAsmRegOrRegClass,
3779        late: bool,
3780        expr: Option<&'hir Expr<'hir>>,
3781    },
3782    InOut {
3783        reg: InlineAsmRegOrRegClass,
3784        late: bool,
3785        expr: &'hir Expr<'hir>,
3786    },
3787    SplitInOut {
3788        reg: InlineAsmRegOrRegClass,
3789        late: bool,
3790        in_expr: &'hir Expr<'hir>,
3791        out_expr: Option<&'hir Expr<'hir>>,
3792    },
3793    Const {
3794        anon_const: ConstBlock,
3795    },
3796    SymFn {
3797        expr: &'hir Expr<'hir>,
3798    },
3799    SymStatic {
3800        path: QPath<'hir>,
3801        def_id: DefId,
3802    },
3803    Label {
3804        block: &'hir Block<'hir>,
3805    },
3806}
3807
3808impl<'hir> InlineAsmOperand<'hir> {
3809    pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3810        match *self {
3811            Self::In { reg, .. }
3812            | Self::Out { reg, .. }
3813            | Self::InOut { reg, .. }
3814            | Self::SplitInOut { reg, .. } => Some(reg),
3815            Self::Const { .. }
3816            | Self::SymFn { .. }
3817            | Self::SymStatic { .. }
3818            | Self::Label { .. } => None,
3819        }
3820    }
3821
3822    pub fn is_clobber(&self) -> bool {
3823        matches!(
3824            self,
3825            InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3826        )
3827    }
3828}
3829
3830#[derive(Debug, Clone, Copy, HashStable_Generic)]
3831pub struct InlineAsm<'hir> {
3832    pub asm_macro: ast::AsmMacro,
3833    pub template: &'hir [InlineAsmTemplatePiece],
3834    pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3835    pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3836    pub options: InlineAsmOptions,
3837    pub line_spans: &'hir [Span],
3838}
3839
3840impl InlineAsm<'_> {
3841    pub fn contains_label(&self) -> bool {
3842        self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3843    }
3844}
3845
3846/// Represents a parameter in a function header.
3847#[derive(Debug, Clone, Copy, HashStable_Generic)]
3848pub struct Param<'hir> {
3849    #[stable_hasher(ignore)]
3850    pub hir_id: HirId,
3851    pub pat: &'hir Pat<'hir>,
3852    pub ty_span: Span,
3853    pub span: Span,
3854}
3855
3856/// Represents the header (not the body) of a function declaration.
3857#[derive(Debug, Clone, Copy, HashStable_Generic)]
3858pub struct FnDecl<'hir> {
3859    /// The types of the function's parameters.
3860    ///
3861    /// Additional argument data is stored in the function's [body](Body::params).
3862    pub inputs: &'hir [Ty<'hir>],
3863    pub output: FnRetTy<'hir>,
3864    pub c_variadic: bool,
3865    /// Does the function have an implicit self?
3866    pub implicit_self: ImplicitSelfKind,
3867    /// Is lifetime elision allowed.
3868    pub lifetime_elision_allowed: bool,
3869}
3870
3871impl<'hir> FnDecl<'hir> {
3872    pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3873        if let FnRetTy::Return(ty) = self.output
3874            && let TyKind::InferDelegation(sig_id, _) = ty.kind
3875        {
3876            return Some(sig_id);
3877        }
3878        None
3879    }
3880}
3881
3882/// Represents what type of implicit self a function has, if any.
3883#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3884pub enum ImplicitSelfKind {
3885    /// Represents a `fn x(self);`.
3886    Imm,
3887    /// Represents a `fn x(mut self);`.
3888    Mut,
3889    /// Represents a `fn x(&self);`.
3890    RefImm,
3891    /// Represents a `fn x(&mut self);`.
3892    RefMut,
3893    /// Represents when a function does not have a self argument or
3894    /// when a function has a `self: X` argument.
3895    None,
3896}
3897
3898impl ImplicitSelfKind {
3899    /// Does this represent an implicit self?
3900    pub fn has_implicit_self(&self) -> bool {
3901        !matches!(*self, ImplicitSelfKind::None)
3902    }
3903}
3904
3905#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3906pub enum IsAsync {
3907    Async(Span),
3908    NotAsync,
3909}
3910
3911impl IsAsync {
3912    pub fn is_async(self) -> bool {
3913        matches!(self, IsAsync::Async(_))
3914    }
3915}
3916
3917#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3918#[derive(Default)]
3919pub enum Defaultness {
3920    Default {
3921        has_value: bool,
3922    },
3923    #[default]
3924    Final,
3925}
3926
3927impl Defaultness {
3928    pub fn has_value(&self) -> bool {
3929        match *self {
3930            Defaultness::Default { has_value } => has_value,
3931            Defaultness::Final => true,
3932        }
3933    }
3934
3935    pub fn is_final(&self) -> bool {
3936        *self == Defaultness::Final
3937    }
3938
3939    pub fn is_default(&self) -> bool {
3940        matches!(*self, Defaultness::Default { .. })
3941    }
3942}
3943
3944#[derive(Debug, Clone, Copy, HashStable_Generic)]
3945pub enum FnRetTy<'hir> {
3946    /// Return type is not specified.
3947    ///
3948    /// Functions default to `()` and
3949    /// closures default to inference. Span points to where return
3950    /// type would be inserted.
3951    DefaultReturn(Span),
3952    /// Everything else.
3953    Return(&'hir Ty<'hir>),
3954}
3955
3956impl<'hir> FnRetTy<'hir> {
3957    #[inline]
3958    pub fn span(&self) -> Span {
3959        match *self {
3960            Self::DefaultReturn(span) => span,
3961            Self::Return(ref ty) => ty.span,
3962        }
3963    }
3964
3965    pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3966        if let Self::Return(ty) = self
3967            && ty.is_suggestable_infer_ty()
3968        {
3969            return Some(*ty);
3970        }
3971        None
3972    }
3973}
3974
3975/// Represents `for<...>` binder before a closure
3976#[derive(Copy, Clone, Debug, HashStable_Generic)]
3977pub enum ClosureBinder {
3978    /// Binder is not specified.
3979    Default,
3980    /// Binder is specified.
3981    ///
3982    /// Span points to the whole `for<...>`.
3983    For { span: Span },
3984}
3985
3986#[derive(Debug, Clone, Copy, HashStable_Generic)]
3987pub struct Mod<'hir> {
3988    pub spans: ModSpans,
3989    pub item_ids: &'hir [ItemId],
3990}
3991
3992#[derive(Copy, Clone, Debug, HashStable_Generic)]
3993pub struct ModSpans {
3994    /// A span from the first token past `{` to the last token until `}`.
3995    /// For `mod foo;`, the inner span ranges from the first token
3996    /// to the last token in the external file.
3997    pub inner_span: Span,
3998    pub inject_use_span: Span,
3999}
4000
4001#[derive(Debug, Clone, Copy, HashStable_Generic)]
4002pub struct EnumDef<'hir> {
4003    pub variants: &'hir [Variant<'hir>],
4004}
4005
4006#[derive(Debug, Clone, Copy, HashStable_Generic)]
4007pub struct Variant<'hir> {
4008    /// Name of the variant.
4009    pub ident: Ident,
4010    /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
4011    #[stable_hasher(ignore)]
4012    pub hir_id: HirId,
4013    pub def_id: LocalDefId,
4014    /// Fields and constructor id of the variant.
4015    pub data: VariantData<'hir>,
4016    /// Explicit discriminant (e.g., `Foo = 1`).
4017    pub disr_expr: Option<&'hir AnonConst>,
4018    /// Span
4019    pub span: Span,
4020}
4021
4022#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
4023pub enum UseKind {
4024    /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
4025    /// Also produced for each element of a list `use`, e.g.
4026    /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
4027    ///
4028    /// The identifier is the name defined by the import. E.g. for `use
4029    /// foo::bar` it is `bar`, for `use foo::bar as baz` it is `baz`.
4030    Single(Ident),
4031
4032    /// Glob import, e.g., `use foo::*`.
4033    Glob,
4034
4035    /// Degenerate list import, e.g., `use foo::{a, b}` produces
4036    /// an additional `use foo::{}` for performing checks such as
4037    /// unstable feature gating. May be removed in the future.
4038    ListStem,
4039}
4040
4041/// References to traits in impls.
4042///
4043/// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
4044/// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
4045/// trait being referred to but just a unique `HirId` that serves as a key
4046/// within the resolution map.
4047#[derive(Clone, Debug, Copy, HashStable_Generic)]
4048pub struct TraitRef<'hir> {
4049    pub path: &'hir Path<'hir>,
4050    // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
4051    #[stable_hasher(ignore)]
4052    pub hir_ref_id: HirId,
4053}
4054
4055impl TraitRef<'_> {
4056    /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
4057    pub fn trait_def_id(&self) -> Option<DefId> {
4058        match self.path.res {
4059            Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
4060            Res::Err => None,
4061            res => panic!("{res:?} did not resolve to a trait or trait alias"),
4062        }
4063    }
4064}
4065
4066#[derive(Clone, Debug, Copy, HashStable_Generic)]
4067pub struct PolyTraitRef<'hir> {
4068    /// The `'a` in `for<'a> Foo<&'a T>`.
4069    pub bound_generic_params: &'hir [GenericParam<'hir>],
4070
4071    /// The constness and polarity of the trait ref.
4072    ///
4073    /// The `async` modifier is lowered directly into a different trait for now.
4074    pub modifiers: TraitBoundModifiers,
4075
4076    /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
4077    pub trait_ref: TraitRef<'hir>,
4078
4079    pub span: Span,
4080}
4081
4082#[derive(Debug, Clone, Copy, HashStable_Generic)]
4083pub struct FieldDef<'hir> {
4084    pub span: Span,
4085    pub vis_span: Span,
4086    pub ident: Ident,
4087    #[stable_hasher(ignore)]
4088    pub hir_id: HirId,
4089    pub def_id: LocalDefId,
4090    pub ty: &'hir Ty<'hir>,
4091    pub safety: Safety,
4092    pub default: Option<&'hir AnonConst>,
4093}
4094
4095impl FieldDef<'_> {
4096    // Still necessary in couple of places
4097    pub fn is_positional(&self) -> bool {
4098        self.ident.as_str().as_bytes()[0].is_ascii_digit()
4099    }
4100}
4101
4102/// Fields and constructor IDs of enum variants and structs.
4103#[derive(Debug, Clone, Copy, HashStable_Generic)]
4104pub enum VariantData<'hir> {
4105    /// A struct variant.
4106    ///
4107    /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
4108    Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4109    /// A tuple variant.
4110    ///
4111    /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
4112    Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4113    /// A unit variant.
4114    ///
4115    /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
4116    Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4117}
4118
4119impl<'hir> VariantData<'hir> {
4120    /// Return the fields of this variant.
4121    pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4122        match *self {
4123            VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4124            _ => &[],
4125        }
4126    }
4127
4128    pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4129        match *self {
4130            VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4131            VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4132            VariantData::Struct { .. } => None,
4133        }
4134    }
4135
4136    #[inline]
4137    pub fn ctor_kind(&self) -> Option<CtorKind> {
4138        self.ctor().map(|(kind, ..)| kind)
4139    }
4140
4141    /// Return the `HirId` of this variant's constructor, if it has one.
4142    #[inline]
4143    pub fn ctor_hir_id(&self) -> Option<HirId> {
4144        self.ctor().map(|(_, hir_id, _)| hir_id)
4145    }
4146
4147    /// Return the `LocalDefId` of this variant's constructor, if it has one.
4148    #[inline]
4149    pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4150        self.ctor().map(|(.., def_id)| def_id)
4151    }
4152}
4153
4154// The bodies for items are stored "out of line", in a separate
4155// hashmap in the `Crate`. Here we just record the hir-id of the item
4156// so it can fetched later.
4157#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4158pub struct ItemId {
4159    pub owner_id: OwnerId,
4160}
4161
4162impl ItemId {
4163    #[inline]
4164    pub fn hir_id(&self) -> HirId {
4165        // Items are always HIR owners.
4166        HirId::make_owner(self.owner_id.def_id)
4167    }
4168}
4169
4170/// An item
4171///
4172/// For more details, see the [rust lang reference].
4173/// Note that the reference does not document nightly-only features.
4174/// There may be also slight differences in the names and representation of AST nodes between
4175/// the compiler and the reference.
4176///
4177/// [rust lang reference]: https://doc.rust-lang.org/reference/items.html
4178#[derive(Debug, Clone, Copy, HashStable_Generic)]
4179pub struct Item<'hir> {
4180    pub owner_id: OwnerId,
4181    pub kind: ItemKind<'hir>,
4182    pub span: Span,
4183    pub vis_span: Span,
4184    pub has_delayed_lints: bool,
4185    /// hint to speed up collection: true if the item is a static or function and has
4186    /// either an `EiiImpls` or `EiiExternTarget` attribute
4187    pub eii: bool,
4188}
4189
4190impl<'hir> Item<'hir> {
4191    #[inline]
4192    pub fn hir_id(&self) -> HirId {
4193        // Items are always HIR owners.
4194        HirId::make_owner(self.owner_id.def_id)
4195    }
4196
4197    pub fn item_id(&self) -> ItemId {
4198        ItemId { owner_id: self.owner_id }
4199    }
4200
4201    /// Check if this is an [`ItemKind::Enum`], [`ItemKind::Struct`] or
4202    /// [`ItemKind::Union`].
4203    pub fn is_adt(&self) -> bool {
4204        matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4205    }
4206
4207    /// Check if this is an [`ItemKind::Struct`] or [`ItemKind::Union`].
4208    pub fn is_struct_or_union(&self) -> bool {
4209        matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4210    }
4211
4212    expect_methods_self_kind! {
4213        expect_extern_crate, (Option<Symbol>, Ident),
4214            ItemKind::ExternCrate(s, ident), (*s, *ident);
4215
4216        expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4217
4218        expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4219            ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4220
4221        expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4222            ItemKind::Const(ident, generics, ty, rhs), (*ident, generics, ty, *rhs);
4223
4224        expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4225            ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4226
4227        expect_macro, (Ident, &ast::MacroDef, MacroKinds),
4228            ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4229
4230        expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4231
4232        expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]),
4233            ItemKind::ForeignMod { abi, items }, (*abi, items);
4234
4235        expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4236
4237        expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4238            ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4239
4240        expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4241            ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4242
4243        expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4244            ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4245
4246        expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4247            ItemKind::Union(ident, generics, data), (*ident, generics, data);
4248
4249        expect_trait,
4250            (
4251                Constness,
4252                IsAuto,
4253                Safety,
4254                Ident,
4255                &'hir Generics<'hir>,
4256                GenericBounds<'hir>,
4257                &'hir [TraitItemId]
4258            ),
4259            ItemKind::Trait(constness, is_auto, safety, ident, generics, bounds, items),
4260            (*constness, *is_auto, *safety, *ident, generics, bounds, items);
4261
4262        expect_trait_alias, (Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4263            ItemKind::TraitAlias(constness, ident, generics, bounds), (*constness, *ident, generics, bounds);
4264
4265        expect_impl, &Impl<'hir>, ItemKind::Impl(imp), imp;
4266    }
4267}
4268
4269#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4270#[derive(Encodable, Decodable, HashStable_Generic, Default)]
4271pub enum Safety {
4272    /// This is the default variant, because the compiler messing up
4273    /// metadata encoding and failing to encode a `Safe` flag, means
4274    /// downstream crates think a thing is `Unsafe` instead of silently
4275    /// treating an unsafe thing as safe.
4276    #[default]
4277    Unsafe,
4278    Safe,
4279}
4280
4281impl Safety {
4282    pub fn prefix_str(self) -> &'static str {
4283        match self {
4284            Self::Unsafe => "unsafe ",
4285            Self::Safe => "",
4286        }
4287    }
4288
4289    #[inline]
4290    pub fn is_unsafe(self) -> bool {
4291        !self.is_safe()
4292    }
4293
4294    #[inline]
4295    pub fn is_safe(self) -> bool {
4296        match self {
4297            Self::Unsafe => false,
4298            Self::Safe => true,
4299        }
4300    }
4301}
4302
4303impl fmt::Display for Safety {
4304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4305        f.write_str(match *self {
4306            Self::Unsafe => "unsafe",
4307            Self::Safe => "safe",
4308        })
4309    }
4310}
4311
4312#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4313#[derive(Default)]
4314pub enum Constness {
4315    #[default]
4316    Const,
4317    NotConst,
4318}
4319
4320impl fmt::Display for Constness {
4321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4322        f.write_str(match *self {
4323            Self::Const => "const",
4324            Self::NotConst => "non-const",
4325        })
4326    }
4327}
4328
4329/// The actual safety specified in syntax. We may treat
4330/// its safety different within the type system to create a
4331/// "sound by default" system that needs checking this enum
4332/// explicitly to allow unsafe operations.
4333#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4334pub enum HeaderSafety {
4335    /// A safe function annotated with `#[target_features]`.
4336    /// The type system treats this function as an unsafe function,
4337    /// but safety checking will check this enum to treat it as safe
4338    /// and allowing calling other safe target feature functions with
4339    /// the same features without requiring an additional unsafe block.
4340    SafeTargetFeatures,
4341    Normal(Safety),
4342}
4343
4344impl From<Safety> for HeaderSafety {
4345    fn from(v: Safety) -> Self {
4346        Self::Normal(v)
4347    }
4348}
4349
4350#[derive(Copy, Clone, Debug, HashStable_Generic)]
4351pub struct FnHeader {
4352    pub safety: HeaderSafety,
4353    pub constness: Constness,
4354    pub asyncness: IsAsync,
4355    pub abi: ExternAbi,
4356}
4357
4358impl FnHeader {
4359    pub fn is_async(&self) -> bool {
4360        matches!(self.asyncness, IsAsync::Async(_))
4361    }
4362
4363    pub fn is_const(&self) -> bool {
4364        matches!(self.constness, Constness::Const)
4365    }
4366
4367    pub fn is_unsafe(&self) -> bool {
4368        self.safety().is_unsafe()
4369    }
4370
4371    pub fn is_safe(&self) -> bool {
4372        self.safety().is_safe()
4373    }
4374
4375    pub fn safety(&self) -> Safety {
4376        match self.safety {
4377            HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4378            HeaderSafety::Normal(safety) => safety,
4379        }
4380    }
4381}
4382
4383#[derive(Debug, Clone, Copy, HashStable_Generic)]
4384pub enum ItemKind<'hir> {
4385    /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
4386    ///
4387    /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
4388    ExternCrate(Option<Symbol>, Ident),
4389
4390    /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
4391    ///
4392    /// or just
4393    ///
4394    /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
4395    Use(&'hir UsePath<'hir>, UseKind),
4396
4397    /// A `static` item.
4398    Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4399    /// A `const` item.
4400    Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4401    /// A function declaration.
4402    Fn {
4403        sig: FnSig<'hir>,
4404        ident: Ident,
4405        generics: &'hir Generics<'hir>,
4406        body: BodyId,
4407        /// Whether this function actually has a body.
4408        /// For functions without a body, `body` is synthesized (to avoid ICEs all over the
4409        /// compiler), but that code should never be translated.
4410        has_body: bool,
4411    },
4412    /// A MBE macro definition (`macro_rules!` or `macro`).
4413    Macro(Ident, &'hir ast::MacroDef, MacroKinds),
4414    /// A module.
4415    Mod(Ident, &'hir Mod<'hir>),
4416    /// An external module, e.g. `extern { .. }`.
4417    ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] },
4418    /// Module-level inline assembly (from `global_asm!`).
4419    GlobalAsm {
4420        asm: &'hir InlineAsm<'hir>,
4421        /// A fake body which stores typeck results for the global asm's sym_fn
4422        /// operands, which are represented as path expressions. This body contains
4423        /// a single [`ExprKind::InlineAsm`] which points to the asm in the field
4424        /// above, and which is typechecked like a inline asm expr just for the
4425        /// typeck results.
4426        fake_body: BodyId,
4427    },
4428    /// A type alias, e.g., `type Foo = Bar<u8>`.
4429    TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4430    /// An enum definition, e.g., `enum Foo<A, B> { C<A>, D<B> }`.
4431    Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4432    /// A struct definition, e.g., `struct Foo<A> {x: A}`.
4433    Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4434    /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
4435    Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4436    /// A trait definition.
4437    Trait(
4438        Constness,
4439        IsAuto,
4440        Safety,
4441        Ident,
4442        &'hir Generics<'hir>,
4443        GenericBounds<'hir>,
4444        &'hir [TraitItemId],
4445    ),
4446    /// A trait alias.
4447    TraitAlias(Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4448
4449    /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
4450    Impl(Impl<'hir>),
4451}
4452
4453/// Represents an impl block declaration.
4454///
4455/// E.g., `impl $Type { .. }` or `impl $Trait for $Type { .. }`
4456/// Refer to [`ImplItem`] for an associated item within an impl block.
4457#[derive(Debug, Clone, Copy, HashStable_Generic)]
4458pub struct Impl<'hir> {
4459    pub generics: &'hir Generics<'hir>,
4460    pub of_trait: Option<&'hir TraitImplHeader<'hir>>,
4461    pub self_ty: &'hir Ty<'hir>,
4462    pub items: &'hir [ImplItemId],
4463    pub constness: Constness,
4464}
4465
4466#[derive(Debug, Clone, Copy, HashStable_Generic)]
4467pub struct TraitImplHeader<'hir> {
4468    pub safety: Safety,
4469    pub polarity: ImplPolarity,
4470    pub defaultness: Defaultness,
4471    // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
4472    // decoding as `Span`s cannot be decoded when a `Session` is not available.
4473    pub defaultness_span: Option<Span>,
4474    pub trait_ref: TraitRef<'hir>,
4475}
4476
4477impl ItemKind<'_> {
4478    pub fn ident(&self) -> Option<Ident> {
4479        match *self {
4480            ItemKind::ExternCrate(_, ident)
4481            | ItemKind::Use(_, UseKind::Single(ident))
4482            | ItemKind::Static(_, ident, ..)
4483            | ItemKind::Const(ident, ..)
4484            | ItemKind::Fn { ident, .. }
4485            | ItemKind::Macro(ident, ..)
4486            | ItemKind::Mod(ident, ..)
4487            | ItemKind::TyAlias(ident, ..)
4488            | ItemKind::Enum(ident, ..)
4489            | ItemKind::Struct(ident, ..)
4490            | ItemKind::Union(ident, ..)
4491            | ItemKind::Trait(_, _, _, ident, ..)
4492            | ItemKind::TraitAlias(_, ident, ..) => Some(ident),
4493
4494            ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4495            | ItemKind::ForeignMod { .. }
4496            | ItemKind::GlobalAsm { .. }
4497            | ItemKind::Impl(_) => None,
4498        }
4499    }
4500
4501    pub fn generics(&self) -> Option<&Generics<'_>> {
4502        Some(match self {
4503            ItemKind::Fn { generics, .. }
4504            | ItemKind::TyAlias(_, generics, _)
4505            | ItemKind::Const(_, generics, _, _)
4506            | ItemKind::Enum(_, generics, _)
4507            | ItemKind::Struct(_, generics, _)
4508            | ItemKind::Union(_, generics, _)
4509            | ItemKind::Trait(_, _, _, _, generics, _, _)
4510            | ItemKind::TraitAlias(_, _, generics, _)
4511            | ItemKind::Impl(Impl { generics, .. }) => generics,
4512            _ => return None,
4513        })
4514    }
4515}
4516
4517// The bodies for items are stored "out of line", in a separate
4518// hashmap in the `Crate`. Here we just record the hir-id of the item
4519// so it can fetched later.
4520#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4521pub struct ForeignItemId {
4522    pub owner_id: OwnerId,
4523}
4524
4525impl ForeignItemId {
4526    #[inline]
4527    pub fn hir_id(&self) -> HirId {
4528        // Items are always HIR owners.
4529        HirId::make_owner(self.owner_id.def_id)
4530    }
4531}
4532
4533#[derive(Debug, Clone, Copy, HashStable_Generic)]
4534pub struct ForeignItem<'hir> {
4535    pub ident: Ident,
4536    pub kind: ForeignItemKind<'hir>,
4537    pub owner_id: OwnerId,
4538    pub span: Span,
4539    pub vis_span: Span,
4540    pub has_delayed_lints: bool,
4541}
4542
4543impl ForeignItem<'_> {
4544    #[inline]
4545    pub fn hir_id(&self) -> HirId {
4546        // Items are always HIR owners.
4547        HirId::make_owner(self.owner_id.def_id)
4548    }
4549
4550    pub fn foreign_item_id(&self) -> ForeignItemId {
4551        ForeignItemId { owner_id: self.owner_id }
4552    }
4553}
4554
4555/// An item within an `extern` block.
4556#[derive(Debug, Clone, Copy, HashStable_Generic)]
4557pub enum ForeignItemKind<'hir> {
4558    /// A foreign function.
4559    ///
4560    /// All argument idents are actually always present (i.e. `Some`), but
4561    /// `&[Option<Ident>]` is used because of code paths shared with `TraitFn`
4562    /// and `FnPtrTy`. The sharing is due to all of these cases not allowing
4563    /// arbitrary patterns for parameters.
4564    Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4565    /// A foreign static item (`static ext: u8`).
4566    Static(&'hir Ty<'hir>, Mutability, Safety),
4567    /// A foreign type.
4568    Type,
4569}
4570
4571/// A variable captured by a closure.
4572#[derive(Debug, Copy, Clone, HashStable_Generic)]
4573pub struct Upvar {
4574    /// First span where it is accessed (there can be multiple).
4575    pub span: Span,
4576}
4577
4578// The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
4579// has length > 0 if the trait is found through an chain of imports, starting with the
4580// import/use statement in the scope where the trait is used.
4581#[derive(Debug, Clone, HashStable_Generic)]
4582pub struct TraitCandidate {
4583    pub def_id: DefId,
4584    pub import_ids: SmallVec<[LocalDefId; 1]>,
4585}
4586
4587#[derive(Copy, Clone, Debug, HashStable_Generic)]
4588pub enum OwnerNode<'hir> {
4589    Item(&'hir Item<'hir>),
4590    ForeignItem(&'hir ForeignItem<'hir>),
4591    TraitItem(&'hir TraitItem<'hir>),
4592    ImplItem(&'hir ImplItem<'hir>),
4593    Crate(&'hir Mod<'hir>),
4594    Synthetic,
4595}
4596
4597impl<'hir> OwnerNode<'hir> {
4598    pub fn span(&self) -> Span {
4599        match self {
4600            OwnerNode::Item(Item { span, .. })
4601            | OwnerNode::ForeignItem(ForeignItem { span, .. })
4602            | OwnerNode::ImplItem(ImplItem { span, .. })
4603            | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4604            OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4605            OwnerNode::Synthetic => unreachable!(),
4606        }
4607    }
4608
4609    pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4610        match self {
4611            OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4612            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4613            | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4614            | OwnerNode::ForeignItem(ForeignItem {
4615                kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4616            }) => Some(fn_sig),
4617            _ => None,
4618        }
4619    }
4620
4621    pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4622        match self {
4623            OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4624            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4625            | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4626            | OwnerNode::ForeignItem(ForeignItem {
4627                kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4628            }) => Some(fn_sig.decl),
4629            _ => None,
4630        }
4631    }
4632
4633    pub fn body_id(&self) -> Option<BodyId> {
4634        match self {
4635            OwnerNode::Item(Item {
4636                kind:
4637                    ItemKind::Static(_, _, _, body)
4638                    | ItemKind::Const(.., ConstItemRhs::Body(body))
4639                    | ItemKind::Fn { body, .. },
4640                ..
4641            })
4642            | OwnerNode::TraitItem(TraitItem {
4643                kind:
4644                    TraitItemKind::Fn(_, TraitFn::Provided(body))
4645                    | TraitItemKind::Const(_, Some(ConstItemRhs::Body(body))),
4646                ..
4647            })
4648            | OwnerNode::ImplItem(ImplItem {
4649                kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, ConstItemRhs::Body(body)),
4650                ..
4651            }) => Some(*body),
4652            _ => None,
4653        }
4654    }
4655
4656    pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4657        Node::generics(self.into())
4658    }
4659
4660    pub fn def_id(self) -> OwnerId {
4661        match self {
4662            OwnerNode::Item(Item { owner_id, .. })
4663            | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4664            | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4665            | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4666            OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4667            OwnerNode::Synthetic => unreachable!(),
4668        }
4669    }
4670
4671    /// Check if node is an impl block.
4672    pub fn is_impl_block(&self) -> bool {
4673        matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4674    }
4675
4676    expect_methods_self! {
4677        expect_item,         &'hir Item<'hir>,        OwnerNode::Item(n),        n;
4678        expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4679        expect_impl_item,    &'hir ImplItem<'hir>,    OwnerNode::ImplItem(n),    n;
4680        expect_trait_item,   &'hir TraitItem<'hir>,   OwnerNode::TraitItem(n),   n;
4681    }
4682}
4683
4684impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4685    fn from(val: &'hir Item<'hir>) -> Self {
4686        OwnerNode::Item(val)
4687    }
4688}
4689
4690impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4691    fn from(val: &'hir ForeignItem<'hir>) -> Self {
4692        OwnerNode::ForeignItem(val)
4693    }
4694}
4695
4696impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4697    fn from(val: &'hir ImplItem<'hir>) -> Self {
4698        OwnerNode::ImplItem(val)
4699    }
4700}
4701
4702impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4703    fn from(val: &'hir TraitItem<'hir>) -> Self {
4704        OwnerNode::TraitItem(val)
4705    }
4706}
4707
4708impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4709    fn from(val: OwnerNode<'hir>) -> Self {
4710        match val {
4711            OwnerNode::Item(n) => Node::Item(n),
4712            OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4713            OwnerNode::ImplItem(n) => Node::ImplItem(n),
4714            OwnerNode::TraitItem(n) => Node::TraitItem(n),
4715            OwnerNode::Crate(n) => Node::Crate(n),
4716            OwnerNode::Synthetic => Node::Synthetic,
4717        }
4718    }
4719}
4720
4721#[derive(Copy, Clone, Debug, HashStable_Generic)]
4722pub enum Node<'hir> {
4723    Param(&'hir Param<'hir>),
4724    Item(&'hir Item<'hir>),
4725    ForeignItem(&'hir ForeignItem<'hir>),
4726    TraitItem(&'hir TraitItem<'hir>),
4727    ImplItem(&'hir ImplItem<'hir>),
4728    Variant(&'hir Variant<'hir>),
4729    Field(&'hir FieldDef<'hir>),
4730    AnonConst(&'hir AnonConst),
4731    ConstBlock(&'hir ConstBlock),
4732    ConstArg(&'hir ConstArg<'hir>),
4733    Expr(&'hir Expr<'hir>),
4734    ExprField(&'hir ExprField<'hir>),
4735    ConstArgExprField(&'hir ConstArgExprField<'hir>),
4736    Stmt(&'hir Stmt<'hir>),
4737    PathSegment(&'hir PathSegment<'hir>),
4738    Ty(&'hir Ty<'hir>),
4739    AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4740    TraitRef(&'hir TraitRef<'hir>),
4741    OpaqueTy(&'hir OpaqueTy<'hir>),
4742    TyPat(&'hir TyPat<'hir>),
4743    Pat(&'hir Pat<'hir>),
4744    PatField(&'hir PatField<'hir>),
4745    /// Needed as its own node with its own HirId for tracking
4746    /// the unadjusted type of literals within patterns
4747    /// (e.g. byte str literals not being of slice type).
4748    PatExpr(&'hir PatExpr<'hir>),
4749    Arm(&'hir Arm<'hir>),
4750    Block(&'hir Block<'hir>),
4751    LetStmt(&'hir LetStmt<'hir>),
4752    /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
4753    /// with synthesized constructors.
4754    Ctor(&'hir VariantData<'hir>),
4755    Lifetime(&'hir Lifetime),
4756    GenericParam(&'hir GenericParam<'hir>),
4757    Crate(&'hir Mod<'hir>),
4758    Infer(&'hir InferArg),
4759    WherePredicate(&'hir WherePredicate<'hir>),
4760    PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4761    // Created by query feeding
4762    Synthetic,
4763    Err(Span),
4764}
4765
4766impl<'hir> Node<'hir> {
4767    /// Get the identifier of this `Node`, if applicable.
4768    ///
4769    /// # Edge cases
4770    ///
4771    /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
4772    /// because `Ctor`s do not have identifiers themselves.
4773    /// Instead, call `.ident()` on the parent struct/variant, like so:
4774    ///
4775    /// ```ignore (illustrative)
4776    /// ctor
4777    ///     .ctor_hir_id()
4778    ///     .map(|ctor_id| tcx.parent_hir_node(ctor_id))
4779    ///     .and_then(|parent| parent.ident())
4780    /// ```
4781    pub fn ident(&self) -> Option<Ident> {
4782        match self {
4783            Node::Item(item) => item.kind.ident(),
4784            Node::TraitItem(TraitItem { ident, .. })
4785            | Node::ImplItem(ImplItem { ident, .. })
4786            | Node::ForeignItem(ForeignItem { ident, .. })
4787            | Node::Field(FieldDef { ident, .. })
4788            | Node::Variant(Variant { ident, .. })
4789            | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4790            Node::Lifetime(lt) => Some(lt.ident),
4791            Node::GenericParam(p) => Some(p.name.ident()),
4792            Node::AssocItemConstraint(c) => Some(c.ident),
4793            Node::PatField(f) => Some(f.ident),
4794            Node::ExprField(f) => Some(f.ident),
4795            Node::ConstArgExprField(f) => Some(f.field),
4796            Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4797            Node::Param(..)
4798            | Node::AnonConst(..)
4799            | Node::ConstBlock(..)
4800            | Node::ConstArg(..)
4801            | Node::Expr(..)
4802            | Node::Stmt(..)
4803            | Node::Block(..)
4804            | Node::Ctor(..)
4805            | Node::Pat(..)
4806            | Node::TyPat(..)
4807            | Node::PatExpr(..)
4808            | Node::Arm(..)
4809            | Node::LetStmt(..)
4810            | Node::Crate(..)
4811            | Node::Ty(..)
4812            | Node::TraitRef(..)
4813            | Node::OpaqueTy(..)
4814            | Node::Infer(..)
4815            | Node::WherePredicate(..)
4816            | Node::Synthetic
4817            | Node::Err(..) => None,
4818        }
4819    }
4820
4821    pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4822        match self {
4823            Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4824            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4825            | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4826            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4827                Some(fn_sig.decl)
4828            }
4829            Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4830                Some(fn_decl)
4831            }
4832            _ => None,
4833        }
4834    }
4835
4836    /// Get a `hir::Impl` if the node is an impl block for the given `trait_def_id`.
4837    pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4838        if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4839            && let Some(of_trait) = impl_block.of_trait
4840            && let Some(trait_id) = of_trait.trait_ref.trait_def_id()
4841            && trait_id == trait_def_id
4842        {
4843            Some(impl_block)
4844        } else {
4845            None
4846        }
4847    }
4848
4849    pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4850        match self {
4851            Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4852            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4853            | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4854            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4855                Some(fn_sig)
4856            }
4857            _ => None,
4858        }
4859    }
4860
4861    /// Get the type for constants, assoc types, type aliases and statics.
4862    pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4863        match self {
4864            Node::Item(it) => match it.kind {
4865                ItemKind::TyAlias(_, _, ty)
4866                | ItemKind::Static(_, _, ty, _)
4867                | ItemKind::Const(_, _, ty, _) => Some(ty),
4868                ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4869                _ => None,
4870            },
4871            Node::TraitItem(it) => match it.kind {
4872                TraitItemKind::Const(ty, _) => Some(ty),
4873                TraitItemKind::Type(_, ty) => ty,
4874                _ => None,
4875            },
4876            Node::ImplItem(it) => match it.kind {
4877                ImplItemKind::Const(ty, _) => Some(ty),
4878                ImplItemKind::Type(ty) => Some(ty),
4879                _ => None,
4880            },
4881            Node::ForeignItem(it) => match it.kind {
4882                ForeignItemKind::Static(ty, ..) => Some(ty),
4883                _ => None,
4884            },
4885            Node::GenericParam(param) => match param.kind {
4886                GenericParamKind::Lifetime { .. } => None,
4887                GenericParamKind::Type { default, .. } => default,
4888                GenericParamKind::Const { ty, .. } => Some(ty),
4889            },
4890            _ => None,
4891        }
4892    }
4893
4894    pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4895        match self {
4896            Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
4897            _ => None,
4898        }
4899    }
4900
4901    #[inline]
4902    pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4903        match self {
4904            Node::Item(Item {
4905                owner_id,
4906                kind:
4907                    ItemKind::Const(.., ConstItemRhs::Body(body))
4908                    | ItemKind::Static(.., body)
4909                    | ItemKind::Fn { body, .. },
4910                ..
4911            })
4912            | Node::TraitItem(TraitItem {
4913                owner_id,
4914                kind:
4915                    TraitItemKind::Const(.., Some(ConstItemRhs::Body(body)))
4916                    | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4917                ..
4918            })
4919            | Node::ImplItem(ImplItem {
4920                owner_id,
4921                kind: ImplItemKind::Const(.., ConstItemRhs::Body(body)) | ImplItemKind::Fn(_, body),
4922                ..
4923            }) => Some((owner_id.def_id, *body)),
4924
4925            Node::Item(Item {
4926                owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4927            }) => Some((owner_id.def_id, *fake_body)),
4928
4929            Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4930                Some((*def_id, *body))
4931            }
4932
4933            Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4934            Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4935
4936            _ => None,
4937        }
4938    }
4939
4940    pub fn body_id(&self) -> Option<BodyId> {
4941        Some(self.associated_body()?.1)
4942    }
4943
4944    pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4945        match self {
4946            Node::ForeignItem(ForeignItem {
4947                kind: ForeignItemKind::Fn(_, _, generics), ..
4948            })
4949            | Node::TraitItem(TraitItem { generics, .. })
4950            | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4951            Node::Item(item) => item.kind.generics(),
4952            _ => None,
4953        }
4954    }
4955
4956    pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4957        match self {
4958            Node::Item(i) => Some(OwnerNode::Item(i)),
4959            Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4960            Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4961            Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4962            Node::Crate(i) => Some(OwnerNode::Crate(i)),
4963            Node::Synthetic => Some(OwnerNode::Synthetic),
4964            _ => None,
4965        }
4966    }
4967
4968    pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4969        match self {
4970            Node::Item(i) => match i.kind {
4971                ItemKind::Fn { ident, sig, generics, .. } => {
4972                    Some(FnKind::ItemFn(ident, generics, sig.header))
4973                }
4974                _ => None,
4975            },
4976            Node::TraitItem(ti) => match ti.kind {
4977                TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4978                _ => None,
4979            },
4980            Node::ImplItem(ii) => match ii.kind {
4981                ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4982                _ => None,
4983            },
4984            Node::Expr(e) => match e.kind {
4985                ExprKind::Closure { .. } => Some(FnKind::Closure),
4986                _ => None,
4987            },
4988            _ => None,
4989        }
4990    }
4991
4992    expect_methods_self! {
4993        expect_param,         &'hir Param<'hir>,        Node::Param(n),        n;
4994        expect_item,          &'hir Item<'hir>,         Node::Item(n),         n;
4995        expect_foreign_item,  &'hir ForeignItem<'hir>,  Node::ForeignItem(n),  n;
4996        expect_trait_item,    &'hir TraitItem<'hir>,    Node::TraitItem(n),    n;
4997        expect_impl_item,     &'hir ImplItem<'hir>,     Node::ImplItem(n),     n;
4998        expect_variant,       &'hir Variant<'hir>,      Node::Variant(n),      n;
4999        expect_field,         &'hir FieldDef<'hir>,     Node::Field(n),        n;
5000        expect_anon_const,    &'hir AnonConst,          Node::AnonConst(n),    n;
5001        expect_inline_const,  &'hir ConstBlock,         Node::ConstBlock(n),   n;
5002        expect_expr,          &'hir Expr<'hir>,         Node::Expr(n),         n;
5003        expect_expr_field,    &'hir ExprField<'hir>,    Node::ExprField(n),    n;
5004        expect_stmt,          &'hir Stmt<'hir>,         Node::Stmt(n),         n;
5005        expect_path_segment,  &'hir PathSegment<'hir>,  Node::PathSegment(n),  n;
5006        expect_ty,            &'hir Ty<'hir>,           Node::Ty(n),           n;
5007        expect_assoc_item_constraint,  &'hir AssocItemConstraint<'hir>,  Node::AssocItemConstraint(n),  n;
5008        expect_trait_ref,     &'hir TraitRef<'hir>,     Node::TraitRef(n),     n;
5009        expect_opaque_ty,     &'hir OpaqueTy<'hir>,     Node::OpaqueTy(n),     n;
5010        expect_pat,           &'hir Pat<'hir>,          Node::Pat(n),          n;
5011        expect_pat_field,     &'hir PatField<'hir>,     Node::PatField(n),     n;
5012        expect_arm,           &'hir Arm<'hir>,          Node::Arm(n),          n;
5013        expect_block,         &'hir Block<'hir>,        Node::Block(n),        n;
5014        expect_let_stmt,      &'hir LetStmt<'hir>,      Node::LetStmt(n),      n;
5015        expect_ctor,          &'hir VariantData<'hir>,  Node::Ctor(n),         n;
5016        expect_lifetime,      &'hir Lifetime,           Node::Lifetime(n),     n;
5017        expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
5018        expect_crate,         &'hir Mod<'hir>,          Node::Crate(n),        n;
5019        expect_infer,         &'hir InferArg,           Node::Infer(n),        n;
5020        expect_closure,       &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
5021    }
5022}
5023
5024// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
5025#[cfg(target_pointer_width = "64")]
5026mod size_asserts {
5027    use rustc_data_structures::static_assert_size;
5028
5029    use super::*;
5030    // tidy-alphabetical-start
5031    static_assert_size!(Block<'_>, 48);
5032    static_assert_size!(Body<'_>, 24);
5033    static_assert_size!(Expr<'_>, 64);
5034    static_assert_size!(ExprKind<'_>, 48);
5035    static_assert_size!(FnDecl<'_>, 40);
5036    static_assert_size!(ForeignItem<'_>, 96);
5037    static_assert_size!(ForeignItemKind<'_>, 56);
5038    static_assert_size!(GenericArg<'_>, 16);
5039    static_assert_size!(GenericBound<'_>, 64);
5040    static_assert_size!(Generics<'_>, 56);
5041    static_assert_size!(Impl<'_>, 48);
5042    static_assert_size!(ImplItem<'_>, 88);
5043    static_assert_size!(ImplItemKind<'_>, 40);
5044    static_assert_size!(Item<'_>, 88);
5045    static_assert_size!(ItemKind<'_>, 64);
5046    static_assert_size!(LetStmt<'_>, 64);
5047    static_assert_size!(Param<'_>, 32);
5048    static_assert_size!(Pat<'_>, 80);
5049    static_assert_size!(PatKind<'_>, 56);
5050    static_assert_size!(Path<'_>, 40);
5051    static_assert_size!(PathSegment<'_>, 48);
5052    static_assert_size!(QPath<'_>, 24);
5053    static_assert_size!(Res, 12);
5054    static_assert_size!(Stmt<'_>, 32);
5055    static_assert_size!(StmtKind<'_>, 16);
5056    static_assert_size!(TraitImplHeader<'_>, 48);
5057    static_assert_size!(TraitItem<'_>, 88);
5058    static_assert_size!(TraitItemKind<'_>, 48);
5059    static_assert_size!(Ty<'_>, 48);
5060    static_assert_size!(TyKind<'_>, 32);
5061    // tidy-alphabetical-end
5062}
5063
5064#[cfg(test)]
5065mod tests;