1use std::fmt;
3
4use rustc_abi::ExternAbi;
5use rustc_ast::attr::AttributeExt;
6use rustc_ast::token::CommentKind;
7use rustc_ast::util::parser::ExprPrecedence;
8use rustc_ast::{
9    self as ast, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitIntType,
10    LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind, join_path_idents,
11};
12pub use rustc_ast::{
13    AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
14    BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
15    MetaItemInner, MetaItemLit, Movability, Mutability, UnOp,
16};
17use rustc_attr_data_structures::AttributeKind;
18use rustc_data_structures::fingerprint::Fingerprint;
19use rustc_data_structures::sorted_map::SortedMap;
20use rustc_data_structures::tagged_ptr::TaggedRef;
21use rustc_index::IndexVec;
22use rustc_macros::{Decodable, Encodable, HashStable_Generic};
23use rustc_span::def_id::LocalDefId;
24use rustc_span::hygiene::MacroKind;
25use rustc_span::source_map::Spanned;
26use rustc_span::{BytePos, DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
27use rustc_target::asm::InlineAsmRegOrRegClass;
28use smallvec::SmallVec;
29use thin_vec::ThinVec;
30use tracing::debug;
31
32use crate::LangItem;
33use crate::def::{CtorKind, DefKind, PerNS, Res};
34use crate::def_id::{DefId, LocalDefIdMap};
35pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId};
36use crate::intravisit::{FnKind, VisitorExt};
37use crate::lints::DelayedLints;
38
39#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
40pub enum AngleBrackets {
41    Missing,
43    Empty,
45    Full,
47}
48
49#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
50pub enum LifetimeSource {
51    Reference,
53
54    Path { angle_brackets: AngleBrackets },
57
58    OutlivesBound,
60
61    PreciseCapturing,
63
64    Other,
71}
72
73#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
74pub enum LifetimeSyntax {
75    Implicit,
77
78    ExplicitAnonymous,
80
81    ExplicitBound,
83}
84
85impl From<Ident> for LifetimeSyntax {
86    fn from(ident: Ident) -> Self {
87        let name = ident.name;
88
89        if name == sym::empty {
90            unreachable!("A lifetime name should never be empty");
91        } else if name == kw::UnderscoreLifetime {
92            LifetimeSyntax::ExplicitAnonymous
93        } else {
94            debug_assert!(name.as_str().starts_with('\''));
95            LifetimeSyntax::ExplicitBound
96        }
97    }
98}
99
100#[derive(Debug, Copy, Clone, HashStable_Generic)]
151pub struct Lifetime {
152    #[stable_hasher(ignore)]
153    pub hir_id: HirId,
154
155    pub ident: Ident,
159
160    pub kind: LifetimeKind,
162
163    pub source: LifetimeSource,
166
167    pub syntax: LifetimeSyntax,
170}
171
172#[derive(Debug, Copy, Clone, HashStable_Generic)]
173pub enum ParamName {
174    Plain(Ident),
176
177    Error(Ident),
183
184    Fresh,
199}
200
201impl ParamName {
202    pub fn ident(&self) -> Ident {
203        match *self {
204            ParamName::Plain(ident) | ParamName::Error(ident) => ident,
205            ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
206        }
207    }
208}
209
210#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
211pub enum LifetimeKind {
212    Param(LocalDefId),
214
215    ImplicitObjectLifetimeDefault,
227
228    Error,
231
232    Infer,
236
237    Static,
239}
240
241impl LifetimeKind {
242    fn is_elided(&self) -> bool {
243        match self {
244            LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true,
245
246            LifetimeKind::Error | LifetimeKind::Param(..) | LifetimeKind::Static => false,
251        }
252    }
253}
254
255impl fmt::Display for Lifetime {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        self.ident.name.fmt(f)
258    }
259}
260
261impl Lifetime {
262    pub fn new(
263        hir_id: HirId,
264        ident: Ident,
265        kind: LifetimeKind,
266        source: LifetimeSource,
267        syntax: LifetimeSyntax,
268    ) -> Lifetime {
269        let lifetime = Lifetime { hir_id, ident, kind, source, syntax };
270
271        #[cfg(debug_assertions)]
273        match (lifetime.is_elided(), lifetime.is_anonymous()) {
274            (false, false) => {} (false, true) => {}  (true, true) => {}   (true, false) => panic!("bad Lifetime"),
278        }
279
280        lifetime
281    }
282
283    pub fn is_elided(&self) -> bool {
284        self.kind.is_elided()
285    }
286
287    pub fn is_anonymous(&self) -> bool {
288        self.ident.name == kw::UnderscoreLifetime
289    }
290
291    pub fn is_implicit(&self) -> bool {
292        matches!(self.syntax, LifetimeSyntax::Implicit)
293    }
294
295    pub fn is_static(&self) -> bool {
296        self.kind == LifetimeKind::Static
297    }
298
299    pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
300        use LifetimeSource::*;
301        use LifetimeSyntax::*;
302
303        debug_assert!(new_lifetime.starts_with('\''));
304
305        match (self.syntax, self.source) {
306            (ExplicitBound | ExplicitAnonymous, _) => (self.ident.span, format!("{new_lifetime}")),
308
309            (Implicit, Path { angle_brackets: AngleBrackets::Full }) => {
311                (self.ident.span, format!("{new_lifetime}, "))
312            }
313
314            (Implicit, Path { angle_brackets: AngleBrackets::Empty }) => {
316                (self.ident.span, format!("{new_lifetime}"))
317            }
318
319            (Implicit, Path { angle_brackets: AngleBrackets::Missing }) => {
321                (self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
322            }
323
324            (Implicit, Reference) => (self.ident.span, format!("{new_lifetime} ")),
326
327            (Implicit, source) => {
328                unreachable!("can't suggest for a implicit lifetime of {source:?}")
329            }
330        }
331    }
332}
333
334#[derive(Debug, Clone, Copy, HashStable_Generic)]
338pub struct Path<'hir, R = Res> {
339    pub span: Span,
340    pub res: R,
342    pub segments: &'hir [PathSegment<'hir>],
344}
345
346pub type UsePath<'hir> = Path<'hir, PerNS<Option<Res>>>;
348
349impl Path<'_> {
350    pub fn is_global(&self) -> bool {
351        self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
352    }
353}
354
355#[derive(Debug, Clone, Copy, HashStable_Generic)]
358pub struct PathSegment<'hir> {
359    pub ident: Ident,
361    #[stable_hasher(ignore)]
362    pub hir_id: HirId,
363    pub res: Res,
364
365    pub args: Option<&'hir GenericArgs<'hir>>,
371
372    pub infer_args: bool,
377}
378
379impl<'hir> PathSegment<'hir> {
380    pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
382        PathSegment { ident, hir_id, res, infer_args: true, args: None }
383    }
384
385    pub fn invalid() -> Self {
386        Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
387    }
388
389    pub fn args(&self) -> &GenericArgs<'hir> {
390        if let Some(ref args) = self.args {
391            args
392        } else {
393            const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
394            DUMMY
395        }
396    }
397}
398
399#[derive(Clone, Copy, Debug, HashStable_Generic)]
415#[repr(C)]
416pub struct ConstArg<'hir, Unambig = ()> {
417    #[stable_hasher(ignore)]
418    pub hir_id: HirId,
419    pub kind: ConstArgKind<'hir, Unambig>,
420}
421
422impl<'hir> ConstArg<'hir, AmbigArg> {
423    pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
434        let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
437        unsafe { &*ptr }
438    }
439}
440
441impl<'hir> ConstArg<'hir> {
442    pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
448        if let ConstArgKind::Infer(_, ()) = self.kind {
449            return None;
450        }
451
452        let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
456        Some(unsafe { &*ptr })
457    }
458}
459
460impl<'hir, Unambig> ConstArg<'hir, Unambig> {
461    pub fn anon_const_hir_id(&self) -> Option<HirId> {
462        match self.kind {
463            ConstArgKind::Anon(ac) => Some(ac.hir_id),
464            _ => None,
465        }
466    }
467
468    pub fn span(&self) -> Span {
469        match self.kind {
470            ConstArgKind::Path(path) => path.span(),
471            ConstArgKind::Anon(anon) => anon.span,
472            ConstArgKind::Infer(span, _) => span,
473        }
474    }
475}
476
477#[derive(Clone, Copy, Debug, HashStable_Generic)]
479#[repr(u8, C)]
480pub enum ConstArgKind<'hir, Unambig = ()> {
481    Path(QPath<'hir>),
487    Anon(&'hir AnonConst),
488    Infer(Span, Unambig),
491}
492
493#[derive(Clone, Copy, Debug, HashStable_Generic)]
494pub struct InferArg {
495    #[stable_hasher(ignore)]
496    pub hir_id: HirId,
497    pub span: Span,
498}
499
500impl InferArg {
501    pub fn to_ty(&self) -> Ty<'static> {
502        Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
503    }
504}
505
506#[derive(Debug, Clone, Copy, HashStable_Generic)]
507pub enum GenericArg<'hir> {
508    Lifetime(&'hir Lifetime),
509    Type(&'hir Ty<'hir, AmbigArg>),
510    Const(&'hir ConstArg<'hir, AmbigArg>),
511    Infer(InferArg),
521}
522
523impl GenericArg<'_> {
524    pub fn span(&self) -> Span {
525        match self {
526            GenericArg::Lifetime(l) => l.ident.span,
527            GenericArg::Type(t) => t.span,
528            GenericArg::Const(c) => c.span(),
529            GenericArg::Infer(i) => i.span,
530        }
531    }
532
533    pub fn hir_id(&self) -> HirId {
534        match self {
535            GenericArg::Lifetime(l) => l.hir_id,
536            GenericArg::Type(t) => t.hir_id,
537            GenericArg::Const(c) => c.hir_id,
538            GenericArg::Infer(i) => i.hir_id,
539        }
540    }
541
542    pub fn descr(&self) -> &'static str {
543        match self {
544            GenericArg::Lifetime(_) => "lifetime",
545            GenericArg::Type(_) => "type",
546            GenericArg::Const(_) => "constant",
547            GenericArg::Infer(_) => "placeholder",
548        }
549    }
550
551    pub fn to_ord(&self) -> ast::ParamKindOrd {
552        match self {
553            GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
554            GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
555                ast::ParamKindOrd::TypeOrConst
556            }
557        }
558    }
559
560    pub fn is_ty_or_const(&self) -> bool {
561        match self {
562            GenericArg::Lifetime(_) => false,
563            GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
564        }
565    }
566}
567
568#[derive(Debug, Clone, Copy, HashStable_Generic)]
570pub struct GenericArgs<'hir> {
571    pub args: &'hir [GenericArg<'hir>],
573    pub constraints: &'hir [AssocItemConstraint<'hir>],
575    pub parenthesized: GenericArgsParentheses,
580    pub span_ext: Span,
593}
594
595impl<'hir> GenericArgs<'hir> {
596    pub const fn none() -> Self {
597        Self {
598            args: &[],
599            constraints: &[],
600            parenthesized: GenericArgsParentheses::No,
601            span_ext: DUMMY_SP,
602        }
603    }
604
605    pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
610        if self.parenthesized != GenericArgsParentheses::ParenSugar {
611            return None;
612        }
613
614        let inputs = self
615            .args
616            .iter()
617            .find_map(|arg| {
618                let GenericArg::Type(ty) = arg else { return None };
619                let TyKind::Tup(tys) = &ty.kind else { return None };
620                Some(tys)
621            })
622            .unwrap();
623
624        Some((inputs, self.paren_sugar_output_inner()))
625    }
626
627    pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
632        (self.parenthesized == GenericArgsParentheses::ParenSugar)
633            .then(|| self.paren_sugar_output_inner())
634    }
635
636    fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
637        let [constraint] = self.constraints.try_into().unwrap();
638        debug_assert_eq!(constraint.ident.name, sym::Output);
639        constraint.ty().unwrap()
640    }
641
642    pub fn has_err(&self) -> Option<ErrorGuaranteed> {
643        self.args
644            .iter()
645            .find_map(|arg| {
646                let GenericArg::Type(ty) = arg else { return None };
647                let TyKind::Err(guar) = ty.kind else { return None };
648                Some(guar)
649            })
650            .or_else(|| {
651                self.constraints.iter().find_map(|constraint| {
652                    let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
653                    Some(guar)
654                })
655            })
656    }
657
658    #[inline]
659    pub fn num_lifetime_params(&self) -> usize {
660        self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
661    }
662
663    #[inline]
664    pub fn has_lifetime_params(&self) -> bool {
665        self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
666    }
667
668    #[inline]
669    pub fn num_generic_params(&self) -> usize {
672        self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
673    }
674
675    pub fn span(&self) -> Option<Span> {
681        let span_ext = self.span_ext()?;
682        Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
683    }
684
685    pub fn span_ext(&self) -> Option<Span> {
687        Some(self.span_ext).filter(|span| !span.is_empty())
688    }
689
690    pub fn is_empty(&self) -> bool {
691        self.args.is_empty()
692    }
693}
694
695#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)]
696pub enum GenericArgsParentheses {
697    No,
698    ReturnTypeNotation,
701    ParenSugar,
703}
704
705#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
707pub struct TraitBoundModifiers {
708    pub constness: BoundConstness,
709    pub polarity: BoundPolarity,
710}
711
712impl TraitBoundModifiers {
713    pub const NONE: Self =
714        TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
715}
716
717#[derive(Clone, Copy, Debug, HashStable_Generic)]
718pub enum GenericBound<'hir> {
719    Trait(PolyTraitRef<'hir>),
720    Outlives(&'hir Lifetime),
721    Use(&'hir [PreciseCapturingArg<'hir>], Span),
722}
723
724impl GenericBound<'_> {
725    pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
726        match self {
727            GenericBound::Trait(data) => Some(&data.trait_ref),
728            _ => None,
729        }
730    }
731
732    pub fn span(&self) -> Span {
733        match self {
734            GenericBound::Trait(t, ..) => t.span,
735            GenericBound::Outlives(l) => l.ident.span,
736            GenericBound::Use(_, span) => *span,
737        }
738    }
739}
740
741pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
742
743#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, Debug)]
744pub enum MissingLifetimeKind {
745    Underscore,
747    Ampersand,
749    Comma,
751    Brackets,
753}
754
755#[derive(Copy, Clone, Debug, HashStable_Generic)]
756pub enum LifetimeParamKind {
757    Explicit,
760
761    Elided(MissingLifetimeKind),
764
765    Error,
767}
768
769#[derive(Debug, Clone, Copy, HashStable_Generic)]
770pub enum GenericParamKind<'hir> {
771    Lifetime {
773        kind: LifetimeParamKind,
774    },
775    Type {
776        default: Option<&'hir Ty<'hir>>,
777        synthetic: bool,
778    },
779    Const {
780        ty: &'hir Ty<'hir>,
781        default: Option<&'hir ConstArg<'hir>>,
783        synthetic: bool,
784    },
785}
786
787#[derive(Debug, Clone, Copy, HashStable_Generic)]
788pub struct GenericParam<'hir> {
789    #[stable_hasher(ignore)]
790    pub hir_id: HirId,
791    pub def_id: LocalDefId,
792    pub name: ParamName,
793    pub span: Span,
794    pub pure_wrt_drop: bool,
795    pub kind: GenericParamKind<'hir>,
796    pub colon_span: Option<Span>,
797    pub source: GenericParamSource,
798}
799
800impl<'hir> GenericParam<'hir> {
801    pub fn is_impl_trait(&self) -> bool {
805        matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
806    }
807
808    pub fn is_elided_lifetime(&self) -> bool {
812        matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
813    }
814}
815
816#[derive(Debug, Clone, Copy, HashStable_Generic)]
823pub enum GenericParamSource {
824    Generics,
826    Binder,
828}
829
830#[derive(Default)]
831pub struct GenericParamCount {
832    pub lifetimes: usize,
833    pub types: usize,
834    pub consts: usize,
835    pub infer: usize,
836}
837
838#[derive(Debug, Clone, Copy, HashStable_Generic)]
841pub struct Generics<'hir> {
842    pub params: &'hir [GenericParam<'hir>],
843    pub predicates: &'hir [WherePredicate<'hir>],
844    pub has_where_clause_predicates: bool,
845    pub where_clause_span: Span,
846    pub span: Span,
847}
848
849impl<'hir> Generics<'hir> {
850    pub const fn empty() -> &'hir Generics<'hir> {
851        const NOPE: Generics<'_> = Generics {
852            params: &[],
853            predicates: &[],
854            has_where_clause_predicates: false,
855            where_clause_span: DUMMY_SP,
856            span: DUMMY_SP,
857        };
858        &NOPE
859    }
860
861    pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
862        self.params.iter().find(|¶m| name == param.name.ident().name)
863    }
864
865    pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
867        if let Some(first) = self.params.first()
868            && self.span.contains(first.span)
869        {
870            Some(first.span.shrink_to_lo())
873        } else {
874            None
875        }
876    }
877
878    pub fn span_for_param_suggestion(&self) -> Option<Span> {
880        self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
881            self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
884        })
885    }
886
887    pub fn tail_span_for_predicate_suggestion(&self) -> Span {
890        let end = self.where_clause_span.shrink_to_hi();
891        if self.has_where_clause_predicates {
892            self.predicates
893                .iter()
894                .rfind(|&p| p.kind.in_where_clause())
895                .map_or(end, |p| p.span)
896                .shrink_to_hi()
897                .to(end)
898        } else {
899            end
900        }
901    }
902
903    pub fn add_where_or_trailing_comma(&self) -> &'static str {
904        if self.has_where_clause_predicates {
905            ","
906        } else if self.where_clause_span.is_empty() {
907            " where"
908        } else {
909            ""
911        }
912    }
913
914    pub fn bounds_for_param(
915        &self,
916        param_def_id: LocalDefId,
917    ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
918        self.predicates.iter().filter_map(move |pred| match pred.kind {
919            WherePredicateKind::BoundPredicate(bp)
920                if bp.is_param_bound(param_def_id.to_def_id()) =>
921            {
922                Some(bp)
923            }
924            _ => None,
925        })
926    }
927
928    pub fn outlives_for_param(
929        &self,
930        param_def_id: LocalDefId,
931    ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
932        self.predicates.iter().filter_map(move |pred| match pred.kind {
933            WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
934            _ => None,
935        })
936    }
937
938    pub fn bounds_span_for_suggestions(
949        &self,
950        param_def_id: LocalDefId,
951    ) -> Option<(Span, Option<Span>)> {
952        self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
953            |bound| {
954                let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
955                    && let [.., segment] = trait_ref.path.segments
956                    && let Some(ret_ty) = segment.args().paren_sugar_output()
957                    && let ret_ty = ret_ty.peel_refs()
958                    && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
959                    && let TraitObjectSyntax::Dyn = tagged_ptr.tag()
960                    && ret_ty.span.can_be_used_for_suggestions()
961                {
962                    Some(ret_ty.span)
963                } else {
964                    None
965                };
966
967                span_for_parentheses.map_or_else(
968                    || {
969                        let bs = bound.span();
972                        bs.can_be_used_for_suggestions().then(|| (bs.shrink_to_hi(), None))
973                    },
974                    |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
975                )
976            },
977        )
978    }
979
980    pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
981        let predicate = &self.predicates[pos];
982        let span = predicate.span;
983
984        if !predicate.kind.in_where_clause() {
985            return span;
988        }
989
990        if pos < self.predicates.len() - 1 {
992            let next_pred = &self.predicates[pos + 1];
993            if next_pred.kind.in_where_clause() {
994                return span.until(next_pred.span);
997            }
998        }
999
1000        if pos > 0 {
1001            let prev_pred = &self.predicates[pos - 1];
1002            if prev_pred.kind.in_where_clause() {
1003                return prev_pred.span.shrink_to_hi().to(span);
1006            }
1007        }
1008
1009        self.where_clause_span
1013    }
1014
1015    pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
1016        let predicate = &self.predicates[predicate_pos];
1017        let bounds = predicate.kind.bounds();
1018
1019        if bounds.len() == 1 {
1020            return self.span_for_predicate_removal(predicate_pos);
1021        }
1022
1023        let bound_span = bounds[bound_pos].span();
1024        if bound_pos < bounds.len() - 1 {
1025            bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
1031        } else {
1032            bound_span.with_lo(bounds[bound_pos - 1].span().hi())
1038        }
1039    }
1040}
1041
1042#[derive(Debug, Clone, Copy, HashStable_Generic)]
1044pub struct WherePredicate<'hir> {
1045    #[stable_hasher(ignore)]
1046    pub hir_id: HirId,
1047    pub span: Span,
1048    pub kind: &'hir WherePredicateKind<'hir>,
1049}
1050
1051#[derive(Debug, Clone, Copy, HashStable_Generic)]
1053pub enum WherePredicateKind<'hir> {
1054    BoundPredicate(WhereBoundPredicate<'hir>),
1056    RegionPredicate(WhereRegionPredicate<'hir>),
1058    EqPredicate(WhereEqPredicate<'hir>),
1060}
1061
1062impl<'hir> WherePredicateKind<'hir> {
1063    pub fn in_where_clause(&self) -> bool {
1064        match self {
1065            WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
1066            WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
1067            WherePredicateKind::EqPredicate(_) => false,
1068        }
1069    }
1070
1071    pub fn bounds(&self) -> GenericBounds<'hir> {
1072        match self {
1073            WherePredicateKind::BoundPredicate(p) => p.bounds,
1074            WherePredicateKind::RegionPredicate(p) => p.bounds,
1075            WherePredicateKind::EqPredicate(_) => &[],
1076        }
1077    }
1078}
1079
1080#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
1081pub enum PredicateOrigin {
1082    WhereClause,
1083    GenericParam,
1084    ImplTrait,
1085}
1086
1087#[derive(Debug, Clone, Copy, HashStable_Generic)]
1089pub struct WhereBoundPredicate<'hir> {
1090    pub origin: PredicateOrigin,
1092    pub bound_generic_params: &'hir [GenericParam<'hir>],
1094    pub bounded_ty: &'hir Ty<'hir>,
1096    pub bounds: GenericBounds<'hir>,
1098}
1099
1100impl<'hir> WhereBoundPredicate<'hir> {
1101    pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
1103        self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
1104    }
1105}
1106
1107#[derive(Debug, Clone, Copy, HashStable_Generic)]
1109pub struct WhereRegionPredicate<'hir> {
1110    pub in_where_clause: bool,
1111    pub lifetime: &'hir Lifetime,
1112    pub bounds: GenericBounds<'hir>,
1113}
1114
1115impl<'hir> WhereRegionPredicate<'hir> {
1116    fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
1118        self.lifetime.kind == LifetimeKind::Param(param_def_id)
1119    }
1120}
1121
1122#[derive(Debug, Clone, Copy, HashStable_Generic)]
1124pub struct WhereEqPredicate<'hir> {
1125    pub lhs_ty: &'hir Ty<'hir>,
1126    pub rhs_ty: &'hir Ty<'hir>,
1127}
1128
1129#[derive(Clone, Copy, Debug)]
1133pub struct ParentedNode<'tcx> {
1134    pub parent: ItemLocalId,
1135    pub node: Node<'tcx>,
1136}
1137
1138#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1140pub enum AttrArgs {
1141    Empty,
1143    Delimited(DelimArgs),
1145    Eq {
1147        eq_span: Span,
1149        expr: MetaItemLit,
1151    },
1152}
1153
1154#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1155pub struct AttrPath {
1156    pub segments: Box<[Ident]>,
1157    pub span: Span,
1158}
1159
1160impl AttrPath {
1161    pub fn from_ast(path: &ast::Path) -> Self {
1162        AttrPath {
1163            segments: path.segments.iter().map(|i| i.ident).collect::<Vec<_>>().into_boxed_slice(),
1164            span: path.span,
1165        }
1166    }
1167}
1168
1169impl fmt::Display for AttrPath {
1170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1171        write!(f, "{}", join_path_idents(&self.segments))
1172    }
1173}
1174
1175#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1176pub struct AttrItem {
1177    pub path: AttrPath,
1179    pub args: AttrArgs,
1180    pub id: HashIgnoredAttrId,
1181    pub style: AttrStyle,
1184    pub span: Span,
1186}
1187
1188#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1191pub struct HashIgnoredAttrId {
1192    pub attr_id: AttrId,
1193}
1194
1195#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1196pub enum Attribute {
1197    Parsed(AttributeKind),
1203
1204    Unparsed(Box<AttrItem>),
1207}
1208
1209impl Attribute {
1210    pub fn get_normal_item(&self) -> &AttrItem {
1211        match &self {
1212            Attribute::Unparsed(normal) => &normal,
1213            _ => panic!("unexpected parsed attribute"),
1214        }
1215    }
1216
1217    pub fn unwrap_normal_item(self) -> AttrItem {
1218        match self {
1219            Attribute::Unparsed(normal) => *normal,
1220            _ => panic!("unexpected parsed attribute"),
1221        }
1222    }
1223
1224    pub fn value_lit(&self) -> Option<&MetaItemLit> {
1225        match &self {
1226            Attribute::Unparsed(n) => match n.as_ref() {
1227                AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1228                _ => None,
1229            },
1230            _ => None,
1231        }
1232    }
1233}
1234
1235impl AttributeExt for Attribute {
1236    #[inline]
1237    fn id(&self) -> AttrId {
1238        match &self {
1239            Attribute::Unparsed(u) => u.id.attr_id,
1240            _ => panic!(),
1241        }
1242    }
1243
1244    #[inline]
1245    fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1246        match &self {
1247            Attribute::Unparsed(n) => match n.as_ref() {
1248                AttrItem { args: AttrArgs::Delimited(d), .. } => {
1249                    ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1250                }
1251                _ => None,
1252            },
1253            _ => None,
1254        }
1255    }
1256
1257    #[inline]
1258    fn value_str(&self) -> Option<Symbol> {
1259        self.value_lit().and_then(|x| x.value_str())
1260    }
1261
1262    #[inline]
1263    fn value_span(&self) -> Option<Span> {
1264        self.value_lit().map(|i| i.span)
1265    }
1266
1267    #[inline]
1269    fn ident(&self) -> Option<Ident> {
1270        match &self {
1271            Attribute::Unparsed(n) => {
1272                if let [ident] = n.path.segments.as_ref() {
1273                    Some(*ident)
1274                } else {
1275                    None
1276                }
1277            }
1278            _ => None,
1279        }
1280    }
1281
1282    #[inline]
1283    fn path_matches(&self, name: &[Symbol]) -> bool {
1284        match &self {
1285            Attribute::Unparsed(n) => {
1286                n.path.segments.len() == name.len()
1287                    && n.path.segments.iter().zip(name).all(|(s, n)| s.name == *n)
1288            }
1289            _ => false,
1290        }
1291    }
1292
1293    #[inline]
1294    fn is_doc_comment(&self) -> bool {
1295        matches!(self, Attribute::Parsed(AttributeKind::DocComment { .. }))
1296    }
1297
1298    #[inline]
1299    fn span(&self) -> Span {
1300        match &self {
1301            Attribute::Unparsed(u) => u.span,
1302            Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1304            Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1305            Attribute::Parsed(AttributeKind::MayDangle(span)) => *span,
1306            Attribute::Parsed(AttributeKind::Ignore { span, .. }) => *span,
1307            Attribute::Parsed(AttributeKind::AutomaticallyDerived(span)) => *span,
1308            a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1309        }
1310    }
1311
1312    #[inline]
1313    fn is_word(&self) -> bool {
1314        match &self {
1315            Attribute::Unparsed(n) => {
1316                matches!(n.args, AttrArgs::Empty)
1317            }
1318            _ => false,
1319        }
1320    }
1321
1322    #[inline]
1323    fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1324        match &self {
1325            Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1326            _ => None,
1327        }
1328    }
1329
1330    #[inline]
1331    fn doc_str(&self) -> Option<Symbol> {
1332        match &self {
1333            Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1334            Attribute::Unparsed(_) if self.has_name(sym::doc) => self.value_str(),
1335            _ => None,
1336        }
1337    }
1338
1339    fn is_automatically_derived_attr(&self) -> bool {
1340        matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)))
1341    }
1342
1343    #[inline]
1344    fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1345        match &self {
1346            Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1347                Some((*comment, *kind))
1348            }
1349            Attribute::Unparsed(_) if self.has_name(sym::doc) => {
1350                self.value_str().map(|s| (s, CommentKind::Line))
1351            }
1352            _ => None,
1353        }
1354    }
1355
1356    fn doc_resolution_scope(&self) -> Option<AttrStyle> {
1357        match self {
1358            Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
1359            Attribute::Unparsed(attr) if self.has_name(sym::doc) && self.value_str().is_some() => {
1360                Some(attr.style)
1361            }
1362            _ => None,
1363        }
1364    }
1365}
1366
1367impl Attribute {
1369    #[inline]
1370    pub fn id(&self) -> AttrId {
1371        AttributeExt::id(self)
1372    }
1373
1374    #[inline]
1375    pub fn name(&self) -> Option<Symbol> {
1376        AttributeExt::name(self)
1377    }
1378
1379    #[inline]
1380    pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1381        AttributeExt::meta_item_list(self)
1382    }
1383
1384    #[inline]
1385    pub fn value_str(&self) -> Option<Symbol> {
1386        AttributeExt::value_str(self)
1387    }
1388
1389    #[inline]
1390    pub fn value_span(&self) -> Option<Span> {
1391        AttributeExt::value_span(self)
1392    }
1393
1394    #[inline]
1395    pub fn ident(&self) -> Option<Ident> {
1396        AttributeExt::ident(self)
1397    }
1398
1399    #[inline]
1400    pub fn path_matches(&self, name: &[Symbol]) -> bool {
1401        AttributeExt::path_matches(self, name)
1402    }
1403
1404    #[inline]
1405    pub fn is_doc_comment(&self) -> bool {
1406        AttributeExt::is_doc_comment(self)
1407    }
1408
1409    #[inline]
1410    pub fn has_name(&self, name: Symbol) -> bool {
1411        AttributeExt::has_name(self, name)
1412    }
1413
1414    #[inline]
1415    pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1416        AttributeExt::has_any_name(self, names)
1417    }
1418
1419    #[inline]
1420    pub fn span(&self) -> Span {
1421        AttributeExt::span(self)
1422    }
1423
1424    #[inline]
1425    pub fn is_word(&self) -> bool {
1426        AttributeExt::is_word(self)
1427    }
1428
1429    #[inline]
1430    pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1431        AttributeExt::path(self)
1432    }
1433
1434    #[inline]
1435    pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1436        AttributeExt::ident_path(self)
1437    }
1438
1439    #[inline]
1440    pub fn doc_str(&self) -> Option<Symbol> {
1441        AttributeExt::doc_str(self)
1442    }
1443
1444    #[inline]
1445    pub fn is_proc_macro_attr(&self) -> bool {
1446        AttributeExt::is_proc_macro_attr(self)
1447    }
1448
1449    #[inline]
1450    pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1451        AttributeExt::doc_str_and_comment_kind(self)
1452    }
1453}
1454
1455#[derive(Debug)]
1457pub struct AttributeMap<'tcx> {
1458    pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1459    pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1461    pub opt_hash: Option<Fingerprint>,
1463}
1464
1465impl<'tcx> AttributeMap<'tcx> {
1466    pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1467        map: SortedMap::new(),
1468        opt_hash: Some(Fingerprint::ZERO),
1469        define_opaque: None,
1470    };
1471
1472    #[inline]
1473    pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1474        self.map.get(&id).copied().unwrap_or(&[])
1475    }
1476}
1477
1478pub struct OwnerNodes<'tcx> {
1482    pub opt_hash_including_bodies: Option<Fingerprint>,
1485    pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1490    pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1492}
1493
1494impl<'tcx> OwnerNodes<'tcx> {
1495    pub fn node(&self) -> OwnerNode<'tcx> {
1496        self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1498    }
1499}
1500
1501impl fmt::Debug for OwnerNodes<'_> {
1502    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1503        f.debug_struct("OwnerNodes")
1504            .field("node", &self.nodes[ItemLocalId::ZERO])
1506            .field(
1507                "parents",
1508                &fmt::from_fn(|f| {
1509                    f.debug_list()
1510                        .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1511                            fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1512                        }))
1513                        .finish()
1514                }),
1515            )
1516            .field("bodies", &self.bodies)
1517            .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1518            .finish()
1519    }
1520}
1521
1522#[derive(Debug, HashStable_Generic)]
1524pub struct OwnerInfo<'hir> {
1525    pub nodes: OwnerNodes<'hir>,
1527    pub parenting: LocalDefIdMap<ItemLocalId>,
1529    pub attrs: AttributeMap<'hir>,
1531    pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1534
1535    pub delayed_lints: DelayedLints,
1538}
1539
1540impl<'tcx> OwnerInfo<'tcx> {
1541    #[inline]
1542    pub fn node(&self) -> OwnerNode<'tcx> {
1543        self.nodes.node()
1544    }
1545}
1546
1547#[derive(Copy, Clone, Debug, HashStable_Generic)]
1548pub enum MaybeOwner<'tcx> {
1549    Owner(&'tcx OwnerInfo<'tcx>),
1550    NonOwner(HirId),
1551    Phantom,
1553}
1554
1555impl<'tcx> MaybeOwner<'tcx> {
1556    pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1557        match self {
1558            MaybeOwner::Owner(i) => Some(i),
1559            MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1560        }
1561    }
1562
1563    pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1564        self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1565    }
1566}
1567
1568#[derive(Debug)]
1575pub struct Crate<'hir> {
1576    pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1577    pub opt_hir_hash: Option<Fingerprint>,
1579}
1580
1581#[derive(Debug, Clone, Copy, HashStable_Generic)]
1582pub struct Closure<'hir> {
1583    pub def_id: LocalDefId,
1584    pub binder: ClosureBinder,
1585    pub constness: Constness,
1586    pub capture_clause: CaptureBy,
1587    pub bound_generic_params: &'hir [GenericParam<'hir>],
1588    pub fn_decl: &'hir FnDecl<'hir>,
1589    pub body: BodyId,
1590    pub fn_decl_span: Span,
1592    pub fn_arg_span: Option<Span>,
1594    pub kind: ClosureKind,
1595}
1596
1597#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1598pub enum ClosureKind {
1599    Closure,
1601    Coroutine(CoroutineKind),
1606    CoroutineClosure(CoroutineDesugaring),
1611}
1612
1613#[derive(Debug, Clone, Copy, HashStable_Generic)]
1617pub struct Block<'hir> {
1618    pub stmts: &'hir [Stmt<'hir>],
1620    pub expr: Option<&'hir Expr<'hir>>,
1623    #[stable_hasher(ignore)]
1624    pub hir_id: HirId,
1625    pub rules: BlockCheckMode,
1627    pub span: Span,
1629    pub targeted_by_break: bool,
1633}
1634
1635impl<'hir> Block<'hir> {
1636    pub fn innermost_block(&self) -> &Block<'hir> {
1637        let mut block = self;
1638        while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1639            block = inner_block;
1640        }
1641        block
1642    }
1643}
1644
1645#[derive(Debug, Clone, Copy, HashStable_Generic)]
1646pub struct TyPat<'hir> {
1647    #[stable_hasher(ignore)]
1648    pub hir_id: HirId,
1649    pub kind: TyPatKind<'hir>,
1650    pub span: Span,
1651}
1652
1653#[derive(Debug, Clone, Copy, HashStable_Generic)]
1654pub struct Pat<'hir> {
1655    #[stable_hasher(ignore)]
1656    pub hir_id: HirId,
1657    pub kind: PatKind<'hir>,
1658    pub span: Span,
1659    pub default_binding_modes: bool,
1662}
1663
1664impl<'hir> Pat<'hir> {
1665    fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1666        if !it(self) {
1667            return false;
1668        }
1669
1670        use PatKind::*;
1671        match self.kind {
1672            Missing => unreachable!(),
1673            Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1674            Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_short_(it),
1675            Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1676            TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1677            Slice(before, slice, after) => {
1678                before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1679            }
1680        }
1681    }
1682
1683    pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1690        self.walk_short_(&mut it)
1691    }
1692
1693    fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1694        if !it(self) {
1695            return;
1696        }
1697
1698        use PatKind::*;
1699        match self.kind {
1700            Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1701            Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1702            Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1703            TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1704            Slice(before, slice, after) => {
1705                before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1706            }
1707        }
1708    }
1709
1710    pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1714        self.walk_(&mut it)
1715    }
1716
1717    pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1721        self.walk(|p| {
1722            it(p);
1723            true
1724        })
1725    }
1726
1727    pub fn is_never_pattern(&self) -> bool {
1729        let mut is_never_pattern = false;
1730        self.walk(|pat| match &pat.kind {
1731            PatKind::Never => {
1732                is_never_pattern = true;
1733                false
1734            }
1735            PatKind::Or(s) => {
1736                is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1737                false
1738            }
1739            _ => true,
1740        });
1741        is_never_pattern
1742    }
1743}
1744
1745#[derive(Debug, Clone, Copy, HashStable_Generic)]
1751pub struct PatField<'hir> {
1752    #[stable_hasher(ignore)]
1753    pub hir_id: HirId,
1754    pub ident: Ident,
1756    pub pat: &'hir Pat<'hir>,
1758    pub is_shorthand: bool,
1759    pub span: Span,
1760}
1761
1762#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1763pub enum RangeEnd {
1764    Included,
1765    Excluded,
1766}
1767
1768impl fmt::Display for RangeEnd {
1769    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1770        f.write_str(match self {
1771            RangeEnd::Included => "..=",
1772            RangeEnd::Excluded => "..",
1773        })
1774    }
1775}
1776
1777#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1781pub struct DotDotPos(u32);
1782
1783impl DotDotPos {
1784    pub fn new(n: Option<usize>) -> Self {
1786        match n {
1787            Some(n) => {
1788                assert!(n < u32::MAX as usize);
1789                Self(n as u32)
1790            }
1791            None => Self(u32::MAX),
1792        }
1793    }
1794
1795    pub fn as_opt_usize(&self) -> Option<usize> {
1796        if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1797    }
1798}
1799
1800impl fmt::Debug for DotDotPos {
1801    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1802        self.as_opt_usize().fmt(f)
1803    }
1804}
1805
1806#[derive(Debug, Clone, Copy, HashStable_Generic)]
1807pub struct PatExpr<'hir> {
1808    #[stable_hasher(ignore)]
1809    pub hir_id: HirId,
1810    pub span: Span,
1811    pub kind: PatExprKind<'hir>,
1812}
1813
1814#[derive(Debug, Clone, Copy, HashStable_Generic)]
1815pub enum PatExprKind<'hir> {
1816    Lit {
1817        lit: Lit,
1818        negated: bool,
1821    },
1822    ConstBlock(ConstBlock),
1823    Path(QPath<'hir>),
1825}
1826
1827#[derive(Debug, Clone, Copy, HashStable_Generic)]
1828pub enum TyPatKind<'hir> {
1829    Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1831
1832    Or(&'hir [TyPat<'hir>]),
1834
1835    Err(ErrorGuaranteed),
1837}
1838
1839#[derive(Debug, Clone, Copy, HashStable_Generic)]
1840pub enum PatKind<'hir> {
1841    Missing,
1843
1844    Wild,
1846
1847    Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1858
1859    Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1862
1863    TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1867
1868    Or(&'hir [Pat<'hir>]),
1871
1872    Never,
1874
1875    Tuple(&'hir [Pat<'hir>], DotDotPos),
1879
1880    Box(&'hir Pat<'hir>),
1882
1883    Deref(&'hir Pat<'hir>),
1885
1886    Ref(&'hir Pat<'hir>, Mutability),
1888
1889    Expr(&'hir PatExpr<'hir>),
1891
1892    Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
1894
1895    Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
1897
1898    Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1908
1909    Err(ErrorGuaranteed),
1911}
1912
1913#[derive(Debug, Clone, Copy, HashStable_Generic)]
1915pub struct Stmt<'hir> {
1916    #[stable_hasher(ignore)]
1917    pub hir_id: HirId,
1918    pub kind: StmtKind<'hir>,
1919    pub span: Span,
1920}
1921
1922#[derive(Debug, Clone, Copy, HashStable_Generic)]
1924pub enum StmtKind<'hir> {
1925    Let(&'hir LetStmt<'hir>),
1927
1928    Item(ItemId),
1930
1931    Expr(&'hir Expr<'hir>),
1933
1934    Semi(&'hir Expr<'hir>),
1936}
1937
1938#[derive(Debug, Clone, Copy, HashStable_Generic)]
1940pub struct LetStmt<'hir> {
1941    pub super_: Option<Span>,
1943    pub pat: &'hir Pat<'hir>,
1944    pub ty: Option<&'hir Ty<'hir>>,
1946    pub init: Option<&'hir Expr<'hir>>,
1948    pub els: Option<&'hir Block<'hir>>,
1950    #[stable_hasher(ignore)]
1951    pub hir_id: HirId,
1952    pub span: Span,
1953    pub source: LocalSource,
1957}
1958
1959#[derive(Debug, Clone, Copy, HashStable_Generic)]
1962pub struct Arm<'hir> {
1963    #[stable_hasher(ignore)]
1964    pub hir_id: HirId,
1965    pub span: Span,
1966    pub pat: &'hir Pat<'hir>,
1968    pub guard: Option<&'hir Expr<'hir>>,
1970    pub body: &'hir Expr<'hir>,
1972}
1973
1974#[derive(Debug, Clone, Copy, HashStable_Generic)]
1980pub struct LetExpr<'hir> {
1981    pub span: Span,
1982    pub pat: &'hir Pat<'hir>,
1983    pub ty: Option<&'hir Ty<'hir>>,
1984    pub init: &'hir Expr<'hir>,
1985    pub recovered: ast::Recovered,
1988}
1989
1990#[derive(Debug, Clone, Copy, HashStable_Generic)]
1991pub struct ExprField<'hir> {
1992    #[stable_hasher(ignore)]
1993    pub hir_id: HirId,
1994    pub ident: Ident,
1995    pub expr: &'hir Expr<'hir>,
1996    pub span: Span,
1997    pub is_shorthand: bool,
1998}
1999
2000#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2001pub enum BlockCheckMode {
2002    DefaultBlock,
2003    UnsafeBlock(UnsafeSource),
2004}
2005
2006#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2007pub enum UnsafeSource {
2008    CompilerGenerated,
2009    UserProvided,
2010}
2011
2012#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
2013pub struct BodyId {
2014    pub hir_id: HirId,
2015}
2016
2017#[derive(Debug, Clone, Copy, HashStable_Generic)]
2039pub struct Body<'hir> {
2040    pub params: &'hir [Param<'hir>],
2041    pub value: &'hir Expr<'hir>,
2042}
2043
2044impl<'hir> Body<'hir> {
2045    pub fn id(&self) -> BodyId {
2046        BodyId { hir_id: self.value.hir_id }
2047    }
2048}
2049
2050#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2052pub enum CoroutineKind {
2053    Desugared(CoroutineDesugaring, CoroutineSource),
2055
2056    Coroutine(Movability),
2058}
2059
2060impl CoroutineKind {
2061    pub fn movability(self) -> Movability {
2062        match self {
2063            CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2064            | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2065            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2066            CoroutineKind::Coroutine(mov) => mov,
2067        }
2068    }
2069
2070    pub fn is_fn_like(self) -> bool {
2071        matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2072    }
2073
2074    pub fn to_plural_string(&self) -> String {
2075        match self {
2076            CoroutineKind::Desugared(d, CoroutineSource::Fn) => format!("{d:#}fn bodies"),
2077            CoroutineKind::Desugared(d, CoroutineSource::Block) => format!("{d:#}blocks"),
2078            CoroutineKind::Desugared(d, CoroutineSource::Closure) => format!("{d:#}closure bodies"),
2079            CoroutineKind::Coroutine(_) => "coroutines".to_string(),
2080        }
2081    }
2082}
2083
2084impl fmt::Display for CoroutineKind {
2085    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2086        match self {
2087            CoroutineKind::Desugared(d, k) => {
2088                d.fmt(f)?;
2089                k.fmt(f)
2090            }
2091            CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2092        }
2093    }
2094}
2095
2096#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
2102pub enum CoroutineSource {
2103    Block,
2105
2106    Closure,
2108
2109    Fn,
2111}
2112
2113impl fmt::Display for CoroutineSource {
2114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2115        match self {
2116            CoroutineSource::Block => "block",
2117            CoroutineSource::Closure => "closure body",
2118            CoroutineSource::Fn => "fn body",
2119        }
2120        .fmt(f)
2121    }
2122}
2123
2124#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2125pub enum CoroutineDesugaring {
2126    Async,
2128
2129    Gen,
2131
2132    AsyncGen,
2135}
2136
2137impl fmt::Display for CoroutineDesugaring {
2138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2139        match self {
2140            CoroutineDesugaring::Async => {
2141                if f.alternate() {
2142                    f.write_str("`async` ")?;
2143                } else {
2144                    f.write_str("async ")?
2145                }
2146            }
2147            CoroutineDesugaring::Gen => {
2148                if f.alternate() {
2149                    f.write_str("`gen` ")?;
2150                } else {
2151                    f.write_str("gen ")?
2152                }
2153            }
2154            CoroutineDesugaring::AsyncGen => {
2155                if f.alternate() {
2156                    f.write_str("`async gen` ")?;
2157                } else {
2158                    f.write_str("async gen ")?
2159                }
2160            }
2161        }
2162
2163        Ok(())
2164    }
2165}
2166
2167#[derive(Copy, Clone, Debug)]
2168pub enum BodyOwnerKind {
2169    Fn,
2171
2172    Closure,
2174
2175    Const { inline: bool },
2177
2178    Static(Mutability),
2180
2181    GlobalAsm,
2183}
2184
2185impl BodyOwnerKind {
2186    pub fn is_fn_or_closure(self) -> bool {
2187        match self {
2188            BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2189            BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2190                false
2191            }
2192        }
2193    }
2194}
2195
2196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2198pub enum ConstContext {
2199    ConstFn,
2201
2202    Static(Mutability),
2204
2205    Const { inline: bool },
2215}
2216
2217impl ConstContext {
2218    pub fn keyword_name(self) -> &'static str {
2222        match self {
2223            Self::Const { .. } => "const",
2224            Self::Static(Mutability::Not) => "static",
2225            Self::Static(Mutability::Mut) => "static mut",
2226            Self::ConstFn => "const fn",
2227        }
2228    }
2229}
2230
2231impl fmt::Display for ConstContext {
2234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2235        match *self {
2236            Self::Const { .. } => write!(f, "constant"),
2237            Self::Static(_) => write!(f, "static"),
2238            Self::ConstFn => write!(f, "constant function"),
2239        }
2240    }
2241}
2242
2243pub type Lit = Spanned<LitKind>;
2248
2249#[derive(Copy, Clone, Debug, HashStable_Generic)]
2258pub struct AnonConst {
2259    #[stable_hasher(ignore)]
2260    pub hir_id: HirId,
2261    pub def_id: LocalDefId,
2262    pub body: BodyId,
2263    pub span: Span,
2264}
2265
2266#[derive(Copy, Clone, Debug, HashStable_Generic)]
2268pub struct ConstBlock {
2269    #[stable_hasher(ignore)]
2270    pub hir_id: HirId,
2271    pub def_id: LocalDefId,
2272    pub body: BodyId,
2273}
2274
2275#[derive(Debug, Clone, Copy, HashStable_Generic)]
2284pub struct Expr<'hir> {
2285    #[stable_hasher(ignore)]
2286    pub hir_id: HirId,
2287    pub kind: ExprKind<'hir>,
2288    pub span: Span,
2289}
2290
2291impl Expr<'_> {
2292    pub fn precedence(&self, has_attr: &dyn Fn(HirId) -> bool) -> ExprPrecedence {
2293        let prefix_attrs_precedence = || -> ExprPrecedence {
2294            if has_attr(self.hir_id) { ExprPrecedence::Prefix } else { ExprPrecedence::Unambiguous }
2295        };
2296
2297        match &self.kind {
2298            ExprKind::Closure(closure) => {
2299                match closure.fn_decl.output {
2300                    FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2301                    FnRetTy::Return(_) => prefix_attrs_precedence(),
2302                }
2303            }
2304
2305            ExprKind::Break(..)
2306            | ExprKind::Ret(..)
2307            | ExprKind::Yield(..)
2308            | ExprKind::Become(..) => ExprPrecedence::Jump,
2309
2310            ExprKind::Binary(op, ..) => op.node.precedence(),
2312            ExprKind::Cast(..) => ExprPrecedence::Cast,
2313
2314            ExprKind::Assign(..) |
2315            ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2316
2317            ExprKind::AddrOf(..)
2319            | ExprKind::Let(..)
2324            | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2325
2326            ExprKind::Array(_)
2328            | ExprKind::Block(..)
2329            | ExprKind::Call(..)
2330            | ExprKind::ConstBlock(_)
2331            | ExprKind::Continue(..)
2332            | ExprKind::Field(..)
2333            | ExprKind::If(..)
2334            | ExprKind::Index(..)
2335            | ExprKind::InlineAsm(..)
2336            | ExprKind::Lit(_)
2337            | ExprKind::Loop(..)
2338            | ExprKind::Match(..)
2339            | ExprKind::MethodCall(..)
2340            | ExprKind::OffsetOf(..)
2341            | ExprKind::Path(..)
2342            | ExprKind::Repeat(..)
2343            | ExprKind::Struct(..)
2344            | ExprKind::Tup(_)
2345            | ExprKind::Type(..)
2346            | ExprKind::UnsafeBinderCast(..)
2347            | ExprKind::Use(..)
2348            | ExprKind::Err(_) => prefix_attrs_precedence(),
2349
2350            ExprKind::DropTemps(expr, ..) => expr.precedence(has_attr),
2351        }
2352    }
2353
2354    pub fn is_syntactic_place_expr(&self) -> bool {
2359        self.is_place_expr(|_| true)
2360    }
2361
2362    pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2367        match self.kind {
2368            ExprKind::Path(QPath::Resolved(_, ref path)) => {
2369                matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2370            }
2371
2372            ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2376
2377            ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2379
2380            ExprKind::Unary(UnOp::Deref, _) => true,
2381
2382            ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2383                allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2384            }
2385
2386            ExprKind::Path(QPath::LangItem(..)) => false,
2388
2389            ExprKind::Err(_guar)
2391            | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2392
2393            ExprKind::Path(QPath::TypeRelative(..))
2396            | ExprKind::Call(..)
2397            | ExprKind::MethodCall(..)
2398            | ExprKind::Use(..)
2399            | ExprKind::Struct(..)
2400            | ExprKind::Tup(..)
2401            | ExprKind::If(..)
2402            | ExprKind::Match(..)
2403            | ExprKind::Closure { .. }
2404            | ExprKind::Block(..)
2405            | ExprKind::Repeat(..)
2406            | ExprKind::Array(..)
2407            | ExprKind::Break(..)
2408            | ExprKind::Continue(..)
2409            | ExprKind::Ret(..)
2410            | ExprKind::Become(..)
2411            | ExprKind::Let(..)
2412            | ExprKind::Loop(..)
2413            | ExprKind::Assign(..)
2414            | ExprKind::InlineAsm(..)
2415            | ExprKind::OffsetOf(..)
2416            | ExprKind::AssignOp(..)
2417            | ExprKind::Lit(_)
2418            | ExprKind::ConstBlock(..)
2419            | ExprKind::Unary(..)
2420            | ExprKind::AddrOf(..)
2421            | ExprKind::Binary(..)
2422            | ExprKind::Yield(..)
2423            | ExprKind::Cast(..)
2424            | ExprKind::DropTemps(..) => false,
2425        }
2426    }
2427
2428    pub fn is_size_lit(&self) -> bool {
2431        matches!(
2432            self.kind,
2433            ExprKind::Lit(Lit {
2434                node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2435                ..
2436            })
2437        )
2438    }
2439
2440    pub fn peel_drop_temps(&self) -> &Self {
2446        let mut expr = self;
2447        while let ExprKind::DropTemps(inner) = &expr.kind {
2448            expr = inner;
2449        }
2450        expr
2451    }
2452
2453    pub fn peel_blocks(&self) -> &Self {
2454        let mut expr = self;
2455        while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2456            expr = inner;
2457        }
2458        expr
2459    }
2460
2461    pub fn peel_borrows(&self) -> &Self {
2462        let mut expr = self;
2463        while let ExprKind::AddrOf(.., inner) = &expr.kind {
2464            expr = inner;
2465        }
2466        expr
2467    }
2468
2469    pub fn can_have_side_effects(&self) -> bool {
2470        match self.peel_drop_temps().kind {
2471            ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2472                false
2473            }
2474            ExprKind::Type(base, _)
2475            | ExprKind::Unary(_, base)
2476            | ExprKind::Field(base, _)
2477            | ExprKind::Index(base, _, _)
2478            | ExprKind::AddrOf(.., base)
2479            | ExprKind::Cast(base, _)
2480            | ExprKind::UnsafeBinderCast(_, base, _) => {
2481                base.can_have_side_effects()
2485            }
2486            ExprKind::Struct(_, fields, init) => {
2487                let init_side_effects = match init {
2488                    StructTailExpr::Base(init) => init.can_have_side_effects(),
2489                    StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2490                };
2491                fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2492                    || init_side_effects
2493            }
2494
2495            ExprKind::Array(args)
2496            | ExprKind::Tup(args)
2497            | ExprKind::Call(
2498                Expr {
2499                    kind:
2500                        ExprKind::Path(QPath::Resolved(
2501                            None,
2502                            Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2503                        )),
2504                    ..
2505                },
2506                args,
2507            ) => args.iter().any(|arg| arg.can_have_side_effects()),
2508            ExprKind::If(..)
2509            | ExprKind::Match(..)
2510            | ExprKind::MethodCall(..)
2511            | ExprKind::Call(..)
2512            | ExprKind::Closure { .. }
2513            | ExprKind::Block(..)
2514            | ExprKind::Repeat(..)
2515            | ExprKind::Break(..)
2516            | ExprKind::Continue(..)
2517            | ExprKind::Ret(..)
2518            | ExprKind::Become(..)
2519            | ExprKind::Let(..)
2520            | ExprKind::Loop(..)
2521            | ExprKind::Assign(..)
2522            | ExprKind::InlineAsm(..)
2523            | ExprKind::AssignOp(..)
2524            | ExprKind::ConstBlock(..)
2525            | ExprKind::Binary(..)
2526            | ExprKind::Yield(..)
2527            | ExprKind::DropTemps(..)
2528            | ExprKind::Err(_) => true,
2529        }
2530    }
2531
2532    pub fn is_approximately_pattern(&self) -> bool {
2534        match &self.kind {
2535            ExprKind::Array(_)
2536            | ExprKind::Call(..)
2537            | ExprKind::Tup(_)
2538            | ExprKind::Lit(_)
2539            | ExprKind::Path(_)
2540            | ExprKind::Struct(..) => true,
2541            _ => false,
2542        }
2543    }
2544
2545    pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2550        match (self.kind, other.kind) {
2551            (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2552            (
2553                ExprKind::Path(QPath::LangItem(item1, _)),
2554                ExprKind::Path(QPath::LangItem(item2, _)),
2555            ) => item1 == item2,
2556            (
2557                ExprKind::Path(QPath::Resolved(None, path1)),
2558                ExprKind::Path(QPath::Resolved(None, path2)),
2559            ) => path1.res == path2.res,
2560            (
2561                ExprKind::Struct(
2562                    QPath::LangItem(LangItem::RangeTo, _),
2563                    [val1],
2564                    StructTailExpr::None,
2565                ),
2566                ExprKind::Struct(
2567                    QPath::LangItem(LangItem::RangeTo, _),
2568                    [val2],
2569                    StructTailExpr::None,
2570                ),
2571            )
2572            | (
2573                ExprKind::Struct(
2574                    QPath::LangItem(LangItem::RangeToInclusive, _),
2575                    [val1],
2576                    StructTailExpr::None,
2577                ),
2578                ExprKind::Struct(
2579                    QPath::LangItem(LangItem::RangeToInclusive, _),
2580                    [val2],
2581                    StructTailExpr::None,
2582                ),
2583            )
2584            | (
2585                ExprKind::Struct(
2586                    QPath::LangItem(LangItem::RangeFrom, _),
2587                    [val1],
2588                    StructTailExpr::None,
2589                ),
2590                ExprKind::Struct(
2591                    QPath::LangItem(LangItem::RangeFrom, _),
2592                    [val2],
2593                    StructTailExpr::None,
2594                ),
2595            )
2596            | (
2597                ExprKind::Struct(
2598                    QPath::LangItem(LangItem::RangeFromCopy, _),
2599                    [val1],
2600                    StructTailExpr::None,
2601                ),
2602                ExprKind::Struct(
2603                    QPath::LangItem(LangItem::RangeFromCopy, _),
2604                    [val2],
2605                    StructTailExpr::None,
2606                ),
2607            ) => val1.expr.equivalent_for_indexing(val2.expr),
2608            (
2609                ExprKind::Struct(
2610                    QPath::LangItem(LangItem::Range, _),
2611                    [val1, val3],
2612                    StructTailExpr::None,
2613                ),
2614                ExprKind::Struct(
2615                    QPath::LangItem(LangItem::Range, _),
2616                    [val2, val4],
2617                    StructTailExpr::None,
2618                ),
2619            )
2620            | (
2621                ExprKind::Struct(
2622                    QPath::LangItem(LangItem::RangeCopy, _),
2623                    [val1, val3],
2624                    StructTailExpr::None,
2625                ),
2626                ExprKind::Struct(
2627                    QPath::LangItem(LangItem::RangeCopy, _),
2628                    [val2, val4],
2629                    StructTailExpr::None,
2630                ),
2631            )
2632            | (
2633                ExprKind::Struct(
2634                    QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2635                    [val1, val3],
2636                    StructTailExpr::None,
2637                ),
2638                ExprKind::Struct(
2639                    QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2640                    [val2, val4],
2641                    StructTailExpr::None,
2642                ),
2643            ) => {
2644                val1.expr.equivalent_for_indexing(val2.expr)
2645                    && val3.expr.equivalent_for_indexing(val4.expr)
2646            }
2647            _ => false,
2648        }
2649    }
2650
2651    pub fn method_ident(&self) -> Option<Ident> {
2652        match self.kind {
2653            ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2654            ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2655            _ => None,
2656        }
2657    }
2658}
2659
2660pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2663    match expr.kind {
2664        ExprKind::Struct(ref qpath, _, _) => matches!(
2666            **qpath,
2667            QPath::LangItem(
2668                LangItem::Range
2669                    | LangItem::RangeTo
2670                    | LangItem::RangeFrom
2671                    | LangItem::RangeFull
2672                    | LangItem::RangeToInclusive
2673                    | LangItem::RangeCopy
2674                    | LangItem::RangeFromCopy
2675                    | LangItem::RangeInclusiveCopy,
2676                ..
2677            )
2678        ),
2679
2680        ExprKind::Call(ref func, _) => {
2682            matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
2683        }
2684
2685        _ => false,
2686    }
2687}
2688
2689pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2696    match expr.kind {
2697        ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2699        _ if is_range_literal(expr) => true,
2701        _ => false,
2702    }
2703}
2704
2705#[derive(Debug, Clone, Copy, HashStable_Generic)]
2706pub enum ExprKind<'hir> {
2707    ConstBlock(ConstBlock),
2709    Array(&'hir [Expr<'hir>]),
2711    Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2718    MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2735    Use(&'hir Expr<'hir>, Span),
2737    Tup(&'hir [Expr<'hir>]),
2739    Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2741    Unary(UnOp, &'hir Expr<'hir>),
2743    Lit(Lit),
2745    Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2747    Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2749    DropTemps(&'hir Expr<'hir>),
2755    Let(&'hir LetExpr<'hir>),
2760    If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2769    Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2775    Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2778    Closure(&'hir Closure<'hir>),
2785    Block(&'hir Block<'hir>, Option<Label>),
2787
2788    Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2790    AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2794    Field(&'hir Expr<'hir>, Ident),
2796    Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2800
2801    Path(QPath<'hir>),
2803
2804    AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2806    Break(Destination, Option<&'hir Expr<'hir>>),
2808    Continue(Destination),
2810    Ret(Option<&'hir Expr<'hir>>),
2812    Become(&'hir Expr<'hir>),
2814
2815    InlineAsm(&'hir InlineAsm<'hir>),
2817
2818    OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2820
2821    Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2826
2827    Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2832
2833    Yield(&'hir Expr<'hir>, YieldSource),
2835
2836    UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2839
2840    Err(rustc_span::ErrorGuaranteed),
2842}
2843
2844#[derive(Debug, Clone, Copy, HashStable_Generic)]
2845pub enum StructTailExpr<'hir> {
2846    None,
2848    Base(&'hir Expr<'hir>),
2851    DefaultFields(Span),
2855}
2856
2857#[derive(Debug, Clone, Copy, HashStable_Generic)]
2863pub enum QPath<'hir> {
2864    Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2871
2872    TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2879
2880    LangItem(LangItem, Span),
2882}
2883
2884impl<'hir> QPath<'hir> {
2885    pub fn span(&self) -> Span {
2887        match *self {
2888            QPath::Resolved(_, path) => path.span,
2889            QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2890            QPath::LangItem(_, span) => span,
2891        }
2892    }
2893
2894    pub fn qself_span(&self) -> Span {
2897        match *self {
2898            QPath::Resolved(_, path) => path.span,
2899            QPath::TypeRelative(qself, _) => qself.span,
2900            QPath::LangItem(_, span) => span,
2901        }
2902    }
2903}
2904
2905#[derive(Copy, Clone, Debug, HashStable_Generic)]
2907pub enum LocalSource {
2908    Normal,
2910    AsyncFn,
2921    AwaitDesugar,
2923    AssignDesugar(Span),
2926    Contract,
2928}
2929
2930#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2932pub enum MatchSource {
2933    Normal,
2935    Postfix,
2937    ForLoopDesugar,
2939    TryDesugar(HirId),
2941    AwaitDesugar,
2943    FormatArgs,
2945}
2946
2947impl MatchSource {
2948    #[inline]
2949    pub const fn name(self) -> &'static str {
2950        use MatchSource::*;
2951        match self {
2952            Normal => "match",
2953            Postfix => ".match",
2954            ForLoopDesugar => "for",
2955            TryDesugar(_) => "?",
2956            AwaitDesugar => ".await",
2957            FormatArgs => "format_args!()",
2958        }
2959    }
2960}
2961
2962#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2964pub enum LoopSource {
2965    Loop,
2967    While,
2969    ForLoop,
2971}
2972
2973impl LoopSource {
2974    pub fn name(self) -> &'static str {
2975        match self {
2976            LoopSource::Loop => "loop",
2977            LoopSource::While => "while",
2978            LoopSource::ForLoop => "for",
2979        }
2980    }
2981}
2982
2983#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2984pub enum LoopIdError {
2985    OutsideLoopScope,
2986    UnlabeledCfInWhileCondition,
2987    UnresolvedLabel,
2988}
2989
2990impl fmt::Display for LoopIdError {
2991    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2992        f.write_str(match self {
2993            LoopIdError::OutsideLoopScope => "not inside loop scope",
2994            LoopIdError::UnlabeledCfInWhileCondition => {
2995                "unlabeled control flow (break or continue) in while condition"
2996            }
2997            LoopIdError::UnresolvedLabel => "label not found",
2998        })
2999    }
3000}
3001
3002#[derive(Copy, Clone, Debug, HashStable_Generic)]
3003pub struct Destination {
3004    pub label: Option<Label>,
3006
3007    pub target_id: Result<HirId, LoopIdError>,
3010}
3011
3012#[derive(Copy, Clone, Debug, HashStable_Generic)]
3014pub enum YieldSource {
3015    Await { expr: Option<HirId> },
3017    Yield,
3019}
3020
3021impl fmt::Display for YieldSource {
3022    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3023        f.write_str(match self {
3024            YieldSource::Await { .. } => "`await`",
3025            YieldSource::Yield => "`yield`",
3026        })
3027    }
3028}
3029
3030#[derive(Debug, Clone, Copy, HashStable_Generic)]
3033pub struct MutTy<'hir> {
3034    pub ty: &'hir Ty<'hir>,
3035    pub mutbl: Mutability,
3036}
3037
3038#[derive(Debug, Clone, Copy, HashStable_Generic)]
3041pub struct FnSig<'hir> {
3042    pub header: FnHeader,
3043    pub decl: &'hir FnDecl<'hir>,
3044    pub span: Span,
3045}
3046
3047#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3051pub struct TraitItemId {
3052    pub owner_id: OwnerId,
3053}
3054
3055impl TraitItemId {
3056    #[inline]
3057    pub fn hir_id(&self) -> HirId {
3058        HirId::make_owner(self.owner_id.def_id)
3060    }
3061}
3062
3063#[derive(Debug, Clone, Copy, HashStable_Generic)]
3068pub struct TraitItem<'hir> {
3069    pub ident: Ident,
3070    pub owner_id: OwnerId,
3071    pub generics: &'hir Generics<'hir>,
3072    pub kind: TraitItemKind<'hir>,
3073    pub span: Span,
3074    pub defaultness: Defaultness,
3075    pub has_delayed_lints: bool,
3076}
3077
3078macro_rules! expect_methods_self_kind {
3079    ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3080        $(
3081            #[track_caller]
3082            pub fn $name(&self) -> $ret_ty {
3083                let $pat = &self.kind else { expect_failed(stringify!($ident), self) };
3084                $ret_val
3085            }
3086        )*
3087    }
3088}
3089
3090macro_rules! expect_methods_self {
3091    ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3092        $(
3093            #[track_caller]
3094            pub fn $name(&self) -> $ret_ty {
3095                let $pat = self else { expect_failed(stringify!($ident), self) };
3096                $ret_val
3097            }
3098        )*
3099    }
3100}
3101
3102#[track_caller]
3103fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3104    panic!("{ident}: found {found:?}")
3105}
3106
3107impl<'hir> TraitItem<'hir> {
3108    #[inline]
3109    pub fn hir_id(&self) -> HirId {
3110        HirId::make_owner(self.owner_id.def_id)
3112    }
3113
3114    pub fn trait_item_id(&self) -> TraitItemId {
3115        TraitItemId { owner_id: self.owner_id }
3116    }
3117
3118    expect_methods_self_kind! {
3119        expect_const, (&'hir Ty<'hir>, Option<BodyId>),
3120            TraitItemKind::Const(ty, body), (ty, *body);
3121
3122        expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3123            TraitItemKind::Fn(ty, trfn), (ty, trfn);
3124
3125        expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3126            TraitItemKind::Type(bounds, ty), (bounds, *ty);
3127    }
3128}
3129
3130#[derive(Debug, Clone, Copy, HashStable_Generic)]
3132pub enum TraitFn<'hir> {
3133    Required(&'hir [Option<Ident>]),
3135
3136    Provided(BodyId),
3138}
3139
3140#[derive(Debug, Clone, Copy, HashStable_Generic)]
3142pub enum TraitItemKind<'hir> {
3143    Const(&'hir Ty<'hir>, Option<BodyId>),
3145    Fn(FnSig<'hir>, TraitFn<'hir>),
3147    Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3150}
3151
3152#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3156pub struct ImplItemId {
3157    pub owner_id: OwnerId,
3158}
3159
3160impl ImplItemId {
3161    #[inline]
3162    pub fn hir_id(&self) -> HirId {
3163        HirId::make_owner(self.owner_id.def_id)
3165    }
3166}
3167
3168#[derive(Debug, Clone, Copy, HashStable_Generic)]
3172pub struct ImplItem<'hir> {
3173    pub ident: Ident,
3174    pub owner_id: OwnerId,
3175    pub generics: &'hir Generics<'hir>,
3176    pub kind: ImplItemKind<'hir>,
3177    pub defaultness: Defaultness,
3178    pub span: Span,
3179    pub vis_span: Span,
3180    pub has_delayed_lints: bool,
3181    pub trait_item_def_id: Option<DefId>,
3183}
3184
3185impl<'hir> ImplItem<'hir> {
3186    #[inline]
3187    pub fn hir_id(&self) -> HirId {
3188        HirId::make_owner(self.owner_id.def_id)
3190    }
3191
3192    pub fn impl_item_id(&self) -> ImplItemId {
3193        ImplItemId { owner_id: self.owner_id }
3194    }
3195
3196    expect_methods_self_kind! {
3197        expect_const, (&'hir Ty<'hir>, BodyId), ImplItemKind::Const(ty, body), (ty, *body);
3198        expect_fn,    (&FnSig<'hir>, BodyId),   ImplItemKind::Fn(ty, body),    (ty, *body);
3199        expect_type,  &'hir Ty<'hir>,           ImplItemKind::Type(ty),        ty;
3200    }
3201}
3202
3203#[derive(Debug, Clone, Copy, HashStable_Generic)]
3205pub enum ImplItemKind<'hir> {
3206    Const(&'hir Ty<'hir>, BodyId),
3209    Fn(FnSig<'hir>, BodyId),
3211    Type(&'hir Ty<'hir>),
3213}
3214
3215#[derive(Debug, Clone, Copy, HashStable_Generic)]
3226pub struct AssocItemConstraint<'hir> {
3227    #[stable_hasher(ignore)]
3228    pub hir_id: HirId,
3229    pub ident: Ident,
3230    pub gen_args: &'hir GenericArgs<'hir>,
3231    pub kind: AssocItemConstraintKind<'hir>,
3232    pub span: Span,
3233}
3234
3235impl<'hir> AssocItemConstraint<'hir> {
3236    pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3238        match self.kind {
3239            AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3240            _ => None,
3241        }
3242    }
3243
3244    pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3246        match self.kind {
3247            AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3248            _ => None,
3249        }
3250    }
3251}
3252
3253#[derive(Debug, Clone, Copy, HashStable_Generic)]
3254pub enum Term<'hir> {
3255    Ty(&'hir Ty<'hir>),
3256    Const(&'hir ConstArg<'hir>),
3257}
3258
3259impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3260    fn from(ty: &'hir Ty<'hir>) -> Self {
3261        Term::Ty(ty)
3262    }
3263}
3264
3265impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3266    fn from(c: &'hir ConstArg<'hir>) -> Self {
3267        Term::Const(c)
3268    }
3269}
3270
3271#[derive(Debug, Clone, Copy, HashStable_Generic)]
3273pub enum AssocItemConstraintKind<'hir> {
3274    Equality { term: Term<'hir> },
3281    Bound { bounds: &'hir [GenericBound<'hir>] },
3283}
3284
3285impl<'hir> AssocItemConstraintKind<'hir> {
3286    pub fn descr(&self) -> &'static str {
3287        match self {
3288            AssocItemConstraintKind::Equality { .. } => "binding",
3289            AssocItemConstraintKind::Bound { .. } => "constraint",
3290        }
3291    }
3292}
3293
3294#[derive(Debug, Clone, Copy, HashStable_Generic)]
3298pub enum AmbigArg {}
3299
3300#[derive(Debug, Clone, Copy, HashStable_Generic)]
3301#[repr(C)]
3302pub struct Ty<'hir, Unambig = ()> {
3309    #[stable_hasher(ignore)]
3310    pub hir_id: HirId,
3311    pub span: Span,
3312    pub kind: TyKind<'hir, Unambig>,
3313}
3314
3315impl<'hir> Ty<'hir, AmbigArg> {
3316    pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3327        let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3330        unsafe { &*ptr }
3331    }
3332}
3333
3334impl<'hir> Ty<'hir> {
3335    pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3341        if let TyKind::Infer(()) = self.kind {
3342            return None;
3343        }
3344
3345        let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3349        Some(unsafe { &*ptr })
3350    }
3351}
3352
3353impl<'hir> Ty<'hir, AmbigArg> {
3354    pub fn peel_refs(&self) -> &Ty<'hir> {
3355        let mut final_ty = self.as_unambig_ty();
3356        while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3357            final_ty = ty;
3358        }
3359        final_ty
3360    }
3361}
3362
3363impl<'hir> Ty<'hir> {
3364    pub fn peel_refs(&self) -> &Self {
3365        let mut final_ty = self;
3366        while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3367            final_ty = ty;
3368        }
3369        final_ty
3370    }
3371
3372    pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3374        let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3375            return None;
3376        };
3377        let [segment] = &path.segments else {
3378            return None;
3379        };
3380        match path.res {
3381            Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3382                Some((def_id, segment.ident))
3383            }
3384            _ => None,
3385        }
3386    }
3387
3388    pub fn find_self_aliases(&self) -> Vec<Span> {
3389        use crate::intravisit::Visitor;
3390        struct MyVisitor(Vec<Span>);
3391        impl<'v> Visitor<'v> for MyVisitor {
3392            fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3393                if matches!(
3394                    &t.kind,
3395                    TyKind::Path(QPath::Resolved(
3396                        _,
3397                        Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3398                    ))
3399                ) {
3400                    self.0.push(t.span);
3401                    return;
3402                }
3403                crate::intravisit::walk_ty(self, t);
3404            }
3405        }
3406
3407        let mut my_visitor = MyVisitor(vec![]);
3408        my_visitor.visit_ty_unambig(self);
3409        my_visitor.0
3410    }
3411
3412    pub fn is_suggestable_infer_ty(&self) -> bool {
3415        fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3416            generic_args.iter().any(|arg| match arg {
3417                GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3418                GenericArg::Infer(_) => true,
3419                _ => false,
3420            })
3421        }
3422        debug!(?self);
3423        match &self.kind {
3424            TyKind::Infer(()) => true,
3425            TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3426            TyKind::Array(ty, length) => {
3427                ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3428            }
3429            TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3430            TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3431            TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3432                ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3433            }
3434            TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3435                ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3436                    || segments
3437                        .iter()
3438                        .any(|segment| are_suggestable_generic_args(segment.args().args))
3439            }
3440            _ => false,
3441        }
3442    }
3443}
3444
3445#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3447pub enum PrimTy {
3448    Int(IntTy),
3449    Uint(UintTy),
3450    Float(FloatTy),
3451    Str,
3452    Bool,
3453    Char,
3454}
3455
3456impl PrimTy {
3457    pub const ALL: [Self; 19] = [
3459        Self::Int(IntTy::I8),
3461        Self::Int(IntTy::I16),
3462        Self::Int(IntTy::I32),
3463        Self::Int(IntTy::I64),
3464        Self::Int(IntTy::I128),
3465        Self::Int(IntTy::Isize),
3466        Self::Uint(UintTy::U8),
3467        Self::Uint(UintTy::U16),
3468        Self::Uint(UintTy::U32),
3469        Self::Uint(UintTy::U64),
3470        Self::Uint(UintTy::U128),
3471        Self::Uint(UintTy::Usize),
3472        Self::Float(FloatTy::F16),
3473        Self::Float(FloatTy::F32),
3474        Self::Float(FloatTy::F64),
3475        Self::Float(FloatTy::F128),
3476        Self::Bool,
3477        Self::Char,
3478        Self::Str,
3479    ];
3480
3481    pub fn name_str(self) -> &'static str {
3485        match self {
3486            PrimTy::Int(i) => i.name_str(),
3487            PrimTy::Uint(u) => u.name_str(),
3488            PrimTy::Float(f) => f.name_str(),
3489            PrimTy::Str => "str",
3490            PrimTy::Bool => "bool",
3491            PrimTy::Char => "char",
3492        }
3493    }
3494
3495    pub fn name(self) -> Symbol {
3496        match self {
3497            PrimTy::Int(i) => i.name(),
3498            PrimTy::Uint(u) => u.name(),
3499            PrimTy::Float(f) => f.name(),
3500            PrimTy::Str => sym::str,
3501            PrimTy::Bool => sym::bool,
3502            PrimTy::Char => sym::char,
3503        }
3504    }
3505
3506    pub fn from_name(name: Symbol) -> Option<Self> {
3509        let ty = match name {
3510            sym::i8 => Self::Int(IntTy::I8),
3512            sym::i16 => Self::Int(IntTy::I16),
3513            sym::i32 => Self::Int(IntTy::I32),
3514            sym::i64 => Self::Int(IntTy::I64),
3515            sym::i128 => Self::Int(IntTy::I128),
3516            sym::isize => Self::Int(IntTy::Isize),
3517            sym::u8 => Self::Uint(UintTy::U8),
3518            sym::u16 => Self::Uint(UintTy::U16),
3519            sym::u32 => Self::Uint(UintTy::U32),
3520            sym::u64 => Self::Uint(UintTy::U64),
3521            sym::u128 => Self::Uint(UintTy::U128),
3522            sym::usize => Self::Uint(UintTy::Usize),
3523            sym::f16 => Self::Float(FloatTy::F16),
3524            sym::f32 => Self::Float(FloatTy::F32),
3525            sym::f64 => Self::Float(FloatTy::F64),
3526            sym::f128 => Self::Float(FloatTy::F128),
3527            sym::bool => Self::Bool,
3528            sym::char => Self::Char,
3529            sym::str => Self::Str,
3530            _ => return None,
3531        };
3532        Some(ty)
3533    }
3534}
3535
3536#[derive(Debug, Clone, Copy, HashStable_Generic)]
3537pub struct FnPtrTy<'hir> {
3538    pub safety: Safety,
3539    pub abi: ExternAbi,
3540    pub generic_params: &'hir [GenericParam<'hir>],
3541    pub decl: &'hir FnDecl<'hir>,
3542    pub param_idents: &'hir [Option<Ident>],
3545}
3546
3547#[derive(Debug, Clone, Copy, HashStable_Generic)]
3548pub struct UnsafeBinderTy<'hir> {
3549    pub generic_params: &'hir [GenericParam<'hir>],
3550    pub inner_ty: &'hir Ty<'hir>,
3551}
3552
3553#[derive(Debug, Clone, Copy, HashStable_Generic)]
3554pub struct OpaqueTy<'hir> {
3555    #[stable_hasher(ignore)]
3556    pub hir_id: HirId,
3557    pub def_id: LocalDefId,
3558    pub bounds: GenericBounds<'hir>,
3559    pub origin: OpaqueTyOrigin<LocalDefId>,
3560    pub span: Span,
3561}
3562
3563#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3564pub enum PreciseCapturingArgKind<T, U> {
3565    Lifetime(T),
3566    Param(U),
3568}
3569
3570pub type PreciseCapturingArg<'hir> =
3571    PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3572
3573impl PreciseCapturingArg<'_> {
3574    pub fn hir_id(self) -> HirId {
3575        match self {
3576            PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3577            PreciseCapturingArg::Param(param) => param.hir_id,
3578        }
3579    }
3580
3581    pub fn name(self) -> Symbol {
3582        match self {
3583            PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3584            PreciseCapturingArg::Param(param) => param.ident.name,
3585        }
3586    }
3587}
3588
3589#[derive(Debug, Clone, Copy, HashStable_Generic)]
3594pub struct PreciseCapturingNonLifetimeArg {
3595    #[stable_hasher(ignore)]
3596    pub hir_id: HirId,
3597    pub ident: Ident,
3598    pub res: Res,
3599}
3600
3601#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3602#[derive(HashStable_Generic, Encodable, Decodable)]
3603pub enum RpitContext {
3604    Trait,
3605    TraitImpl,
3606}
3607
3608#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3610#[derive(HashStable_Generic, Encodable, Decodable)]
3611pub enum OpaqueTyOrigin<D> {
3612    FnReturn {
3614        parent: D,
3616        in_trait_or_impl: Option<RpitContext>,
3618    },
3619    AsyncFn {
3621        parent: D,
3623        in_trait_or_impl: Option<RpitContext>,
3625    },
3626    TyAlias {
3628        parent: D,
3630        in_assoc_ty: bool,
3632    },
3633}
3634
3635#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3636pub enum InferDelegationKind {
3637    Input(usize),
3638    Output,
3639}
3640
3641#[derive(Debug, Clone, Copy, HashStable_Generic)]
3643#[repr(u8, C)]
3645pub enum TyKind<'hir, Unambig = ()> {
3646    InferDelegation(DefId, InferDelegationKind),
3648    Slice(&'hir Ty<'hir>),
3650    Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3652    Ptr(MutTy<'hir>),
3654    Ref(&'hir Lifetime, MutTy<'hir>),
3656    FnPtr(&'hir FnPtrTy<'hir>),
3658    UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3660    Never,
3662    Tup(&'hir [Ty<'hir>]),
3664    Path(QPath<'hir>),
3669    OpaqueDef(&'hir OpaqueTy<'hir>),
3671    TraitAscription(GenericBounds<'hir>),
3673    TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3679    Typeof(&'hir AnonConst),
3681    Err(rustc_span::ErrorGuaranteed),
3683    Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3685    Infer(Unambig),
3691}
3692
3693#[derive(Debug, Clone, Copy, HashStable_Generic)]
3694pub enum InlineAsmOperand<'hir> {
3695    In {
3696        reg: InlineAsmRegOrRegClass,
3697        expr: &'hir Expr<'hir>,
3698    },
3699    Out {
3700        reg: InlineAsmRegOrRegClass,
3701        late: bool,
3702        expr: Option<&'hir Expr<'hir>>,
3703    },
3704    InOut {
3705        reg: InlineAsmRegOrRegClass,
3706        late: bool,
3707        expr: &'hir Expr<'hir>,
3708    },
3709    SplitInOut {
3710        reg: InlineAsmRegOrRegClass,
3711        late: bool,
3712        in_expr: &'hir Expr<'hir>,
3713        out_expr: Option<&'hir Expr<'hir>>,
3714    },
3715    Const {
3716        anon_const: ConstBlock,
3717    },
3718    SymFn {
3719        expr: &'hir Expr<'hir>,
3720    },
3721    SymStatic {
3722        path: QPath<'hir>,
3723        def_id: DefId,
3724    },
3725    Label {
3726        block: &'hir Block<'hir>,
3727    },
3728}
3729
3730impl<'hir> InlineAsmOperand<'hir> {
3731    pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3732        match *self {
3733            Self::In { reg, .. }
3734            | Self::Out { reg, .. }
3735            | Self::InOut { reg, .. }
3736            | Self::SplitInOut { reg, .. } => Some(reg),
3737            Self::Const { .. }
3738            | Self::SymFn { .. }
3739            | Self::SymStatic { .. }
3740            | Self::Label { .. } => None,
3741        }
3742    }
3743
3744    pub fn is_clobber(&self) -> bool {
3745        matches!(
3746            self,
3747            InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3748        )
3749    }
3750}
3751
3752#[derive(Debug, Clone, Copy, HashStable_Generic)]
3753pub struct InlineAsm<'hir> {
3754    pub asm_macro: ast::AsmMacro,
3755    pub template: &'hir [InlineAsmTemplatePiece],
3756    pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3757    pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3758    pub options: InlineAsmOptions,
3759    pub line_spans: &'hir [Span],
3760}
3761
3762impl InlineAsm<'_> {
3763    pub fn contains_label(&self) -> bool {
3764        self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3765    }
3766}
3767
3768#[derive(Debug, Clone, Copy, HashStable_Generic)]
3770pub struct Param<'hir> {
3771    #[stable_hasher(ignore)]
3772    pub hir_id: HirId,
3773    pub pat: &'hir Pat<'hir>,
3774    pub ty_span: Span,
3775    pub span: Span,
3776}
3777
3778#[derive(Debug, Clone, Copy, HashStable_Generic)]
3780pub struct FnDecl<'hir> {
3781    pub inputs: &'hir [Ty<'hir>],
3785    pub output: FnRetTy<'hir>,
3786    pub c_variadic: bool,
3787    pub implicit_self: ImplicitSelfKind,
3789    pub lifetime_elision_allowed: bool,
3791}
3792
3793impl<'hir> FnDecl<'hir> {
3794    pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3795        if let FnRetTy::Return(ty) = self.output
3796            && let TyKind::InferDelegation(sig_id, _) = ty.kind
3797        {
3798            return Some(sig_id);
3799        }
3800        None
3801    }
3802}
3803
3804#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3806pub enum ImplicitSelfKind {
3807    Imm,
3809    Mut,
3811    RefImm,
3813    RefMut,
3815    None,
3818}
3819
3820impl ImplicitSelfKind {
3821    pub fn has_implicit_self(&self) -> bool {
3823        !matches!(*self, ImplicitSelfKind::None)
3824    }
3825}
3826
3827#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3828pub enum IsAsync {
3829    Async(Span),
3830    NotAsync,
3831}
3832
3833impl IsAsync {
3834    pub fn is_async(self) -> bool {
3835        matches!(self, IsAsync::Async(_))
3836    }
3837}
3838
3839#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3840pub enum Defaultness {
3841    Default { has_value: bool },
3842    Final,
3843}
3844
3845impl Defaultness {
3846    pub fn has_value(&self) -> bool {
3847        match *self {
3848            Defaultness::Default { has_value } => has_value,
3849            Defaultness::Final => true,
3850        }
3851    }
3852
3853    pub fn is_final(&self) -> bool {
3854        *self == Defaultness::Final
3855    }
3856
3857    pub fn is_default(&self) -> bool {
3858        matches!(*self, Defaultness::Default { .. })
3859    }
3860}
3861
3862#[derive(Debug, Clone, Copy, HashStable_Generic)]
3863pub enum FnRetTy<'hir> {
3864    DefaultReturn(Span),
3870    Return(&'hir Ty<'hir>),
3872}
3873
3874impl<'hir> FnRetTy<'hir> {
3875    #[inline]
3876    pub fn span(&self) -> Span {
3877        match *self {
3878            Self::DefaultReturn(span) => span,
3879            Self::Return(ref ty) => ty.span,
3880        }
3881    }
3882
3883    pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3884        if let Self::Return(ty) = self
3885            && ty.is_suggestable_infer_ty()
3886        {
3887            return Some(*ty);
3888        }
3889        None
3890    }
3891}
3892
3893#[derive(Copy, Clone, Debug, HashStable_Generic)]
3895pub enum ClosureBinder {
3896    Default,
3898    For { span: Span },
3902}
3903
3904#[derive(Debug, Clone, Copy, HashStable_Generic)]
3905pub struct Mod<'hir> {
3906    pub spans: ModSpans,
3907    pub item_ids: &'hir [ItemId],
3908}
3909
3910#[derive(Copy, Clone, Debug, HashStable_Generic)]
3911pub struct ModSpans {
3912    pub inner_span: Span,
3916    pub inject_use_span: Span,
3917}
3918
3919#[derive(Debug, Clone, Copy, HashStable_Generic)]
3920pub struct EnumDef<'hir> {
3921    pub variants: &'hir [Variant<'hir>],
3922}
3923
3924#[derive(Debug, Clone, Copy, HashStable_Generic)]
3925pub struct Variant<'hir> {
3926    pub ident: Ident,
3928    #[stable_hasher(ignore)]
3930    pub hir_id: HirId,
3931    pub def_id: LocalDefId,
3932    pub data: VariantData<'hir>,
3934    pub disr_expr: Option<&'hir AnonConst>,
3936    pub span: Span,
3938}
3939
3940#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3941pub enum UseKind {
3942    Single(Ident),
3949
3950    Glob,
3952
3953    ListStem,
3957}
3958
3959#[derive(Clone, Debug, Copy, HashStable_Generic)]
3966pub struct TraitRef<'hir> {
3967    pub path: &'hir Path<'hir>,
3968    #[stable_hasher(ignore)]
3970    pub hir_ref_id: HirId,
3971}
3972
3973impl TraitRef<'_> {
3974    pub fn trait_def_id(&self) -> Option<DefId> {
3976        match self.path.res {
3977            Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3978            Res::Err => None,
3979            res => panic!("{res:?} did not resolve to a trait or trait alias"),
3980        }
3981    }
3982}
3983
3984#[derive(Clone, Debug, Copy, HashStable_Generic)]
3985pub struct PolyTraitRef<'hir> {
3986    pub bound_generic_params: &'hir [GenericParam<'hir>],
3988
3989    pub modifiers: TraitBoundModifiers,
3993
3994    pub trait_ref: TraitRef<'hir>,
3996
3997    pub span: Span,
3998}
3999
4000#[derive(Debug, Clone, Copy, HashStable_Generic)]
4001pub struct FieldDef<'hir> {
4002    pub span: Span,
4003    pub vis_span: Span,
4004    pub ident: Ident,
4005    #[stable_hasher(ignore)]
4006    pub hir_id: HirId,
4007    pub def_id: LocalDefId,
4008    pub ty: &'hir Ty<'hir>,
4009    pub safety: Safety,
4010    pub default: Option<&'hir AnonConst>,
4011}
4012
4013impl FieldDef<'_> {
4014    pub fn is_positional(&self) -> bool {
4016        self.ident.as_str().as_bytes()[0].is_ascii_digit()
4017    }
4018}
4019
4020#[derive(Debug, Clone, Copy, HashStable_Generic)]
4022pub enum VariantData<'hir> {
4023    Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4027    Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4031    Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4035}
4036
4037impl<'hir> VariantData<'hir> {
4038    pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4040        match *self {
4041            VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4042            _ => &[],
4043        }
4044    }
4045
4046    pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4047        match *self {
4048            VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4049            VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4050            VariantData::Struct { .. } => None,
4051        }
4052    }
4053
4054    #[inline]
4055    pub fn ctor_kind(&self) -> Option<CtorKind> {
4056        self.ctor().map(|(kind, ..)| kind)
4057    }
4058
4059    #[inline]
4061    pub fn ctor_hir_id(&self) -> Option<HirId> {
4062        self.ctor().map(|(_, hir_id, _)| hir_id)
4063    }
4064
4065    #[inline]
4067    pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4068        self.ctor().map(|(.., def_id)| def_id)
4069    }
4070}
4071
4072#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4076pub struct ItemId {
4077    pub owner_id: OwnerId,
4078}
4079
4080impl ItemId {
4081    #[inline]
4082    pub fn hir_id(&self) -> HirId {
4083        HirId::make_owner(self.owner_id.def_id)
4085    }
4086}
4087
4088#[derive(Debug, Clone, Copy, HashStable_Generic)]
4097pub struct Item<'hir> {
4098    pub owner_id: OwnerId,
4099    pub kind: ItemKind<'hir>,
4100    pub span: Span,
4101    pub vis_span: Span,
4102    pub has_delayed_lints: bool,
4103}
4104
4105impl<'hir> Item<'hir> {
4106    #[inline]
4107    pub fn hir_id(&self) -> HirId {
4108        HirId::make_owner(self.owner_id.def_id)
4110    }
4111
4112    pub fn item_id(&self) -> ItemId {
4113        ItemId { owner_id: self.owner_id }
4114    }
4115
4116    pub fn is_adt(&self) -> bool {
4119        matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4120    }
4121
4122    pub fn is_struct_or_union(&self) -> bool {
4124        matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4125    }
4126
4127    expect_methods_self_kind! {
4128        expect_extern_crate, (Option<Symbol>, Ident),
4129            ItemKind::ExternCrate(s, ident), (*s, *ident);
4130
4131        expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4132
4133        expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4134            ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4135
4136        expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, BodyId),
4137            ItemKind::Const(ident, generics, ty, body), (*ident, generics, ty, *body);
4138
4139        expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4140            ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4141
4142        expect_macro, (Ident, &ast::MacroDef, MacroKind),
4143            ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4144
4145        expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4146
4147        expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]),
4148            ItemKind::ForeignMod { abi, items }, (*abi, items);
4149
4150        expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4151
4152        expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4153            ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4154
4155        expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4156            ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4157
4158        expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4159            ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4160
4161        expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4162            ItemKind::Union(ident, generics, data), (*ident, generics, data);
4163
4164        expect_trait,
4165            (
4166                Constness,
4167                IsAuto,
4168                Safety,
4169                Ident,
4170                &'hir Generics<'hir>,
4171                GenericBounds<'hir>,
4172                &'hir [TraitItemId]
4173            ),
4174            ItemKind::Trait(constness, is_auto, safety, ident, generics, bounds, items),
4175            (*constness, *is_auto, *safety, *ident, generics, bounds, items);
4176
4177        expect_trait_alias, (Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4178            ItemKind::TraitAlias(ident, generics, bounds), (*ident, generics, bounds);
4179
4180        expect_impl, &'hir Impl<'hir>, ItemKind::Impl(imp), imp;
4181    }
4182}
4183
4184#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4185#[derive(Encodable, Decodable, HashStable_Generic)]
4186pub enum Safety {
4187    Unsafe,
4188    Safe,
4189}
4190
4191impl Safety {
4192    pub fn prefix_str(self) -> &'static str {
4193        match self {
4194            Self::Unsafe => "unsafe ",
4195            Self::Safe => "",
4196        }
4197    }
4198
4199    #[inline]
4200    pub fn is_unsafe(self) -> bool {
4201        !self.is_safe()
4202    }
4203
4204    #[inline]
4205    pub fn is_safe(self) -> bool {
4206        match self {
4207            Self::Unsafe => false,
4208            Self::Safe => true,
4209        }
4210    }
4211}
4212
4213impl fmt::Display for Safety {
4214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4215        f.write_str(match *self {
4216            Self::Unsafe => "unsafe",
4217            Self::Safe => "safe",
4218        })
4219    }
4220}
4221
4222#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4223pub enum Constness {
4224    Const,
4225    NotConst,
4226}
4227
4228impl fmt::Display for Constness {
4229    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4230        f.write_str(match *self {
4231            Self::Const => "const",
4232            Self::NotConst => "non-const",
4233        })
4234    }
4235}
4236
4237#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4242pub enum HeaderSafety {
4243    SafeTargetFeatures,
4249    Normal(Safety),
4250}
4251
4252impl From<Safety> for HeaderSafety {
4253    fn from(v: Safety) -> Self {
4254        Self::Normal(v)
4255    }
4256}
4257
4258#[derive(Copy, Clone, Debug, HashStable_Generic)]
4259pub struct FnHeader {
4260    pub safety: HeaderSafety,
4261    pub constness: Constness,
4262    pub asyncness: IsAsync,
4263    pub abi: ExternAbi,
4264}
4265
4266impl FnHeader {
4267    pub fn is_async(&self) -> bool {
4268        matches!(self.asyncness, IsAsync::Async(_))
4269    }
4270
4271    pub fn is_const(&self) -> bool {
4272        matches!(self.constness, Constness::Const)
4273    }
4274
4275    pub fn is_unsafe(&self) -> bool {
4276        self.safety().is_unsafe()
4277    }
4278
4279    pub fn is_safe(&self) -> bool {
4280        self.safety().is_safe()
4281    }
4282
4283    pub fn safety(&self) -> Safety {
4284        match self.safety {
4285            HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4286            HeaderSafety::Normal(safety) => safety,
4287        }
4288    }
4289}
4290
4291#[derive(Debug, Clone, Copy, HashStable_Generic)]
4292pub enum ItemKind<'hir> {
4293    ExternCrate(Option<Symbol>, Ident),
4297
4298    Use(&'hir UsePath<'hir>, UseKind),
4304
4305    Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4307    Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, BodyId),
4309    Fn {
4311        sig: FnSig<'hir>,
4312        ident: Ident,
4313        generics: &'hir Generics<'hir>,
4314        body: BodyId,
4315        has_body: bool,
4319    },
4320    Macro(Ident, &'hir ast::MacroDef, MacroKind),
4322    Mod(Ident, &'hir Mod<'hir>),
4324    ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] },
4326    GlobalAsm {
4328        asm: &'hir InlineAsm<'hir>,
4329        fake_body: BodyId,
4335    },
4336    TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4338    Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4340    Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4342    Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4344    Trait(
4346        Constness,
4347        IsAuto,
4348        Safety,
4349        Ident,
4350        &'hir Generics<'hir>,
4351        GenericBounds<'hir>,
4352        &'hir [TraitItemId],
4353    ),
4354    TraitAlias(Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4356
4357    Impl(&'hir Impl<'hir>),
4359}
4360
4361#[derive(Debug, Clone, Copy, HashStable_Generic)]
4366pub struct Impl<'hir> {
4367    pub constness: Constness,
4368    pub safety: Safety,
4369    pub polarity: ImplPolarity,
4370    pub defaultness: Defaultness,
4371    pub defaultness_span: Option<Span>,
4374    pub generics: &'hir Generics<'hir>,
4375
4376    pub of_trait: Option<TraitRef<'hir>>,
4378
4379    pub self_ty: &'hir Ty<'hir>,
4380    pub items: &'hir [ImplItemId],
4381}
4382
4383impl ItemKind<'_> {
4384    pub fn ident(&self) -> Option<Ident> {
4385        match *self {
4386            ItemKind::ExternCrate(_, ident)
4387            | ItemKind::Use(_, UseKind::Single(ident))
4388            | ItemKind::Static(_, ident, ..)
4389            | ItemKind::Const(ident, ..)
4390            | ItemKind::Fn { ident, .. }
4391            | ItemKind::Macro(ident, ..)
4392            | ItemKind::Mod(ident, ..)
4393            | ItemKind::TyAlias(ident, ..)
4394            | ItemKind::Enum(ident, ..)
4395            | ItemKind::Struct(ident, ..)
4396            | ItemKind::Union(ident, ..)
4397            | ItemKind::Trait(_, _, _, ident, ..)
4398            | ItemKind::TraitAlias(ident, ..) => Some(ident),
4399
4400            ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4401            | ItemKind::ForeignMod { .. }
4402            | ItemKind::GlobalAsm { .. }
4403            | ItemKind::Impl(_) => None,
4404        }
4405    }
4406
4407    pub fn generics(&self) -> Option<&Generics<'_>> {
4408        Some(match self {
4409            ItemKind::Fn { generics, .. }
4410            | ItemKind::TyAlias(_, generics, _)
4411            | ItemKind::Const(_, generics, _, _)
4412            | ItemKind::Enum(_, generics, _)
4413            | ItemKind::Struct(_, generics, _)
4414            | ItemKind::Union(_, generics, _)
4415            | ItemKind::Trait(_, _, _, _, generics, _, _)
4416            | ItemKind::TraitAlias(_, generics, _)
4417            | ItemKind::Impl(Impl { generics, .. }) => generics,
4418            _ => return None,
4419        })
4420    }
4421}
4422
4423#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4427pub struct ForeignItemId {
4428    pub owner_id: OwnerId,
4429}
4430
4431impl ForeignItemId {
4432    #[inline]
4433    pub fn hir_id(&self) -> HirId {
4434        HirId::make_owner(self.owner_id.def_id)
4436    }
4437}
4438
4439#[derive(Debug, Clone, Copy, HashStable_Generic)]
4440pub struct ForeignItem<'hir> {
4441    pub ident: Ident,
4442    pub kind: ForeignItemKind<'hir>,
4443    pub owner_id: OwnerId,
4444    pub span: Span,
4445    pub vis_span: Span,
4446    pub has_delayed_lints: bool,
4447}
4448
4449impl ForeignItem<'_> {
4450    #[inline]
4451    pub fn hir_id(&self) -> HirId {
4452        HirId::make_owner(self.owner_id.def_id)
4454    }
4455
4456    pub fn foreign_item_id(&self) -> ForeignItemId {
4457        ForeignItemId { owner_id: self.owner_id }
4458    }
4459}
4460
4461#[derive(Debug, Clone, Copy, HashStable_Generic)]
4463pub enum ForeignItemKind<'hir> {
4464    Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4471    Static(&'hir Ty<'hir>, Mutability, Safety),
4473    Type,
4475}
4476
4477#[derive(Debug, Copy, Clone, HashStable_Generic)]
4479pub struct Upvar {
4480    pub span: Span,
4482}
4483
4484#[derive(Debug, Clone, HashStable_Generic)]
4488pub struct TraitCandidate {
4489    pub def_id: DefId,
4490    pub import_ids: SmallVec<[LocalDefId; 1]>,
4491}
4492
4493#[derive(Copy, Clone, Debug, HashStable_Generic)]
4494pub enum OwnerNode<'hir> {
4495    Item(&'hir Item<'hir>),
4496    ForeignItem(&'hir ForeignItem<'hir>),
4497    TraitItem(&'hir TraitItem<'hir>),
4498    ImplItem(&'hir ImplItem<'hir>),
4499    Crate(&'hir Mod<'hir>),
4500    Synthetic,
4501}
4502
4503impl<'hir> OwnerNode<'hir> {
4504    pub fn span(&self) -> Span {
4505        match self {
4506            OwnerNode::Item(Item { span, .. })
4507            | OwnerNode::ForeignItem(ForeignItem { span, .. })
4508            | OwnerNode::ImplItem(ImplItem { span, .. })
4509            | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4510            OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4511            OwnerNode::Synthetic => unreachable!(),
4512        }
4513    }
4514
4515    pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4516        match self {
4517            OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4518            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4519            | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4520            | OwnerNode::ForeignItem(ForeignItem {
4521                kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4522            }) => Some(fn_sig),
4523            _ => None,
4524        }
4525    }
4526
4527    pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4528        match self {
4529            OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4530            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4531            | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4532            | OwnerNode::ForeignItem(ForeignItem {
4533                kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4534            }) => Some(fn_sig.decl),
4535            _ => None,
4536        }
4537    }
4538
4539    pub fn body_id(&self) -> Option<BodyId> {
4540        match self {
4541            OwnerNode::Item(Item {
4542                kind:
4543                    ItemKind::Static(_, _, _, body)
4544                    | ItemKind::Const(_, _, _, body)
4545                    | ItemKind::Fn { body, .. },
4546                ..
4547            })
4548            | OwnerNode::TraitItem(TraitItem {
4549                kind:
4550                    TraitItemKind::Fn(_, TraitFn::Provided(body)) | TraitItemKind::Const(_, Some(body)),
4551                ..
4552            })
4553            | OwnerNode::ImplItem(ImplItem {
4554                kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, body),
4555                ..
4556            }) => Some(*body),
4557            _ => None,
4558        }
4559    }
4560
4561    pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4562        Node::generics(self.into())
4563    }
4564
4565    pub fn def_id(self) -> OwnerId {
4566        match self {
4567            OwnerNode::Item(Item { owner_id, .. })
4568            | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4569            | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4570            | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4571            OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4572            OwnerNode::Synthetic => unreachable!(),
4573        }
4574    }
4575
4576    pub fn is_impl_block(&self) -> bool {
4578        matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4579    }
4580
4581    expect_methods_self! {
4582        expect_item,         &'hir Item<'hir>,        OwnerNode::Item(n),        n;
4583        expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4584        expect_impl_item,    &'hir ImplItem<'hir>,    OwnerNode::ImplItem(n),    n;
4585        expect_trait_item,   &'hir TraitItem<'hir>,   OwnerNode::TraitItem(n),   n;
4586    }
4587}
4588
4589impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4590    fn from(val: &'hir Item<'hir>) -> Self {
4591        OwnerNode::Item(val)
4592    }
4593}
4594
4595impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4596    fn from(val: &'hir ForeignItem<'hir>) -> Self {
4597        OwnerNode::ForeignItem(val)
4598    }
4599}
4600
4601impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4602    fn from(val: &'hir ImplItem<'hir>) -> Self {
4603        OwnerNode::ImplItem(val)
4604    }
4605}
4606
4607impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4608    fn from(val: &'hir TraitItem<'hir>) -> Self {
4609        OwnerNode::TraitItem(val)
4610    }
4611}
4612
4613impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4614    fn from(val: OwnerNode<'hir>) -> Self {
4615        match val {
4616            OwnerNode::Item(n) => Node::Item(n),
4617            OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4618            OwnerNode::ImplItem(n) => Node::ImplItem(n),
4619            OwnerNode::TraitItem(n) => Node::TraitItem(n),
4620            OwnerNode::Crate(n) => Node::Crate(n),
4621            OwnerNode::Synthetic => Node::Synthetic,
4622        }
4623    }
4624}
4625
4626#[derive(Copy, Clone, Debug, HashStable_Generic)]
4627pub enum Node<'hir> {
4628    Param(&'hir Param<'hir>),
4629    Item(&'hir Item<'hir>),
4630    ForeignItem(&'hir ForeignItem<'hir>),
4631    TraitItem(&'hir TraitItem<'hir>),
4632    ImplItem(&'hir ImplItem<'hir>),
4633    Variant(&'hir Variant<'hir>),
4634    Field(&'hir FieldDef<'hir>),
4635    AnonConst(&'hir AnonConst),
4636    ConstBlock(&'hir ConstBlock),
4637    ConstArg(&'hir ConstArg<'hir>),
4638    Expr(&'hir Expr<'hir>),
4639    ExprField(&'hir ExprField<'hir>),
4640    Stmt(&'hir Stmt<'hir>),
4641    PathSegment(&'hir PathSegment<'hir>),
4642    Ty(&'hir Ty<'hir>),
4643    AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4644    TraitRef(&'hir TraitRef<'hir>),
4645    OpaqueTy(&'hir OpaqueTy<'hir>),
4646    TyPat(&'hir TyPat<'hir>),
4647    Pat(&'hir Pat<'hir>),
4648    PatField(&'hir PatField<'hir>),
4649    PatExpr(&'hir PatExpr<'hir>),
4653    Arm(&'hir Arm<'hir>),
4654    Block(&'hir Block<'hir>),
4655    LetStmt(&'hir LetStmt<'hir>),
4656    Ctor(&'hir VariantData<'hir>),
4659    Lifetime(&'hir Lifetime),
4660    GenericParam(&'hir GenericParam<'hir>),
4661    Crate(&'hir Mod<'hir>),
4662    Infer(&'hir InferArg),
4663    WherePredicate(&'hir WherePredicate<'hir>),
4664    PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4665    Synthetic,
4667    Err(Span),
4668}
4669
4670impl<'hir> Node<'hir> {
4671    pub fn ident(&self) -> Option<Ident> {
4686        match self {
4687            Node::Item(item) => item.kind.ident(),
4688            Node::TraitItem(TraitItem { ident, .. })
4689            | Node::ImplItem(ImplItem { ident, .. })
4690            | Node::ForeignItem(ForeignItem { ident, .. })
4691            | Node::Field(FieldDef { ident, .. })
4692            | Node::Variant(Variant { ident, .. })
4693            | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4694            Node::Lifetime(lt) => Some(lt.ident),
4695            Node::GenericParam(p) => Some(p.name.ident()),
4696            Node::AssocItemConstraint(c) => Some(c.ident),
4697            Node::PatField(f) => Some(f.ident),
4698            Node::ExprField(f) => Some(f.ident),
4699            Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4700            Node::Param(..)
4701            | Node::AnonConst(..)
4702            | Node::ConstBlock(..)
4703            | Node::ConstArg(..)
4704            | Node::Expr(..)
4705            | Node::Stmt(..)
4706            | Node::Block(..)
4707            | Node::Ctor(..)
4708            | Node::Pat(..)
4709            | Node::TyPat(..)
4710            | Node::PatExpr(..)
4711            | Node::Arm(..)
4712            | Node::LetStmt(..)
4713            | Node::Crate(..)
4714            | Node::Ty(..)
4715            | Node::TraitRef(..)
4716            | Node::OpaqueTy(..)
4717            | Node::Infer(..)
4718            | Node::WherePredicate(..)
4719            | Node::Synthetic
4720            | Node::Err(..) => None,
4721        }
4722    }
4723
4724    pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4725        match self {
4726            Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4727            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4728            | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4729            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4730                Some(fn_sig.decl)
4731            }
4732            Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4733                Some(fn_decl)
4734            }
4735            _ => None,
4736        }
4737    }
4738
4739    pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4741        if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4742            && let Some(trait_ref) = impl_block.of_trait
4743            && let Some(trait_id) = trait_ref.trait_def_id()
4744            && trait_id == trait_def_id
4745        {
4746            Some(impl_block)
4747        } else {
4748            None
4749        }
4750    }
4751
4752    pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4753        match self {
4754            Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4755            | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4756            | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4757            | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4758                Some(fn_sig)
4759            }
4760            _ => None,
4761        }
4762    }
4763
4764    pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4766        match self {
4767            Node::Item(it) => match it.kind {
4768                ItemKind::TyAlias(_, _, ty)
4769                | ItemKind::Static(_, _, ty, _)
4770                | ItemKind::Const(_, _, ty, _) => Some(ty),
4771                ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4772                _ => None,
4773            },
4774            Node::TraitItem(it) => match it.kind {
4775                TraitItemKind::Const(ty, _) => Some(ty),
4776                TraitItemKind::Type(_, ty) => ty,
4777                _ => None,
4778            },
4779            Node::ImplItem(it) => match it.kind {
4780                ImplItemKind::Const(ty, _) => Some(ty),
4781                ImplItemKind::Type(ty) => Some(ty),
4782                _ => None,
4783            },
4784            Node::ForeignItem(it) => match it.kind {
4785                ForeignItemKind::Static(ty, ..) => Some(ty),
4786                _ => None,
4787            },
4788            _ => None,
4789        }
4790    }
4791
4792    pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4793        match self {
4794            Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
4795            _ => None,
4796        }
4797    }
4798
4799    #[inline]
4800    pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4801        match self {
4802            Node::Item(Item {
4803                owner_id,
4804                kind:
4805                    ItemKind::Const(_, _, _, body)
4806                    | ItemKind::Static(.., body)
4807                    | ItemKind::Fn { body, .. },
4808                ..
4809            })
4810            | Node::TraitItem(TraitItem {
4811                owner_id,
4812                kind:
4813                    TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4814                ..
4815            })
4816            | Node::ImplItem(ImplItem {
4817                owner_id,
4818                kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
4819                ..
4820            }) => Some((owner_id.def_id, *body)),
4821
4822            Node::Item(Item {
4823                owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4824            }) => Some((owner_id.def_id, *fake_body)),
4825
4826            Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4827                Some((*def_id, *body))
4828            }
4829
4830            Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4831            Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4832
4833            _ => None,
4834        }
4835    }
4836
4837    pub fn body_id(&self) -> Option<BodyId> {
4838        Some(self.associated_body()?.1)
4839    }
4840
4841    pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4842        match self {
4843            Node::ForeignItem(ForeignItem {
4844                kind: ForeignItemKind::Fn(_, _, generics), ..
4845            })
4846            | Node::TraitItem(TraitItem { generics, .. })
4847            | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4848            Node::Item(item) => item.kind.generics(),
4849            _ => None,
4850        }
4851    }
4852
4853    pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4854        match self {
4855            Node::Item(i) => Some(OwnerNode::Item(i)),
4856            Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4857            Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4858            Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4859            Node::Crate(i) => Some(OwnerNode::Crate(i)),
4860            Node::Synthetic => Some(OwnerNode::Synthetic),
4861            _ => None,
4862        }
4863    }
4864
4865    pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4866        match self {
4867            Node::Item(i) => match i.kind {
4868                ItemKind::Fn { ident, sig, generics, .. } => {
4869                    Some(FnKind::ItemFn(ident, generics, sig.header))
4870                }
4871                _ => None,
4872            },
4873            Node::TraitItem(ti) => match ti.kind {
4874                TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4875                _ => None,
4876            },
4877            Node::ImplItem(ii) => match ii.kind {
4878                ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4879                _ => None,
4880            },
4881            Node::Expr(e) => match e.kind {
4882                ExprKind::Closure { .. } => Some(FnKind::Closure),
4883                _ => None,
4884            },
4885            _ => None,
4886        }
4887    }
4888
4889    expect_methods_self! {
4890        expect_param,         &'hir Param<'hir>,        Node::Param(n),        n;
4891        expect_item,          &'hir Item<'hir>,         Node::Item(n),         n;
4892        expect_foreign_item,  &'hir ForeignItem<'hir>,  Node::ForeignItem(n),  n;
4893        expect_trait_item,    &'hir TraitItem<'hir>,    Node::TraitItem(n),    n;
4894        expect_impl_item,     &'hir ImplItem<'hir>,     Node::ImplItem(n),     n;
4895        expect_variant,       &'hir Variant<'hir>,      Node::Variant(n),      n;
4896        expect_field,         &'hir FieldDef<'hir>,     Node::Field(n),        n;
4897        expect_anon_const,    &'hir AnonConst,          Node::AnonConst(n),    n;
4898        expect_inline_const,  &'hir ConstBlock,         Node::ConstBlock(n),   n;
4899        expect_expr,          &'hir Expr<'hir>,         Node::Expr(n),         n;
4900        expect_expr_field,    &'hir ExprField<'hir>,    Node::ExprField(n),    n;
4901        expect_stmt,          &'hir Stmt<'hir>,         Node::Stmt(n),         n;
4902        expect_path_segment,  &'hir PathSegment<'hir>,  Node::PathSegment(n),  n;
4903        expect_ty,            &'hir Ty<'hir>,           Node::Ty(n),           n;
4904        expect_assoc_item_constraint,  &'hir AssocItemConstraint<'hir>,  Node::AssocItemConstraint(n),  n;
4905        expect_trait_ref,     &'hir TraitRef<'hir>,     Node::TraitRef(n),     n;
4906        expect_opaque_ty,     &'hir OpaqueTy<'hir>,     Node::OpaqueTy(n),     n;
4907        expect_pat,           &'hir Pat<'hir>,          Node::Pat(n),          n;
4908        expect_pat_field,     &'hir PatField<'hir>,     Node::PatField(n),     n;
4909        expect_arm,           &'hir Arm<'hir>,          Node::Arm(n),          n;
4910        expect_block,         &'hir Block<'hir>,        Node::Block(n),        n;
4911        expect_let_stmt,      &'hir LetStmt<'hir>,      Node::LetStmt(n),      n;
4912        expect_ctor,          &'hir VariantData<'hir>,  Node::Ctor(n),         n;
4913        expect_lifetime,      &'hir Lifetime,           Node::Lifetime(n),     n;
4914        expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4915        expect_crate,         &'hir Mod<'hir>,          Node::Crate(n),        n;
4916        expect_infer,         &'hir InferArg,           Node::Infer(n),        n;
4917        expect_closure,       &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4918    }
4919}
4920
4921#[cfg(target_pointer_width = "64")]
4923mod size_asserts {
4924    use rustc_data_structures::static_assert_size;
4925
4926    use super::*;
4927    static_assert_size!(Block<'_>, 48);
4929    static_assert_size!(Body<'_>, 24);
4930    static_assert_size!(Expr<'_>, 64);
4931    static_assert_size!(ExprKind<'_>, 48);
4932    static_assert_size!(FnDecl<'_>, 40);
4933    static_assert_size!(ForeignItem<'_>, 96);
4934    static_assert_size!(ForeignItemKind<'_>, 56);
4935    static_assert_size!(GenericArg<'_>, 16);
4936    static_assert_size!(GenericBound<'_>, 64);
4937    static_assert_size!(Generics<'_>, 56);
4938    static_assert_size!(Impl<'_>, 80);
4939    static_assert_size!(ImplItem<'_>, 96);
4940    static_assert_size!(ImplItemKind<'_>, 40);
4941    static_assert_size!(Item<'_>, 88);
4942    static_assert_size!(ItemKind<'_>, 64);
4943    static_assert_size!(LetStmt<'_>, 72);
4944    static_assert_size!(Param<'_>, 32);
4945    static_assert_size!(Pat<'_>, 72);
4946    static_assert_size!(PatKind<'_>, 48);
4947    static_assert_size!(Path<'_>, 40);
4948    static_assert_size!(PathSegment<'_>, 48);
4949    static_assert_size!(QPath<'_>, 24);
4950    static_assert_size!(Res, 12);
4951    static_assert_size!(Stmt<'_>, 32);
4952    static_assert_size!(StmtKind<'_>, 16);
4953    static_assert_size!(TraitItem<'_>, 88);
4954    static_assert_size!(TraitItemKind<'_>, 48);
4955    static_assert_size!(Ty<'_>, 48);
4956    static_assert_size!(TyKind<'_>, 32);
4957    }
4959
4960#[cfg(test)]
4961mod tests;