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