rustc_hir/
hir.rs

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