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