rustc_hir/
hir.rs

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