rustc_hir/
hir.rs

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