rustc_hir/
hir.rs

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