rustc_hir/
hir.rs

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