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, 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, SmallVec<[Res; 3]>>;
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            // Partially qualified paths in expressions can only legally
2374            // refer to associated items which are always rvalues.
2375            ExprKind::Path(QPath::TypeRelative(..))
2376            | ExprKind::Call(..)
2377            | ExprKind::MethodCall(..)
2378            | ExprKind::Use(..)
2379            | ExprKind::Struct(..)
2380            | ExprKind::Tup(..)
2381            | ExprKind::If(..)
2382            | ExprKind::Match(..)
2383            | ExprKind::Closure { .. }
2384            | ExprKind::Block(..)
2385            | ExprKind::Repeat(..)
2386            | ExprKind::Array(..)
2387            | ExprKind::Break(..)
2388            | ExprKind::Continue(..)
2389            | ExprKind::Ret(..)
2390            | ExprKind::Become(..)
2391            | ExprKind::Let(..)
2392            | ExprKind::Loop(..)
2393            | ExprKind::Assign(..)
2394            | ExprKind::InlineAsm(..)
2395            | ExprKind::OffsetOf(..)
2396            | ExprKind::AssignOp(..)
2397            | ExprKind::Lit(_)
2398            | ExprKind::ConstBlock(..)
2399            | ExprKind::Unary(..)
2400            | ExprKind::AddrOf(..)
2401            | ExprKind::Binary(..)
2402            | ExprKind::Yield(..)
2403            | ExprKind::Cast(..)
2404            | ExprKind::DropTemps(..)
2405            | ExprKind::Err(_) => false,
2406        }
2407    }
2408
2409    /// Check if expression is an integer literal that can be used
2410    /// where `usize` is expected.
2411    pub fn is_size_lit(&self) -> bool {
2412        matches!(
2413            self.kind,
2414            ExprKind::Lit(Lit {
2415                node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2416                ..
2417            })
2418        )
2419    }
2420
2421    /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
2422    /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
2423    /// silent, only signaling the ownership system. By doing this, suggestions that check the
2424    /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
2425    /// beyond remembering to call this function before doing analysis on it.
2426    pub fn peel_drop_temps(&self) -> &Self {
2427        let mut expr = self;
2428        while let ExprKind::DropTemps(inner) = &expr.kind {
2429            expr = inner;
2430        }
2431        expr
2432    }
2433
2434    pub fn peel_blocks(&self) -> &Self {
2435        let mut expr = self;
2436        while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2437            expr = inner;
2438        }
2439        expr
2440    }
2441
2442    pub fn peel_borrows(&self) -> &Self {
2443        let mut expr = self;
2444        while let ExprKind::AddrOf(.., inner) = &expr.kind {
2445            expr = inner;
2446        }
2447        expr
2448    }
2449
2450    pub fn can_have_side_effects(&self) -> bool {
2451        match self.peel_drop_temps().kind {
2452            ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2453                false
2454            }
2455            ExprKind::Type(base, _)
2456            | ExprKind::Unary(_, base)
2457            | ExprKind::Field(base, _)
2458            | ExprKind::Index(base, _, _)
2459            | ExprKind::AddrOf(.., base)
2460            | ExprKind::Cast(base, _)
2461            | ExprKind::UnsafeBinderCast(_, base, _) => {
2462                // This isn't exactly true for `Index` and all `Unary`, but we are using this
2463                // method exclusively for diagnostics and there's a *cultural* pressure against
2464                // them being used only for its side-effects.
2465                base.can_have_side_effects()
2466            }
2467            ExprKind::Struct(_, fields, init) => {
2468                let init_side_effects = match init {
2469                    StructTailExpr::Base(init) => init.can_have_side_effects(),
2470                    StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2471                };
2472                fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2473                    || init_side_effects
2474            }
2475
2476            ExprKind::Array(args)
2477            | ExprKind::Tup(args)
2478            | ExprKind::Call(
2479                Expr {
2480                    kind:
2481                        ExprKind::Path(QPath::Resolved(
2482                            None,
2483                            Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2484                        )),
2485                    ..
2486                },
2487                args,
2488            ) => args.iter().any(|arg| arg.can_have_side_effects()),
2489            ExprKind::If(..)
2490            | ExprKind::Match(..)
2491            | ExprKind::MethodCall(..)
2492            | ExprKind::Call(..)
2493            | ExprKind::Closure { .. }
2494            | ExprKind::Block(..)
2495            | ExprKind::Repeat(..)
2496            | ExprKind::Break(..)
2497            | ExprKind::Continue(..)
2498            | ExprKind::Ret(..)
2499            | ExprKind::Become(..)
2500            | ExprKind::Let(..)
2501            | ExprKind::Loop(..)
2502            | ExprKind::Assign(..)
2503            | ExprKind::InlineAsm(..)
2504            | ExprKind::AssignOp(..)
2505            | ExprKind::ConstBlock(..)
2506            | ExprKind::Binary(..)
2507            | ExprKind::Yield(..)
2508            | ExprKind::DropTemps(..)
2509            | ExprKind::Err(_) => true,
2510        }
2511    }
2512
2513    /// To a first-order approximation, is this a pattern?
2514    pub fn is_approximately_pattern(&self) -> bool {
2515        match &self.kind {
2516            ExprKind::Array(_)
2517            | ExprKind::Call(..)
2518            | ExprKind::Tup(_)
2519            | ExprKind::Lit(_)
2520            | ExprKind::Path(_)
2521            | ExprKind::Struct(..) => true,
2522            _ => false,
2523        }
2524    }
2525
2526    /// Whether this and the `other` expression are the same for purposes of an indexing operation.
2527    ///
2528    /// This is only used for diagnostics to see if we have things like `foo[i]` where `foo` is
2529    /// borrowed multiple times with `i`.
2530    pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2531        match (self.kind, other.kind) {
2532            (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2533            (
2534                ExprKind::Path(QPath::LangItem(item1, _)),
2535                ExprKind::Path(QPath::LangItem(item2, _)),
2536            ) => item1 == item2,
2537            (
2538                ExprKind::Path(QPath::Resolved(None, path1)),
2539                ExprKind::Path(QPath::Resolved(None, path2)),
2540            ) => path1.res == path2.res,
2541            (
2542                ExprKind::Struct(
2543                    QPath::LangItem(LangItem::RangeTo, _),
2544                    [val1],
2545                    StructTailExpr::None,
2546                ),
2547                ExprKind::Struct(
2548                    QPath::LangItem(LangItem::RangeTo, _),
2549                    [val2],
2550                    StructTailExpr::None,
2551                ),
2552            )
2553            | (
2554                ExprKind::Struct(
2555                    QPath::LangItem(LangItem::RangeToInclusive, _),
2556                    [val1],
2557                    StructTailExpr::None,
2558                ),
2559                ExprKind::Struct(
2560                    QPath::LangItem(LangItem::RangeToInclusive, _),
2561                    [val2],
2562                    StructTailExpr::None,
2563                ),
2564            )
2565            | (
2566                ExprKind::Struct(
2567                    QPath::LangItem(LangItem::RangeFrom, _),
2568                    [val1],
2569                    StructTailExpr::None,
2570                ),
2571                ExprKind::Struct(
2572                    QPath::LangItem(LangItem::RangeFrom, _),
2573                    [val2],
2574                    StructTailExpr::None,
2575                ),
2576            )
2577            | (
2578                ExprKind::Struct(
2579                    QPath::LangItem(LangItem::RangeFromCopy, _),
2580                    [val1],
2581                    StructTailExpr::None,
2582                ),
2583                ExprKind::Struct(
2584                    QPath::LangItem(LangItem::RangeFromCopy, _),
2585                    [val2],
2586                    StructTailExpr::None,
2587                ),
2588            ) => val1.expr.equivalent_for_indexing(val2.expr),
2589            (
2590                ExprKind::Struct(
2591                    QPath::LangItem(LangItem::Range, _),
2592                    [val1, val3],
2593                    StructTailExpr::None,
2594                ),
2595                ExprKind::Struct(
2596                    QPath::LangItem(LangItem::Range, _),
2597                    [val2, val4],
2598                    StructTailExpr::None,
2599                ),
2600            )
2601            | (
2602                ExprKind::Struct(
2603                    QPath::LangItem(LangItem::RangeCopy, _),
2604                    [val1, val3],
2605                    StructTailExpr::None,
2606                ),
2607                ExprKind::Struct(
2608                    QPath::LangItem(LangItem::RangeCopy, _),
2609                    [val2, val4],
2610                    StructTailExpr::None,
2611                ),
2612            )
2613            | (
2614                ExprKind::Struct(
2615                    QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2616                    [val1, val3],
2617                    StructTailExpr::None,
2618                ),
2619                ExprKind::Struct(
2620                    QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2621                    [val2, val4],
2622                    StructTailExpr::None,
2623                ),
2624            ) => {
2625                val1.expr.equivalent_for_indexing(val2.expr)
2626                    && val3.expr.equivalent_for_indexing(val4.expr)
2627            }
2628            _ => false,
2629        }
2630    }
2631
2632    pub fn method_ident(&self) -> Option<Ident> {
2633        match self.kind {
2634            ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2635            ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2636            _ => None,
2637        }
2638    }
2639}
2640
2641/// Checks if the specified expression is a built-in range literal.
2642/// (See: `LoweringContext::lower_expr()`).
2643pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2644    match expr.kind {
2645        // All built-in range literals but `..=` and `..` desugar to `Struct`s.
2646        ExprKind::Struct(ref qpath, _, _) => matches!(
2647            **qpath,
2648            QPath::LangItem(
2649                LangItem::Range
2650                    | LangItem::RangeTo
2651                    | LangItem::RangeFrom
2652                    | LangItem::RangeFull
2653                    | LangItem::RangeToInclusive
2654                    | LangItem::RangeCopy
2655                    | LangItem::RangeFromCopy
2656                    | LangItem::RangeInclusiveCopy,
2657                ..
2658            )
2659        ),
2660
2661        // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
2662        ExprKind::Call(ref func, _) => {
2663            matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
2664        }
2665
2666        _ => false,
2667    }
2668}
2669
2670/// Checks if the specified expression needs parentheses for prefix
2671/// or postfix suggestions to be valid.
2672/// For example, `a + b` requires parentheses to suggest `&(a + b)`,
2673/// but just `a` does not.
2674/// Similarly, `(a + b).c()` also requires parentheses.
2675/// This should not be used for other types of suggestions.
2676pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2677    match expr.kind {
2678        // parenthesize if needed (Issue #46756)
2679        ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2680        // parenthesize borrows of range literals (Issue #54505)
2681        _ if is_range_literal(expr) => true,
2682        _ => false,
2683    }
2684}
2685
2686#[derive(Debug, Clone, Copy, HashStable_Generic)]
2687pub enum ExprKind<'hir> {
2688    /// Allow anonymous constants from an inline `const` block
2689    ConstBlock(ConstBlock),
2690    /// An array (e.g., `[a, b, c, d]`).
2691    Array(&'hir [Expr<'hir>]),
2692    /// A function call.
2693    ///
2694    /// The first field resolves to the function itself (usually an `ExprKind::Path`),
2695    /// and the second field is the list of arguments.
2696    /// This also represents calling the constructor of
2697    /// tuple-like ADTs such as tuple structs and enum variants.
2698    Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2699    /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
2700    ///
2701    /// The `PathSegment` represents the method name and its generic arguments
2702    /// (within the angle brackets).
2703    /// The `&Expr` is the expression that evaluates
2704    /// to the object on which the method is being called on (the receiver),
2705    /// and the `&[Expr]` is the rest of the arguments.
2706    /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
2707    /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
2708    /// The final `Span` represents the span of the function and arguments
2709    /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
2710    ///
2711    /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
2712    /// the `hir_id` of the `MethodCall` node itself.
2713    ///
2714    /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
2715    MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2716    /// An use expression (e.g., `var.use`).
2717    Use(&'hir Expr<'hir>, Span),
2718    /// A tuple (e.g., `(a, b, c, d)`).
2719    Tup(&'hir [Expr<'hir>]),
2720    /// A binary operation (e.g., `a + b`, `a * b`).
2721    Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2722    /// A unary operation (e.g., `!x`, `*x`).
2723    Unary(UnOp, &'hir Expr<'hir>),
2724    /// A literal (e.g., `1`, `"foo"`).
2725    Lit(&'hir Lit),
2726    /// A cast (e.g., `foo as f64`).
2727    Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2728    /// A type ascription (e.g., `x: Foo`). See RFC 3307.
2729    Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2730    /// Wraps the expression in a terminating scope.
2731    /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
2732    ///
2733    /// This construct only exists to tweak the drop order in AST lowering.
2734    /// An example of that is the desugaring of `for` loops.
2735    DropTemps(&'hir Expr<'hir>),
2736    /// A `let $pat = $expr` expression.
2737    ///
2738    /// These are not [`LetStmt`] and only occur as expressions.
2739    /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
2740    Let(&'hir LetExpr<'hir>),
2741    /// An `if` block, with an optional else block.
2742    ///
2743    /// I.e., `if <expr> { <expr> } else { <expr> }`.
2744    ///
2745    /// The "then" expr is always `ExprKind::Block`. If present, the "else" expr is always
2746    /// `ExprKind::Block` (for `else`) or `ExprKind::If` (for `else if`).
2747    /// Note that using an `Expr` instead of a `Block` for the "then" part is intentional,
2748    /// as it simplifies the type coercion machinery.
2749    If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2750    /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
2751    ///
2752    /// I.e., `'label: loop { <block> }`.
2753    ///
2754    /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
2755    Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2756    /// A `match` block, with a source that indicates whether or not it is
2757    /// the result of a desugaring, and if so, which kind.
2758    Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2759    /// A closure (e.g., `move |a, b, c| {a + b + c}`).
2760    ///
2761    /// The `Span` is the argument block `|...|`.
2762    ///
2763    /// This may also be a coroutine literal or an `async block` as indicated by the
2764    /// `Option<Movability>`.
2765    Closure(&'hir Closure<'hir>),
2766    /// A block (e.g., `'label: { ... }`).
2767    Block(&'hir Block<'hir>, Option<Label>),
2768
2769    /// An assignment (e.g., `a = foo()`).
2770    Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2771    /// An assignment with an operator.
2772    ///
2773    /// E.g., `a += 1`.
2774    AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2775    /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
2776    Field(&'hir Expr<'hir>, Ident),
2777    /// An indexing operation (`foo[2]`).
2778    /// Similar to [`ExprKind::MethodCall`], the final `Span` represents the span of the brackets
2779    /// and index.
2780    Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2781
2782    /// Path to a definition, possibly containing lifetime or type parameters.
2783    Path(QPath<'hir>),
2784
2785    /// A referencing operation (i.e., `&a` or `&mut a`).
2786    AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2787    /// A `break`, with an optional label to break.
2788    Break(Destination, Option<&'hir Expr<'hir>>),
2789    /// A `continue`, with an optional label.
2790    Continue(Destination),
2791    /// A `return`, with an optional value to be returned.
2792    Ret(Option<&'hir Expr<'hir>>),
2793    /// A `become`, with the value to be returned.
2794    Become(&'hir Expr<'hir>),
2795
2796    /// Inline assembly (from `asm!`), with its outputs and inputs.
2797    InlineAsm(&'hir InlineAsm<'hir>),
2798
2799    /// Field offset (`offset_of!`)
2800    OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2801
2802    /// A struct or struct-like variant literal expression.
2803    ///
2804    /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2805    /// where `base` is the `Option<Expr>`.
2806    Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2807
2808    /// An array literal constructed from one repeated element.
2809    ///
2810    /// E.g., `[1; 5]`. The first expression is the element
2811    /// to be repeated; the second is the number of times to repeat it.
2812    Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2813
2814    /// A suspension point for coroutines (i.e., `yield <expr>`).
2815    Yield(&'hir Expr<'hir>, YieldSource),
2816
2817    /// Operators which can be used to interconvert `unsafe` binder types.
2818    /// e.g. `unsafe<'a> &'a i32` <=> `&i32`.
2819    UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2820
2821    /// A placeholder for an expression that wasn't syntactically well formed in some way.
2822    Err(rustc_span::ErrorGuaranteed),
2823}
2824
2825#[derive(Debug, Clone, Copy, HashStable_Generic)]
2826pub enum StructTailExpr<'hir> {
2827    /// A struct expression where all the fields are explicitly enumerated: `Foo { a, b }`.
2828    None,
2829    /// A struct expression with a "base", an expression of the same type as the outer struct that
2830    /// will be used to populate any fields not explicitly mentioned: `Foo { ..base }`
2831    Base(&'hir Expr<'hir>),
2832    /// A struct expression with a `..` tail but no "base" expression. The values from the struct
2833    /// fields' default values will be used to populate any fields not explicitly mentioned:
2834    /// `Foo { .. }`.
2835    DefaultFields(Span),
2836}
2837
2838/// Represents an optionally `Self`-qualified value/type path or associated extension.
2839///
2840/// To resolve the path to a `DefId`, call [`qpath_res`].
2841///
2842/// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2843#[derive(Debug, Clone, Copy, HashStable_Generic)]
2844pub enum QPath<'hir> {
2845    /// Path to a definition, optionally "fully-qualified" with a `Self`
2846    /// type, if the path points to an associated item in a trait.
2847    ///
2848    /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2849    /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2850    /// even though they both have the same two-segment `Clone::clone` `Path`.
2851    Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2852
2853    /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2854    /// Will be resolved by type-checking to an associated item.
2855    ///
2856    /// UFCS source paths can desugar into this, with `Vec::new` turning into
2857    /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2858    /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2859    TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2860
2861    /// Reference to a `#[lang = "foo"]` item.
2862    LangItem(LangItem, Span),
2863}
2864
2865impl<'hir> QPath<'hir> {
2866    /// Returns the span of this `QPath`.
2867    pub fn span(&self) -> Span {
2868        match *self {
2869            QPath::Resolved(_, path) => path.span,
2870            QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2871            QPath::LangItem(_, span) => span,
2872        }
2873    }
2874
2875    /// Returns the span of the qself of this `QPath`. For example, `()` in
2876    /// `<() as Trait>::method`.
2877    pub fn qself_span(&self) -> Span {
2878        match *self {
2879            QPath::Resolved(_, path) => path.span,
2880            QPath::TypeRelative(qself, _) => qself.span,
2881            QPath::LangItem(_, span) => span,
2882        }
2883    }
2884}
2885
2886/// Hints at the original code for a let statement.
2887#[derive(Copy, Clone, Debug, HashStable_Generic)]
2888pub enum LocalSource {
2889    /// A `match _ { .. }`.
2890    Normal,
2891    /// When lowering async functions, we create locals within the `async move` so that
2892    /// all parameters are dropped after the future is polled.
2893    ///
2894    /// ```ignore (pseudo-Rust)
2895    /// async fn foo(<pattern> @ x: Type) {
2896    ///     async move {
2897    ///         let <pattern> = x;
2898    ///     }
2899    /// }
2900    /// ```
2901    AsyncFn,
2902    /// A desugared `<expr>.await`.
2903    AwaitDesugar,
2904    /// A desugared `expr = expr`, where the LHS is a tuple, struct, array or underscore expression.
2905    /// The span is that of the `=` sign.
2906    AssignDesugar(Span),
2907    /// A contract `#[ensures(..)]` attribute injects a let binding for the check that runs at point of return.
2908    Contract,
2909}
2910
2911/// Hints at the original code for a `match _ { .. }`.
2912#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2913pub enum MatchSource {
2914    /// A `match _ { .. }`.
2915    Normal,
2916    /// A `expr.match { .. }`.
2917    Postfix,
2918    /// A desugared `for _ in _ { .. }` loop.
2919    ForLoopDesugar,
2920    /// A desugared `?` operator.
2921    TryDesugar(HirId),
2922    /// A desugared `<expr>.await`.
2923    AwaitDesugar,
2924    /// A desugared `format_args!()`.
2925    FormatArgs,
2926}
2927
2928impl MatchSource {
2929    #[inline]
2930    pub const fn name(self) -> &'static str {
2931        use MatchSource::*;
2932        match self {
2933            Normal => "match",
2934            Postfix => ".match",
2935            ForLoopDesugar => "for",
2936            TryDesugar(_) => "?",
2937            AwaitDesugar => ".await",
2938            FormatArgs => "format_args!()",
2939        }
2940    }
2941}
2942
2943/// The loop type that yielded an `ExprKind::Loop`.
2944#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2945pub enum LoopSource {
2946    /// A `loop { .. }` loop.
2947    Loop,
2948    /// A `while _ { .. }` loop.
2949    While,
2950    /// A `for _ in _ { .. }` loop.
2951    ForLoop,
2952}
2953
2954impl LoopSource {
2955    pub fn name(self) -> &'static str {
2956        match self {
2957            LoopSource::Loop => "loop",
2958            LoopSource::While => "while",
2959            LoopSource::ForLoop => "for",
2960        }
2961    }
2962}
2963
2964#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2965pub enum LoopIdError {
2966    OutsideLoopScope,
2967    UnlabeledCfInWhileCondition,
2968    UnresolvedLabel,
2969}
2970
2971impl fmt::Display for LoopIdError {
2972    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2973        f.write_str(match self {
2974            LoopIdError::OutsideLoopScope => "not inside loop scope",
2975            LoopIdError::UnlabeledCfInWhileCondition => {
2976                "unlabeled control flow (break or continue) in while condition"
2977            }
2978            LoopIdError::UnresolvedLabel => "label not found",
2979        })
2980    }
2981}
2982
2983#[derive(Copy, Clone, Debug, HashStable_Generic)]
2984pub struct Destination {
2985    /// This is `Some(_)` iff there is an explicit user-specified 'label
2986    pub label: Option<Label>,
2987
2988    /// These errors are caught and then reported during the diagnostics pass in
2989    /// `librustc_passes/loops.rs`
2990    pub target_id: Result<HirId, LoopIdError>,
2991}
2992
2993/// The yield kind that caused an `ExprKind::Yield`.
2994#[derive(Copy, Clone, Debug, HashStable_Generic)]
2995pub enum YieldSource {
2996    /// An `<expr>.await`.
2997    Await { expr: Option<HirId> },
2998    /// A plain `yield`.
2999    Yield,
3000}
3001
3002impl fmt::Display for YieldSource {
3003    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3004        f.write_str(match self {
3005            YieldSource::Await { .. } => "`await`",
3006            YieldSource::Yield => "`yield`",
3007        })
3008    }
3009}
3010
3011// N.B., if you change this, you'll probably want to change the corresponding
3012// type structure in middle/ty.rs as well.
3013#[derive(Debug, Clone, Copy, HashStable_Generic)]
3014pub struct MutTy<'hir> {
3015    pub ty: &'hir Ty<'hir>,
3016    pub mutbl: Mutability,
3017}
3018
3019/// Represents a function's signature in a trait declaration,
3020/// trait implementation, or a free function.
3021#[derive(Debug, Clone, Copy, HashStable_Generic)]
3022pub struct FnSig<'hir> {
3023    pub header: FnHeader,
3024    pub decl: &'hir FnDecl<'hir>,
3025    pub span: Span,
3026}
3027
3028// The bodies for items are stored "out of line", in a separate
3029// hashmap in the `Crate`. Here we just record the hir-id of the item
3030// so it can fetched later.
3031#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3032pub struct TraitItemId {
3033    pub owner_id: OwnerId,
3034}
3035
3036impl TraitItemId {
3037    #[inline]
3038    pub fn hir_id(&self) -> HirId {
3039        // Items are always HIR owners.
3040        HirId::make_owner(self.owner_id.def_id)
3041    }
3042}
3043
3044/// Represents an item declaration within a trait declaration,
3045/// possibly including a default implementation. A trait item is
3046/// either required (meaning it doesn't have an implementation, just a
3047/// signature) or provided (meaning it has a default implementation).
3048#[derive(Debug, Clone, Copy, HashStable_Generic)]
3049pub struct TraitItem<'hir> {
3050    pub ident: Ident,
3051    pub owner_id: OwnerId,
3052    pub generics: &'hir Generics<'hir>,
3053    pub kind: TraitItemKind<'hir>,
3054    pub span: Span,
3055    pub defaultness: Defaultness,
3056}
3057
3058macro_rules! expect_methods_self_kind {
3059    ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3060        $(
3061            #[track_caller]
3062            pub fn $name(&self) -> $ret_ty {
3063                let $pat = &self.kind else { expect_failed(stringify!($ident), self) };
3064                $ret_val
3065            }
3066        )*
3067    }
3068}
3069
3070macro_rules! expect_methods_self {
3071    ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3072        $(
3073            #[track_caller]
3074            pub fn $name(&self) -> $ret_ty {
3075                let $pat = self else { expect_failed(stringify!($ident), self) };
3076                $ret_val
3077            }
3078        )*
3079    }
3080}
3081
3082#[track_caller]
3083fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3084    panic!("{ident}: found {found:?}")
3085}
3086
3087impl<'hir> TraitItem<'hir> {
3088    #[inline]
3089    pub fn hir_id(&self) -> HirId {
3090        // Items are always HIR owners.
3091        HirId::make_owner(self.owner_id.def_id)
3092    }
3093
3094    pub fn trait_item_id(&self) -> TraitItemId {
3095        TraitItemId { owner_id: self.owner_id }
3096    }
3097
3098    expect_methods_self_kind! {
3099        expect_const, (&'hir Ty<'hir>, Option<BodyId>),
3100            TraitItemKind::Const(ty, body), (ty, *body);
3101
3102        expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3103            TraitItemKind::Fn(ty, trfn), (ty, trfn);
3104
3105        expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3106            TraitItemKind::Type(bounds, ty), (bounds, *ty);
3107    }
3108}
3109
3110/// Represents a trait method's body (or just argument names).
3111#[derive(Debug, Clone, Copy, HashStable_Generic)]
3112pub enum TraitFn<'hir> {
3113    /// No default body in the trait, just a signature.
3114    Required(&'hir [Option<Ident>]),
3115
3116    /// Both signature and body are provided in the trait.
3117    Provided(BodyId),
3118}
3119
3120/// Represents a trait method or associated constant or type
3121#[derive(Debug, Clone, Copy, HashStable_Generic)]
3122pub enum TraitItemKind<'hir> {
3123    /// An associated constant with an optional value (otherwise `impl`s must contain a value).
3124    Const(&'hir Ty<'hir>, Option<BodyId>),
3125    /// An associated function with an optional body.
3126    Fn(FnSig<'hir>, TraitFn<'hir>),
3127    /// An associated type with (possibly empty) bounds and optional concrete
3128    /// type.
3129    Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3130}
3131
3132// The bodies for items are stored "out of line", in a separate
3133// hashmap in the `Crate`. Here we just record the hir-id of the item
3134// so it can fetched later.
3135#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3136pub struct ImplItemId {
3137    pub owner_id: OwnerId,
3138}
3139
3140impl ImplItemId {
3141    #[inline]
3142    pub fn hir_id(&self) -> HirId {
3143        // Items are always HIR owners.
3144        HirId::make_owner(self.owner_id.def_id)
3145    }
3146}
3147
3148/// Represents an associated item within an impl block.
3149///
3150/// Refer to [`Impl`] for an impl block declaration.
3151#[derive(Debug, Clone, Copy, HashStable_Generic)]
3152pub struct ImplItem<'hir> {
3153    pub ident: Ident,
3154    pub owner_id: OwnerId,
3155    pub generics: &'hir Generics<'hir>,
3156    pub kind: ImplItemKind<'hir>,
3157    pub defaultness: Defaultness,
3158    pub span: Span,
3159    pub vis_span: Span,
3160}
3161
3162impl<'hir> ImplItem<'hir> {
3163    #[inline]
3164    pub fn hir_id(&self) -> HirId {
3165        // Items are always HIR owners.
3166        HirId::make_owner(self.owner_id.def_id)
3167    }
3168
3169    pub fn impl_item_id(&self) -> ImplItemId {
3170        ImplItemId { owner_id: self.owner_id }
3171    }
3172
3173    expect_methods_self_kind! {
3174        expect_const, (&'hir Ty<'hir>, BodyId), ImplItemKind::Const(ty, body), (ty, *body);
3175        expect_fn,    (&FnSig<'hir>, BodyId),   ImplItemKind::Fn(ty, body),    (ty, *body);
3176        expect_type,  &'hir Ty<'hir>,           ImplItemKind::Type(ty),        ty;
3177    }
3178}
3179
3180/// Represents various kinds of content within an `impl`.
3181#[derive(Debug, Clone, Copy, HashStable_Generic)]
3182pub enum ImplItemKind<'hir> {
3183    /// An associated constant of the given type, set to the constant result
3184    /// of the expression.
3185    Const(&'hir Ty<'hir>, BodyId),
3186    /// An associated function implementation with the given signature and body.
3187    Fn(FnSig<'hir>, BodyId),
3188    /// An associated type.
3189    Type(&'hir Ty<'hir>),
3190}
3191
3192/// A constraint on an associated item.
3193///
3194/// ### Examples
3195///
3196/// * the `A = Ty` and `B = Ty` in `Trait<A = Ty, B = Ty>`
3197/// * the `G<Ty> = Ty` in `Trait<G<Ty> = Ty>`
3198/// * the `A: Bound` in `Trait<A: Bound>`
3199/// * the `RetTy` in `Trait(ArgTy, ArgTy) -> RetTy`
3200/// * the `C = { Ct }` in `Trait<C = { Ct }>` (feature `associated_const_equality`)
3201/// * the `f(..): Bound` in `Trait<f(..): Bound>` (feature `return_type_notation`)
3202#[derive(Debug, Clone, Copy, HashStable_Generic)]
3203pub struct AssocItemConstraint<'hir> {
3204    #[stable_hasher(ignore)]
3205    pub hir_id: HirId,
3206    pub ident: Ident,
3207    pub gen_args: &'hir GenericArgs<'hir>,
3208    pub kind: AssocItemConstraintKind<'hir>,
3209    pub span: Span,
3210}
3211
3212impl<'hir> AssocItemConstraint<'hir> {
3213    /// Obtain the type on the RHS of an assoc ty equality constraint if applicable.
3214    pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3215        match self.kind {
3216            AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3217            _ => None,
3218        }
3219    }
3220
3221    /// Obtain the const on the RHS of an assoc const equality constraint if applicable.
3222    pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3223        match self.kind {
3224            AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3225            _ => None,
3226        }
3227    }
3228}
3229
3230#[derive(Debug, Clone, Copy, HashStable_Generic)]
3231pub enum Term<'hir> {
3232    Ty(&'hir Ty<'hir>),
3233    Const(&'hir ConstArg<'hir>),
3234}
3235
3236impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3237    fn from(ty: &'hir Ty<'hir>) -> Self {
3238        Term::Ty(ty)
3239    }
3240}
3241
3242impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3243    fn from(c: &'hir ConstArg<'hir>) -> Self {
3244        Term::Const(c)
3245    }
3246}
3247
3248/// The kind of [associated item constraint][AssocItemConstraint].
3249#[derive(Debug, Clone, Copy, HashStable_Generic)]
3250pub enum AssocItemConstraintKind<'hir> {
3251    /// An equality constraint for an associated item (e.g., `AssocTy = Ty` in `Trait<AssocTy = Ty>`).
3252    ///
3253    /// Also known as an *associated item binding* (we *bind* an associated item to a term).
3254    ///
3255    /// Furthermore, associated type equality constraints can also be referred to as *associated type
3256    /// bindings*. Similarly with associated const equality constraints and *associated const bindings*.
3257    Equality { term: Term<'hir> },
3258    /// A bound on an associated type (e.g., `AssocTy: Bound` in `Trait<AssocTy: Bound>`).
3259    Bound { bounds: &'hir [GenericBound<'hir>] },
3260}
3261
3262impl<'hir> AssocItemConstraintKind<'hir> {
3263    pub fn descr(&self) -> &'static str {
3264        match self {
3265            AssocItemConstraintKind::Equality { .. } => "binding",
3266            AssocItemConstraintKind::Bound { .. } => "constraint",
3267        }
3268    }
3269}
3270
3271/// An uninhabited enum used to make `Infer` variants on [`Ty`] and [`ConstArg`] be
3272/// unreachable. Zero-Variant enums are guaranteed to have the same layout as the never
3273/// type.
3274#[derive(Debug, Clone, Copy, HashStable_Generic)]
3275pub enum AmbigArg {}
3276
3277#[derive(Debug, Clone, Copy, HashStable_Generic)]
3278#[repr(C)]
3279/// Represents a type in the `HIR`.
3280///
3281/// The `Unambig` generic parameter represents whether the position this type is from is
3282/// unambiguously a type or ambiguous as to whether it is a type or a const. When in an
3283/// ambiguous context the parameter is instantiated with an uninhabited type making the
3284/// [`TyKind::Infer`] variant unusable and [`GenericArg::Infer`] is used instead.
3285pub struct Ty<'hir, Unambig = ()> {
3286    #[stable_hasher(ignore)]
3287    pub hir_id: HirId,
3288    pub span: Span,
3289    pub kind: TyKind<'hir, Unambig>,
3290}
3291
3292impl<'hir> Ty<'hir, AmbigArg> {
3293    /// Converts a `Ty` in an ambiguous position to one in an unambiguous position.
3294    ///
3295    /// Functions accepting an unambiguous types may expect the [`TyKind::Infer`] variant
3296    /// to be used. Care should be taken to separately handle infer types when calling this
3297    /// function as it cannot be handled by downstream code making use of the returned ty.
3298    ///
3299    /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or
3300    /// specifically matching on [`GenericArg::Infer`] when handling generic arguments.
3301    ///
3302    /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer]
3303    pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3304        // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is
3305        // the same across different ZST type arguments.
3306        let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3307        unsafe { &*ptr }
3308    }
3309}
3310
3311impl<'hir> Ty<'hir> {
3312    /// Converts a `Ty` in an unambigous position to one in an ambiguous position. This is
3313    /// fallible as the [`TyKind::Infer`] variant is not present in ambiguous positions.
3314    ///
3315    /// Functions accepting ambiguous types will not handle the [`TyKind::Infer`] variant, if
3316    /// infer types are relevant to you then care should be taken to handle them separately.
3317    pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3318        if let TyKind::Infer(()) = self.kind {
3319            return None;
3320        }
3321
3322        // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is
3323        // the same across different ZST type arguments. We also asserted that the `self` is
3324        // not a `TyKind::Infer` so there is no risk of transmuting a `()` to `AmbigArg`.
3325        let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3326        Some(unsafe { &*ptr })
3327    }
3328}
3329
3330impl<'hir> Ty<'hir, AmbigArg> {
3331    pub fn peel_refs(&self) -> &Ty<'hir> {
3332        let mut final_ty = self.as_unambig_ty();
3333        while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3334            final_ty = ty;
3335        }
3336        final_ty
3337    }
3338}
3339
3340impl<'hir> Ty<'hir> {
3341    pub fn peel_refs(&self) -> &Self {
3342        let mut final_ty = self;
3343        while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3344            final_ty = ty;
3345        }
3346        final_ty
3347    }
3348
3349    /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
3350    pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3351        let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3352            return None;
3353        };
3354        let [segment] = &path.segments else {
3355            return None;
3356        };
3357        match path.res {
3358            Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3359                Some((def_id, segment.ident))
3360            }
3361            _ => None,
3362        }
3363    }
3364
3365    pub fn find_self_aliases(&self) -> Vec<Span> {
3366        use crate::intravisit::Visitor;
3367        struct MyVisitor(Vec<Span>);
3368        impl<'v> Visitor<'v> for MyVisitor {
3369            fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3370                if matches!(
3371                    &t.kind,
3372                    TyKind::Path(QPath::Resolved(
3373                        _,
3374                        Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3375                    ))
3376                ) {
3377                    self.0.push(t.span);
3378                    return;
3379                }
3380                crate::intravisit::walk_ty(self, t);
3381            }
3382        }
3383
3384        let mut my_visitor = MyVisitor(vec![]);
3385        my_visitor.visit_ty_unambig(self);
3386        my_visitor.0
3387    }
3388
3389    /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
3390    /// use inference to provide suggestions for the appropriate type if possible.
3391    pub fn is_suggestable_infer_ty(&self) -> bool {
3392        fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3393            generic_args.iter().any(|arg| match arg {
3394                GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3395                GenericArg::Infer(_) => true,
3396                _ => false,
3397            })
3398        }
3399        debug!(?self);
3400        match &self.kind {
3401            TyKind::Infer(()) => true,
3402            TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3403            TyKind::Array(ty, length) => {
3404                ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3405            }
3406            TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3407            TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3408            TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3409                ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3410            }
3411            TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3412                ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3413                    || segments
3414                        .iter()
3415                        .any(|segment| are_suggestable_generic_args(segment.args().args))
3416            }
3417            _ => false,
3418        }
3419    }
3420}
3421
3422/// Not represented directly in the AST; referred to by name through a `ty_path`.
3423#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3424pub enum PrimTy {
3425    Int(IntTy),
3426    Uint(UintTy),
3427    Float(FloatTy),
3428    Str,
3429    Bool,
3430    Char,
3431}
3432
3433impl PrimTy {
3434    /// All of the primitive types
3435    pub const ALL: [Self; 19] = [
3436        // any changes here should also be reflected in `PrimTy::from_name`
3437        Self::Int(IntTy::I8),
3438        Self::Int(IntTy::I16),
3439        Self::Int(IntTy::I32),
3440        Self::Int(IntTy::I64),
3441        Self::Int(IntTy::I128),
3442        Self::Int(IntTy::Isize),
3443        Self::Uint(UintTy::U8),
3444        Self::Uint(UintTy::U16),
3445        Self::Uint(UintTy::U32),
3446        Self::Uint(UintTy::U64),
3447        Self::Uint(UintTy::U128),
3448        Self::Uint(UintTy::Usize),
3449        Self::Float(FloatTy::F16),
3450        Self::Float(FloatTy::F32),
3451        Self::Float(FloatTy::F64),
3452        Self::Float(FloatTy::F128),
3453        Self::Bool,
3454        Self::Char,
3455        Self::Str,
3456    ];
3457
3458    /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
3459    ///
3460    /// Used by clippy.
3461    pub fn name_str(self) -> &'static str {
3462        match self {
3463            PrimTy::Int(i) => i.name_str(),
3464            PrimTy::Uint(u) => u.name_str(),
3465            PrimTy::Float(f) => f.name_str(),
3466            PrimTy::Str => "str",
3467            PrimTy::Bool => "bool",
3468            PrimTy::Char => "char",
3469        }
3470    }
3471
3472    pub fn name(self) -> Symbol {
3473        match self {
3474            PrimTy::Int(i) => i.name(),
3475            PrimTy::Uint(u) => u.name(),
3476            PrimTy::Float(f) => f.name(),
3477            PrimTy::Str => sym::str,
3478            PrimTy::Bool => sym::bool,
3479            PrimTy::Char => sym::char,
3480        }
3481    }
3482
3483    /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
3484    /// Returns `None` if no matching type is found.
3485    pub fn from_name(name: Symbol) -> Option<Self> {
3486        let ty = match name {
3487            // any changes here should also be reflected in `PrimTy::ALL`
3488            sym::i8 => Self::Int(IntTy::I8),
3489            sym::i16 => Self::Int(IntTy::I16),
3490            sym::i32 => Self::Int(IntTy::I32),
3491            sym::i64 => Self::Int(IntTy::I64),
3492            sym::i128 => Self::Int(IntTy::I128),
3493            sym::isize => Self::Int(IntTy::Isize),
3494            sym::u8 => Self::Uint(UintTy::U8),
3495            sym::u16 => Self::Uint(UintTy::U16),
3496            sym::u32 => Self::Uint(UintTy::U32),
3497            sym::u64 => Self::Uint(UintTy::U64),
3498            sym::u128 => Self::Uint(UintTy::U128),
3499            sym::usize => Self::Uint(UintTy::Usize),
3500            sym::f16 => Self::Float(FloatTy::F16),
3501            sym::f32 => Self::Float(FloatTy::F32),
3502            sym::f64 => Self::Float(FloatTy::F64),
3503            sym::f128 => Self::Float(FloatTy::F128),
3504            sym::bool => Self::Bool,
3505            sym::char => Self::Char,
3506            sym::str => Self::Str,
3507            _ => return None,
3508        };
3509        Some(ty)
3510    }
3511}
3512
3513#[derive(Debug, Clone, Copy, HashStable_Generic)]
3514pub struct BareFnTy<'hir> {
3515    pub safety: Safety,
3516    pub abi: ExternAbi,
3517    pub generic_params: &'hir [GenericParam<'hir>],
3518    pub decl: &'hir FnDecl<'hir>,
3519    // `Option` because bare fn parameter identifiers are optional. We also end up
3520    // with `None` in some error cases, e.g. invalid parameter patterns.
3521    pub param_idents: &'hir [Option<Ident>],
3522}
3523
3524#[derive(Debug, Clone, Copy, HashStable_Generic)]
3525pub struct UnsafeBinderTy<'hir> {
3526    pub generic_params: &'hir [GenericParam<'hir>],
3527    pub inner_ty: &'hir Ty<'hir>,
3528}
3529
3530#[derive(Debug, Clone, Copy, HashStable_Generic)]
3531pub struct OpaqueTy<'hir> {
3532    #[stable_hasher(ignore)]
3533    pub hir_id: HirId,
3534    pub def_id: LocalDefId,
3535    pub bounds: GenericBounds<'hir>,
3536    pub origin: OpaqueTyOrigin<LocalDefId>,
3537    pub span: Span,
3538}
3539
3540#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3541pub enum PreciseCapturingArgKind<T, U> {
3542    Lifetime(T),
3543    /// Non-lifetime argument (type or const)
3544    Param(U),
3545}
3546
3547pub type PreciseCapturingArg<'hir> =
3548    PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3549
3550impl PreciseCapturingArg<'_> {
3551    pub fn hir_id(self) -> HirId {
3552        match self {
3553            PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3554            PreciseCapturingArg::Param(param) => param.hir_id,
3555        }
3556    }
3557
3558    pub fn name(self) -> Symbol {
3559        match self {
3560            PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3561            PreciseCapturingArg::Param(param) => param.ident.name,
3562        }
3563    }
3564}
3565
3566/// We need to have a [`Node`] for the [`HirId`] that we attach the type/const param
3567/// resolution to. Lifetimes don't have this problem, and for them, it's actually
3568/// kind of detrimental to use a custom node type versus just using [`Lifetime`],
3569/// since resolve_bound_vars operates on `Lifetime`s.
3570#[derive(Debug, Clone, Copy, HashStable_Generic)]
3571pub struct PreciseCapturingNonLifetimeArg {
3572    #[stable_hasher(ignore)]
3573    pub hir_id: HirId,
3574    pub ident: Ident,
3575    pub res: Res,
3576}
3577
3578#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3579#[derive(HashStable_Generic, Encodable, Decodable)]
3580pub enum RpitContext {
3581    Trait,
3582    TraitImpl,
3583}
3584
3585/// From whence the opaque type came.
3586#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3587#[derive(HashStable_Generic, Encodable, Decodable)]
3588pub enum OpaqueTyOrigin<D> {
3589    /// `-> impl Trait`
3590    FnReturn {
3591        /// The defining function.
3592        parent: D,
3593        // Whether this is an RPITIT (return position impl trait in trait)
3594        in_trait_or_impl: Option<RpitContext>,
3595    },
3596    /// `async fn`
3597    AsyncFn {
3598        /// The defining function.
3599        parent: D,
3600        // Whether this is an AFIT (async fn in trait)
3601        in_trait_or_impl: Option<RpitContext>,
3602    },
3603    /// type aliases: `type Foo = impl Trait;`
3604    TyAlias {
3605        /// The type alias or associated type parent of the TAIT/ATPIT
3606        parent: D,
3607        /// associated types in impl blocks for traits.
3608        in_assoc_ty: bool,
3609    },
3610}
3611
3612#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3613pub enum InferDelegationKind {
3614    Input(usize),
3615    Output,
3616}
3617
3618/// The various kinds of types recognized by the compiler.
3619#[derive(Debug, Clone, Copy, HashStable_Generic)]
3620// SAFETY: `repr(u8)` is required so that `TyKind<()>` and `TyKind<!>` are layout compatible
3621#[repr(u8, C)]
3622pub enum TyKind<'hir, Unambig = ()> {
3623    /// Actual type should be inherited from `DefId` signature
3624    InferDelegation(DefId, InferDelegationKind),
3625    /// A variable length slice (i.e., `[T]`).
3626    Slice(&'hir Ty<'hir>),
3627    /// A fixed length array (i.e., `[T; n]`).
3628    Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3629    /// A raw pointer (i.e., `*const T` or `*mut T`).
3630    Ptr(MutTy<'hir>),
3631    /// A reference (i.e., `&'a T` or `&'a mut T`).
3632    Ref(&'hir Lifetime, MutTy<'hir>),
3633    /// A bare function (e.g., `fn(usize) -> bool`).
3634    BareFn(&'hir BareFnTy<'hir>),
3635    /// An unsafe binder type (e.g. `unsafe<'a> Foo<'a>`).
3636    UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3637    /// The never type (`!`).
3638    Never,
3639    /// A tuple (`(A, B, C, D, ...)`).
3640    Tup(&'hir [Ty<'hir>]),
3641    /// A path to a type definition (`module::module::...::Type`), or an
3642    /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
3643    ///
3644    /// Type parameters may be stored in each `PathSegment`.
3645    Path(QPath<'hir>),
3646    /// An opaque type definition itself. This is only used for `impl Trait`.
3647    OpaqueDef(&'hir OpaqueTy<'hir>),
3648    /// A trait ascription type, which is `impl Trait` within a local binding.
3649    TraitAscription(GenericBounds<'hir>),
3650    /// A trait object type `Bound1 + Bound2 + Bound3`
3651    /// where `Bound` is a trait or a lifetime.
3652    ///
3653    /// We use pointer tagging to represent a `&'hir Lifetime` and `TraitObjectSyntax` pair
3654    /// as otherwise this type being `repr(C)` would result in `TyKind` increasing in size.
3655    TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3656    /// Unused for now.
3657    Typeof(&'hir AnonConst),
3658    /// Placeholder for a type that has failed to be defined.
3659    Err(rustc_span::ErrorGuaranteed),
3660    /// Pattern types (`pattern_type!(u32 is 1..)`)
3661    Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3662    /// `TyKind::Infer` means the type should be inferred instead of it having been
3663    /// specified. This can appear anywhere in a type.
3664    ///
3665    /// This variant is not always used to represent inference types, sometimes
3666    /// [`GenericArg::Infer`] is used instead.
3667    Infer(Unambig),
3668}
3669
3670#[derive(Debug, Clone, Copy, HashStable_Generic)]
3671pub enum InlineAsmOperand<'hir> {
3672    In {
3673        reg: InlineAsmRegOrRegClass,
3674        expr: &'hir Expr<'hir>,
3675    },
3676    Out {
3677        reg: InlineAsmRegOrRegClass,
3678        late: bool,
3679        expr: Option<&'hir Expr<'hir>>,
3680    },
3681    InOut {
3682        reg: InlineAsmRegOrRegClass,
3683        late: bool,
3684        expr: &'hir Expr<'hir>,
3685    },
3686    SplitInOut {
3687        reg: InlineAsmRegOrRegClass,
3688        late: bool,
3689        in_expr: &'hir Expr<'hir>,
3690        out_expr: Option<&'hir Expr<'hir>>,
3691    },
3692    Const {
3693        anon_const: ConstBlock,
3694    },
3695    SymFn {
3696        expr: &'hir Expr<'hir>,
3697    },
3698    SymStatic {
3699        path: QPath<'hir>,
3700        def_id: DefId,
3701    },
3702    Label {
3703        block: &'hir Block<'hir>,
3704    },
3705}
3706
3707impl<'hir> InlineAsmOperand<'hir> {
3708    pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3709        match *self {
3710            Self::In { reg, .. }
3711            | Self::Out { reg, .. }
3712            | Self::InOut { reg, .. }
3713            | Self::SplitInOut { reg, .. } => Some(reg),
3714            Self::Const { .. }
3715            | Self::SymFn { .. }
3716            | Self::SymStatic { .. }
3717            | Self::Label { .. } => None,
3718        }
3719    }
3720
3721    pub fn is_clobber(&self) -> bool {
3722        matches!(
3723            self,
3724            InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3725        )
3726    }
3727}
3728
3729#[derive(Debug, Clone, Copy, HashStable_Generic)]
3730pub struct InlineAsm<'hir> {
3731    pub asm_macro: ast::AsmMacro,
3732    pub template: &'hir [InlineAsmTemplatePiece],
3733    pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3734    pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3735    pub options: InlineAsmOptions,
3736    pub line_spans: &'hir [Span],
3737}
3738
3739impl InlineAsm<'_> {
3740    pub fn contains_label(&self) -> bool {
3741        self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3742    }
3743}
3744
3745/// Represents a parameter in a function header.
3746#[derive(Debug, Clone, Copy, HashStable_Generic)]
3747pub struct Param<'hir> {
3748    #[stable_hasher(ignore)]
3749    pub hir_id: HirId,
3750    pub pat: &'hir Pat<'hir>,
3751    pub ty_span: Span,
3752    pub span: Span,
3753}
3754
3755/// Represents the header (not the body) of a function declaration.
3756#[derive(Debug, Clone, Copy, HashStable_Generic)]
3757pub struct FnDecl<'hir> {
3758    /// The types of the function's parameters.
3759    ///
3760    /// Additional argument data is stored in the function's [body](Body::params).
3761    pub inputs: &'hir [Ty<'hir>],
3762    pub output: FnRetTy<'hir>,
3763    pub c_variadic: bool,
3764    /// Does the function have an implicit self?
3765    pub implicit_self: ImplicitSelfKind,
3766    /// Is lifetime elision allowed.
3767    pub lifetime_elision_allowed: bool,
3768}
3769
3770impl<'hir> FnDecl<'hir> {
3771    pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3772        if let FnRetTy::Return(ty) = self.output
3773            && let TyKind::InferDelegation(sig_id, _) = ty.kind
3774        {
3775            return Some(sig_id);
3776        }
3777        None
3778    }
3779}
3780
3781/// Represents what type of implicit self a function has, if any.
3782#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3783pub enum ImplicitSelfKind {
3784    /// Represents a `fn x(self);`.
3785    Imm,
3786    /// Represents a `fn x(mut self);`.
3787    Mut,
3788    /// Represents a `fn x(&self);`.
3789    RefImm,
3790    /// Represents a `fn x(&mut self);`.
3791    RefMut,
3792    /// Represents when a function does not have a self argument or
3793    /// when a function has a `self: X` argument.
3794    None,
3795}
3796
3797impl ImplicitSelfKind {
3798    /// Does this represent an implicit self?
3799    pub fn has_implicit_self(&self) -> bool {
3800        !matches!(*self, ImplicitSelfKind::None)
3801    }
3802}
3803
3804#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3805pub enum IsAsync {
3806    Async(Span),
3807    NotAsync,
3808}
3809
3810impl IsAsync {
3811    pub fn is_async(self) -> bool {
3812        matches!(self, IsAsync::Async(_))
3813    }
3814}
3815
3816#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3817pub enum Defaultness {
3818    Default { has_value: bool },
3819    Final,
3820}
3821
3822impl Defaultness {
3823    pub fn has_value(&self) -> bool {
3824        match *self {
3825            Defaultness::Default { has_value } => has_value,
3826            Defaultness::Final => true,
3827        }
3828    }
3829
3830    pub fn is_final(&self) -> bool {
3831        *self == Defaultness::Final
3832    }
3833
3834    pub fn is_default(&self) -> bool {
3835        matches!(*self, Defaultness::Default { .. })
3836    }
3837}
3838
3839#[derive(Debug, Clone, Copy, HashStable_Generic)]
3840pub enum FnRetTy<'hir> {
3841    /// Return type is not specified.
3842    ///
3843    /// Functions default to `()` and
3844    /// closures default to inference. Span points to where return
3845    /// type would be inserted.
3846    DefaultReturn(Span),
3847    /// Everything else.
3848    Return(&'hir Ty<'hir>),
3849}
3850
3851impl<'hir> FnRetTy<'hir> {
3852    #[inline]
3853    pub fn span(&self) -> Span {
3854        match *self {
3855            Self::DefaultReturn(span) => span,
3856            Self::Return(ref ty) => ty.span,
3857        }
3858    }
3859
3860    pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3861        if let Self::Return(ty) = self
3862            && ty.is_suggestable_infer_ty()
3863        {
3864            return Some(*ty);
3865        }
3866        None
3867    }
3868}
3869
3870/// Represents `for<...>` binder before a closure
3871#[derive(Copy, Clone, Debug, HashStable_Generic)]
3872pub enum ClosureBinder {
3873    /// Binder is not specified.
3874    Default,
3875    /// Binder is specified.
3876    ///
3877    /// Span points to the whole `for<...>`.
3878    For { span: Span },
3879}
3880
3881#[derive(Debug, Clone, Copy, HashStable_Generic)]
3882pub struct Mod<'hir> {
3883    pub spans: ModSpans,
3884    pub item_ids: &'hir [ItemId],
3885}
3886
3887#[derive(Copy, Clone, Debug, HashStable_Generic)]
3888pub struct ModSpans {
3889    /// A span from the first token past `{` to the last token until `}`.
3890    /// For `mod foo;`, the inner span ranges from the first token
3891    /// to the last token in the external file.
3892    pub inner_span: Span,
3893    pub inject_use_span: Span,
3894}
3895
3896#[derive(Debug, Clone, Copy, HashStable_Generic)]
3897pub struct EnumDef<'hir> {
3898    pub variants: &'hir [Variant<'hir>],
3899}
3900
3901#[derive(Debug, Clone, Copy, HashStable_Generic)]
3902pub struct Variant<'hir> {
3903    /// Name of the variant.
3904    pub ident: Ident,
3905    /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
3906    #[stable_hasher(ignore)]
3907    pub hir_id: HirId,
3908    pub def_id: LocalDefId,
3909    /// Fields and constructor id of the variant.
3910    pub data: VariantData<'hir>,
3911    /// Explicit discriminant (e.g., `Foo = 1`).
3912    pub disr_expr: Option<&'hir AnonConst>,
3913    /// Span
3914    pub span: Span,
3915}
3916
3917#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3918pub enum UseKind {
3919    /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
3920    /// Also produced for each element of a list `use`, e.g.
3921    /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
3922    ///
3923    /// The identifier is the name defined by the import. E.g. for `use
3924    /// foo::bar` it is `bar`, for `use foo::bar as baz` it is `baz`.
3925    Single(Ident),
3926
3927    /// Glob import, e.g., `use foo::*`.
3928    Glob,
3929
3930    /// Degenerate list import, e.g., `use foo::{a, b}` produces
3931    /// an additional `use foo::{}` for performing checks such as
3932    /// unstable feature gating. May be removed in the future.
3933    ListStem,
3934}
3935
3936/// References to traits in impls.
3937///
3938/// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
3939/// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
3940/// trait being referred to but just a unique `HirId` that serves as a key
3941/// within the resolution map.
3942#[derive(Clone, Debug, Copy, HashStable_Generic)]
3943pub struct TraitRef<'hir> {
3944    pub path: &'hir Path<'hir>,
3945    // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
3946    #[stable_hasher(ignore)]
3947    pub hir_ref_id: HirId,
3948}
3949
3950impl TraitRef<'_> {
3951    /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
3952    pub fn trait_def_id(&self) -> Option<DefId> {
3953        match self.path.res {
3954            Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3955            Res::Err => None,
3956            res => panic!("{res:?} did not resolve to a trait or trait alias"),
3957        }
3958    }
3959}
3960
3961#[derive(Clone, Debug, Copy, HashStable_Generic)]
3962pub struct PolyTraitRef<'hir> {
3963    /// The `'a` in `for<'a> Foo<&'a T>`.
3964    pub bound_generic_params: &'hir [GenericParam<'hir>],
3965
3966    /// The constness and polarity of the trait ref.
3967    ///
3968    /// The `async` modifier is lowered directly into a different trait for now.
3969    pub modifiers: TraitBoundModifiers,
3970
3971    /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
3972    pub trait_ref: TraitRef<'hir>,
3973
3974    pub span: Span,
3975}
3976
3977#[derive(Debug, Clone, Copy, HashStable_Generic)]
3978pub struct FieldDef<'hir> {
3979    pub span: Span,
3980    pub vis_span: Span,
3981    pub ident: Ident,
3982    #[stable_hasher(ignore)]
3983    pub hir_id: HirId,
3984    pub def_id: LocalDefId,
3985    pub ty: &'hir Ty<'hir>,
3986    pub safety: Safety,
3987    pub default: Option<&'hir AnonConst>,
3988}
3989
3990impl FieldDef<'_> {
3991    // Still necessary in couple of places
3992    pub fn is_positional(&self) -> bool {
3993        self.ident.as_str().as_bytes()[0].is_ascii_digit()
3994    }
3995}
3996
3997/// Fields and constructor IDs of enum variants and structs.
3998#[derive(Debug, Clone, Copy, HashStable_Generic)]
3999pub enum VariantData<'hir> {
4000    /// A struct variant.
4001    ///
4002    /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
4003    Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4004    /// A tuple variant.
4005    ///
4006    /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
4007    Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4008    /// A unit variant.
4009    ///
4010    /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
4011    Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4012}
4013
4014impl<'hir> VariantData<'hir> {
4015    /// Return the fields of this variant.
4016    pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4017        match *self {
4018            VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4019            _ => &[],
4020        }
4021    }
4022
4023    pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4024        match *self {
4025            VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4026            VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4027            VariantData::Struct { .. } => None,
4028        }
4029    }
4030
4031    #[inline]
4032    pub fn ctor_kind(&self) -> Option<CtorKind> {
4033        self.ctor().map(|(kind, ..)| kind)
4034    }
4035
4036    /// Return the `HirId` of this variant's constructor, if it has one.
4037    #[inline]
4038    pub fn ctor_hir_id(&self) -> Option<HirId> {
4039        self.ctor().map(|(_, hir_id, _)| hir_id)
4040    }
4041
4042    /// Return the `LocalDefId` of this variant's constructor, if it has one.
4043    #[inline]
4044    pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4045        self.ctor().map(|(.., def_id)| def_id)
4046    }
4047}
4048
4049// The bodies for items are stored "out of line", in a separate
4050// hashmap in the `Crate`. Here we just record the hir-id of the item
4051// so it can fetched later.
4052#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4053pub struct ItemId {
4054    pub owner_id: OwnerId,
4055}
4056
4057impl ItemId {
4058    #[inline]
4059    pub fn hir_id(&self) -> HirId {
4060        // Items are always HIR owners.
4061        HirId::make_owner(self.owner_id.def_id)
4062    }
4063}
4064
4065/// An item
4066///
4067/// For more details, see the [rust lang reference].
4068/// Note that the reference does not document nightly-only features.
4069/// There may be also slight differences in the names and representation of AST nodes between
4070/// the compiler and the reference.
4071///
4072/// [rust lang reference]: https://doc.rust-lang.org/reference/items.html
4073#[derive(Debug, Clone, Copy, HashStable_Generic)]
4074pub struct Item<'hir> {
4075    pub owner_id: OwnerId,
4076    pub kind: ItemKind<'hir>,
4077    pub span: Span,
4078    pub vis_span: Span,
4079}
4080
4081impl<'hir> Item<'hir> {
4082    #[inline]
4083    pub fn hir_id(&self) -> HirId {
4084        // Items are always HIR owners.
4085        HirId::make_owner(self.owner_id.def_id)
4086    }
4087
4088    pub fn item_id(&self) -> ItemId {
4089        ItemId { owner_id: self.owner_id }
4090    }
4091
4092    /// Check if this is an [`ItemKind::Enum`], [`ItemKind::Struct`] or
4093    /// [`ItemKind::Union`].
4094    pub fn is_adt(&self) -> bool {
4095        matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4096    }
4097
4098    /// Check if this is an [`ItemKind::Struct`] or [`ItemKind::Union`].
4099    pub fn is_struct_or_union(&self) -> bool {
4100        matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4101    }
4102
4103    expect_methods_self_kind! {
4104        expect_extern_crate, (Option<Symbol>, Ident),
4105            ItemKind::ExternCrate(s, ident), (*s, *ident);
4106
4107        expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4108
4109        expect_static, (Ident, &'hir Ty<'hir>, Mutability, BodyId),
4110            ItemKind::Static(ident, ty, mutbl, body), (*ident, ty, *mutbl, *body);
4111
4112        expect_const, (Ident, &'hir Ty<'hir>, &'hir Generics<'hir>, BodyId),
4113            ItemKind::Const(ident, ty, generics, body), (*ident, ty, generics, *body);
4114
4115        expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4116            ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4117
4118        expect_macro, (Ident, &ast::MacroDef, MacroKind),
4119            ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4120
4121        expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4122
4123        expect_foreign_mod, (ExternAbi, &'hir [ForeignItemRef]),
4124            ItemKind::ForeignMod { abi, items }, (*abi, items);
4125
4126        expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4127
4128        expect_ty_alias, (Ident, &'hir Ty<'hir>, &'hir Generics<'hir>),
4129            ItemKind::TyAlias(ident, ty, generics), (*ident, ty, generics);
4130
4131        expect_enum, (Ident, &EnumDef<'hir>, &'hir Generics<'hir>),
4132            ItemKind::Enum(ident, def, generics), (*ident, def, generics);
4133
4134        expect_struct, (Ident, &VariantData<'hir>, &'hir Generics<'hir>),
4135            ItemKind::Struct(ident, data, generics), (*ident, data, generics);
4136
4137        expect_union, (Ident, &VariantData<'hir>, &'hir Generics<'hir>),
4138            ItemKind::Union(ident, data, generics), (*ident, data, generics);
4139
4140        expect_trait,
4141            (
4142                IsAuto,
4143                Safety,
4144                Ident,
4145                &'hir Generics<'hir>,
4146                GenericBounds<'hir>,
4147                &'hir [TraitItemRef]
4148            ),
4149            ItemKind::Trait(is_auto, safety, ident, generics, bounds, items),
4150            (*is_auto, *safety, *ident, generics, bounds, items);
4151
4152        expect_trait_alias, (Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4153            ItemKind::TraitAlias(ident, generics, bounds), (*ident, generics, bounds);
4154
4155        expect_impl, &'hir Impl<'hir>, ItemKind::Impl(imp), imp;
4156    }
4157}
4158
4159#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4160#[derive(Encodable, Decodable, HashStable_Generic)]
4161pub enum Safety {
4162    Unsafe,
4163    Safe,
4164}
4165
4166impl Safety {
4167    pub fn prefix_str(self) -> &'static str {
4168        match self {
4169            Self::Unsafe => "unsafe ",
4170            Self::Safe => "",
4171        }
4172    }
4173
4174    #[inline]
4175    pub fn is_unsafe(self) -> bool {
4176        !self.is_safe()
4177    }
4178
4179    #[inline]
4180    pub fn is_safe(self) -> bool {
4181        match self {
4182            Self::Unsafe => false,
4183            Self::Safe => true,
4184        }
4185    }
4186}
4187
4188impl fmt::Display for Safety {
4189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4190        f.write_str(match *self {
4191            Self::Unsafe => "unsafe",
4192            Self::Safe => "safe",
4193        })
4194    }
4195}
4196
4197#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4198pub enum Constness {
4199    Const,
4200    NotConst,
4201}
4202
4203impl fmt::Display for Constness {
4204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4205        f.write_str(match *self {
4206            Self::Const => "const",
4207            Self::NotConst => "non-const",
4208        })
4209    }
4210}
4211
4212/// The actualy safety specified in syntax. We may treat
4213/// its safety different within the type system to create a
4214/// "sound by default" system that needs checking this enum
4215/// explicitly to allow unsafe operations.
4216#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4217pub enum HeaderSafety {
4218    /// A safe function annotated with `#[target_features]`.
4219    /// The type system treats this function as an unsafe function,
4220    /// but safety checking will check this enum to treat it as safe
4221    /// and allowing calling other safe target feature functions with
4222    /// the same features without requiring an additional unsafe block.
4223    SafeTargetFeatures,
4224    Normal(Safety),
4225}
4226
4227impl From<Safety> for HeaderSafety {
4228    fn from(v: Safety) -> Self {
4229        Self::Normal(v)
4230    }
4231}
4232
4233#[derive(Copy, Clone, Debug, HashStable_Generic)]
4234pub struct FnHeader {
4235    pub safety: HeaderSafety,
4236    pub constness: Constness,
4237    pub asyncness: IsAsync,
4238    pub abi: ExternAbi,
4239}
4240
4241impl FnHeader {
4242    pub fn is_async(&self) -> bool {
4243        matches!(self.asyncness, IsAsync::Async(_))
4244    }
4245
4246    pub fn is_const(&self) -> bool {
4247        matches!(self.constness, Constness::Const)
4248    }
4249
4250    pub fn is_unsafe(&self) -> bool {
4251        self.safety().is_unsafe()
4252    }
4253
4254    pub fn is_safe(&self) -> bool {
4255        self.safety().is_safe()
4256    }
4257
4258    pub fn safety(&self) -> Safety {
4259        match self.safety {
4260            HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4261            HeaderSafety::Normal(safety) => safety,
4262        }
4263    }
4264}
4265
4266#[derive(Debug, Clone, Copy, HashStable_Generic)]
4267pub enum ItemKind<'hir> {
4268    /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
4269    ///
4270    /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
4271    ExternCrate(Option<Symbol>, Ident),
4272
4273    /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
4274    ///
4275    /// or just
4276    ///
4277    /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
4278    Use(&'hir UsePath<'hir>, UseKind),
4279
4280    /// A `static` item.
4281    Static(Ident, &'hir Ty<'hir>, Mutability, BodyId),
4282    /// A `const` item.
4283    Const(Ident, &'hir Ty<'hir>, &'hir Generics<'hir>, BodyId),
4284    /// A function declaration.
4285    Fn {
4286        ident: Ident,
4287        sig: FnSig<'hir>,
4288        generics: &'hir Generics<'hir>,
4289        body: BodyId,
4290        /// Whether this function actually has a body.
4291        /// For functions without a body, `body` is synthesized (to avoid ICEs all over the
4292        /// compiler), but that code should never be translated.
4293        has_body: bool,
4294    },
4295    /// A MBE macro definition (`macro_rules!` or `macro`).
4296    Macro(Ident, &'hir ast::MacroDef, MacroKind),
4297    /// A module.
4298    Mod(Ident, &'hir Mod<'hir>),
4299    /// An external module, e.g. `extern { .. }`.
4300    ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemRef] },
4301    /// Module-level inline assembly (from `global_asm!`).
4302    GlobalAsm {
4303        asm: &'hir InlineAsm<'hir>,
4304        /// A fake body which stores typeck results for the global asm's sym_fn
4305        /// operands, which are represented as path expressions. This body contains
4306        /// a single [`ExprKind::InlineAsm`] which points to the asm in the field
4307        /// above, and which is typechecked like a inline asm expr just for the
4308        /// typeck results.
4309        fake_body: BodyId,
4310    },
4311    /// A type alias, e.g., `type Foo = Bar<u8>`.
4312    TyAlias(Ident, &'hir Ty<'hir>, &'hir Generics<'hir>),
4313    /// An enum definition, e.g., `enum Foo<A, B> { C<A>, D<B> }`.
4314    Enum(Ident, EnumDef<'hir>, &'hir Generics<'hir>),
4315    /// A struct definition, e.g., `struct Foo<A> {x: A}`.
4316    Struct(Ident, VariantData<'hir>, &'hir Generics<'hir>),
4317    /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
4318    Union(Ident, VariantData<'hir>, &'hir Generics<'hir>),
4319    /// A trait definition.
4320    Trait(IsAuto, Safety, Ident, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
4321    /// A trait alias.
4322    TraitAlias(Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4323
4324    /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
4325    Impl(&'hir Impl<'hir>),
4326}
4327
4328/// Represents an impl block declaration.
4329///
4330/// E.g., `impl $Type { .. }` or `impl $Trait for $Type { .. }`
4331/// Refer to [`ImplItem`] for an associated item within an impl block.
4332#[derive(Debug, Clone, Copy, HashStable_Generic)]
4333pub struct Impl<'hir> {
4334    pub constness: Constness,
4335    pub safety: Safety,
4336    pub polarity: ImplPolarity,
4337    pub defaultness: Defaultness,
4338    // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
4339    // decoding as `Span`s cannot be decoded when a `Session` is not available.
4340    pub defaultness_span: Option<Span>,
4341    pub generics: &'hir Generics<'hir>,
4342
4343    /// The trait being implemented, if any.
4344    pub of_trait: Option<TraitRef<'hir>>,
4345
4346    pub self_ty: &'hir Ty<'hir>,
4347    pub items: &'hir [ImplItemRef],
4348}
4349
4350impl ItemKind<'_> {
4351    pub fn ident(&self) -> Option<Ident> {
4352        match *self {
4353            ItemKind::ExternCrate(_, ident)
4354            | ItemKind::Use(_, UseKind::Single(ident))
4355            | ItemKind::Static(ident, ..)
4356            | ItemKind::Const(ident, ..)
4357            | ItemKind::Fn { ident, .. }
4358            | ItemKind::Macro(ident, ..)
4359            | ItemKind::Mod(ident, ..)
4360            | ItemKind::TyAlias(ident, ..)
4361            | ItemKind::Enum(ident, ..)
4362            | ItemKind::Struct(ident, ..)
4363            | ItemKind::Union(ident, ..)
4364            | ItemKind::Trait(_, _, ident, ..)
4365            | ItemKind::TraitAlias(ident, ..) => Some(ident),
4366
4367            ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4368            | ItemKind::ForeignMod { .. }
4369            | ItemKind::GlobalAsm { .. }
4370            | ItemKind::Impl(_) => None,
4371        }
4372    }
4373
4374    pub fn generics(&self) -> Option<&Generics<'_>> {
4375        Some(match self {
4376            ItemKind::Fn { generics, .. }
4377            | ItemKind::TyAlias(_, _, generics)
4378            | ItemKind::Const(_, _, generics, _)
4379            | ItemKind::Enum(_, _, generics)
4380            | ItemKind::Struct(_, _, generics)
4381            | ItemKind::Union(_, _, generics)
4382            | ItemKind::Trait(_, _, _, generics, _, _)
4383            | ItemKind::TraitAlias(_, generics, _)
4384            | ItemKind::Impl(Impl { generics, .. }) => generics,
4385            _ => return None,
4386        })
4387    }
4388
4389    pub fn descr(&self) -> &'static str {
4390        match self {
4391            ItemKind::ExternCrate(..) => "extern crate",
4392            ItemKind::Use(..) => "`use` import",
4393            ItemKind::Static(..) => "static item",
4394            ItemKind::Const(..) => "constant item",
4395            ItemKind::Fn { .. } => "function",
4396            ItemKind::Macro(..) => "macro",
4397            ItemKind::Mod(..) => "module",
4398            ItemKind::ForeignMod { .. } => "extern block",
4399            ItemKind::GlobalAsm { .. } => "global asm item",
4400            ItemKind::TyAlias(..) => "type alias",
4401            ItemKind::Enum(..) => "enum",
4402            ItemKind::Struct(..) => "struct",
4403            ItemKind::Union(..) => "union",
4404            ItemKind::Trait(..) => "trait",
4405            ItemKind::TraitAlias(..) => "trait alias",
4406            ItemKind::Impl(..) => "implementation",
4407        }
4408    }
4409}
4410
4411/// A reference from an trait to one of its associated items. This
4412/// contains the item's id, naturally, but also the item's name and
4413/// some other high-level details (like whether it is an associated
4414/// type or method, and whether it is public). This allows other
4415/// passes to find the impl they want without loading the ID (which
4416/// means fewer edges in the incremental compilation graph).
4417#[derive(Debug, Clone, Copy, HashStable_Generic)]
4418pub struct TraitItemRef {
4419    pub id: TraitItemId,
4420    pub ident: Ident,
4421    pub kind: AssocItemKind,
4422    pub span: Span,
4423}
4424
4425/// A reference from an impl to one of its associated items. This
4426/// contains the item's ID, naturally, but also the item's name and
4427/// some other high-level details (like whether it is an associated
4428/// type or method, and whether it is public). This allows other
4429/// passes to find the impl they want without loading the ID (which
4430/// means fewer edges in the incremental compilation graph).
4431#[derive(Debug, Clone, Copy, HashStable_Generic)]
4432pub struct ImplItemRef {
4433    pub id: ImplItemId,
4434    pub ident: Ident,
4435    pub kind: AssocItemKind,
4436    pub span: Span,
4437    /// When we are in a trait impl, link to the trait-item's id.
4438    pub trait_item_def_id: Option<DefId>,
4439}
4440
4441#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
4442pub enum AssocItemKind {
4443    Const,
4444    Fn { has_self: bool },
4445    Type,
4446}
4447
4448// The bodies for items are stored "out of line", in a separate
4449// hashmap in the `Crate`. Here we just record the hir-id of the item
4450// so it can fetched later.
4451#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4452pub struct ForeignItemId {
4453    pub owner_id: OwnerId,
4454}
4455
4456impl ForeignItemId {
4457    #[inline]
4458    pub fn hir_id(&self) -> HirId {
4459        // Items are always HIR owners.
4460        HirId::make_owner(self.owner_id.def_id)
4461    }
4462}
4463
4464/// A reference from a foreign block to one of its items. This
4465/// contains the item's ID, naturally, but also the item's name and
4466/// some other high-level details (like whether it is an associated
4467/// type or method, and whether it is public). This allows other
4468/// passes to find the impl they want without loading the ID (which
4469/// means fewer edges in the incremental compilation graph).
4470#[derive(Debug, Clone, Copy, HashStable_Generic)]
4471pub struct ForeignItemRef {
4472    pub id: ForeignItemId,
4473    pub ident: Ident,
4474    pub span: Span,
4475}
4476
4477#[derive(Debug, Clone, Copy, HashStable_Generic)]
4478pub struct ForeignItem<'hir> {
4479    pub ident: Ident,
4480    pub kind: ForeignItemKind<'hir>,
4481    pub owner_id: OwnerId,
4482    pub span: Span,
4483    pub vis_span: Span,
4484}
4485
4486impl ForeignItem<'_> {
4487    #[inline]
4488    pub fn hir_id(&self) -> HirId {
4489        // Items are always HIR owners.
4490        HirId::make_owner(self.owner_id.def_id)
4491    }
4492
4493    pub fn foreign_item_id(&self) -> ForeignItemId {
4494        ForeignItemId { owner_id: self.owner_id }
4495    }
4496}
4497
4498/// An item within an `extern` block.
4499#[derive(Debug, Clone, Copy, HashStable_Generic)]
4500pub enum ForeignItemKind<'hir> {
4501    /// A foreign function.
4502    ///
4503    /// All argument idents are actually always present (i.e. `Some`), but
4504    /// `&[Option<Ident>]` is used because of code paths shared with `TraitFn`
4505    /// and `BareFnTy`. The sharing is due to all of these cases not allowing
4506    /// arbitrary patterns for parameters.
4507    Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4508    /// A foreign static item (`static ext: u8`).
4509    Static(&'hir Ty<'hir>, Mutability, Safety),
4510    /// A foreign type.
4511    Type,
4512}
4513
4514/// A variable captured by a closure.
4515#[derive(Debug, Copy, Clone, HashStable_Generic)]
4516pub struct Upvar {
4517    /// First span where it is accessed (there can be multiple).
4518    pub span: Span,
4519}
4520
4521// The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
4522// has length > 0 if the trait is found through an chain of imports, starting with the
4523// import/use statement in the scope where the trait is used.
4524#[derive(Debug, Clone, HashStable_Generic)]
4525pub struct TraitCandidate {
4526    pub def_id: DefId,
4527    pub import_ids: SmallVec<[LocalDefId; 1]>,
4528}
4529
4530#[derive(Copy, Clone, Debug, HashStable_Generic)]
4531pub enum OwnerNode<'hir> {
4532    Item(&'hir Item<'hir>),
4533    ForeignItem(&'hir ForeignItem<'hir>),
4534    TraitItem(&'hir TraitItem<'hir>),
4535    ImplItem(&'hir ImplItem<'hir>),
4536    Crate(&'hir Mod<'hir>),
4537    Synthetic,
4538}
4539
4540impl<'hir> OwnerNode<'hir> {
4541    pub fn span(&self) -> Span {
4542        match self {
4543            OwnerNode::Item(Item { span, .. })
4544            | OwnerNode::ForeignItem(ForeignItem { span, .. })
4545            | OwnerNode::ImplItem(ImplItem { span, .. })
4546            | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4547            OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4548            OwnerNode::Synthetic => unreachable!(),
4549        }
4550    }
4551
4552    pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4553        match self {
4554            OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4555            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4556            | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4557            | OwnerNode::ForeignItem(ForeignItem {
4558                kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4559            }) => Some(fn_sig),
4560            _ => None,
4561        }
4562    }
4563
4564    pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4565        match self {
4566            OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4567            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4568            | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4569            | OwnerNode::ForeignItem(ForeignItem {
4570                kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4571            }) => Some(fn_sig.decl),
4572            _ => None,
4573        }
4574    }
4575
4576    pub fn body_id(&self) -> Option<BodyId> {
4577        match self {
4578            OwnerNode::Item(Item {
4579                kind:
4580                    ItemKind::Static(_, _, _, body)
4581                    | ItemKind::Const(_, _, _, body)
4582                    | ItemKind::Fn { body, .. },
4583                ..
4584            })
4585            | OwnerNode::TraitItem(TraitItem {
4586                kind:
4587                    TraitItemKind::Fn(_, TraitFn::Provided(body)) | TraitItemKind::Const(_, Some(body)),
4588                ..
4589            })
4590            | OwnerNode::ImplItem(ImplItem {
4591                kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, body),
4592                ..
4593            }) => Some(*body),
4594            _ => None,
4595        }
4596    }
4597
4598    pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4599        Node::generics(self.into())
4600    }
4601
4602    pub fn def_id(self) -> OwnerId {
4603        match self {
4604            OwnerNode::Item(Item { owner_id, .. })
4605            | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4606            | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4607            | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4608            OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4609            OwnerNode::Synthetic => unreachable!(),
4610        }
4611    }
4612
4613    /// Check if node is an impl block.
4614    pub fn is_impl_block(&self) -> bool {
4615        matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4616    }
4617
4618    expect_methods_self! {
4619        expect_item,         &'hir Item<'hir>,        OwnerNode::Item(n),        n;
4620        expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4621        expect_impl_item,    &'hir ImplItem<'hir>,    OwnerNode::ImplItem(n),    n;
4622        expect_trait_item,   &'hir TraitItem<'hir>,   OwnerNode::TraitItem(n),   n;
4623    }
4624}
4625
4626impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4627    fn from(val: &'hir Item<'hir>) -> Self {
4628        OwnerNode::Item(val)
4629    }
4630}
4631
4632impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4633    fn from(val: &'hir ForeignItem<'hir>) -> Self {
4634        OwnerNode::ForeignItem(val)
4635    }
4636}
4637
4638impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4639    fn from(val: &'hir ImplItem<'hir>) -> Self {
4640        OwnerNode::ImplItem(val)
4641    }
4642}
4643
4644impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4645    fn from(val: &'hir TraitItem<'hir>) -> Self {
4646        OwnerNode::TraitItem(val)
4647    }
4648}
4649
4650impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4651    fn from(val: OwnerNode<'hir>) -> Self {
4652        match val {
4653            OwnerNode::Item(n) => Node::Item(n),
4654            OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4655            OwnerNode::ImplItem(n) => Node::ImplItem(n),
4656            OwnerNode::TraitItem(n) => Node::TraitItem(n),
4657            OwnerNode::Crate(n) => Node::Crate(n),
4658            OwnerNode::Synthetic => Node::Synthetic,
4659        }
4660    }
4661}
4662
4663#[derive(Copy, Clone, Debug, HashStable_Generic)]
4664pub enum Node<'hir> {
4665    Param(&'hir Param<'hir>),
4666    Item(&'hir Item<'hir>),
4667    ForeignItem(&'hir ForeignItem<'hir>),
4668    TraitItem(&'hir TraitItem<'hir>),
4669    ImplItem(&'hir ImplItem<'hir>),
4670    Variant(&'hir Variant<'hir>),
4671    Field(&'hir FieldDef<'hir>),
4672    AnonConst(&'hir AnonConst),
4673    ConstBlock(&'hir ConstBlock),
4674    ConstArg(&'hir ConstArg<'hir>),
4675    Expr(&'hir Expr<'hir>),
4676    ExprField(&'hir ExprField<'hir>),
4677    Stmt(&'hir Stmt<'hir>),
4678    PathSegment(&'hir PathSegment<'hir>),
4679    Ty(&'hir Ty<'hir>),
4680    AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4681    TraitRef(&'hir TraitRef<'hir>),
4682    OpaqueTy(&'hir OpaqueTy<'hir>),
4683    TyPat(&'hir TyPat<'hir>),
4684    Pat(&'hir Pat<'hir>),
4685    PatField(&'hir PatField<'hir>),
4686    /// Needed as its own node with its own HirId for tracking
4687    /// the unadjusted type of literals within patterns
4688    /// (e.g. byte str literals not being of slice type).
4689    PatExpr(&'hir PatExpr<'hir>),
4690    Arm(&'hir Arm<'hir>),
4691    Block(&'hir Block<'hir>),
4692    LetStmt(&'hir LetStmt<'hir>),
4693    /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
4694    /// with synthesized constructors.
4695    Ctor(&'hir VariantData<'hir>),
4696    Lifetime(&'hir Lifetime),
4697    GenericParam(&'hir GenericParam<'hir>),
4698    Crate(&'hir Mod<'hir>),
4699    Infer(&'hir InferArg),
4700    WherePredicate(&'hir WherePredicate<'hir>),
4701    PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4702    // Created by query feeding
4703    Synthetic,
4704    Err(Span),
4705}
4706
4707impl<'hir> Node<'hir> {
4708    /// Get the identifier of this `Node`, if applicable.
4709    ///
4710    /// # Edge cases
4711    ///
4712    /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
4713    /// because `Ctor`s do not have identifiers themselves.
4714    /// Instead, call `.ident()` on the parent struct/variant, like so:
4715    ///
4716    /// ```ignore (illustrative)
4717    /// ctor
4718    ///     .ctor_hir_id()
4719    ///     .map(|ctor_id| tcx.parent_hir_node(ctor_id))
4720    ///     .and_then(|parent| parent.ident())
4721    /// ```
4722    pub fn ident(&self) -> Option<Ident> {
4723        match self {
4724            Node::Item(item) => item.kind.ident(),
4725            Node::TraitItem(TraitItem { ident, .. })
4726            | Node::ImplItem(ImplItem { ident, .. })
4727            | Node::ForeignItem(ForeignItem { ident, .. })
4728            | Node::Field(FieldDef { ident, .. })
4729            | Node::Variant(Variant { ident, .. })
4730            | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4731            Node::Lifetime(lt) => Some(lt.ident),
4732            Node::GenericParam(p) => Some(p.name.ident()),
4733            Node::AssocItemConstraint(c) => Some(c.ident),
4734            Node::PatField(f) => Some(f.ident),
4735            Node::ExprField(f) => Some(f.ident),
4736            Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4737            Node::Param(..)
4738            | Node::AnonConst(..)
4739            | Node::ConstBlock(..)
4740            | Node::ConstArg(..)
4741            | Node::Expr(..)
4742            | Node::Stmt(..)
4743            | Node::Block(..)
4744            | Node::Ctor(..)
4745            | Node::Pat(..)
4746            | Node::TyPat(..)
4747            | Node::PatExpr(..)
4748            | Node::Arm(..)
4749            | Node::LetStmt(..)
4750            | Node::Crate(..)
4751            | Node::Ty(..)
4752            | Node::TraitRef(..)
4753            | Node::OpaqueTy(..)
4754            | Node::Infer(..)
4755            | Node::WherePredicate(..)
4756            | Node::Synthetic
4757            | Node::Err(..) => None,
4758        }
4759    }
4760
4761    pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4762        match self {
4763            Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4764            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4765            | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4766            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4767                Some(fn_sig.decl)
4768            }
4769            Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4770                Some(fn_decl)
4771            }
4772            _ => None,
4773        }
4774    }
4775
4776    /// Get a `hir::Impl` if the node is an impl block for the given `trait_def_id`.
4777    pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4778        if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4779            && let Some(trait_ref) = impl_block.of_trait
4780            && let Some(trait_id) = trait_ref.trait_def_id()
4781            && trait_id == trait_def_id
4782        {
4783            Some(impl_block)
4784        } else {
4785            None
4786        }
4787    }
4788
4789    pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4790        match self {
4791            Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4792            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4793            | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4794            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4795                Some(fn_sig)
4796            }
4797            _ => None,
4798        }
4799    }
4800
4801    /// Get the type for constants, assoc types, type aliases and statics.
4802    pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4803        match self {
4804            Node::Item(it) => match it.kind {
4805                ItemKind::TyAlias(_, ty, _)
4806                | ItemKind::Static(_, ty, _, _)
4807                | ItemKind::Const(_, ty, _, _) => Some(ty),
4808                ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4809                _ => None,
4810            },
4811            Node::TraitItem(it) => match it.kind {
4812                TraitItemKind::Const(ty, _) => Some(ty),
4813                TraitItemKind::Type(_, ty) => ty,
4814                _ => None,
4815            },
4816            Node::ImplItem(it) => match it.kind {
4817                ImplItemKind::Const(ty, _) => Some(ty),
4818                ImplItemKind::Type(ty) => Some(ty),
4819                _ => None,
4820            },
4821            _ => None,
4822        }
4823    }
4824
4825    pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4826        match self {
4827            Node::Item(Item { kind: ItemKind::TyAlias(_, ty, _), .. }) => Some(ty),
4828            _ => None,
4829        }
4830    }
4831
4832    #[inline]
4833    pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4834        match self {
4835            Node::Item(Item {
4836                owner_id,
4837                kind:
4838                    ItemKind::Const(_, _, _, body)
4839                    | ItemKind::Static(.., body)
4840                    | ItemKind::Fn { body, .. },
4841                ..
4842            })
4843            | Node::TraitItem(TraitItem {
4844                owner_id,
4845                kind:
4846                    TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4847                ..
4848            })
4849            | Node::ImplItem(ImplItem {
4850                owner_id,
4851                kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
4852                ..
4853            }) => Some((owner_id.def_id, *body)),
4854
4855            Node::Item(Item {
4856                owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4857            }) => Some((owner_id.def_id, *fake_body)),
4858
4859            Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4860                Some((*def_id, *body))
4861            }
4862
4863            Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4864            Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4865
4866            _ => None,
4867        }
4868    }
4869
4870    pub fn body_id(&self) -> Option<BodyId> {
4871        Some(self.associated_body()?.1)
4872    }
4873
4874    pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4875        match self {
4876            Node::ForeignItem(ForeignItem {
4877                kind: ForeignItemKind::Fn(_, _, generics), ..
4878            })
4879            | Node::TraitItem(TraitItem { generics, .. })
4880            | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4881            Node::Item(item) => item.kind.generics(),
4882            _ => None,
4883        }
4884    }
4885
4886    pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4887        match self {
4888            Node::Item(i) => Some(OwnerNode::Item(i)),
4889            Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4890            Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4891            Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4892            Node::Crate(i) => Some(OwnerNode::Crate(i)),
4893            Node::Synthetic => Some(OwnerNode::Synthetic),
4894            _ => None,
4895        }
4896    }
4897
4898    pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4899        match self {
4900            Node::Item(i) => match i.kind {
4901                ItemKind::Fn { ident, sig, generics, .. } => {
4902                    Some(FnKind::ItemFn(ident, generics, sig.header))
4903                }
4904                _ => None,
4905            },
4906            Node::TraitItem(ti) => match ti.kind {
4907                TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4908                _ => None,
4909            },
4910            Node::ImplItem(ii) => match ii.kind {
4911                ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4912                _ => None,
4913            },
4914            Node::Expr(e) => match e.kind {
4915                ExprKind::Closure { .. } => Some(FnKind::Closure),
4916                _ => None,
4917            },
4918            _ => None,
4919        }
4920    }
4921
4922    expect_methods_self! {
4923        expect_param,         &'hir Param<'hir>,        Node::Param(n),        n;
4924        expect_item,          &'hir Item<'hir>,         Node::Item(n),         n;
4925        expect_foreign_item,  &'hir ForeignItem<'hir>,  Node::ForeignItem(n),  n;
4926        expect_trait_item,    &'hir TraitItem<'hir>,    Node::TraitItem(n),    n;
4927        expect_impl_item,     &'hir ImplItem<'hir>,     Node::ImplItem(n),     n;
4928        expect_variant,       &'hir Variant<'hir>,      Node::Variant(n),      n;
4929        expect_field,         &'hir FieldDef<'hir>,     Node::Field(n),        n;
4930        expect_anon_const,    &'hir AnonConst,          Node::AnonConst(n),    n;
4931        expect_inline_const,  &'hir ConstBlock,         Node::ConstBlock(n),   n;
4932        expect_expr,          &'hir Expr<'hir>,         Node::Expr(n),         n;
4933        expect_expr_field,    &'hir ExprField<'hir>,    Node::ExprField(n),    n;
4934        expect_stmt,          &'hir Stmt<'hir>,         Node::Stmt(n),         n;
4935        expect_path_segment,  &'hir PathSegment<'hir>,  Node::PathSegment(n),  n;
4936        expect_ty,            &'hir Ty<'hir>,           Node::Ty(n),           n;
4937        expect_assoc_item_constraint,  &'hir AssocItemConstraint<'hir>,  Node::AssocItemConstraint(n),  n;
4938        expect_trait_ref,     &'hir TraitRef<'hir>,     Node::TraitRef(n),     n;
4939        expect_opaque_ty,     &'hir OpaqueTy<'hir>,     Node::OpaqueTy(n),     n;
4940        expect_pat,           &'hir Pat<'hir>,          Node::Pat(n),          n;
4941        expect_pat_field,     &'hir PatField<'hir>,     Node::PatField(n),     n;
4942        expect_arm,           &'hir Arm<'hir>,          Node::Arm(n),          n;
4943        expect_block,         &'hir Block<'hir>,        Node::Block(n),        n;
4944        expect_let_stmt,      &'hir LetStmt<'hir>,      Node::LetStmt(n),      n;
4945        expect_ctor,          &'hir VariantData<'hir>,  Node::Ctor(n),         n;
4946        expect_lifetime,      &'hir Lifetime,           Node::Lifetime(n),     n;
4947        expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4948        expect_crate,         &'hir Mod<'hir>,          Node::Crate(n),        n;
4949        expect_infer,         &'hir InferArg,           Node::Infer(n),        n;
4950        expect_closure,       &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4951    }
4952}
4953
4954// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
4955#[cfg(target_pointer_width = "64")]
4956mod size_asserts {
4957    use rustc_data_structures::static_assert_size;
4958
4959    use super::*;
4960    // tidy-alphabetical-start
4961    static_assert_size!(Block<'_>, 48);
4962    static_assert_size!(Body<'_>, 24);
4963    static_assert_size!(Expr<'_>, 64);
4964    static_assert_size!(ExprKind<'_>, 48);
4965    static_assert_size!(FnDecl<'_>, 40);
4966    static_assert_size!(ForeignItem<'_>, 88);
4967    static_assert_size!(ForeignItemKind<'_>, 56);
4968    static_assert_size!(GenericArg<'_>, 16);
4969    static_assert_size!(GenericBound<'_>, 64);
4970    static_assert_size!(Generics<'_>, 56);
4971    static_assert_size!(Impl<'_>, 80);
4972    static_assert_size!(ImplItem<'_>, 88);
4973    static_assert_size!(ImplItemKind<'_>, 40);
4974    static_assert_size!(Item<'_>, 88);
4975    static_assert_size!(ItemKind<'_>, 64);
4976    static_assert_size!(LetStmt<'_>, 72);
4977    static_assert_size!(Param<'_>, 32);
4978    static_assert_size!(Pat<'_>, 72);
4979    static_assert_size!(Path<'_>, 40);
4980    static_assert_size!(PathSegment<'_>, 48);
4981    static_assert_size!(PatKind<'_>, 48);
4982    static_assert_size!(QPath<'_>, 24);
4983    static_assert_size!(Res, 12);
4984    static_assert_size!(Stmt<'_>, 32);
4985    static_assert_size!(StmtKind<'_>, 16);
4986    static_assert_size!(TraitItem<'_>, 88);
4987    static_assert_size!(TraitItemKind<'_>, 48);
4988    static_assert_size!(Ty<'_>, 48);
4989    static_assert_size!(TyKind<'_>, 32);
4990    // tidy-alphabetical-end
4991}
4992
4993#[cfg(test)]
4994mod tests;