rustc_hir/
hir.rs

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