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