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::CommentKind;
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) -> Self {
1197        AttrPath {
1198            segments: path.segments.iter().map(|i| i.ident).collect::<Vec<_>>().into_boxed_slice(),
1199            span: path.span,
1200        }
1201    }
1202}
1203
1204impl fmt::Display for AttrPath {
1205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1206        write!(f, "{}", join_path_idents(&self.segments))
1207    }
1208}
1209
1210#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1211pub struct AttrItem {
1212    // Not lowered to hir::Path because we have no NodeId to resolve to.
1213    pub path: AttrPath,
1214    pub args: AttrArgs,
1215    pub id: HashIgnoredAttrId,
1216    /// Denotes if the attribute decorates the following construct (outer)
1217    /// or the construct this attribute is contained within (inner).
1218    pub style: AttrStyle,
1219    /// Span of the entire attribute
1220    pub span: Span,
1221}
1222
1223/// The derived implementation of [`HashStable_Generic`] on [`Attribute`]s shouldn't hash
1224/// [`AttrId`]s. By wrapping them in this, we make sure we never do.
1225#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1226pub struct HashIgnoredAttrId {
1227    pub attr_id: AttrId,
1228}
1229
1230#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1231pub enum Attribute {
1232    /// A parsed built-in attribute.
1233    ///
1234    /// Each attribute has a span connected to it. However, you must be somewhat careful using it.
1235    /// That's because sometimes we merge multiple attributes together, like when an item has
1236    /// multiple `repr` attributes. In this case the span might not be very useful.
1237    Parsed(AttributeKind),
1238
1239    /// An attribute that could not be parsed, out of a token-like representation.
1240    /// This is the case for custom tool attributes.
1241    Unparsed(Box<AttrItem>),
1242}
1243
1244impl Attribute {
1245    pub fn get_normal_item(&self) -> &AttrItem {
1246        match &self {
1247            Attribute::Unparsed(normal) => &normal,
1248            _ => panic!("unexpected parsed attribute"),
1249        }
1250    }
1251
1252    pub fn unwrap_normal_item(self) -> AttrItem {
1253        match self {
1254            Attribute::Unparsed(normal) => *normal,
1255            _ => panic!("unexpected parsed attribute"),
1256        }
1257    }
1258
1259    pub fn value_lit(&self) -> Option<&MetaItemLit> {
1260        match &self {
1261            Attribute::Unparsed(n) => match n.as_ref() {
1262                AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1263                _ => None,
1264            },
1265            _ => None,
1266        }
1267    }
1268
1269    pub fn is_parsed_attr(&self) -> bool {
1270        match self {
1271            Attribute::Parsed(_) => true,
1272            Attribute::Unparsed(_) => false,
1273        }
1274    }
1275}
1276
1277impl AttributeExt for Attribute {
1278    #[inline]
1279    fn id(&self) -> AttrId {
1280        match &self {
1281            Attribute::Unparsed(u) => u.id.attr_id,
1282            _ => panic!(),
1283        }
1284    }
1285
1286    #[inline]
1287    fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1288        match &self {
1289            Attribute::Unparsed(n) => match n.as_ref() {
1290                AttrItem { args: AttrArgs::Delimited(d), .. } => {
1291                    ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1292                }
1293                _ => None,
1294            },
1295            _ => None,
1296        }
1297    }
1298
1299    #[inline]
1300    fn value_str(&self) -> Option<Symbol> {
1301        self.value_lit().and_then(|x| x.value_str())
1302    }
1303
1304    #[inline]
1305    fn value_span(&self) -> Option<Span> {
1306        self.value_lit().map(|i| i.span)
1307    }
1308
1309    /// For a single-segment attribute, returns its name; otherwise, returns `None`.
1310    #[inline]
1311    fn ident(&self) -> Option<Ident> {
1312        match &self {
1313            Attribute::Unparsed(n) => {
1314                if let [ident] = n.path.segments.as_ref() {
1315                    Some(*ident)
1316                } else {
1317                    None
1318                }
1319            }
1320            _ => None,
1321        }
1322    }
1323
1324    #[inline]
1325    fn path_matches(&self, name: &[Symbol]) -> bool {
1326        match &self {
1327            Attribute::Unparsed(n) => n.path.segments.iter().map(|ident| &ident.name).eq(name),
1328            _ => false,
1329        }
1330    }
1331
1332    #[inline]
1333    fn is_doc_comment(&self) -> Option<Span> {
1334        if let Attribute::Parsed(AttributeKind::DocComment { span, .. }) = self {
1335            Some(*span)
1336        } else {
1337            None
1338        }
1339    }
1340
1341    #[inline]
1342    fn span(&self) -> Span {
1343        match &self {
1344            Attribute::Unparsed(u) => u.span,
1345            // FIXME: should not be needed anymore when all attrs are parsed
1346            Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1347            Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1348            a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1349        }
1350    }
1351
1352    #[inline]
1353    fn is_word(&self) -> bool {
1354        match &self {
1355            Attribute::Unparsed(n) => {
1356                matches!(n.args, AttrArgs::Empty)
1357            }
1358            _ => false,
1359        }
1360    }
1361
1362    #[inline]
1363    fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1364        match &self {
1365            Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1366            _ => None,
1367        }
1368    }
1369
1370    #[inline]
1371    fn doc_str(&self) -> Option<Symbol> {
1372        match &self {
1373            Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1374            Attribute::Unparsed(_) if self.has_name(sym::doc) => self.value_str(),
1375            _ => None,
1376        }
1377    }
1378
1379    fn is_automatically_derived_attr(&self) -> bool {
1380        matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)))
1381    }
1382
1383    #[inline]
1384    fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1385        match &self {
1386            Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1387                Some((*comment, *kind))
1388            }
1389            Attribute::Unparsed(_) if self.has_name(sym::doc) => {
1390                self.value_str().map(|s| (s, CommentKind::Line))
1391            }
1392            _ => None,
1393        }
1394    }
1395
1396    fn doc_resolution_scope(&self) -> Option<AttrStyle> {
1397        match self {
1398            Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
1399            Attribute::Unparsed(attr) if self.has_name(sym::doc) && self.value_str().is_some() => {
1400                Some(attr.style)
1401            }
1402            _ => None,
1403        }
1404    }
1405
1406    fn is_proc_macro_attr(&self) -> bool {
1407        matches!(
1408            self,
1409            Attribute::Parsed(
1410                AttributeKind::ProcMacro(..)
1411                    | AttributeKind::ProcMacroAttribute(..)
1412                    | AttributeKind::ProcMacroDerive { .. }
1413            )
1414        )
1415    }
1416}
1417
1418// FIXME(fn_delegation): use function delegation instead of manually forwarding
1419impl Attribute {
1420    #[inline]
1421    pub fn id(&self) -> AttrId {
1422        AttributeExt::id(self)
1423    }
1424
1425    #[inline]
1426    pub fn name(&self) -> Option<Symbol> {
1427        AttributeExt::name(self)
1428    }
1429
1430    #[inline]
1431    pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1432        AttributeExt::meta_item_list(self)
1433    }
1434
1435    #[inline]
1436    pub fn value_str(&self) -> Option<Symbol> {
1437        AttributeExt::value_str(self)
1438    }
1439
1440    #[inline]
1441    pub fn value_span(&self) -> Option<Span> {
1442        AttributeExt::value_span(self)
1443    }
1444
1445    #[inline]
1446    pub fn ident(&self) -> Option<Ident> {
1447        AttributeExt::ident(self)
1448    }
1449
1450    #[inline]
1451    pub fn path_matches(&self, name: &[Symbol]) -> bool {
1452        AttributeExt::path_matches(self, name)
1453    }
1454
1455    #[inline]
1456    pub fn is_doc_comment(&self) -> Option<Span> {
1457        AttributeExt::is_doc_comment(self)
1458    }
1459
1460    #[inline]
1461    pub fn has_name(&self, name: Symbol) -> bool {
1462        AttributeExt::has_name(self, name)
1463    }
1464
1465    #[inline]
1466    pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1467        AttributeExt::has_any_name(self, names)
1468    }
1469
1470    #[inline]
1471    pub fn span(&self) -> Span {
1472        AttributeExt::span(self)
1473    }
1474
1475    #[inline]
1476    pub fn is_word(&self) -> bool {
1477        AttributeExt::is_word(self)
1478    }
1479
1480    #[inline]
1481    pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1482        AttributeExt::path(self)
1483    }
1484
1485    #[inline]
1486    pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1487        AttributeExt::ident_path(self)
1488    }
1489
1490    #[inline]
1491    pub fn doc_str(&self) -> Option<Symbol> {
1492        AttributeExt::doc_str(self)
1493    }
1494
1495    #[inline]
1496    pub fn is_proc_macro_attr(&self) -> bool {
1497        AttributeExt::is_proc_macro_attr(self)
1498    }
1499
1500    #[inline]
1501    pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1502        AttributeExt::doc_str_and_comment_kind(self)
1503    }
1504}
1505
1506/// Attributes owned by a HIR owner.
1507#[derive(Debug)]
1508pub struct AttributeMap<'tcx> {
1509    pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1510    /// Preprocessed `#[define_opaque]` attribute.
1511    pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1512    // Only present when the crate hash is needed.
1513    pub opt_hash: Option<Fingerprint>,
1514}
1515
1516impl<'tcx> AttributeMap<'tcx> {
1517    pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1518        map: SortedMap::new(),
1519        opt_hash: Some(Fingerprint::ZERO),
1520        define_opaque: None,
1521    };
1522
1523    #[inline]
1524    pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1525        self.map.get(&id).copied().unwrap_or(&[])
1526    }
1527}
1528
1529/// Map of all HIR nodes inside the current owner.
1530/// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
1531/// The HIR tree, including bodies, is pre-hashed.
1532pub struct OwnerNodes<'tcx> {
1533    /// Pre-computed hash of the full HIR. Used in the crate hash. Only present
1534    /// when incr. comp. is enabled.
1535    pub opt_hash_including_bodies: Option<Fingerprint>,
1536    /// Full HIR for the current owner.
1537    // The zeroth node's parent should never be accessed: the owner's parent is computed by the
1538    // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
1539    // used.
1540    pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1541    /// Content of local bodies.
1542    pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1543}
1544
1545impl<'tcx> OwnerNodes<'tcx> {
1546    pub fn node(&self) -> OwnerNode<'tcx> {
1547        // Indexing must ensure it is an OwnerNode.
1548        self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1549    }
1550}
1551
1552impl fmt::Debug for OwnerNodes<'_> {
1553    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1554        f.debug_struct("OwnerNodes")
1555            // Do not print all the pointers to all the nodes, as it would be unreadable.
1556            .field("node", &self.nodes[ItemLocalId::ZERO])
1557            .field(
1558                "parents",
1559                &fmt::from_fn(|f| {
1560                    f.debug_list()
1561                        .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1562                            fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1563                        }))
1564                        .finish()
1565                }),
1566            )
1567            .field("bodies", &self.bodies)
1568            .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1569            .finish()
1570    }
1571}
1572
1573/// Full information resulting from lowering an AST node.
1574#[derive(Debug, HashStable_Generic)]
1575pub struct OwnerInfo<'hir> {
1576    /// Contents of the HIR.
1577    pub nodes: OwnerNodes<'hir>,
1578    /// Map from each nested owner to its parent's local id.
1579    pub parenting: LocalDefIdMap<ItemLocalId>,
1580    /// Collected attributes of the HIR nodes.
1581    pub attrs: AttributeMap<'hir>,
1582    /// Map indicating what traits are in scope for places where this
1583    /// is relevant; generated by resolve.
1584    pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1585
1586    /// Lints delayed during ast lowering to be emitted
1587    /// after hir has completely built
1588    pub delayed_lints: DelayedLints,
1589}
1590
1591impl<'tcx> OwnerInfo<'tcx> {
1592    #[inline]
1593    pub fn node(&self) -> OwnerNode<'tcx> {
1594        self.nodes.node()
1595    }
1596}
1597
1598#[derive(Copy, Clone, Debug, HashStable_Generic)]
1599pub enum MaybeOwner<'tcx> {
1600    Owner(&'tcx OwnerInfo<'tcx>),
1601    NonOwner(HirId),
1602    /// Used as a placeholder for unused LocalDefId.
1603    Phantom,
1604}
1605
1606impl<'tcx> MaybeOwner<'tcx> {
1607    pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1608        match self {
1609            MaybeOwner::Owner(i) => Some(i),
1610            MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1611        }
1612    }
1613
1614    pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1615        self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1616    }
1617}
1618
1619/// The top-level data structure that stores the entire contents of
1620/// the crate currently being compiled.
1621///
1622/// For more details, see the [rustc dev guide].
1623///
1624/// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
1625#[derive(Debug)]
1626pub struct Crate<'hir> {
1627    pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1628    // Only present when incr. comp. is enabled.
1629    pub opt_hir_hash: Option<Fingerprint>,
1630}
1631
1632#[derive(Debug, Clone, Copy, HashStable_Generic)]
1633pub struct Closure<'hir> {
1634    pub def_id: LocalDefId,
1635    pub binder: ClosureBinder,
1636    pub constness: Constness,
1637    pub capture_clause: CaptureBy,
1638    pub bound_generic_params: &'hir [GenericParam<'hir>],
1639    pub fn_decl: &'hir FnDecl<'hir>,
1640    pub body: BodyId,
1641    /// The span of the declaration block: 'move |...| -> ...'
1642    pub fn_decl_span: Span,
1643    /// The span of the argument block `|...|`
1644    pub fn_arg_span: Option<Span>,
1645    pub kind: ClosureKind,
1646}
1647
1648#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1649pub enum ClosureKind {
1650    /// This is a plain closure expression.
1651    Closure,
1652    /// This is a coroutine expression -- i.e. a closure expression in which
1653    /// we've found a `yield`. These can arise either from "plain" coroutine
1654    ///  usage (e.g. `let x = || { yield (); }`) or from a desugared expression
1655    /// (e.g. `async` and `gen` blocks).
1656    Coroutine(CoroutineKind),
1657    /// This is a coroutine-closure, which is a special sugared closure that
1658    /// returns one of the sugared coroutine (`async`/`gen`/`async gen`). It
1659    /// additionally allows capturing the coroutine's upvars by ref, and therefore
1660    /// needs to be specially treated during analysis and borrowck.
1661    CoroutineClosure(CoroutineDesugaring),
1662}
1663
1664/// A block of statements `{ .. }`, which may have a label (in this case the
1665/// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
1666/// the `rules` being anything but `DefaultBlock`.
1667#[derive(Debug, Clone, Copy, HashStable_Generic)]
1668pub struct Block<'hir> {
1669    /// Statements in a block.
1670    pub stmts: &'hir [Stmt<'hir>],
1671    /// An expression at the end of the block
1672    /// without a semicolon, if any.
1673    pub expr: Option<&'hir Expr<'hir>>,
1674    #[stable_hasher(ignore)]
1675    pub hir_id: HirId,
1676    /// Distinguishes between `unsafe { ... }` and `{ ... }`.
1677    pub rules: BlockCheckMode,
1678    /// The span includes the curly braces `{` and `}` around the block.
1679    pub span: Span,
1680    /// If true, then there may exist `break 'a` values that aim to
1681    /// break out of this block early.
1682    /// Used by `'label: {}` blocks and by `try {}` blocks.
1683    pub targeted_by_break: bool,
1684}
1685
1686impl<'hir> Block<'hir> {
1687    pub fn innermost_block(&self) -> &Block<'hir> {
1688        let mut block = self;
1689        while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1690            block = inner_block;
1691        }
1692        block
1693    }
1694}
1695
1696#[derive(Debug, Clone, Copy, HashStable_Generic)]
1697pub struct TyPat<'hir> {
1698    #[stable_hasher(ignore)]
1699    pub hir_id: HirId,
1700    pub kind: TyPatKind<'hir>,
1701    pub span: Span,
1702}
1703
1704#[derive(Debug, Clone, Copy, HashStable_Generic)]
1705pub struct Pat<'hir> {
1706    #[stable_hasher(ignore)]
1707    pub hir_id: HirId,
1708    pub kind: PatKind<'hir>,
1709    pub span: Span,
1710    /// Whether to use default binding modes.
1711    /// At present, this is false only for destructuring assignment.
1712    pub default_binding_modes: bool,
1713}
1714
1715impl<'hir> Pat<'hir> {
1716    fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1717        if !it(self) {
1718            return false;
1719        }
1720
1721        use PatKind::*;
1722        match self.kind {
1723            Missing => unreachable!(),
1724            Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1725            Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => {
1726                s.walk_short_(it)
1727            }
1728            Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1729            TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1730            Slice(before, slice, after) => {
1731                before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1732            }
1733        }
1734    }
1735
1736    /// Walk the pattern in left-to-right order,
1737    /// short circuiting (with `.all(..)`) if `false` is returned.
1738    ///
1739    /// Note that when visiting e.g. `Tuple(ps)`,
1740    /// if visiting `ps[0]` returns `false`,
1741    /// then `ps[1]` will not be visited.
1742    pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1743        self.walk_short_(&mut it)
1744    }
1745
1746    fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1747        if !it(self) {
1748            return;
1749        }
1750
1751        use PatKind::*;
1752        match self.kind {
1753            Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1754            Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1755            Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1756            TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1757            Slice(before, slice, after) => {
1758                before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1759            }
1760        }
1761    }
1762
1763    /// Walk the pattern in left-to-right order.
1764    ///
1765    /// If `it(pat)` returns `false`, the children are not visited.
1766    pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1767        self.walk_(&mut it)
1768    }
1769
1770    /// Walk the pattern in left-to-right order.
1771    ///
1772    /// If you always want to recurse, prefer this method over `walk`.
1773    pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1774        self.walk(|p| {
1775            it(p);
1776            true
1777        })
1778    }
1779
1780    /// Whether this a never pattern.
1781    pub fn is_never_pattern(&self) -> bool {
1782        let mut is_never_pattern = false;
1783        self.walk(|pat| match &pat.kind {
1784            PatKind::Never => {
1785                is_never_pattern = true;
1786                false
1787            }
1788            PatKind::Or(s) => {
1789                is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1790                false
1791            }
1792            _ => true,
1793        });
1794        is_never_pattern
1795    }
1796}
1797
1798/// A single field in a struct pattern.
1799///
1800/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1801/// are treated the same as` x: x, y: ref y, z: ref mut z`,
1802/// except `is_shorthand` is true.
1803#[derive(Debug, Clone, Copy, HashStable_Generic)]
1804pub struct PatField<'hir> {
1805    #[stable_hasher(ignore)]
1806    pub hir_id: HirId,
1807    /// The identifier for the field.
1808    pub ident: Ident,
1809    /// The pattern the field is destructured to.
1810    pub pat: &'hir Pat<'hir>,
1811    pub is_shorthand: bool,
1812    pub span: Span,
1813}
1814
1815#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1816pub enum RangeEnd {
1817    Included,
1818    Excluded,
1819}
1820
1821impl fmt::Display for RangeEnd {
1822    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1823        f.write_str(match self {
1824            RangeEnd::Included => "..=",
1825            RangeEnd::Excluded => "..",
1826        })
1827    }
1828}
1829
1830// Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1831// this type only takes up 4 bytes, at the cost of being restricted to a
1832// maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1833#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1834pub struct DotDotPos(u32);
1835
1836impl DotDotPos {
1837    /// Panics if n >= u32::MAX.
1838    pub fn new(n: Option<usize>) -> Self {
1839        match n {
1840            Some(n) => {
1841                assert!(n < u32::MAX as usize);
1842                Self(n as u32)
1843            }
1844            None => Self(u32::MAX),
1845        }
1846    }
1847
1848    pub fn as_opt_usize(&self) -> Option<usize> {
1849        if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1850    }
1851}
1852
1853impl fmt::Debug for DotDotPos {
1854    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1855        self.as_opt_usize().fmt(f)
1856    }
1857}
1858
1859#[derive(Debug, Clone, Copy, HashStable_Generic)]
1860pub struct PatExpr<'hir> {
1861    #[stable_hasher(ignore)]
1862    pub hir_id: HirId,
1863    pub span: Span,
1864    pub kind: PatExprKind<'hir>,
1865}
1866
1867#[derive(Debug, Clone, Copy, HashStable_Generic)]
1868pub enum PatExprKind<'hir> {
1869    Lit {
1870        lit: Lit,
1871        // FIXME: move this into `Lit` and handle negated literal expressions
1872        // once instead of matching on unop neg expressions everywhere.
1873        negated: bool,
1874    },
1875    ConstBlock(ConstBlock),
1876    /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1877    Path(QPath<'hir>),
1878}
1879
1880#[derive(Debug, Clone, Copy, HashStable_Generic)]
1881pub enum TyPatKind<'hir> {
1882    /// A range pattern (e.g., `1..=2` or `1..2`).
1883    Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1884
1885    /// A pattern that excludes null pointers
1886    NotNull,
1887
1888    /// A list of patterns where only one needs to be satisfied
1889    Or(&'hir [TyPat<'hir>]),
1890
1891    /// A placeholder for a pattern that wasn't well formed in some way.
1892    Err(ErrorGuaranteed),
1893}
1894
1895#[derive(Debug, Clone, Copy, HashStable_Generic)]
1896pub enum PatKind<'hir> {
1897    /// A missing pattern, e.g. for an anonymous param in a bare fn like `fn f(u32)`.
1898    Missing,
1899
1900    /// Represents a wildcard pattern (i.e., `_`).
1901    Wild,
1902
1903    /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1904    /// The `HirId` is the canonical ID for the variable being bound,
1905    /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1906    /// which is the pattern ID of the first `x`.
1907    ///
1908    /// The `BindingMode` is what's provided by the user, before match
1909    /// ergonomics are applied. For the binding mode actually in use,
1910    /// see [`TypeckResults::extract_binding_mode`].
1911    ///
1912    /// [`TypeckResults::extract_binding_mode`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.extract_binding_mode
1913    Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1914
1915    /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1916    /// The `Option` contains the span of a possible `..`.
1917    Struct(QPath<'hir>, &'hir [PatField<'hir>], Option<Span>),
1918
1919    /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1920    /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1921    /// `0 <= position <= subpats.len()`
1922    TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1923
1924    /// An or-pattern `A | B | C`.
1925    /// Invariant: `pats.len() >= 2`.
1926    Or(&'hir [Pat<'hir>]),
1927
1928    /// A never pattern `!`.
1929    Never,
1930
1931    /// A tuple pattern (e.g., `(a, b)`).
1932    /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1933    /// `0 <= position <= subpats.len()`
1934    Tuple(&'hir [Pat<'hir>], DotDotPos),
1935
1936    /// A `box` pattern.
1937    Box(&'hir Pat<'hir>),
1938
1939    /// A `deref` pattern (currently `deref!()` macro-based syntax).
1940    Deref(&'hir Pat<'hir>),
1941
1942    /// A reference pattern (e.g., `&mut (a, b)`).
1943    Ref(&'hir Pat<'hir>, Pinnedness, Mutability),
1944
1945    /// A literal, const block or path.
1946    Expr(&'hir PatExpr<'hir>),
1947
1948    /// A guard pattern (e.g., `x if guard(x)`).
1949    Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
1950
1951    /// A range pattern (e.g., `1..=2` or `1..2`).
1952    Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
1953
1954    /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1955    ///
1956    /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1957    /// If `slice` exists, then `after` can be non-empty.
1958    ///
1959    /// The representation for e.g., `[a, b, .., c, d]` is:
1960    /// ```ignore (illustrative)
1961    /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1962    /// ```
1963    Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1964
1965    /// A placeholder for a pattern that wasn't well formed in some way.
1966    Err(ErrorGuaranteed),
1967}
1968
1969/// A statement.
1970#[derive(Debug, Clone, Copy, HashStable_Generic)]
1971pub struct Stmt<'hir> {
1972    #[stable_hasher(ignore)]
1973    pub hir_id: HirId,
1974    pub kind: StmtKind<'hir>,
1975    pub span: Span,
1976}
1977
1978/// The contents of a statement.
1979#[derive(Debug, Clone, Copy, HashStable_Generic)]
1980pub enum StmtKind<'hir> {
1981    /// A local (`let`) binding.
1982    Let(&'hir LetStmt<'hir>),
1983
1984    /// An item binding.
1985    Item(ItemId),
1986
1987    /// An expression without a trailing semi-colon (must have unit type).
1988    Expr(&'hir Expr<'hir>),
1989
1990    /// An expression with a trailing semi-colon (may have any type).
1991    Semi(&'hir Expr<'hir>),
1992}
1993
1994/// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1995#[derive(Debug, Clone, Copy, HashStable_Generic)]
1996pub struct LetStmt<'hir> {
1997    /// Span of `super` in `super let`.
1998    pub super_: Option<Span>,
1999    pub pat: &'hir Pat<'hir>,
2000    /// Type annotation, if any (otherwise the type will be inferred).
2001    pub ty: Option<&'hir Ty<'hir>>,
2002    /// Initializer expression to set the value, if any.
2003    pub init: Option<&'hir Expr<'hir>>,
2004    /// Else block for a `let...else` binding.
2005    pub els: Option<&'hir Block<'hir>>,
2006    #[stable_hasher(ignore)]
2007    pub hir_id: HirId,
2008    pub span: Span,
2009    /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
2010    /// desugaring, or `AssignDesugar` if it is the result of a complex
2011    /// assignment desugaring. Otherwise will be `Normal`.
2012    pub source: LocalSource,
2013}
2014
2015/// Represents a single arm of a `match` expression, e.g.
2016/// `<pat> (if <guard>) => <body>`.
2017#[derive(Debug, Clone, Copy, HashStable_Generic)]
2018pub struct Arm<'hir> {
2019    #[stable_hasher(ignore)]
2020    pub hir_id: HirId,
2021    pub span: Span,
2022    /// If this pattern and the optional guard matches, then `body` is evaluated.
2023    pub pat: &'hir Pat<'hir>,
2024    /// Optional guard clause.
2025    pub guard: Option<&'hir Expr<'hir>>,
2026    /// The expression the arm evaluates to if this arm matches.
2027    pub body: &'hir Expr<'hir>,
2028}
2029
2030/// Represents a `let <pat>[: <ty>] = <expr>` expression (not a [`LetStmt`]), occurring in an `if-let`
2031/// or `let-else`, evaluating to a boolean. Typically the pattern is refutable.
2032///
2033/// In an `if let`, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of
2034/// the desugaring to if-let. Only let-else supports the type annotation at present.
2035#[derive(Debug, Clone, Copy, HashStable_Generic)]
2036pub struct LetExpr<'hir> {
2037    pub span: Span,
2038    pub pat: &'hir Pat<'hir>,
2039    pub ty: Option<&'hir Ty<'hir>>,
2040    pub init: &'hir Expr<'hir>,
2041    /// `Recovered::Yes` when this let expressions is not in a syntactically valid location.
2042    /// Used to prevent building MIR in such situations.
2043    pub recovered: ast::Recovered,
2044}
2045
2046#[derive(Debug, Clone, Copy, HashStable_Generic)]
2047pub struct ExprField<'hir> {
2048    #[stable_hasher(ignore)]
2049    pub hir_id: HirId,
2050    pub ident: Ident,
2051    pub expr: &'hir Expr<'hir>,
2052    pub span: Span,
2053    pub is_shorthand: bool,
2054}
2055
2056#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2057pub enum BlockCheckMode {
2058    DefaultBlock,
2059    UnsafeBlock(UnsafeSource),
2060}
2061
2062#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2063pub enum UnsafeSource {
2064    CompilerGenerated,
2065    UserProvided,
2066}
2067
2068#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
2069pub struct BodyId {
2070    pub hir_id: HirId,
2071}
2072
2073/// The body of a function, closure, or constant value. In the case of
2074/// a function, the body contains not only the function body itself
2075/// (which is an expression), but also the argument patterns, since
2076/// those are something that the caller doesn't really care about.
2077///
2078/// # Examples
2079///
2080/// ```
2081/// fn foo((x, y): (u32, u32)) -> u32 {
2082///     x + y
2083/// }
2084/// ```
2085///
2086/// Here, the `Body` associated with `foo()` would contain:
2087///
2088/// - an `params` array containing the `(x, y)` pattern
2089/// - a `value` containing the `x + y` expression (maybe wrapped in a block)
2090/// - `coroutine_kind` would be `None`
2091///
2092/// All bodies have an **owner**, which can be accessed via the HIR
2093/// map using `body_owner_def_id()`.
2094#[derive(Debug, Clone, Copy, HashStable_Generic)]
2095pub struct Body<'hir> {
2096    pub params: &'hir [Param<'hir>],
2097    pub value: &'hir Expr<'hir>,
2098}
2099
2100impl<'hir> Body<'hir> {
2101    pub fn id(&self) -> BodyId {
2102        BodyId { hir_id: self.value.hir_id }
2103    }
2104}
2105
2106/// The type of source expression that caused this coroutine to be created.
2107#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2108pub enum CoroutineKind {
2109    /// A coroutine that comes from a desugaring.
2110    Desugared(CoroutineDesugaring, CoroutineSource),
2111
2112    /// A coroutine literal created via a `yield` inside a closure.
2113    Coroutine(Movability),
2114}
2115
2116impl CoroutineKind {
2117    pub fn movability(self) -> Movability {
2118        match self {
2119            CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2120            | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2121            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2122            CoroutineKind::Coroutine(mov) => mov,
2123        }
2124    }
2125
2126    pub fn is_fn_like(self) -> bool {
2127        matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2128    }
2129
2130    pub fn to_plural_string(&self) -> String {
2131        match self {
2132            CoroutineKind::Desugared(d, CoroutineSource::Fn) => format!("{d:#}fn bodies"),
2133            CoroutineKind::Desugared(d, CoroutineSource::Block) => format!("{d:#}blocks"),
2134            CoroutineKind::Desugared(d, CoroutineSource::Closure) => format!("{d:#}closure bodies"),
2135            CoroutineKind::Coroutine(_) => "coroutines".to_string(),
2136        }
2137    }
2138}
2139
2140impl fmt::Display for CoroutineKind {
2141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2142        match self {
2143            CoroutineKind::Desugared(d, k) => {
2144                d.fmt(f)?;
2145                k.fmt(f)
2146            }
2147            CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2148        }
2149    }
2150}
2151
2152/// In the case of a coroutine created as part of an async/gen construct,
2153/// which kind of async/gen construct caused it to be created?
2154///
2155/// This helps error messages but is also used to drive coercions in
2156/// type-checking (see #60424).
2157#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
2158pub enum CoroutineSource {
2159    /// An explicit `async`/`gen` block written by the user.
2160    Block,
2161
2162    /// An explicit `async`/`gen` closure written by the user.
2163    Closure,
2164
2165    /// The `async`/`gen` block generated as the body of an async/gen function.
2166    Fn,
2167}
2168
2169impl fmt::Display for CoroutineSource {
2170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2171        match self {
2172            CoroutineSource::Block => "block",
2173            CoroutineSource::Closure => "closure body",
2174            CoroutineSource::Fn => "fn body",
2175        }
2176        .fmt(f)
2177    }
2178}
2179
2180#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2181pub enum CoroutineDesugaring {
2182    /// An explicit `async` block or the body of an `async` function.
2183    Async,
2184
2185    /// An explicit `gen` block or the body of a `gen` function.
2186    Gen,
2187
2188    /// An explicit `async gen` block or the body of an `async gen` function,
2189    /// which is able to both `yield` and `.await`.
2190    AsyncGen,
2191}
2192
2193impl fmt::Display for CoroutineDesugaring {
2194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2195        match self {
2196            CoroutineDesugaring::Async => {
2197                if f.alternate() {
2198                    f.write_str("`async` ")?;
2199                } else {
2200                    f.write_str("async ")?
2201                }
2202            }
2203            CoroutineDesugaring::Gen => {
2204                if f.alternate() {
2205                    f.write_str("`gen` ")?;
2206                } else {
2207                    f.write_str("gen ")?
2208                }
2209            }
2210            CoroutineDesugaring::AsyncGen => {
2211                if f.alternate() {
2212                    f.write_str("`async gen` ")?;
2213                } else {
2214                    f.write_str("async gen ")?
2215                }
2216            }
2217        }
2218
2219        Ok(())
2220    }
2221}
2222
2223#[derive(Copy, Clone, Debug)]
2224pub enum BodyOwnerKind {
2225    /// Functions and methods.
2226    Fn,
2227
2228    /// Closures
2229    Closure,
2230
2231    /// Constants and associated constants, also including inline constants.
2232    Const { inline: bool },
2233
2234    /// Initializer of a `static` item.
2235    Static(Mutability),
2236
2237    /// Fake body for a global asm to store its const-like value types.
2238    GlobalAsm,
2239}
2240
2241impl BodyOwnerKind {
2242    pub fn is_fn_or_closure(self) -> bool {
2243        match self {
2244            BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2245            BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2246                false
2247            }
2248        }
2249    }
2250}
2251
2252/// The kind of an item that requires const-checking.
2253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2254pub enum ConstContext {
2255    /// A `const fn`.
2256    ConstFn,
2257
2258    /// A `static` or `static mut`.
2259    Static(Mutability),
2260
2261    /// A `const`, associated `const`, or other const context.
2262    ///
2263    /// Other contexts include:
2264    /// - Array length expressions
2265    /// - Enum discriminants
2266    /// - Const generics
2267    ///
2268    /// For the most part, other contexts are treated just like a regular `const`, so they are
2269    /// lumped into the same category.
2270    Const { inline: bool },
2271}
2272
2273impl ConstContext {
2274    /// A description of this const context that can appear between backticks in an error message.
2275    ///
2276    /// E.g. `const` or `static mut`.
2277    pub fn keyword_name(self) -> &'static str {
2278        match self {
2279            Self::Const { .. } => "const",
2280            Self::Static(Mutability::Not) => "static",
2281            Self::Static(Mutability::Mut) => "static mut",
2282            Self::ConstFn => "const fn",
2283        }
2284    }
2285}
2286
2287/// A colloquial, trivially pluralizable description of this const context for use in error
2288/// messages.
2289impl fmt::Display for ConstContext {
2290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2291        match *self {
2292            Self::Const { .. } => write!(f, "constant"),
2293            Self::Static(_) => write!(f, "static"),
2294            Self::ConstFn => write!(f, "constant function"),
2295        }
2296    }
2297}
2298
2299impl IntoDiagArg for ConstContext {
2300    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
2301        DiagArgValue::Str(Cow::Borrowed(match self {
2302            ConstContext::ConstFn => "const_fn",
2303            ConstContext::Static(_) => "static",
2304            ConstContext::Const { .. } => "const",
2305        }))
2306    }
2307}
2308
2309/// A literal.
2310pub type Lit = Spanned<LitKind>;
2311
2312/// A constant (expression) that's not an item or associated item,
2313/// but needs its own `DefId` for type-checking, const-eval, etc.
2314/// These are usually found nested inside types (e.g., array lengths)
2315/// or expressions (e.g., repeat counts), and also used to define
2316/// explicit discriminant values for enum variants.
2317///
2318/// You can check if this anon const is a default in a const param
2319/// `const N: usize = { ... }` with `tcx.hir_opt_const_param_default_param_def_id(..)`
2320#[derive(Copy, Clone, Debug, HashStable_Generic)]
2321pub struct AnonConst {
2322    #[stable_hasher(ignore)]
2323    pub hir_id: HirId,
2324    pub def_id: LocalDefId,
2325    pub body: BodyId,
2326    pub span: Span,
2327}
2328
2329/// An inline constant expression `const { something }`.
2330#[derive(Copy, Clone, Debug, HashStable_Generic)]
2331pub struct ConstBlock {
2332    #[stable_hasher(ignore)]
2333    pub hir_id: HirId,
2334    pub def_id: LocalDefId,
2335    pub body: BodyId,
2336}
2337
2338/// An expression.
2339///
2340/// For more details, see the [rust lang reference].
2341/// Note that the reference does not document nightly-only features.
2342/// There may be also slight differences in the names and representation of AST nodes between
2343/// the compiler and the reference.
2344///
2345/// [rust lang reference]: https://doc.rust-lang.org/reference/expressions.html
2346#[derive(Debug, Clone, Copy, HashStable_Generic)]
2347pub struct Expr<'hir> {
2348    #[stable_hasher(ignore)]
2349    pub hir_id: HirId,
2350    pub kind: ExprKind<'hir>,
2351    pub span: Span,
2352}
2353
2354impl Expr<'_> {
2355    pub fn precedence(&self, has_attr: &dyn Fn(HirId) -> bool) -> ExprPrecedence {
2356        let prefix_attrs_precedence = || -> ExprPrecedence {
2357            if has_attr(self.hir_id) { ExprPrecedence::Prefix } else { ExprPrecedence::Unambiguous }
2358        };
2359
2360        match &self.kind {
2361            ExprKind::Closure(closure) => {
2362                match closure.fn_decl.output {
2363                    FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2364                    FnRetTy::Return(_) => prefix_attrs_precedence(),
2365                }
2366            }
2367
2368            ExprKind::Break(..)
2369            | ExprKind::Ret(..)
2370            | ExprKind::Yield(..)
2371            | ExprKind::Become(..) => ExprPrecedence::Jump,
2372
2373            // Binop-like expr kinds, handled by `AssocOp`.
2374            ExprKind::Binary(op, ..) => op.node.precedence(),
2375            ExprKind::Cast(..) => ExprPrecedence::Cast,
2376
2377            ExprKind::Assign(..) |
2378            ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2379
2380            // Unary, prefix
2381            ExprKind::AddrOf(..)
2382            // Here `let pats = expr` has `let pats =` as a "unary" prefix of `expr`.
2383            // However, this is not exactly right. When `let _ = a` is the LHS of a binop we
2384            // need parens sometimes. E.g. we can print `(let _ = a) && b` as `let _ = a && b`
2385            // but we need to print `(let _ = a) < b` as-is with parens.
2386            | ExprKind::Let(..)
2387            | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2388
2389            // Need parens if and only if there are prefix attributes.
2390            ExprKind::Array(_)
2391            | ExprKind::Block(..)
2392            | ExprKind::Call(..)
2393            | ExprKind::ConstBlock(_)
2394            | ExprKind::Continue(..)
2395            | ExprKind::Field(..)
2396            | ExprKind::If(..)
2397            | ExprKind::Index(..)
2398            | ExprKind::InlineAsm(..)
2399            | ExprKind::Lit(_)
2400            | ExprKind::Loop(..)
2401            | ExprKind::Match(..)
2402            | ExprKind::MethodCall(..)
2403            | ExprKind::OffsetOf(..)
2404            | ExprKind::Path(..)
2405            | ExprKind::Repeat(..)
2406            | ExprKind::Struct(..)
2407            | ExprKind::Tup(_)
2408            | ExprKind::Type(..)
2409            | ExprKind::UnsafeBinderCast(..)
2410            | ExprKind::Use(..)
2411            | ExprKind::Err(_) => prefix_attrs_precedence(),
2412
2413            ExprKind::DropTemps(expr, ..) => expr.precedence(has_attr),
2414        }
2415    }
2416
2417    /// Whether this looks like a place expr, without checking for deref
2418    /// adjustments.
2419    /// This will return `true` in some potentially surprising cases such as
2420    /// `CONSTANT.field`.
2421    pub fn is_syntactic_place_expr(&self) -> bool {
2422        self.is_place_expr(|_| true)
2423    }
2424
2425    /// Whether this is a place expression.
2426    ///
2427    /// `allow_projections_from` should return `true` if indexing a field or index expression based
2428    /// on the given expression should be considered a place expression.
2429    pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2430        match self.kind {
2431            ExprKind::Path(QPath::Resolved(_, ref path)) => {
2432                matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2433            }
2434
2435            // Type ascription inherits its place expression kind from its
2436            // operand. See:
2437            // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
2438            ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2439
2440            // Unsafe binder cast preserves place-ness of the sub-expression.
2441            ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2442
2443            ExprKind::Unary(UnOp::Deref, _) => true,
2444
2445            ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2446                allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2447            }
2448
2449            // Suppress errors for bad expressions.
2450            ExprKind::Err(_guar)
2451            | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2452
2453            // Partially qualified paths in expressions can only legally
2454            // refer to associated items which are always rvalues.
2455            ExprKind::Path(QPath::TypeRelative(..))
2456            | ExprKind::Call(..)
2457            | ExprKind::MethodCall(..)
2458            | ExprKind::Use(..)
2459            | ExprKind::Struct(..)
2460            | ExprKind::Tup(..)
2461            | ExprKind::If(..)
2462            | ExprKind::Match(..)
2463            | ExprKind::Closure { .. }
2464            | ExprKind::Block(..)
2465            | ExprKind::Repeat(..)
2466            | ExprKind::Array(..)
2467            | ExprKind::Break(..)
2468            | ExprKind::Continue(..)
2469            | ExprKind::Ret(..)
2470            | ExprKind::Become(..)
2471            | ExprKind::Let(..)
2472            | ExprKind::Loop(..)
2473            | ExprKind::Assign(..)
2474            | ExprKind::InlineAsm(..)
2475            | ExprKind::OffsetOf(..)
2476            | ExprKind::AssignOp(..)
2477            | ExprKind::Lit(_)
2478            | ExprKind::ConstBlock(..)
2479            | ExprKind::Unary(..)
2480            | ExprKind::AddrOf(..)
2481            | ExprKind::Binary(..)
2482            | ExprKind::Yield(..)
2483            | ExprKind::Cast(..)
2484            | ExprKind::DropTemps(..) => false,
2485        }
2486    }
2487
2488    /// If this is a desugared range expression,
2489    /// returns the span of the range without desugaring context.
2490    pub fn range_span(&self) -> Option<Span> {
2491        is_range_literal(self).then(|| self.span.parent_callsite().unwrap())
2492    }
2493
2494    /// Check if expression is an integer literal that can be used
2495    /// where `usize` is expected.
2496    pub fn is_size_lit(&self) -> bool {
2497        matches!(
2498            self.kind,
2499            ExprKind::Lit(Lit {
2500                node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2501                ..
2502            })
2503        )
2504    }
2505
2506    /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
2507    /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
2508    /// silent, only signaling the ownership system. By doing this, suggestions that check the
2509    /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
2510    /// beyond remembering to call this function before doing analysis on it.
2511    pub fn peel_drop_temps(&self) -> &Self {
2512        let mut expr = self;
2513        while let ExprKind::DropTemps(inner) = &expr.kind {
2514            expr = inner;
2515        }
2516        expr
2517    }
2518
2519    pub fn peel_blocks(&self) -> &Self {
2520        let mut expr = self;
2521        while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2522            expr = inner;
2523        }
2524        expr
2525    }
2526
2527    pub fn peel_borrows(&self) -> &Self {
2528        let mut expr = self;
2529        while let ExprKind::AddrOf(.., inner) = &expr.kind {
2530            expr = inner;
2531        }
2532        expr
2533    }
2534
2535    pub fn can_have_side_effects(&self) -> bool {
2536        match self.peel_drop_temps().kind {
2537            ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2538                false
2539            }
2540            ExprKind::Type(base, _)
2541            | ExprKind::Unary(_, base)
2542            | ExprKind::Field(base, _)
2543            | ExprKind::Index(base, _, _)
2544            | ExprKind::AddrOf(.., base)
2545            | ExprKind::Cast(base, _)
2546            | ExprKind::UnsafeBinderCast(_, base, _) => {
2547                // This isn't exactly true for `Index` and all `Unary`, but we are using this
2548                // method exclusively for diagnostics and there's a *cultural* pressure against
2549                // them being used only for its side-effects.
2550                base.can_have_side_effects()
2551            }
2552            ExprKind::Struct(_, fields, init) => {
2553                let init_side_effects = match init {
2554                    StructTailExpr::Base(init) => init.can_have_side_effects(),
2555                    StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2556                };
2557                fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2558                    || init_side_effects
2559            }
2560
2561            ExprKind::Array(args)
2562            | ExprKind::Tup(args)
2563            | ExprKind::Call(
2564                Expr {
2565                    kind:
2566                        ExprKind::Path(QPath::Resolved(
2567                            None,
2568                            Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2569                        )),
2570                    ..
2571                },
2572                args,
2573            ) => args.iter().any(|arg| arg.can_have_side_effects()),
2574            ExprKind::If(..)
2575            | ExprKind::Match(..)
2576            | ExprKind::MethodCall(..)
2577            | ExprKind::Call(..)
2578            | ExprKind::Closure { .. }
2579            | ExprKind::Block(..)
2580            | ExprKind::Repeat(..)
2581            | ExprKind::Break(..)
2582            | ExprKind::Continue(..)
2583            | ExprKind::Ret(..)
2584            | ExprKind::Become(..)
2585            | ExprKind::Let(..)
2586            | ExprKind::Loop(..)
2587            | ExprKind::Assign(..)
2588            | ExprKind::InlineAsm(..)
2589            | ExprKind::AssignOp(..)
2590            | ExprKind::ConstBlock(..)
2591            | ExprKind::Binary(..)
2592            | ExprKind::Yield(..)
2593            | ExprKind::DropTemps(..)
2594            | ExprKind::Err(_) => true,
2595        }
2596    }
2597
2598    /// To a first-order approximation, is this a pattern?
2599    pub fn is_approximately_pattern(&self) -> bool {
2600        match &self.kind {
2601            ExprKind::Array(_)
2602            | ExprKind::Call(..)
2603            | ExprKind::Tup(_)
2604            | ExprKind::Lit(_)
2605            | ExprKind::Path(_)
2606            | ExprKind::Struct(..) => true,
2607            _ => false,
2608        }
2609    }
2610
2611    /// Whether this and the `other` expression are the same for purposes of an indexing operation.
2612    ///
2613    /// This is only used for diagnostics to see if we have things like `foo[i]` where `foo` is
2614    /// borrowed multiple times with `i`.
2615    pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2616        match (self.kind, other.kind) {
2617            (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2618            (
2619                ExprKind::Path(QPath::Resolved(None, path1)),
2620                ExprKind::Path(QPath::Resolved(None, path2)),
2621            ) => path1.res == path2.res,
2622            (
2623                ExprKind::Struct(
2624                    &QPath::Resolved(None, &Path { res: Res::Def(_, path1_def_id), .. }),
2625                    args1,
2626                    StructTailExpr::None,
2627                ),
2628                ExprKind::Struct(
2629                    &QPath::Resolved(None, &Path { res: Res::Def(_, path2_def_id), .. }),
2630                    args2,
2631                    StructTailExpr::None,
2632                ),
2633            ) => {
2634                path2_def_id == path1_def_id
2635                    && is_range_literal(self)
2636                    && is_range_literal(other)
2637                    && std::iter::zip(args1, args2)
2638                        .all(|(a, b)| a.expr.equivalent_for_indexing(b.expr))
2639            }
2640            _ => false,
2641        }
2642    }
2643
2644    pub fn method_ident(&self) -> Option<Ident> {
2645        match self.kind {
2646            ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2647            ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2648            _ => None,
2649        }
2650    }
2651}
2652
2653/// Checks if the specified expression is a built-in range literal.
2654/// (See: `LoweringContext::lower_expr()`).
2655pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2656    if let ExprKind::Struct(QPath::Resolved(None, path), _, StructTailExpr::None) = expr.kind
2657        && let [.., segment] = path.segments
2658        && let sym::RangeFrom
2659        | sym::RangeFull
2660        | sym::Range
2661        | sym::RangeToInclusive
2662        | sym::RangeTo
2663        | sym::RangeFromCopy
2664        | sym::RangeCopy
2665        | sym::RangeInclusiveCopy
2666        | sym::RangeToInclusiveCopy = segment.ident.name
2667        && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2668    {
2669        true
2670    } else if let ExprKind::Call(func, _) = &expr.kind
2671        && let ExprKind::Path(QPath::Resolved(None, path)) = func.kind
2672        && let [.., segment] = path.segments
2673        && let sym::range_inclusive_new = segment.ident.name
2674        && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2675    {
2676        true
2677    } else {
2678        false
2679    }
2680}
2681
2682/// Checks if the specified expression needs parentheses for prefix
2683/// or postfix suggestions to be valid.
2684/// For example, `a + b` requires parentheses to suggest `&(a + b)`,
2685/// but just `a` does not.
2686/// Similarly, `(a + b).c()` also requires parentheses.
2687/// This should not be used for other types of suggestions.
2688pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2689    match expr.kind {
2690        // parenthesize if needed (Issue #46756)
2691        ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2692        // parenthesize borrows of range literals (Issue #54505)
2693        _ if is_range_literal(expr) => true,
2694        _ => false,
2695    }
2696}
2697
2698#[derive(Debug, Clone, Copy, HashStable_Generic)]
2699pub enum ExprKind<'hir> {
2700    /// Allow anonymous constants from an inline `const` block
2701    ConstBlock(ConstBlock),
2702    /// An array (e.g., `[a, b, c, d]`).
2703    Array(&'hir [Expr<'hir>]),
2704    /// A function call.
2705    ///
2706    /// The first field resolves to the function itself (usually an `ExprKind::Path`),
2707    /// and the second field is the list of arguments.
2708    /// This also represents calling the constructor of
2709    /// tuple-like ADTs such as tuple structs and enum variants.
2710    Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2711    /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
2712    ///
2713    /// The `PathSegment` represents the method name and its generic arguments
2714    /// (within the angle brackets).
2715    /// The `&Expr` is the expression that evaluates
2716    /// to the object on which the method is being called on (the receiver),
2717    /// and the `&[Expr]` is the rest of the arguments.
2718    /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
2719    /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
2720    /// The final `Span` represents the span of the function and arguments
2721    /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
2722    ///
2723    /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
2724    /// the `hir_id` of the `MethodCall` node itself.
2725    ///
2726    /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
2727    MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2728    /// An use expression (e.g., `var.use`).
2729    Use(&'hir Expr<'hir>, Span),
2730    /// A tuple (e.g., `(a, b, c, d)`).
2731    Tup(&'hir [Expr<'hir>]),
2732    /// A binary operation (e.g., `a + b`, `a * b`).
2733    Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2734    /// A unary operation (e.g., `!x`, `*x`).
2735    Unary(UnOp, &'hir Expr<'hir>),
2736    /// A literal (e.g., `1`, `"foo"`).
2737    Lit(Lit),
2738    /// A cast (e.g., `foo as f64`).
2739    Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2740    /// A type ascription (e.g., `x: Foo`). See RFC 3307.
2741    Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2742    /// Wraps the expression in a terminating scope.
2743    /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
2744    ///
2745    /// This construct only exists to tweak the drop order in AST lowering.
2746    /// An example of that is the desugaring of `for` loops.
2747    DropTemps(&'hir Expr<'hir>),
2748    /// A `let $pat = $expr` expression.
2749    ///
2750    /// These are not [`LetStmt`] and only occur as expressions.
2751    /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
2752    Let(&'hir LetExpr<'hir>),
2753    /// An `if` block, with an optional else block.
2754    ///
2755    /// I.e., `if <expr> { <expr> } else { <expr> }`.
2756    ///
2757    /// The "then" expr is always `ExprKind::Block`. If present, the "else" expr is always
2758    /// `ExprKind::Block` (for `else`) or `ExprKind::If` (for `else if`).
2759    /// Note that using an `Expr` instead of a `Block` for the "then" part is intentional,
2760    /// as it simplifies the type coercion machinery.
2761    If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2762    /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
2763    ///
2764    /// I.e., `'label: loop { <block> }`.
2765    ///
2766    /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
2767    Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2768    /// A `match` block, with a source that indicates whether or not it is
2769    /// the result of a desugaring, and if so, which kind.
2770    Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2771    /// A closure (e.g., `move |a, b, c| {a + b + c}`).
2772    ///
2773    /// The `Span` is the argument block `|...|`.
2774    ///
2775    /// This may also be a coroutine literal or an `async block` as indicated by the
2776    /// `Option<Movability>`.
2777    Closure(&'hir Closure<'hir>),
2778    /// A block (e.g., `'label: { ... }`).
2779    Block(&'hir Block<'hir>, Option<Label>),
2780
2781    /// An assignment (e.g., `a = foo()`).
2782    Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2783    /// An assignment with an operator.
2784    ///
2785    /// E.g., `a += 1`.
2786    AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2787    /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
2788    Field(&'hir Expr<'hir>, Ident),
2789    /// An indexing operation (`foo[2]`).
2790    /// Similar to [`ExprKind::MethodCall`], the final `Span` represents the span of the brackets
2791    /// and index.
2792    Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2793
2794    /// Path to a definition, possibly containing lifetime or type parameters.
2795    Path(QPath<'hir>),
2796
2797    /// A referencing operation (i.e., `&a` or `&mut a`).
2798    AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2799    /// A `break`, with an optional label to break.
2800    Break(Destination, Option<&'hir Expr<'hir>>),
2801    /// A `continue`, with an optional label.
2802    Continue(Destination),
2803    /// A `return`, with an optional value to be returned.
2804    Ret(Option<&'hir Expr<'hir>>),
2805    /// A `become`, with the value to be returned.
2806    Become(&'hir Expr<'hir>),
2807
2808    /// Inline assembly (from `asm!`), with its outputs and inputs.
2809    InlineAsm(&'hir InlineAsm<'hir>),
2810
2811    /// Field offset (`offset_of!`)
2812    OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2813
2814    /// A struct or struct-like variant literal expression.
2815    ///
2816    /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2817    /// where `base` is the `Option<Expr>`.
2818    Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2819
2820    /// An array literal constructed from one repeated element.
2821    ///
2822    /// E.g., `[1; 5]`. The first expression is the element
2823    /// to be repeated; the second is the number of times to repeat it.
2824    Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2825
2826    /// A suspension point for coroutines (i.e., `yield <expr>`).
2827    Yield(&'hir Expr<'hir>, YieldSource),
2828
2829    /// Operators which can be used to interconvert `unsafe` binder types.
2830    /// e.g. `unsafe<'a> &'a i32` <=> `&i32`.
2831    UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2832
2833    /// A placeholder for an expression that wasn't syntactically well formed in some way.
2834    Err(rustc_span::ErrorGuaranteed),
2835}
2836
2837#[derive(Debug, Clone, Copy, HashStable_Generic)]
2838pub enum StructTailExpr<'hir> {
2839    /// A struct expression where all the fields are explicitly enumerated: `Foo { a, b }`.
2840    None,
2841    /// A struct expression with a "base", an expression of the same type as the outer struct that
2842    /// will be used to populate any fields not explicitly mentioned: `Foo { ..base }`
2843    Base(&'hir Expr<'hir>),
2844    /// A struct expression with a `..` tail but no "base" expression. The values from the struct
2845    /// fields' default values will be used to populate any fields not explicitly mentioned:
2846    /// `Foo { .. }`.
2847    DefaultFields(Span),
2848}
2849
2850/// Represents an optionally `Self`-qualified value/type path or associated extension.
2851///
2852/// To resolve the path to a `DefId`, call [`qpath_res`].
2853///
2854/// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2855#[derive(Debug, Clone, Copy, HashStable_Generic)]
2856pub enum QPath<'hir> {
2857    /// Path to a definition, optionally "fully-qualified" with a `Self`
2858    /// type, if the path points to an associated item in a trait.
2859    ///
2860    /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2861    /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2862    /// even though they both have the same two-segment `Clone::clone` `Path`.
2863    Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2864
2865    /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2866    /// Will be resolved by type-checking to an associated item.
2867    ///
2868    /// UFCS source paths can desugar into this, with `Vec::new` turning into
2869    /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2870    /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2871    TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2872}
2873
2874impl<'hir> QPath<'hir> {
2875    /// Returns the span of this `QPath`.
2876    pub fn span(&self) -> Span {
2877        match *self {
2878            QPath::Resolved(_, path) => path.span,
2879            QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2880        }
2881    }
2882
2883    /// Returns the span of the qself of this `QPath`. For example, `()` in
2884    /// `<() as Trait>::method`.
2885    pub fn qself_span(&self) -> Span {
2886        match *self {
2887            QPath::Resolved(_, path) => path.span,
2888            QPath::TypeRelative(qself, _) => qself.span,
2889        }
2890    }
2891}
2892
2893/// Hints at the original code for a let statement.
2894#[derive(Copy, Clone, Debug, HashStable_Generic)]
2895pub enum LocalSource {
2896    /// A `match _ { .. }`.
2897    Normal,
2898    /// When lowering async functions, we create locals within the `async move` so that
2899    /// all parameters are dropped after the future is polled.
2900    ///
2901    /// ```ignore (pseudo-Rust)
2902    /// async fn foo(<pattern> @ x: Type) {
2903    ///     async move {
2904    ///         let <pattern> = x;
2905    ///     }
2906    /// }
2907    /// ```
2908    AsyncFn,
2909    /// A desugared `<expr>.await`.
2910    AwaitDesugar,
2911    /// A desugared `expr = expr`, where the LHS is a tuple, struct, array or underscore expression.
2912    AssignDesugar,
2913    /// A contract `#[ensures(..)]` attribute injects a let binding for the check that runs at point of return.
2914    Contract,
2915}
2916
2917/// Hints at the original code for a `match _ { .. }`.
2918#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2919pub enum MatchSource {
2920    /// A `match _ { .. }`.
2921    Normal,
2922    /// A `expr.match { .. }`.
2923    Postfix,
2924    /// A desugared `for _ in _ { .. }` loop.
2925    ForLoopDesugar,
2926    /// A desugared `?` operator.
2927    TryDesugar(HirId),
2928    /// A desugared `<expr>.await`.
2929    AwaitDesugar,
2930    /// A desugared `format_args!()`.
2931    FormatArgs,
2932}
2933
2934impl MatchSource {
2935    #[inline]
2936    pub const fn name(self) -> &'static str {
2937        use MatchSource::*;
2938        match self {
2939            Normal => "match",
2940            Postfix => ".match",
2941            ForLoopDesugar => "for",
2942            TryDesugar(_) => "?",
2943            AwaitDesugar => ".await",
2944            FormatArgs => "format_args!()",
2945        }
2946    }
2947}
2948
2949/// The loop type that yielded an `ExprKind::Loop`.
2950#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2951pub enum LoopSource {
2952    /// A `loop { .. }` loop.
2953    Loop,
2954    /// A `while _ { .. }` loop.
2955    While,
2956    /// A `for _ in _ { .. }` loop.
2957    ForLoop,
2958}
2959
2960impl LoopSource {
2961    pub fn name(self) -> &'static str {
2962        match self {
2963            LoopSource::Loop => "loop",
2964            LoopSource::While => "while",
2965            LoopSource::ForLoop => "for",
2966        }
2967    }
2968}
2969
2970#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2971pub enum LoopIdError {
2972    OutsideLoopScope,
2973    UnlabeledCfInWhileCondition,
2974    UnresolvedLabel,
2975}
2976
2977impl fmt::Display for LoopIdError {
2978    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2979        f.write_str(match self {
2980            LoopIdError::OutsideLoopScope => "not inside loop scope",
2981            LoopIdError::UnlabeledCfInWhileCondition => {
2982                "unlabeled control flow (break or continue) in while condition"
2983            }
2984            LoopIdError::UnresolvedLabel => "label not found",
2985        })
2986    }
2987}
2988
2989#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2990pub struct Destination {
2991    /// This is `Some(_)` iff there is an explicit user-specified 'label
2992    pub label: Option<Label>,
2993
2994    /// These errors are caught and then reported during the diagnostics pass in
2995    /// `librustc_passes/loops.rs`
2996    pub target_id: Result<HirId, LoopIdError>,
2997}
2998
2999/// The yield kind that caused an `ExprKind::Yield`.
3000#[derive(Copy, Clone, Debug, HashStable_Generic)]
3001pub enum YieldSource {
3002    /// An `<expr>.await`.
3003    Await { expr: Option<HirId> },
3004    /// A plain `yield`.
3005    Yield,
3006}
3007
3008impl fmt::Display for YieldSource {
3009    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3010        f.write_str(match self {
3011            YieldSource::Await { .. } => "`await`",
3012            YieldSource::Yield => "`yield`",
3013        })
3014    }
3015}
3016
3017// N.B., if you change this, you'll probably want to change the corresponding
3018// type structure in middle/ty.rs as well.
3019#[derive(Debug, Clone, Copy, HashStable_Generic)]
3020pub struct MutTy<'hir> {
3021    pub ty: &'hir Ty<'hir>,
3022    pub mutbl: Mutability,
3023}
3024
3025/// Represents a function's signature in a trait declaration,
3026/// trait implementation, or a free function.
3027#[derive(Debug, Clone, Copy, HashStable_Generic)]
3028pub struct FnSig<'hir> {
3029    pub header: FnHeader,
3030    pub decl: &'hir FnDecl<'hir>,
3031    pub span: Span,
3032}
3033
3034// The bodies for items are stored "out of line", in a separate
3035// hashmap in the `Crate`. Here we just record the hir-id of the item
3036// so it can fetched later.
3037#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3038pub struct TraitItemId {
3039    pub owner_id: OwnerId,
3040}
3041
3042impl TraitItemId {
3043    #[inline]
3044    pub fn hir_id(&self) -> HirId {
3045        // Items are always HIR owners.
3046        HirId::make_owner(self.owner_id.def_id)
3047    }
3048}
3049
3050/// Represents an item declaration within a trait declaration,
3051/// possibly including a default implementation. A trait item is
3052/// either required (meaning it doesn't have an implementation, just a
3053/// signature) or provided (meaning it has a default implementation).
3054#[derive(Debug, Clone, Copy, HashStable_Generic)]
3055pub struct TraitItem<'hir> {
3056    pub ident: Ident,
3057    pub owner_id: OwnerId,
3058    pub generics: &'hir Generics<'hir>,
3059    pub kind: TraitItemKind<'hir>,
3060    pub span: Span,
3061    pub defaultness: Defaultness,
3062    pub has_delayed_lints: bool,
3063}
3064
3065macro_rules! expect_methods_self_kind {
3066    ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3067        $(
3068            #[track_caller]
3069            pub fn $name(&self) -> $ret_ty {
3070                let $pat = &self.kind else { expect_failed(stringify!($name), self) };
3071                $ret_val
3072            }
3073        )*
3074    }
3075}
3076
3077macro_rules! expect_methods_self {
3078    ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3079        $(
3080            #[track_caller]
3081            pub fn $name(&self) -> $ret_ty {
3082                let $pat = self else { expect_failed(stringify!($name), self) };
3083                $ret_val
3084            }
3085        )*
3086    }
3087}
3088
3089#[track_caller]
3090fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3091    panic!("{ident}: found {found:?}")
3092}
3093
3094impl<'hir> TraitItem<'hir> {
3095    #[inline]
3096    pub fn hir_id(&self) -> HirId {
3097        // Items are always HIR owners.
3098        HirId::make_owner(self.owner_id.def_id)
3099    }
3100
3101    pub fn trait_item_id(&self) -> TraitItemId {
3102        TraitItemId { owner_id: self.owner_id }
3103    }
3104
3105    expect_methods_self_kind! {
3106        expect_const, (&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3107            TraitItemKind::Const(ty, rhs), (ty, *rhs);
3108
3109        expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3110            TraitItemKind::Fn(ty, trfn), (ty, trfn);
3111
3112        expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3113            TraitItemKind::Type(bounds, ty), (bounds, *ty);
3114    }
3115}
3116
3117/// Represents a trait method's body (or just argument names).
3118#[derive(Debug, Clone, Copy, HashStable_Generic)]
3119pub enum TraitFn<'hir> {
3120    /// No default body in the trait, just a signature.
3121    Required(&'hir [Option<Ident>]),
3122
3123    /// Both signature and body are provided in the trait.
3124    Provided(BodyId),
3125}
3126
3127/// Represents a trait method or associated constant or type
3128#[derive(Debug, Clone, Copy, HashStable_Generic)]
3129pub enum TraitItemKind<'hir> {
3130    /// An associated constant with an optional value (otherwise `impl`s must contain a value).
3131    Const(&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3132    /// An associated function with an optional body.
3133    Fn(FnSig<'hir>, TraitFn<'hir>),
3134    /// An associated type with (possibly empty) bounds and optional concrete
3135    /// type.
3136    Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3137}
3138
3139// The bodies for items are stored "out of line", in a separate
3140// hashmap in the `Crate`. Here we just record the hir-id of the item
3141// so it can fetched later.
3142#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3143pub struct ImplItemId {
3144    pub owner_id: OwnerId,
3145}
3146
3147impl ImplItemId {
3148    #[inline]
3149    pub fn hir_id(&self) -> HirId {
3150        // Items are always HIR owners.
3151        HirId::make_owner(self.owner_id.def_id)
3152    }
3153}
3154
3155/// Represents an associated item within an impl block.
3156///
3157/// Refer to [`Impl`] for an impl block declaration.
3158#[derive(Debug, Clone, Copy, HashStable_Generic)]
3159pub struct ImplItem<'hir> {
3160    pub ident: Ident,
3161    pub owner_id: OwnerId,
3162    pub generics: &'hir Generics<'hir>,
3163    pub kind: ImplItemKind<'hir>,
3164    pub impl_kind: ImplItemImplKind,
3165    pub span: Span,
3166    pub has_delayed_lints: bool,
3167}
3168
3169#[derive(Debug, Clone, Copy, HashStable_Generic)]
3170pub enum ImplItemImplKind {
3171    Inherent {
3172        vis_span: Span,
3173    },
3174    Trait {
3175        defaultness: Defaultness,
3176        /// Item in the trait that this item implements
3177        trait_item_def_id: Result<DefId, ErrorGuaranteed>,
3178    },
3179}
3180
3181impl<'hir> ImplItem<'hir> {
3182    #[inline]
3183    pub fn hir_id(&self) -> HirId {
3184        // Items are always HIR owners.
3185        HirId::make_owner(self.owner_id.def_id)
3186    }
3187
3188    pub fn impl_item_id(&self) -> ImplItemId {
3189        ImplItemId { owner_id: self.owner_id }
3190    }
3191
3192    pub fn vis_span(&self) -> Option<Span> {
3193        match self.impl_kind {
3194            ImplItemImplKind::Trait { .. } => None,
3195            ImplItemImplKind::Inherent { vis_span, .. } => Some(vis_span),
3196        }
3197    }
3198
3199    expect_methods_self_kind! {
3200        expect_const, (&'hir Ty<'hir>, ConstItemRhs<'hir>), ImplItemKind::Const(ty, rhs), (ty, *rhs);
3201        expect_fn,    (&FnSig<'hir>, BodyId),               ImplItemKind::Fn(ty, body),   (ty, *body);
3202        expect_type,  &'hir Ty<'hir>,                       ImplItemKind::Type(ty),       ty;
3203    }
3204}
3205
3206/// Represents various kinds of content within an `impl`.
3207#[derive(Debug, Clone, Copy, HashStable_Generic)]
3208pub enum ImplItemKind<'hir> {
3209    /// An associated constant of the given type, set to the constant result
3210    /// of the expression.
3211    Const(&'hir Ty<'hir>, ConstItemRhs<'hir>),
3212    /// An associated function implementation with the given signature and body.
3213    Fn(FnSig<'hir>, BodyId),
3214    /// An associated type.
3215    Type(&'hir Ty<'hir>),
3216}
3217
3218/// A constraint on an associated item.
3219///
3220/// ### Examples
3221///
3222/// * the `A = Ty` and `B = Ty` in `Trait<A = Ty, B = Ty>`
3223/// * the `G<Ty> = Ty` in `Trait<G<Ty> = Ty>`
3224/// * the `A: Bound` in `Trait<A: Bound>`
3225/// * the `RetTy` in `Trait(ArgTy, ArgTy) -> RetTy`
3226/// * the `C = { Ct }` in `Trait<C = { Ct }>` (feature `associated_const_equality`)
3227/// * the `f(..): Bound` in `Trait<f(..): Bound>` (feature `return_type_notation`)
3228#[derive(Debug, Clone, Copy, HashStable_Generic)]
3229pub struct AssocItemConstraint<'hir> {
3230    #[stable_hasher(ignore)]
3231    pub hir_id: HirId,
3232    pub ident: Ident,
3233    pub gen_args: &'hir GenericArgs<'hir>,
3234    pub kind: AssocItemConstraintKind<'hir>,
3235    pub span: Span,
3236}
3237
3238impl<'hir> AssocItemConstraint<'hir> {
3239    /// Obtain the type on the RHS of an assoc ty equality constraint if applicable.
3240    pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3241        match self.kind {
3242            AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3243            _ => None,
3244        }
3245    }
3246
3247    /// Obtain the const on the RHS of an assoc const equality constraint if applicable.
3248    pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3249        match self.kind {
3250            AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3251            _ => None,
3252        }
3253    }
3254}
3255
3256#[derive(Debug, Clone, Copy, HashStable_Generic)]
3257pub enum Term<'hir> {
3258    Ty(&'hir Ty<'hir>),
3259    Const(&'hir ConstArg<'hir>),
3260}
3261
3262impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3263    fn from(ty: &'hir Ty<'hir>) -> Self {
3264        Term::Ty(ty)
3265    }
3266}
3267
3268impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3269    fn from(c: &'hir ConstArg<'hir>) -> Self {
3270        Term::Const(c)
3271    }
3272}
3273
3274/// The kind of [associated item constraint][AssocItemConstraint].
3275#[derive(Debug, Clone, Copy, HashStable_Generic)]
3276pub enum AssocItemConstraintKind<'hir> {
3277    /// An equality constraint for an associated item (e.g., `AssocTy = Ty` in `Trait<AssocTy = Ty>`).
3278    ///
3279    /// Also known as an *associated item binding* (we *bind* an associated item to a term).
3280    ///
3281    /// Furthermore, associated type equality constraints can also be referred to as *associated type
3282    /// bindings*. Similarly with associated const equality constraints and *associated const bindings*.
3283    Equality { term: Term<'hir> },
3284    /// A bound on an associated type (e.g., `AssocTy: Bound` in `Trait<AssocTy: Bound>`).
3285    Bound { bounds: &'hir [GenericBound<'hir>] },
3286}
3287
3288impl<'hir> AssocItemConstraintKind<'hir> {
3289    pub fn descr(&self) -> &'static str {
3290        match self {
3291            AssocItemConstraintKind::Equality { .. } => "binding",
3292            AssocItemConstraintKind::Bound { .. } => "constraint",
3293        }
3294    }
3295}
3296
3297/// An uninhabited enum used to make `Infer` variants on [`Ty`] and [`ConstArg`] be
3298/// unreachable. Zero-Variant enums are guaranteed to have the same layout as the never
3299/// type.
3300#[derive(Debug, Clone, Copy, HashStable_Generic)]
3301pub enum AmbigArg {}
3302
3303/// Represents a type in the `HIR`.
3304///
3305/// For an explanation of the `Unambig` generic parameter see the dev-guide:
3306/// <https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html>
3307#[derive(Debug, Clone, Copy, HashStable_Generic)]
3308#[repr(C)]
3309pub struct Ty<'hir, Unambig = ()> {
3310    #[stable_hasher(ignore)]
3311    pub hir_id: HirId,
3312    pub span: Span,
3313    pub kind: TyKind<'hir, Unambig>,
3314}
3315
3316impl<'hir> Ty<'hir, AmbigArg> {
3317    /// Converts a `Ty` in an ambiguous position to one in an unambiguous position.
3318    ///
3319    /// Functions accepting an unambiguous types may expect the [`TyKind::Infer`] variant
3320    /// to be used. Care should be taken to separately handle infer types when calling this
3321    /// function as it cannot be handled by downstream code making use of the returned ty.
3322    ///
3323    /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or
3324    /// specifically matching on [`GenericArg::Infer`] when handling generic arguments.
3325    ///
3326    /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer]
3327    pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3328        // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is
3329        // the same across different ZST type arguments.
3330        let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3331        unsafe { &*ptr }
3332    }
3333}
3334
3335impl<'hir> Ty<'hir> {
3336    /// Converts a `Ty` in an unambiguous position to one in an ambiguous position. This is
3337    /// fallible as the [`TyKind::Infer`] variant is not present in ambiguous positions.
3338    ///
3339    /// Functions accepting ambiguous types will not handle the [`TyKind::Infer`] variant, if
3340    /// infer types are relevant to you then care should be taken to handle them separately.
3341    pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3342        if let TyKind::Infer(()) = self.kind {
3343            return None;
3344        }
3345
3346        // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is
3347        // the same across different ZST type arguments. We also asserted that the `self` is
3348        // not a `TyKind::Infer` so there is no risk of transmuting a `()` to `AmbigArg`.
3349        let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3350        Some(unsafe { &*ptr })
3351    }
3352}
3353
3354impl<'hir> Ty<'hir, AmbigArg> {
3355    pub fn peel_refs(&self) -> &Ty<'hir> {
3356        let mut final_ty = self.as_unambig_ty();
3357        while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3358            final_ty = ty;
3359        }
3360        final_ty
3361    }
3362}
3363
3364impl<'hir> Ty<'hir> {
3365    pub fn peel_refs(&self) -> &Self {
3366        let mut final_ty = self;
3367        while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3368            final_ty = ty;
3369        }
3370        final_ty
3371    }
3372
3373    /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
3374    pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3375        let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3376            return None;
3377        };
3378        let [segment] = &path.segments else {
3379            return None;
3380        };
3381        match path.res {
3382            Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3383                Some((def_id, segment.ident))
3384            }
3385            _ => None,
3386        }
3387    }
3388
3389    pub fn find_self_aliases(&self) -> Vec<Span> {
3390        use crate::intravisit::Visitor;
3391        struct MyVisitor(Vec<Span>);
3392        impl<'v> Visitor<'v> for MyVisitor {
3393            fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3394                if matches!(
3395                    &t.kind,
3396                    TyKind::Path(QPath::Resolved(
3397                        _,
3398                        Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3399                    ))
3400                ) {
3401                    self.0.push(t.span);
3402                    return;
3403                }
3404                crate::intravisit::walk_ty(self, t);
3405            }
3406        }
3407
3408        let mut my_visitor = MyVisitor(vec![]);
3409        my_visitor.visit_ty_unambig(self);
3410        my_visitor.0
3411    }
3412
3413    /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
3414    /// use inference to provide suggestions for the appropriate type if possible.
3415    pub fn is_suggestable_infer_ty(&self) -> bool {
3416        fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3417            generic_args.iter().any(|arg| match arg {
3418                GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3419                GenericArg::Infer(_) => true,
3420                _ => false,
3421            })
3422        }
3423        debug!(?self);
3424        match &self.kind {
3425            TyKind::Infer(()) => true,
3426            TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3427            TyKind::Array(ty, length) => {
3428                ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3429            }
3430            TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3431            TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3432            TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3433                ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3434            }
3435            TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3436                ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3437                    || segments
3438                        .iter()
3439                        .any(|segment| are_suggestable_generic_args(segment.args().args))
3440            }
3441            _ => false,
3442        }
3443    }
3444}
3445
3446/// Not represented directly in the AST; referred to by name through a `ty_path`.
3447#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3448pub enum PrimTy {
3449    Int(IntTy),
3450    Uint(UintTy),
3451    Float(FloatTy),
3452    Str,
3453    Bool,
3454    Char,
3455}
3456
3457impl PrimTy {
3458    /// All of the primitive types
3459    pub const ALL: [Self; 19] = [
3460        // any changes here should also be reflected in `PrimTy::from_name`
3461        Self::Int(IntTy::I8),
3462        Self::Int(IntTy::I16),
3463        Self::Int(IntTy::I32),
3464        Self::Int(IntTy::I64),
3465        Self::Int(IntTy::I128),
3466        Self::Int(IntTy::Isize),
3467        Self::Uint(UintTy::U8),
3468        Self::Uint(UintTy::U16),
3469        Self::Uint(UintTy::U32),
3470        Self::Uint(UintTy::U64),
3471        Self::Uint(UintTy::U128),
3472        Self::Uint(UintTy::Usize),
3473        Self::Float(FloatTy::F16),
3474        Self::Float(FloatTy::F32),
3475        Self::Float(FloatTy::F64),
3476        Self::Float(FloatTy::F128),
3477        Self::Bool,
3478        Self::Char,
3479        Self::Str,
3480    ];
3481
3482    /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
3483    ///
3484    /// Used by clippy.
3485    pub fn name_str(self) -> &'static str {
3486        match self {
3487            PrimTy::Int(i) => i.name_str(),
3488            PrimTy::Uint(u) => u.name_str(),
3489            PrimTy::Float(f) => f.name_str(),
3490            PrimTy::Str => "str",
3491            PrimTy::Bool => "bool",
3492            PrimTy::Char => "char",
3493        }
3494    }
3495
3496    pub fn name(self) -> Symbol {
3497        match self {
3498            PrimTy::Int(i) => i.name(),
3499            PrimTy::Uint(u) => u.name(),
3500            PrimTy::Float(f) => f.name(),
3501            PrimTy::Str => sym::str,
3502            PrimTy::Bool => sym::bool,
3503            PrimTy::Char => sym::char,
3504        }
3505    }
3506
3507    /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
3508    /// Returns `None` if no matching type is found.
3509    pub fn from_name(name: Symbol) -> Option<Self> {
3510        let ty = match name {
3511            // any changes here should also be reflected in `PrimTy::ALL`
3512            sym::i8 => Self::Int(IntTy::I8),
3513            sym::i16 => Self::Int(IntTy::I16),
3514            sym::i32 => Self::Int(IntTy::I32),
3515            sym::i64 => Self::Int(IntTy::I64),
3516            sym::i128 => Self::Int(IntTy::I128),
3517            sym::isize => Self::Int(IntTy::Isize),
3518            sym::u8 => Self::Uint(UintTy::U8),
3519            sym::u16 => Self::Uint(UintTy::U16),
3520            sym::u32 => Self::Uint(UintTy::U32),
3521            sym::u64 => Self::Uint(UintTy::U64),
3522            sym::u128 => Self::Uint(UintTy::U128),
3523            sym::usize => Self::Uint(UintTy::Usize),
3524            sym::f16 => Self::Float(FloatTy::F16),
3525            sym::f32 => Self::Float(FloatTy::F32),
3526            sym::f64 => Self::Float(FloatTy::F64),
3527            sym::f128 => Self::Float(FloatTy::F128),
3528            sym::bool => Self::Bool,
3529            sym::char => Self::Char,
3530            sym::str => Self::Str,
3531            _ => return None,
3532        };
3533        Some(ty)
3534    }
3535}
3536
3537#[derive(Debug, Clone, Copy, HashStable_Generic)]
3538pub struct FnPtrTy<'hir> {
3539    pub safety: Safety,
3540    pub abi: ExternAbi,
3541    pub generic_params: &'hir [GenericParam<'hir>],
3542    pub decl: &'hir FnDecl<'hir>,
3543    // `Option` because bare fn parameter identifiers are optional. We also end up
3544    // with `None` in some error cases, e.g. invalid parameter patterns.
3545    pub param_idents: &'hir [Option<Ident>],
3546}
3547
3548#[derive(Debug, Clone, Copy, HashStable_Generic)]
3549pub struct UnsafeBinderTy<'hir> {
3550    pub generic_params: &'hir [GenericParam<'hir>],
3551    pub inner_ty: &'hir Ty<'hir>,
3552}
3553
3554#[derive(Debug, Clone, Copy, HashStable_Generic)]
3555pub struct OpaqueTy<'hir> {
3556    #[stable_hasher(ignore)]
3557    pub hir_id: HirId,
3558    pub def_id: LocalDefId,
3559    pub bounds: GenericBounds<'hir>,
3560    pub origin: OpaqueTyOrigin<LocalDefId>,
3561    pub span: Span,
3562}
3563
3564#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3565pub enum PreciseCapturingArgKind<T, U> {
3566    Lifetime(T),
3567    /// Non-lifetime argument (type or const)
3568    Param(U),
3569}
3570
3571pub type PreciseCapturingArg<'hir> =
3572    PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3573
3574impl PreciseCapturingArg<'_> {
3575    pub fn hir_id(self) -> HirId {
3576        match self {
3577            PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3578            PreciseCapturingArg::Param(param) => param.hir_id,
3579        }
3580    }
3581
3582    pub fn name(self) -> Symbol {
3583        match self {
3584            PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3585            PreciseCapturingArg::Param(param) => param.ident.name,
3586        }
3587    }
3588}
3589
3590/// We need to have a [`Node`] for the [`HirId`] that we attach the type/const param
3591/// resolution to. Lifetimes don't have this problem, and for them, it's actually
3592/// kind of detrimental to use a custom node type versus just using [`Lifetime`],
3593/// since resolve_bound_vars operates on `Lifetime`s.
3594#[derive(Debug, Clone, Copy, HashStable_Generic)]
3595pub struct PreciseCapturingNonLifetimeArg {
3596    #[stable_hasher(ignore)]
3597    pub hir_id: HirId,
3598    pub ident: Ident,
3599    pub res: Res,
3600}
3601
3602#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3603#[derive(HashStable_Generic, Encodable, Decodable)]
3604pub enum RpitContext {
3605    Trait,
3606    TraitImpl,
3607}
3608
3609/// From whence the opaque type came.
3610#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3611#[derive(HashStable_Generic, Encodable, Decodable)]
3612pub enum OpaqueTyOrigin<D> {
3613    /// `-> impl Trait`
3614    FnReturn {
3615        /// The defining function.
3616        parent: D,
3617        // Whether this is an RPITIT (return position impl trait in trait)
3618        in_trait_or_impl: Option<RpitContext>,
3619    },
3620    /// `async fn`
3621    AsyncFn {
3622        /// The defining function.
3623        parent: D,
3624        // Whether this is an AFIT (async fn in trait)
3625        in_trait_or_impl: Option<RpitContext>,
3626    },
3627    /// type aliases: `type Foo = impl Trait;`
3628    TyAlias {
3629        /// The type alias or associated type parent of the TAIT/ATPIT
3630        parent: D,
3631        /// associated types in impl blocks for traits.
3632        in_assoc_ty: bool,
3633    },
3634}
3635
3636#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3637pub enum InferDelegationKind {
3638    Input(usize),
3639    Output,
3640}
3641
3642/// The various kinds of types recognized by the compiler.
3643///
3644/// For an explanation of the `Unambig` generic parameter see the dev-guide:
3645/// <https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html>
3646// SAFETY: `repr(u8)` is required so that `TyKind<()>` and `TyKind<!>` are layout compatible
3647#[repr(u8, C)]
3648#[derive(Debug, Clone, Copy, HashStable_Generic)]
3649pub enum TyKind<'hir, Unambig = ()> {
3650    /// Actual type should be inherited from `DefId` signature
3651    InferDelegation(DefId, InferDelegationKind),
3652    /// A variable length slice (i.e., `[T]`).
3653    Slice(&'hir Ty<'hir>),
3654    /// A fixed length array (i.e., `[T; n]`).
3655    Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3656    /// A raw pointer (i.e., `*const T` or `*mut T`).
3657    Ptr(MutTy<'hir>),
3658    /// A reference (i.e., `&'a T` or `&'a mut T`).
3659    Ref(&'hir Lifetime, MutTy<'hir>),
3660    /// A function pointer (e.g., `fn(usize) -> bool`).
3661    FnPtr(&'hir FnPtrTy<'hir>),
3662    /// An unsafe binder type (e.g. `unsafe<'a> Foo<'a>`).
3663    UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3664    /// The never type (`!`).
3665    Never,
3666    /// A tuple (`(A, B, C, D, ...)`).
3667    Tup(&'hir [Ty<'hir>]),
3668    /// A path to a type definition (`module::module::...::Type`), or an
3669    /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
3670    ///
3671    /// Type parameters may be stored in each `PathSegment`.
3672    Path(QPath<'hir>),
3673    /// An opaque type definition itself. This is only used for `impl Trait`.
3674    OpaqueDef(&'hir OpaqueTy<'hir>),
3675    /// A trait ascription type, which is `impl Trait` within a local binding.
3676    TraitAscription(GenericBounds<'hir>),
3677    /// A trait object type `Bound1 + Bound2 + Bound3`
3678    /// where `Bound` is a trait or a lifetime.
3679    ///
3680    /// We use pointer tagging to represent a `&'hir Lifetime` and `TraitObjectSyntax` pair
3681    /// as otherwise this type being `repr(C)` would result in `TyKind` increasing in size.
3682    TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3683    /// Unused for now.
3684    Typeof(&'hir AnonConst),
3685    /// Placeholder for a type that has failed to be defined.
3686    Err(rustc_span::ErrorGuaranteed),
3687    /// Pattern types (`pattern_type!(u32 is 1..)`)
3688    Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3689    /// `TyKind::Infer` means the type should be inferred instead of it having been
3690    /// specified. This can appear anywhere in a type.
3691    ///
3692    /// This variant is not always used to represent inference types, sometimes
3693    /// [`GenericArg::Infer`] is used instead.
3694    Infer(Unambig),
3695}
3696
3697#[derive(Debug, Clone, Copy, HashStable_Generic)]
3698pub enum InlineAsmOperand<'hir> {
3699    In {
3700        reg: InlineAsmRegOrRegClass,
3701        expr: &'hir Expr<'hir>,
3702    },
3703    Out {
3704        reg: InlineAsmRegOrRegClass,
3705        late: bool,
3706        expr: Option<&'hir Expr<'hir>>,
3707    },
3708    InOut {
3709        reg: InlineAsmRegOrRegClass,
3710        late: bool,
3711        expr: &'hir Expr<'hir>,
3712    },
3713    SplitInOut {
3714        reg: InlineAsmRegOrRegClass,
3715        late: bool,
3716        in_expr: &'hir Expr<'hir>,
3717        out_expr: Option<&'hir Expr<'hir>>,
3718    },
3719    Const {
3720        anon_const: ConstBlock,
3721    },
3722    SymFn {
3723        expr: &'hir Expr<'hir>,
3724    },
3725    SymStatic {
3726        path: QPath<'hir>,
3727        def_id: DefId,
3728    },
3729    Label {
3730        block: &'hir Block<'hir>,
3731    },
3732}
3733
3734impl<'hir> InlineAsmOperand<'hir> {
3735    pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3736        match *self {
3737            Self::In { reg, .. }
3738            | Self::Out { reg, .. }
3739            | Self::InOut { reg, .. }
3740            | Self::SplitInOut { reg, .. } => Some(reg),
3741            Self::Const { .. }
3742            | Self::SymFn { .. }
3743            | Self::SymStatic { .. }
3744            | Self::Label { .. } => None,
3745        }
3746    }
3747
3748    pub fn is_clobber(&self) -> bool {
3749        matches!(
3750            self,
3751            InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3752        )
3753    }
3754}
3755
3756#[derive(Debug, Clone, Copy, HashStable_Generic)]
3757pub struct InlineAsm<'hir> {
3758    pub asm_macro: ast::AsmMacro,
3759    pub template: &'hir [InlineAsmTemplatePiece],
3760    pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3761    pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3762    pub options: InlineAsmOptions,
3763    pub line_spans: &'hir [Span],
3764}
3765
3766impl InlineAsm<'_> {
3767    pub fn contains_label(&self) -> bool {
3768        self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3769    }
3770}
3771
3772/// Represents a parameter in a function header.
3773#[derive(Debug, Clone, Copy, HashStable_Generic)]
3774pub struct Param<'hir> {
3775    #[stable_hasher(ignore)]
3776    pub hir_id: HirId,
3777    pub pat: &'hir Pat<'hir>,
3778    pub ty_span: Span,
3779    pub span: Span,
3780}
3781
3782/// Represents the header (not the body) of a function declaration.
3783#[derive(Debug, Clone, Copy, HashStable_Generic)]
3784pub struct FnDecl<'hir> {
3785    /// The types of the function's parameters.
3786    ///
3787    /// Additional argument data is stored in the function's [body](Body::params).
3788    pub inputs: &'hir [Ty<'hir>],
3789    pub output: FnRetTy<'hir>,
3790    pub c_variadic: bool,
3791    /// Does the function have an implicit self?
3792    pub implicit_self: ImplicitSelfKind,
3793    /// Is lifetime elision allowed.
3794    pub lifetime_elision_allowed: bool,
3795}
3796
3797impl<'hir> FnDecl<'hir> {
3798    pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3799        if let FnRetTy::Return(ty) = self.output
3800            && let TyKind::InferDelegation(sig_id, _) = ty.kind
3801        {
3802            return Some(sig_id);
3803        }
3804        None
3805    }
3806}
3807
3808/// Represents what type of implicit self a function has, if any.
3809#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3810pub enum ImplicitSelfKind {
3811    /// Represents a `fn x(self);`.
3812    Imm,
3813    /// Represents a `fn x(mut self);`.
3814    Mut,
3815    /// Represents a `fn x(&self);`.
3816    RefImm,
3817    /// Represents a `fn x(&mut self);`.
3818    RefMut,
3819    /// Represents when a function does not have a self argument or
3820    /// when a function has a `self: X` argument.
3821    None,
3822}
3823
3824impl ImplicitSelfKind {
3825    /// Does this represent an implicit self?
3826    pub fn has_implicit_self(&self) -> bool {
3827        !matches!(*self, ImplicitSelfKind::None)
3828    }
3829}
3830
3831#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3832pub enum IsAsync {
3833    Async(Span),
3834    NotAsync,
3835}
3836
3837impl IsAsync {
3838    pub fn is_async(self) -> bool {
3839        matches!(self, IsAsync::Async(_))
3840    }
3841}
3842
3843#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3844pub enum Defaultness {
3845    Default { has_value: bool },
3846    Final,
3847}
3848
3849impl Defaultness {
3850    pub fn has_value(&self) -> bool {
3851        match *self {
3852            Defaultness::Default { has_value } => has_value,
3853            Defaultness::Final => true,
3854        }
3855    }
3856
3857    pub fn is_final(&self) -> bool {
3858        *self == Defaultness::Final
3859    }
3860
3861    pub fn is_default(&self) -> bool {
3862        matches!(*self, Defaultness::Default { .. })
3863    }
3864}
3865
3866#[derive(Debug, Clone, Copy, HashStable_Generic)]
3867pub enum FnRetTy<'hir> {
3868    /// Return type is not specified.
3869    ///
3870    /// Functions default to `()` and
3871    /// closures default to inference. Span points to where return
3872    /// type would be inserted.
3873    DefaultReturn(Span),
3874    /// Everything else.
3875    Return(&'hir Ty<'hir>),
3876}
3877
3878impl<'hir> FnRetTy<'hir> {
3879    #[inline]
3880    pub fn span(&self) -> Span {
3881        match *self {
3882            Self::DefaultReturn(span) => span,
3883            Self::Return(ref ty) => ty.span,
3884        }
3885    }
3886
3887    pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3888        if let Self::Return(ty) = self
3889            && ty.is_suggestable_infer_ty()
3890        {
3891            return Some(*ty);
3892        }
3893        None
3894    }
3895}
3896
3897/// Represents `for<...>` binder before a closure
3898#[derive(Copy, Clone, Debug, HashStable_Generic)]
3899pub enum ClosureBinder {
3900    /// Binder is not specified.
3901    Default,
3902    /// Binder is specified.
3903    ///
3904    /// Span points to the whole `for<...>`.
3905    For { span: Span },
3906}
3907
3908#[derive(Debug, Clone, Copy, HashStable_Generic)]
3909pub struct Mod<'hir> {
3910    pub spans: ModSpans,
3911    pub item_ids: &'hir [ItemId],
3912}
3913
3914#[derive(Copy, Clone, Debug, HashStable_Generic)]
3915pub struct ModSpans {
3916    /// A span from the first token past `{` to the last token until `}`.
3917    /// For `mod foo;`, the inner span ranges from the first token
3918    /// to the last token in the external file.
3919    pub inner_span: Span,
3920    pub inject_use_span: Span,
3921}
3922
3923#[derive(Debug, Clone, Copy, HashStable_Generic)]
3924pub struct EnumDef<'hir> {
3925    pub variants: &'hir [Variant<'hir>],
3926}
3927
3928#[derive(Debug, Clone, Copy, HashStable_Generic)]
3929pub struct Variant<'hir> {
3930    /// Name of the variant.
3931    pub ident: Ident,
3932    /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
3933    #[stable_hasher(ignore)]
3934    pub hir_id: HirId,
3935    pub def_id: LocalDefId,
3936    /// Fields and constructor id of the variant.
3937    pub data: VariantData<'hir>,
3938    /// Explicit discriminant (e.g., `Foo = 1`).
3939    pub disr_expr: Option<&'hir AnonConst>,
3940    /// Span
3941    pub span: Span,
3942}
3943
3944#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3945pub enum UseKind {
3946    /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
3947    /// Also produced for each element of a list `use`, e.g.
3948    /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
3949    ///
3950    /// The identifier is the name defined by the import. E.g. for `use
3951    /// foo::bar` it is `bar`, for `use foo::bar as baz` it is `baz`.
3952    Single(Ident),
3953
3954    /// Glob import, e.g., `use foo::*`.
3955    Glob,
3956
3957    /// Degenerate list import, e.g., `use foo::{a, b}` produces
3958    /// an additional `use foo::{}` for performing checks such as
3959    /// unstable feature gating. May be removed in the future.
3960    ListStem,
3961}
3962
3963/// References to traits in impls.
3964///
3965/// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
3966/// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
3967/// trait being referred to but just a unique `HirId` that serves as a key
3968/// within the resolution map.
3969#[derive(Clone, Debug, Copy, HashStable_Generic)]
3970pub struct TraitRef<'hir> {
3971    pub path: &'hir Path<'hir>,
3972    // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
3973    #[stable_hasher(ignore)]
3974    pub hir_ref_id: HirId,
3975}
3976
3977impl TraitRef<'_> {
3978    /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
3979    pub fn trait_def_id(&self) -> Option<DefId> {
3980        match self.path.res {
3981            Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3982            Res::Err => None,
3983            res => panic!("{res:?} did not resolve to a trait or trait alias"),
3984        }
3985    }
3986}
3987
3988#[derive(Clone, Debug, Copy, HashStable_Generic)]
3989pub struct PolyTraitRef<'hir> {
3990    /// The `'a` in `for<'a> Foo<&'a T>`.
3991    pub bound_generic_params: &'hir [GenericParam<'hir>],
3992
3993    /// The constness and polarity of the trait ref.
3994    ///
3995    /// The `async` modifier is lowered directly into a different trait for now.
3996    pub modifiers: TraitBoundModifiers,
3997
3998    /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
3999    pub trait_ref: TraitRef<'hir>,
4000
4001    pub span: Span,
4002}
4003
4004#[derive(Debug, Clone, Copy, HashStable_Generic)]
4005pub struct FieldDef<'hir> {
4006    pub span: Span,
4007    pub vis_span: Span,
4008    pub ident: Ident,
4009    #[stable_hasher(ignore)]
4010    pub hir_id: HirId,
4011    pub def_id: LocalDefId,
4012    pub ty: &'hir Ty<'hir>,
4013    pub safety: Safety,
4014    pub default: Option<&'hir AnonConst>,
4015}
4016
4017impl FieldDef<'_> {
4018    // Still necessary in couple of places
4019    pub fn is_positional(&self) -> bool {
4020        self.ident.as_str().as_bytes()[0].is_ascii_digit()
4021    }
4022}
4023
4024/// Fields and constructor IDs of enum variants and structs.
4025#[derive(Debug, Clone, Copy, HashStable_Generic)]
4026pub enum VariantData<'hir> {
4027    /// A struct variant.
4028    ///
4029    /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
4030    Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4031    /// A tuple variant.
4032    ///
4033    /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
4034    Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4035    /// A unit variant.
4036    ///
4037    /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
4038    Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4039}
4040
4041impl<'hir> VariantData<'hir> {
4042    /// Return the fields of this variant.
4043    pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4044        match *self {
4045            VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4046            _ => &[],
4047        }
4048    }
4049
4050    pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4051        match *self {
4052            VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4053            VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4054            VariantData::Struct { .. } => None,
4055        }
4056    }
4057
4058    #[inline]
4059    pub fn ctor_kind(&self) -> Option<CtorKind> {
4060        self.ctor().map(|(kind, ..)| kind)
4061    }
4062
4063    /// Return the `HirId` of this variant's constructor, if it has one.
4064    #[inline]
4065    pub fn ctor_hir_id(&self) -> Option<HirId> {
4066        self.ctor().map(|(_, hir_id, _)| hir_id)
4067    }
4068
4069    /// Return the `LocalDefId` of this variant's constructor, if it has one.
4070    #[inline]
4071    pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4072        self.ctor().map(|(.., def_id)| def_id)
4073    }
4074}
4075
4076// The bodies for items are stored "out of line", in a separate
4077// hashmap in the `Crate`. Here we just record the hir-id of the item
4078// so it can fetched later.
4079#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4080pub struct ItemId {
4081    pub owner_id: OwnerId,
4082}
4083
4084impl ItemId {
4085    #[inline]
4086    pub fn hir_id(&self) -> HirId {
4087        // Items are always HIR owners.
4088        HirId::make_owner(self.owner_id.def_id)
4089    }
4090}
4091
4092/// An item
4093///
4094/// For more details, see the [rust lang reference].
4095/// Note that the reference does not document nightly-only features.
4096/// There may be also slight differences in the names and representation of AST nodes between
4097/// the compiler and the reference.
4098///
4099/// [rust lang reference]: https://doc.rust-lang.org/reference/items.html
4100#[derive(Debug, Clone, Copy, HashStable_Generic)]
4101pub struct Item<'hir> {
4102    pub owner_id: OwnerId,
4103    pub kind: ItemKind<'hir>,
4104    pub span: Span,
4105    pub vis_span: Span,
4106    pub has_delayed_lints: bool,
4107}
4108
4109impl<'hir> Item<'hir> {
4110    #[inline]
4111    pub fn hir_id(&self) -> HirId {
4112        // Items are always HIR owners.
4113        HirId::make_owner(self.owner_id.def_id)
4114    }
4115
4116    pub fn item_id(&self) -> ItemId {
4117        ItemId { owner_id: self.owner_id }
4118    }
4119
4120    /// Check if this is an [`ItemKind::Enum`], [`ItemKind::Struct`] or
4121    /// [`ItemKind::Union`].
4122    pub fn is_adt(&self) -> bool {
4123        matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4124    }
4125
4126    /// Check if this is an [`ItemKind::Struct`] or [`ItemKind::Union`].
4127    pub fn is_struct_or_union(&self) -> bool {
4128        matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4129    }
4130
4131    expect_methods_self_kind! {
4132        expect_extern_crate, (Option<Symbol>, Ident),
4133            ItemKind::ExternCrate(s, ident), (*s, *ident);
4134
4135        expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4136
4137        expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4138            ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4139
4140        expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4141            ItemKind::Const(ident, generics, ty, rhs), (*ident, generics, ty, *rhs);
4142
4143        expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4144            ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4145
4146        expect_macro, (Ident, &ast::MacroDef, MacroKinds),
4147            ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4148
4149        expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4150
4151        expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]),
4152            ItemKind::ForeignMod { abi, items }, (*abi, items);
4153
4154        expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4155
4156        expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4157            ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4158
4159        expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4160            ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4161
4162        expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4163            ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4164
4165        expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4166            ItemKind::Union(ident, generics, data), (*ident, generics, data);
4167
4168        expect_trait,
4169            (
4170                Constness,
4171                IsAuto,
4172                Safety,
4173                Ident,
4174                &'hir Generics<'hir>,
4175                GenericBounds<'hir>,
4176                &'hir [TraitItemId]
4177            ),
4178            ItemKind::Trait(constness, is_auto, safety, ident, generics, bounds, items),
4179            (*constness, *is_auto, *safety, *ident, generics, bounds, items);
4180
4181        expect_trait_alias, (Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4182            ItemKind::TraitAlias(constness, ident, generics, bounds), (*constness, *ident, generics, bounds);
4183
4184        expect_impl, &Impl<'hir>, ItemKind::Impl(imp), imp;
4185    }
4186}
4187
4188#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4189#[derive(Encodable, Decodable, HashStable_Generic)]
4190pub enum Safety {
4191    Unsafe,
4192    Safe,
4193}
4194
4195impl Safety {
4196    pub fn prefix_str(self) -> &'static str {
4197        match self {
4198            Self::Unsafe => "unsafe ",
4199            Self::Safe => "",
4200        }
4201    }
4202
4203    #[inline]
4204    pub fn is_unsafe(self) -> bool {
4205        !self.is_safe()
4206    }
4207
4208    #[inline]
4209    pub fn is_safe(self) -> bool {
4210        match self {
4211            Self::Unsafe => false,
4212            Self::Safe => true,
4213        }
4214    }
4215}
4216
4217impl fmt::Display for Safety {
4218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4219        f.write_str(match *self {
4220            Self::Unsafe => "unsafe",
4221            Self::Safe => "safe",
4222        })
4223    }
4224}
4225
4226#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4227pub enum Constness {
4228    Const,
4229    NotConst,
4230}
4231
4232impl fmt::Display for Constness {
4233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4234        f.write_str(match *self {
4235            Self::Const => "const",
4236            Self::NotConst => "non-const",
4237        })
4238    }
4239}
4240
4241/// The actual safety specified in syntax. We may treat
4242/// its safety different within the type system to create a
4243/// "sound by default" system that needs checking this enum
4244/// explicitly to allow unsafe operations.
4245#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4246pub enum HeaderSafety {
4247    /// A safe function annotated with `#[target_features]`.
4248    /// The type system treats this function as an unsafe function,
4249    /// but safety checking will check this enum to treat it as safe
4250    /// and allowing calling other safe target feature functions with
4251    /// the same features without requiring an additional unsafe block.
4252    SafeTargetFeatures,
4253    Normal(Safety),
4254}
4255
4256impl From<Safety> for HeaderSafety {
4257    fn from(v: Safety) -> Self {
4258        Self::Normal(v)
4259    }
4260}
4261
4262#[derive(Copy, Clone, Debug, HashStable_Generic)]
4263pub struct FnHeader {
4264    pub safety: HeaderSafety,
4265    pub constness: Constness,
4266    pub asyncness: IsAsync,
4267    pub abi: ExternAbi,
4268}
4269
4270impl FnHeader {
4271    pub fn is_async(&self) -> bool {
4272        matches!(self.asyncness, IsAsync::Async(_))
4273    }
4274
4275    pub fn is_const(&self) -> bool {
4276        matches!(self.constness, Constness::Const)
4277    }
4278
4279    pub fn is_unsafe(&self) -> bool {
4280        self.safety().is_unsafe()
4281    }
4282
4283    pub fn is_safe(&self) -> bool {
4284        self.safety().is_safe()
4285    }
4286
4287    pub fn safety(&self) -> Safety {
4288        match self.safety {
4289            HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4290            HeaderSafety::Normal(safety) => safety,
4291        }
4292    }
4293}
4294
4295#[derive(Debug, Clone, Copy, HashStable_Generic)]
4296pub enum ItemKind<'hir> {
4297    /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
4298    ///
4299    /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
4300    ExternCrate(Option<Symbol>, Ident),
4301
4302    /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
4303    ///
4304    /// or just
4305    ///
4306    /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
4307    Use(&'hir UsePath<'hir>, UseKind),
4308
4309    /// A `static` item.
4310    Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4311    /// A `const` item.
4312    Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4313    /// A function declaration.
4314    Fn {
4315        sig: FnSig<'hir>,
4316        ident: Ident,
4317        generics: &'hir Generics<'hir>,
4318        body: BodyId,
4319        /// Whether this function actually has a body.
4320        /// For functions without a body, `body` is synthesized (to avoid ICEs all over the
4321        /// compiler), but that code should never be translated.
4322        has_body: bool,
4323    },
4324    /// A MBE macro definition (`macro_rules!` or `macro`).
4325    Macro(Ident, &'hir ast::MacroDef, MacroKinds),
4326    /// A module.
4327    Mod(Ident, &'hir Mod<'hir>),
4328    /// An external module, e.g. `extern { .. }`.
4329    ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] },
4330    /// Module-level inline assembly (from `global_asm!`).
4331    GlobalAsm {
4332        asm: &'hir InlineAsm<'hir>,
4333        /// A fake body which stores typeck results for the global asm's sym_fn
4334        /// operands, which are represented as path expressions. This body contains
4335        /// a single [`ExprKind::InlineAsm`] which points to the asm in the field
4336        /// above, and which is typechecked like a inline asm expr just for the
4337        /// typeck results.
4338        fake_body: BodyId,
4339    },
4340    /// A type alias, e.g., `type Foo = Bar<u8>`.
4341    TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4342    /// An enum definition, e.g., `enum Foo<A, B> { C<A>, D<B> }`.
4343    Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4344    /// A struct definition, e.g., `struct Foo<A> {x: A}`.
4345    Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4346    /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
4347    Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4348    /// A trait definition.
4349    Trait(
4350        Constness,
4351        IsAuto,
4352        Safety,
4353        Ident,
4354        &'hir Generics<'hir>,
4355        GenericBounds<'hir>,
4356        &'hir [TraitItemId],
4357    ),
4358    /// A trait alias.
4359    TraitAlias(Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4360
4361    /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
4362    Impl(Impl<'hir>),
4363}
4364
4365/// Represents an impl block declaration.
4366///
4367/// E.g., `impl $Type { .. }` or `impl $Trait for $Type { .. }`
4368/// Refer to [`ImplItem`] for an associated item within an impl block.
4369#[derive(Debug, Clone, Copy, HashStable_Generic)]
4370pub struct Impl<'hir> {
4371    pub generics: &'hir Generics<'hir>,
4372    pub of_trait: Option<&'hir TraitImplHeader<'hir>>,
4373    pub self_ty: &'hir Ty<'hir>,
4374    pub items: &'hir [ImplItemId],
4375}
4376
4377#[derive(Debug, Clone, Copy, HashStable_Generic)]
4378pub struct TraitImplHeader<'hir> {
4379    pub constness: Constness,
4380    pub safety: Safety,
4381    pub polarity: ImplPolarity,
4382    pub defaultness: Defaultness,
4383    // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
4384    // decoding as `Span`s cannot be decoded when a `Session` is not available.
4385    pub defaultness_span: Option<Span>,
4386    pub trait_ref: TraitRef<'hir>,
4387}
4388
4389impl ItemKind<'_> {
4390    pub fn ident(&self) -> Option<Ident> {
4391        match *self {
4392            ItemKind::ExternCrate(_, ident)
4393            | ItemKind::Use(_, UseKind::Single(ident))
4394            | ItemKind::Static(_, ident, ..)
4395            | ItemKind::Const(ident, ..)
4396            | ItemKind::Fn { ident, .. }
4397            | ItemKind::Macro(ident, ..)
4398            | ItemKind::Mod(ident, ..)
4399            | ItemKind::TyAlias(ident, ..)
4400            | ItemKind::Enum(ident, ..)
4401            | ItemKind::Struct(ident, ..)
4402            | ItemKind::Union(ident, ..)
4403            | ItemKind::Trait(_, _, _, ident, ..)
4404            | ItemKind::TraitAlias(_, ident, ..) => Some(ident),
4405
4406            ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4407            | ItemKind::ForeignMod { .. }
4408            | ItemKind::GlobalAsm { .. }
4409            | ItemKind::Impl(_) => None,
4410        }
4411    }
4412
4413    pub fn generics(&self) -> Option<&Generics<'_>> {
4414        Some(match self {
4415            ItemKind::Fn { generics, .. }
4416            | ItemKind::TyAlias(_, generics, _)
4417            | ItemKind::Const(_, generics, _, _)
4418            | ItemKind::Enum(_, generics, _)
4419            | ItemKind::Struct(_, generics, _)
4420            | ItemKind::Union(_, generics, _)
4421            | ItemKind::Trait(_, _, _, _, generics, _, _)
4422            | ItemKind::TraitAlias(_, _, generics, _)
4423            | ItemKind::Impl(Impl { generics, .. }) => generics,
4424            _ => return None,
4425        })
4426    }
4427}
4428
4429// The bodies for items are stored "out of line", in a separate
4430// hashmap in the `Crate`. Here we just record the hir-id of the item
4431// so it can fetched later.
4432#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4433pub struct ForeignItemId {
4434    pub owner_id: OwnerId,
4435}
4436
4437impl ForeignItemId {
4438    #[inline]
4439    pub fn hir_id(&self) -> HirId {
4440        // Items are always HIR owners.
4441        HirId::make_owner(self.owner_id.def_id)
4442    }
4443}
4444
4445#[derive(Debug, Clone, Copy, HashStable_Generic)]
4446pub struct ForeignItem<'hir> {
4447    pub ident: Ident,
4448    pub kind: ForeignItemKind<'hir>,
4449    pub owner_id: OwnerId,
4450    pub span: Span,
4451    pub vis_span: Span,
4452    pub has_delayed_lints: bool,
4453}
4454
4455impl ForeignItem<'_> {
4456    #[inline]
4457    pub fn hir_id(&self) -> HirId {
4458        // Items are always HIR owners.
4459        HirId::make_owner(self.owner_id.def_id)
4460    }
4461
4462    pub fn foreign_item_id(&self) -> ForeignItemId {
4463        ForeignItemId { owner_id: self.owner_id }
4464    }
4465}
4466
4467/// An item within an `extern` block.
4468#[derive(Debug, Clone, Copy, HashStable_Generic)]
4469pub enum ForeignItemKind<'hir> {
4470    /// A foreign function.
4471    ///
4472    /// All argument idents are actually always present (i.e. `Some`), but
4473    /// `&[Option<Ident>]` is used because of code paths shared with `TraitFn`
4474    /// and `FnPtrTy`. The sharing is due to all of these cases not allowing
4475    /// arbitrary patterns for parameters.
4476    Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4477    /// A foreign static item (`static ext: u8`).
4478    Static(&'hir Ty<'hir>, Mutability, Safety),
4479    /// A foreign type.
4480    Type,
4481}
4482
4483/// A variable captured by a closure.
4484#[derive(Debug, Copy, Clone, HashStable_Generic)]
4485pub struct Upvar {
4486    /// First span where it is accessed (there can be multiple).
4487    pub span: Span,
4488}
4489
4490// The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
4491// has length > 0 if the trait is found through an chain of imports, starting with the
4492// import/use statement in the scope where the trait is used.
4493#[derive(Debug, Clone, HashStable_Generic)]
4494pub struct TraitCandidate {
4495    pub def_id: DefId,
4496    pub import_ids: SmallVec<[LocalDefId; 1]>,
4497}
4498
4499#[derive(Copy, Clone, Debug, HashStable_Generic)]
4500pub enum OwnerNode<'hir> {
4501    Item(&'hir Item<'hir>),
4502    ForeignItem(&'hir ForeignItem<'hir>),
4503    TraitItem(&'hir TraitItem<'hir>),
4504    ImplItem(&'hir ImplItem<'hir>),
4505    Crate(&'hir Mod<'hir>),
4506    Synthetic,
4507}
4508
4509impl<'hir> OwnerNode<'hir> {
4510    pub fn span(&self) -> Span {
4511        match self {
4512            OwnerNode::Item(Item { span, .. })
4513            | OwnerNode::ForeignItem(ForeignItem { span, .. })
4514            | OwnerNode::ImplItem(ImplItem { span, .. })
4515            | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4516            OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4517            OwnerNode::Synthetic => unreachable!(),
4518        }
4519    }
4520
4521    pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4522        match self {
4523            OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4524            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4525            | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4526            | OwnerNode::ForeignItem(ForeignItem {
4527                kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4528            }) => Some(fn_sig),
4529            _ => None,
4530        }
4531    }
4532
4533    pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4534        match self {
4535            OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4536            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4537            | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4538            | OwnerNode::ForeignItem(ForeignItem {
4539                kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4540            }) => Some(fn_sig.decl),
4541            _ => None,
4542        }
4543    }
4544
4545    pub fn body_id(&self) -> Option<BodyId> {
4546        match self {
4547            OwnerNode::Item(Item {
4548                kind:
4549                    ItemKind::Static(_, _, _, body)
4550                    | ItemKind::Const(.., ConstItemRhs::Body(body))
4551                    | ItemKind::Fn { body, .. },
4552                ..
4553            })
4554            | OwnerNode::TraitItem(TraitItem {
4555                kind:
4556                    TraitItemKind::Fn(_, TraitFn::Provided(body))
4557                    | TraitItemKind::Const(_, Some(ConstItemRhs::Body(body))),
4558                ..
4559            })
4560            | OwnerNode::ImplItem(ImplItem {
4561                kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, ConstItemRhs::Body(body)),
4562                ..
4563            }) => Some(*body),
4564            _ => None,
4565        }
4566    }
4567
4568    pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4569        Node::generics(self.into())
4570    }
4571
4572    pub fn def_id(self) -> OwnerId {
4573        match self {
4574            OwnerNode::Item(Item { owner_id, .. })
4575            | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4576            | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4577            | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4578            OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4579            OwnerNode::Synthetic => unreachable!(),
4580        }
4581    }
4582
4583    /// Check if node is an impl block.
4584    pub fn is_impl_block(&self) -> bool {
4585        matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4586    }
4587
4588    expect_methods_self! {
4589        expect_item,         &'hir Item<'hir>,        OwnerNode::Item(n),        n;
4590        expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4591        expect_impl_item,    &'hir ImplItem<'hir>,    OwnerNode::ImplItem(n),    n;
4592        expect_trait_item,   &'hir TraitItem<'hir>,   OwnerNode::TraitItem(n),   n;
4593    }
4594}
4595
4596impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4597    fn from(val: &'hir Item<'hir>) -> Self {
4598        OwnerNode::Item(val)
4599    }
4600}
4601
4602impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4603    fn from(val: &'hir ForeignItem<'hir>) -> Self {
4604        OwnerNode::ForeignItem(val)
4605    }
4606}
4607
4608impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4609    fn from(val: &'hir ImplItem<'hir>) -> Self {
4610        OwnerNode::ImplItem(val)
4611    }
4612}
4613
4614impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4615    fn from(val: &'hir TraitItem<'hir>) -> Self {
4616        OwnerNode::TraitItem(val)
4617    }
4618}
4619
4620impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4621    fn from(val: OwnerNode<'hir>) -> Self {
4622        match val {
4623            OwnerNode::Item(n) => Node::Item(n),
4624            OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4625            OwnerNode::ImplItem(n) => Node::ImplItem(n),
4626            OwnerNode::TraitItem(n) => Node::TraitItem(n),
4627            OwnerNode::Crate(n) => Node::Crate(n),
4628            OwnerNode::Synthetic => Node::Synthetic,
4629        }
4630    }
4631}
4632
4633#[derive(Copy, Clone, Debug, HashStable_Generic)]
4634pub enum Node<'hir> {
4635    Param(&'hir Param<'hir>),
4636    Item(&'hir Item<'hir>),
4637    ForeignItem(&'hir ForeignItem<'hir>),
4638    TraitItem(&'hir TraitItem<'hir>),
4639    ImplItem(&'hir ImplItem<'hir>),
4640    Variant(&'hir Variant<'hir>),
4641    Field(&'hir FieldDef<'hir>),
4642    AnonConst(&'hir AnonConst),
4643    ConstBlock(&'hir ConstBlock),
4644    ConstArg(&'hir ConstArg<'hir>),
4645    Expr(&'hir Expr<'hir>),
4646    ExprField(&'hir ExprField<'hir>),
4647    Stmt(&'hir Stmt<'hir>),
4648    PathSegment(&'hir PathSegment<'hir>),
4649    Ty(&'hir Ty<'hir>),
4650    AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4651    TraitRef(&'hir TraitRef<'hir>),
4652    OpaqueTy(&'hir OpaqueTy<'hir>),
4653    TyPat(&'hir TyPat<'hir>),
4654    Pat(&'hir Pat<'hir>),
4655    PatField(&'hir PatField<'hir>),
4656    /// Needed as its own node with its own HirId for tracking
4657    /// the unadjusted type of literals within patterns
4658    /// (e.g. byte str literals not being of slice type).
4659    PatExpr(&'hir PatExpr<'hir>),
4660    Arm(&'hir Arm<'hir>),
4661    Block(&'hir Block<'hir>),
4662    LetStmt(&'hir LetStmt<'hir>),
4663    /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
4664    /// with synthesized constructors.
4665    Ctor(&'hir VariantData<'hir>),
4666    Lifetime(&'hir Lifetime),
4667    GenericParam(&'hir GenericParam<'hir>),
4668    Crate(&'hir Mod<'hir>),
4669    Infer(&'hir InferArg),
4670    WherePredicate(&'hir WherePredicate<'hir>),
4671    PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4672    // Created by query feeding
4673    Synthetic,
4674    Err(Span),
4675}
4676
4677impl<'hir> Node<'hir> {
4678    /// Get the identifier of this `Node`, if applicable.
4679    ///
4680    /// # Edge cases
4681    ///
4682    /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
4683    /// because `Ctor`s do not have identifiers themselves.
4684    /// Instead, call `.ident()` on the parent struct/variant, like so:
4685    ///
4686    /// ```ignore (illustrative)
4687    /// ctor
4688    ///     .ctor_hir_id()
4689    ///     .map(|ctor_id| tcx.parent_hir_node(ctor_id))
4690    ///     .and_then(|parent| parent.ident())
4691    /// ```
4692    pub fn ident(&self) -> Option<Ident> {
4693        match self {
4694            Node::Item(item) => item.kind.ident(),
4695            Node::TraitItem(TraitItem { ident, .. })
4696            | Node::ImplItem(ImplItem { ident, .. })
4697            | Node::ForeignItem(ForeignItem { ident, .. })
4698            | Node::Field(FieldDef { ident, .. })
4699            | Node::Variant(Variant { ident, .. })
4700            | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4701            Node::Lifetime(lt) => Some(lt.ident),
4702            Node::GenericParam(p) => Some(p.name.ident()),
4703            Node::AssocItemConstraint(c) => Some(c.ident),
4704            Node::PatField(f) => Some(f.ident),
4705            Node::ExprField(f) => Some(f.ident),
4706            Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4707            Node::Param(..)
4708            | Node::AnonConst(..)
4709            | Node::ConstBlock(..)
4710            | Node::ConstArg(..)
4711            | Node::Expr(..)
4712            | Node::Stmt(..)
4713            | Node::Block(..)
4714            | Node::Ctor(..)
4715            | Node::Pat(..)
4716            | Node::TyPat(..)
4717            | Node::PatExpr(..)
4718            | Node::Arm(..)
4719            | Node::LetStmt(..)
4720            | Node::Crate(..)
4721            | Node::Ty(..)
4722            | Node::TraitRef(..)
4723            | Node::OpaqueTy(..)
4724            | Node::Infer(..)
4725            | Node::WherePredicate(..)
4726            | Node::Synthetic
4727            | Node::Err(..) => None,
4728        }
4729    }
4730
4731    pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4732        match self {
4733            Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4734            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4735            | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4736            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4737                Some(fn_sig.decl)
4738            }
4739            Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4740                Some(fn_decl)
4741            }
4742            _ => None,
4743        }
4744    }
4745
4746    /// Get a `hir::Impl` if the node is an impl block for the given `trait_def_id`.
4747    pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4748        if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4749            && let Some(of_trait) = impl_block.of_trait
4750            && let Some(trait_id) = of_trait.trait_ref.trait_def_id()
4751            && trait_id == trait_def_id
4752        {
4753            Some(impl_block)
4754        } else {
4755            None
4756        }
4757    }
4758
4759    pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4760        match self {
4761            Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4762            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4763            | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4764            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4765                Some(fn_sig)
4766            }
4767            _ => None,
4768        }
4769    }
4770
4771    /// Get the type for constants, assoc types, type aliases and statics.
4772    pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4773        match self {
4774            Node::Item(it) => match it.kind {
4775                ItemKind::TyAlias(_, _, ty)
4776                | ItemKind::Static(_, _, ty, _)
4777                | ItemKind::Const(_, _, ty, _) => Some(ty),
4778                ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4779                _ => None,
4780            },
4781            Node::TraitItem(it) => match it.kind {
4782                TraitItemKind::Const(ty, _) => Some(ty),
4783                TraitItemKind::Type(_, ty) => ty,
4784                _ => None,
4785            },
4786            Node::ImplItem(it) => match it.kind {
4787                ImplItemKind::Const(ty, _) => Some(ty),
4788                ImplItemKind::Type(ty) => Some(ty),
4789                _ => None,
4790            },
4791            Node::ForeignItem(it) => match it.kind {
4792                ForeignItemKind::Static(ty, ..) => Some(ty),
4793                _ => None,
4794            },
4795            Node::GenericParam(param) => match param.kind {
4796                GenericParamKind::Lifetime { .. } => None,
4797                GenericParamKind::Type { default, .. } => default,
4798                GenericParamKind::Const { ty, .. } => Some(ty),
4799            },
4800            _ => None,
4801        }
4802    }
4803
4804    pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4805        match self {
4806            Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
4807            _ => None,
4808        }
4809    }
4810
4811    #[inline]
4812    pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4813        match self {
4814            Node::Item(Item {
4815                owner_id,
4816                kind:
4817                    ItemKind::Const(.., ConstItemRhs::Body(body))
4818                    | ItemKind::Static(.., body)
4819                    | ItemKind::Fn { body, .. },
4820                ..
4821            })
4822            | Node::TraitItem(TraitItem {
4823                owner_id,
4824                kind:
4825                    TraitItemKind::Const(.., Some(ConstItemRhs::Body(body)))
4826                    | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4827                ..
4828            })
4829            | Node::ImplItem(ImplItem {
4830                owner_id,
4831                kind: ImplItemKind::Const(.., ConstItemRhs::Body(body)) | ImplItemKind::Fn(_, body),
4832                ..
4833            }) => Some((owner_id.def_id, *body)),
4834
4835            Node::Item(Item {
4836                owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4837            }) => Some((owner_id.def_id, *fake_body)),
4838
4839            Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4840                Some((*def_id, *body))
4841            }
4842
4843            Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4844            Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4845
4846            _ => None,
4847        }
4848    }
4849
4850    pub fn body_id(&self) -> Option<BodyId> {
4851        Some(self.associated_body()?.1)
4852    }
4853
4854    pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4855        match self {
4856            Node::ForeignItem(ForeignItem {
4857                kind: ForeignItemKind::Fn(_, _, generics), ..
4858            })
4859            | Node::TraitItem(TraitItem { generics, .. })
4860            | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4861            Node::Item(item) => item.kind.generics(),
4862            _ => None,
4863        }
4864    }
4865
4866    pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4867        match self {
4868            Node::Item(i) => Some(OwnerNode::Item(i)),
4869            Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4870            Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4871            Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4872            Node::Crate(i) => Some(OwnerNode::Crate(i)),
4873            Node::Synthetic => Some(OwnerNode::Synthetic),
4874            _ => None,
4875        }
4876    }
4877
4878    pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4879        match self {
4880            Node::Item(i) => match i.kind {
4881                ItemKind::Fn { ident, sig, generics, .. } => {
4882                    Some(FnKind::ItemFn(ident, generics, sig.header))
4883                }
4884                _ => None,
4885            },
4886            Node::TraitItem(ti) => match ti.kind {
4887                TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4888                _ => None,
4889            },
4890            Node::ImplItem(ii) => match ii.kind {
4891                ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4892                _ => None,
4893            },
4894            Node::Expr(e) => match e.kind {
4895                ExprKind::Closure { .. } => Some(FnKind::Closure),
4896                _ => None,
4897            },
4898            _ => None,
4899        }
4900    }
4901
4902    expect_methods_self! {
4903        expect_param,         &'hir Param<'hir>,        Node::Param(n),        n;
4904        expect_item,          &'hir Item<'hir>,         Node::Item(n),         n;
4905        expect_foreign_item,  &'hir ForeignItem<'hir>,  Node::ForeignItem(n),  n;
4906        expect_trait_item,    &'hir TraitItem<'hir>,    Node::TraitItem(n),    n;
4907        expect_impl_item,     &'hir ImplItem<'hir>,     Node::ImplItem(n),     n;
4908        expect_variant,       &'hir Variant<'hir>,      Node::Variant(n),      n;
4909        expect_field,         &'hir FieldDef<'hir>,     Node::Field(n),        n;
4910        expect_anon_const,    &'hir AnonConst,          Node::AnonConst(n),    n;
4911        expect_inline_const,  &'hir ConstBlock,         Node::ConstBlock(n),   n;
4912        expect_expr,          &'hir Expr<'hir>,         Node::Expr(n),         n;
4913        expect_expr_field,    &'hir ExprField<'hir>,    Node::ExprField(n),    n;
4914        expect_stmt,          &'hir Stmt<'hir>,         Node::Stmt(n),         n;
4915        expect_path_segment,  &'hir PathSegment<'hir>,  Node::PathSegment(n),  n;
4916        expect_ty,            &'hir Ty<'hir>,           Node::Ty(n),           n;
4917        expect_assoc_item_constraint,  &'hir AssocItemConstraint<'hir>,  Node::AssocItemConstraint(n),  n;
4918        expect_trait_ref,     &'hir TraitRef<'hir>,     Node::TraitRef(n),     n;
4919        expect_opaque_ty,     &'hir OpaqueTy<'hir>,     Node::OpaqueTy(n),     n;
4920        expect_pat,           &'hir Pat<'hir>,          Node::Pat(n),          n;
4921        expect_pat_field,     &'hir PatField<'hir>,     Node::PatField(n),     n;
4922        expect_arm,           &'hir Arm<'hir>,          Node::Arm(n),          n;
4923        expect_block,         &'hir Block<'hir>,        Node::Block(n),        n;
4924        expect_let_stmt,      &'hir LetStmt<'hir>,      Node::LetStmt(n),      n;
4925        expect_ctor,          &'hir VariantData<'hir>,  Node::Ctor(n),         n;
4926        expect_lifetime,      &'hir Lifetime,           Node::Lifetime(n),     n;
4927        expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4928        expect_crate,         &'hir Mod<'hir>,          Node::Crate(n),        n;
4929        expect_infer,         &'hir InferArg,           Node::Infer(n),        n;
4930        expect_closure,       &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4931    }
4932}
4933
4934// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
4935#[cfg(target_pointer_width = "64")]
4936mod size_asserts {
4937    use rustc_data_structures::static_assert_size;
4938
4939    use super::*;
4940    // tidy-alphabetical-start
4941    static_assert_size!(Block<'_>, 48);
4942    static_assert_size!(Body<'_>, 24);
4943    static_assert_size!(Expr<'_>, 64);
4944    static_assert_size!(ExprKind<'_>, 48);
4945    static_assert_size!(FnDecl<'_>, 40);
4946    static_assert_size!(ForeignItem<'_>, 96);
4947    static_assert_size!(ForeignItemKind<'_>, 56);
4948    static_assert_size!(GenericArg<'_>, 16);
4949    static_assert_size!(GenericBound<'_>, 64);
4950    static_assert_size!(Generics<'_>, 56);
4951    static_assert_size!(Impl<'_>, 40);
4952    static_assert_size!(ImplItem<'_>, 88);
4953    static_assert_size!(ImplItemKind<'_>, 40);
4954    static_assert_size!(Item<'_>, 88);
4955    static_assert_size!(ItemKind<'_>, 64);
4956    static_assert_size!(LetStmt<'_>, 64);
4957    static_assert_size!(Param<'_>, 32);
4958    static_assert_size!(Pat<'_>, 80);
4959    static_assert_size!(PatKind<'_>, 56);
4960    static_assert_size!(Path<'_>, 40);
4961    static_assert_size!(PathSegment<'_>, 48);
4962    static_assert_size!(QPath<'_>, 24);
4963    static_assert_size!(Res, 12);
4964    static_assert_size!(Stmt<'_>, 32);
4965    static_assert_size!(StmtKind<'_>, 16);
4966    static_assert_size!(TraitImplHeader<'_>, 48);
4967    static_assert_size!(TraitItem<'_>, 88);
4968    static_assert_size!(TraitItemKind<'_>, 48);
4969    static_assert_size!(Ty<'_>, 48);
4970    static_assert_size!(TyKind<'_>, 32);
4971    // tidy-alphabetical-end
4972}
4973
4974#[cfg(test)]
4975mod tests;