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