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