rustc_hir/
hir.rs

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