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