rustc_hir/
hir.rs

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