1use std::borrow::Cow;
3use std::fmt;
4
5use rustc_abi::ExternAbi;
6use rustc_ast::attr::AttributeExt;
7use rustc_ast::token::DocFragmentKind;
8use rustc_ast::util::parser::ExprPrecedence;
9use rustc_ast::{
10 self as ast, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitIntType,
11 LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind, join_path_idents,
12};
13pub use rustc_ast::{
14 AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
15 BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
16 MetaItemInner, MetaItemLit, Movability, Mutability, Pinnedness, UnOp,
17};
18use rustc_data_structures::fingerprint::Fingerprint;
19use rustc_data_structures::sorted_map::SortedMap;
20use rustc_data_structures::tagged_ptr::TaggedRef;
21use rustc_error_messages::{DiagArgValue, IntoDiagArg};
22use rustc_index::IndexVec;
23use rustc_macros::{Decodable, Encodable, HashStable_Generic};
24use rustc_span::def_id::LocalDefId;
25use rustc_span::source_map::Spanned;
26use rustc_span::{
27 BytePos, DUMMY_SP, DesugaringKind, ErrorGuaranteed, Ident, Span, Symbol, kw, sym,
28};
29use rustc_target::asm::InlineAsmRegOrRegClass;
30use smallvec::SmallVec;
31use thin_vec::ThinVec;
32use tracing::debug;
33
34use crate::attrs::AttributeKind;
35use crate::def::{CtorKind, DefKind, MacroKinds, PerNS, Res};
36use crate::def_id::{DefId, LocalDefIdMap};
37pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId};
38use crate::intravisit::{FnKind, VisitorExt};
39use crate::lints::DelayedLints;
40
41#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
42pub enum AngleBrackets {
43 Missing,
45 Empty,
47 Full,
49}
50
51#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
52pub enum LifetimeSource {
53 Reference,
55
56 Path { angle_brackets: AngleBrackets },
59
60 OutlivesBound,
62
63 PreciseCapturing,
65
66 Other,
73}
74
75#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
76pub enum LifetimeSyntax {
77 Implicit,
79
80 ExplicitAnonymous,
82
83 ExplicitBound,
85}
86
87impl From<Ident> for LifetimeSyntax {
88 fn from(ident: Ident) -> Self {
89 let name = ident.name;
90
91 if name == sym::empty {
92 unreachable!("A lifetime name should never be empty");
93 } else if name == kw::UnderscoreLifetime {
94 LifetimeSyntax::ExplicitAnonymous
95 } else {
96 debug_assert!(name.as_str().starts_with('\''));
97 LifetimeSyntax::ExplicitBound
98 }
99 }
100}
101
102#[derive(Debug, Copy, Clone, HashStable_Generic)]
153#[repr(align(4))]
161pub struct Lifetime {
162 #[stable_hasher(ignore)]
163 pub hir_id: HirId,
164
165 pub ident: Ident,
169
170 pub kind: LifetimeKind,
172
173 pub source: LifetimeSource,
176
177 pub syntax: LifetimeSyntax,
180}
181
182#[derive(Debug, Copy, Clone, HashStable_Generic)]
183pub enum ParamName {
184 Plain(Ident),
186
187 Error(Ident),
193
194 Fresh,
209}
210
211impl ParamName {
212 pub fn ident(&self) -> Ident {
213 match *self {
214 ParamName::Plain(ident) | ParamName::Error(ident) => ident,
215 ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
216 }
217 }
218}
219
220#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
221pub enum LifetimeKind {
222 Param(LocalDefId),
224
225 ImplicitObjectLifetimeDefault,
237
238 Error,
241
242 Infer,
246
247 Static,
249}
250
251impl LifetimeKind {
252 fn is_elided(&self) -> bool {
253 match self {
254 LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true,
255
256 LifetimeKind::Error | LifetimeKind::Param(..) | LifetimeKind::Static => false,
261 }
262 }
263}
264
265impl fmt::Display for Lifetime {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 self.ident.name.fmt(f)
268 }
269}
270
271impl Lifetime {
272 pub fn new(
273 hir_id: HirId,
274 ident: Ident,
275 kind: LifetimeKind,
276 source: LifetimeSource,
277 syntax: LifetimeSyntax,
278 ) -> Lifetime {
279 let lifetime = Lifetime { hir_id, ident, kind, source, syntax };
280
281 #[cfg(debug_assertions)]
283 match (lifetime.is_elided(), lifetime.is_anonymous()) {
284 (false, false) => {} (false, true) => {} (true, true) => {} (true, false) => panic!("bad Lifetime"),
288 }
289
290 lifetime
291 }
292
293 pub fn is_elided(&self) -> bool {
294 self.kind.is_elided()
295 }
296
297 pub fn is_anonymous(&self) -> bool {
298 self.ident.name == kw::UnderscoreLifetime
299 }
300
301 pub fn is_implicit(&self) -> bool {
302 matches!(self.syntax, LifetimeSyntax::Implicit)
303 }
304
305 pub fn is_static(&self) -> bool {
306 self.kind == LifetimeKind::Static
307 }
308
309 pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
310 use LifetimeSource::*;
311 use LifetimeSyntax::*;
312
313 debug_assert!(new_lifetime.starts_with('\''));
314
315 match (self.syntax, self.source) {
316 (ExplicitBound | ExplicitAnonymous, _) => (self.ident.span, format!("{new_lifetime}")),
318
319 (Implicit, Path { angle_brackets: AngleBrackets::Full }) => {
321 (self.ident.span, format!("{new_lifetime}, "))
322 }
323
324 (Implicit, Path { angle_brackets: AngleBrackets::Empty }) => {
326 (self.ident.span, format!("{new_lifetime}"))
327 }
328
329 (Implicit, Path { angle_brackets: AngleBrackets::Missing }) => {
331 (self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
332 }
333
334 (Implicit, Reference) => (self.ident.span, format!("{new_lifetime} ")),
336
337 (Implicit, source) => {
338 unreachable!("can't suggest for a implicit lifetime of {source:?}")
339 }
340 }
341 }
342}
343
344#[derive(Debug, Clone, Copy, HashStable_Generic)]
348pub struct Path<'hir, R = Res> {
349 pub span: Span,
350 pub res: R,
352 pub segments: &'hir [PathSegment<'hir>],
354}
355
356pub type UsePath<'hir> = Path<'hir, PerNS<Option<Res>>>;
358
359impl Path<'_> {
360 pub fn is_global(&self) -> bool {
361 self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
362 }
363}
364
365#[derive(Debug, Clone, Copy, HashStable_Generic)]
368pub struct PathSegment<'hir> {
369 pub ident: Ident,
371 #[stable_hasher(ignore)]
372 pub hir_id: HirId,
373 pub res: Res,
374
375 pub args: Option<&'hir GenericArgs<'hir>>,
381
382 pub infer_args: bool,
387}
388
389impl<'hir> PathSegment<'hir> {
390 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
392 PathSegment { ident, hir_id, res, infer_args: true, args: None }
393 }
394
395 pub fn invalid() -> Self {
396 Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
397 }
398
399 pub fn args(&self) -> &GenericArgs<'hir> {
400 if let Some(ref args) = self.args {
401 args
402 } else {
403 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
404 DUMMY
405 }
406 }
407}
408
409#[derive(Clone, Copy, Debug, HashStable_Generic)]
410pub enum ConstItemRhs<'hir> {
411 Body(BodyId),
412 TypeConst(&'hir ConstArg<'hir>),
413}
414
415impl<'hir> ConstItemRhs<'hir> {
416 pub fn hir_id(&self) -> HirId {
417 match self {
418 ConstItemRhs::Body(body_id) => body_id.hir_id,
419 ConstItemRhs::TypeConst(ct_arg) => ct_arg.hir_id,
420 }
421 }
422
423 pub fn span<'tcx>(&self, tcx: impl crate::intravisit::HirTyCtxt<'tcx>) -> Span {
424 match self {
425 ConstItemRhs::Body(body_id) => tcx.hir_body(*body_id).value.span,
426 ConstItemRhs::TypeConst(ct_arg) => ct_arg.span,
427 }
428 }
429}
430
431#[derive(Clone, Copy, Debug, HashStable_Generic)]
445#[repr(C)]
446pub struct ConstArg<'hir, Unambig = ()> {
447 #[stable_hasher(ignore)]
448 pub hir_id: HirId,
449 pub kind: ConstArgKind<'hir, Unambig>,
450 pub span: Span,
451}
452
453impl<'hir> ConstArg<'hir, AmbigArg> {
454 pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
465 let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
468 unsafe { &*ptr }
469 }
470}
471
472impl<'hir> ConstArg<'hir> {
473 pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
479 if let ConstArgKind::Infer(()) = self.kind {
480 return None;
481 }
482
483 let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
487 Some(unsafe { &*ptr })
488 }
489}
490
491impl<'hir, Unambig> ConstArg<'hir, Unambig> {
492 pub fn anon_const_hir_id(&self) -> Option<HirId> {
493 match self.kind {
494 ConstArgKind::Anon(ac) => Some(ac.hir_id),
495 _ => None,
496 }
497 }
498}
499
500#[derive(Clone, Copy, Debug, HashStable_Generic)]
502#[repr(u8, C)]
503pub enum ConstArgKind<'hir, Unambig = ()> {
504 Tup(&'hir [&'hir ConstArg<'hir, Unambig>]),
505 Path(QPath<'hir>),
511 Anon(&'hir AnonConst),
512 Struct(QPath<'hir>, &'hir [&'hir ConstArgExprField<'hir>]),
514 TupleCall(QPath<'hir>, &'hir [&'hir ConstArg<'hir>]),
516 Array(&'hir ConstArgArrayExpr<'hir>),
518 Error(ErrorGuaranteed),
520 Infer(Unambig),
523 Literal(LitKind),
524}
525
526#[derive(Clone, Copy, Debug, HashStable_Generic)]
527pub struct ConstArgExprField<'hir> {
528 pub hir_id: HirId,
529 pub span: Span,
530 pub field: Ident,
531 pub expr: &'hir ConstArg<'hir>,
532}
533
534#[derive(Clone, Copy, Debug, HashStable_Generic)]
535pub struct ConstArgArrayExpr<'hir> {
536 pub span: Span,
537 pub elems: &'hir [&'hir ConstArg<'hir>],
538}
539
540#[derive(Clone, Copy, Debug, HashStable_Generic)]
541pub struct InferArg {
542 #[stable_hasher(ignore)]
543 pub hir_id: HirId,
544 pub span: Span,
545}
546
547impl InferArg {
548 pub fn to_ty(&self) -> Ty<'static> {
549 Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
550 }
551}
552
553#[derive(Debug, Clone, Copy, HashStable_Generic)]
554pub enum GenericArg<'hir> {
555 Lifetime(&'hir Lifetime),
556 Type(&'hir Ty<'hir, AmbigArg>),
557 Const(&'hir ConstArg<'hir, AmbigArg>),
558 Infer(InferArg),
568}
569
570impl GenericArg<'_> {
571 pub fn span(&self) -> Span {
572 match self {
573 GenericArg::Lifetime(l) => l.ident.span,
574 GenericArg::Type(t) => t.span,
575 GenericArg::Const(c) => c.span,
576 GenericArg::Infer(i) => i.span,
577 }
578 }
579
580 pub fn hir_id(&self) -> HirId {
581 match self {
582 GenericArg::Lifetime(l) => l.hir_id,
583 GenericArg::Type(t) => t.hir_id,
584 GenericArg::Const(c) => c.hir_id,
585 GenericArg::Infer(i) => i.hir_id,
586 }
587 }
588
589 pub fn descr(&self) -> &'static str {
590 match self {
591 GenericArg::Lifetime(_) => "lifetime",
592 GenericArg::Type(_) => "type",
593 GenericArg::Const(_) => "constant",
594 GenericArg::Infer(_) => "placeholder",
595 }
596 }
597
598 pub fn to_ord(&self) -> ast::ParamKindOrd {
599 match self {
600 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
601 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
602 ast::ParamKindOrd::TypeOrConst
603 }
604 }
605 }
606
607 pub fn is_ty_or_const(&self) -> bool {
608 match self {
609 GenericArg::Lifetime(_) => false,
610 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
611 }
612 }
613}
614
615#[derive(Debug, Clone, Copy, HashStable_Generic)]
617pub struct GenericArgs<'hir> {
618 pub args: &'hir [GenericArg<'hir>],
620 pub constraints: &'hir [AssocItemConstraint<'hir>],
622 pub parenthesized: GenericArgsParentheses,
627 pub span_ext: Span,
640}
641
642impl<'hir> GenericArgs<'hir> {
643 pub const fn none() -> Self {
644 Self {
645 args: &[],
646 constraints: &[],
647 parenthesized: GenericArgsParentheses::No,
648 span_ext: DUMMY_SP,
649 }
650 }
651
652 pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
657 if self.parenthesized != GenericArgsParentheses::ParenSugar {
658 return None;
659 }
660
661 let inputs = self
662 .args
663 .iter()
664 .find_map(|arg| {
665 let GenericArg::Type(ty) = arg else { return None };
666 let TyKind::Tup(tys) = &ty.kind else { return None };
667 Some(tys)
668 })
669 .unwrap();
670
671 Some((inputs, self.paren_sugar_output_inner()))
672 }
673
674 pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
679 (self.parenthesized == GenericArgsParentheses::ParenSugar)
680 .then(|| self.paren_sugar_output_inner())
681 }
682
683 fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
684 let [constraint] = self.constraints.try_into().unwrap();
685 debug_assert_eq!(constraint.ident.name, sym::Output);
686 constraint.ty().unwrap()
687 }
688
689 pub fn has_err(&self) -> Option<ErrorGuaranteed> {
690 self.args
691 .iter()
692 .find_map(|arg| {
693 let GenericArg::Type(ty) = arg else { return None };
694 let TyKind::Err(guar) = ty.kind else { return None };
695 Some(guar)
696 })
697 .or_else(|| {
698 self.constraints.iter().find_map(|constraint| {
699 let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
700 Some(guar)
701 })
702 })
703 }
704
705 #[inline]
706 pub fn num_lifetime_params(&self) -> usize {
707 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
708 }
709
710 #[inline]
711 pub fn has_lifetime_params(&self) -> bool {
712 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
713 }
714
715 #[inline]
716 pub fn num_generic_params(&self) -> usize {
719 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
720 }
721
722 pub fn span(&self) -> Option<Span> {
728 let span_ext = self.span_ext()?;
729 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
730 }
731
732 pub fn span_ext(&self) -> Option<Span> {
734 Some(self.span_ext).filter(|span| !span.is_empty())
735 }
736
737 pub fn is_empty(&self) -> bool {
738 self.args.is_empty()
739 }
740}
741
742#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)]
743pub enum GenericArgsParentheses {
744 No,
745 ReturnTypeNotation,
748 ParenSugar,
750}
751
752#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
754pub struct TraitBoundModifiers {
755 pub constness: BoundConstness,
756 pub polarity: BoundPolarity,
757}
758
759impl TraitBoundModifiers {
760 pub const NONE: Self =
761 TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
762}
763
764#[derive(Clone, Copy, Debug, HashStable_Generic)]
765pub enum GenericBound<'hir> {
766 Trait(PolyTraitRef<'hir>),
767 Outlives(&'hir Lifetime),
768 Use(&'hir [PreciseCapturingArg<'hir>], Span),
769}
770
771impl GenericBound<'_> {
772 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
773 match self {
774 GenericBound::Trait(data) => Some(&data.trait_ref),
775 _ => None,
776 }
777 }
778
779 pub fn span(&self) -> Span {
780 match self {
781 GenericBound::Trait(t, ..) => t.span,
782 GenericBound::Outlives(l) => l.ident.span,
783 GenericBound::Use(_, span) => *span,
784 }
785 }
786}
787
788pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
789
790#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, Debug)]
791pub enum MissingLifetimeKind {
792 Underscore,
794 Ampersand,
796 Comma,
798 Brackets,
800}
801
802#[derive(Copy, Clone, Debug, HashStable_Generic)]
803pub enum LifetimeParamKind {
804 Explicit,
807
808 Elided(MissingLifetimeKind),
811
812 Error,
814}
815
816#[derive(Debug, Clone, Copy, HashStable_Generic)]
817pub enum GenericParamKind<'hir> {
818 Lifetime {
820 kind: LifetimeParamKind,
821 },
822 Type {
823 default: Option<&'hir Ty<'hir>>,
824 synthetic: bool,
825 },
826 Const {
827 ty: &'hir Ty<'hir>,
828 default: Option<&'hir ConstArg<'hir>>,
830 },
831}
832
833#[derive(Debug, Clone, Copy, HashStable_Generic)]
834pub struct GenericParam<'hir> {
835 #[stable_hasher(ignore)]
836 pub hir_id: HirId,
837 pub def_id: LocalDefId,
838 pub name: ParamName,
839 pub span: Span,
840 pub pure_wrt_drop: bool,
841 pub kind: GenericParamKind<'hir>,
842 pub colon_span: Option<Span>,
843 pub source: GenericParamSource,
844}
845
846impl<'hir> GenericParam<'hir> {
847 pub fn is_impl_trait(&self) -> bool {
851 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
852 }
853
854 pub fn is_elided_lifetime(&self) -> bool {
858 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
859 }
860}
861
862#[derive(Debug, Clone, Copy, HashStable_Generic)]
869pub enum GenericParamSource {
870 Generics,
872 Binder,
874}
875
876#[derive(Default)]
877pub struct GenericParamCount {
878 pub lifetimes: usize,
879 pub types: usize,
880 pub consts: usize,
881 pub infer: usize,
882}
883
884#[derive(Debug, Clone, Copy, HashStable_Generic)]
887pub struct Generics<'hir> {
888 pub params: &'hir [GenericParam<'hir>],
889 pub predicates: &'hir [WherePredicate<'hir>],
890 pub has_where_clause_predicates: bool,
891 pub where_clause_span: Span,
892 pub span: Span,
893}
894
895impl<'hir> Generics<'hir> {
896 pub const fn empty() -> &'hir Generics<'hir> {
897 const NOPE: Generics<'_> = Generics {
898 params: &[],
899 predicates: &[],
900 has_where_clause_predicates: false,
901 where_clause_span: DUMMY_SP,
902 span: DUMMY_SP,
903 };
904 &NOPE
905 }
906
907 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
908 self.params.iter().find(|¶m| name == param.name.ident().name)
909 }
910
911 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
913 if let Some(first) = self.params.first()
914 && self.span.contains(first.span)
915 {
916 Some(first.span.shrink_to_lo())
919 } else {
920 None
921 }
922 }
923
924 pub fn span_for_param_suggestion(&self) -> Option<Span> {
926 self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
927 self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
930 })
931 }
932
933 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
936 let end = self.where_clause_span.shrink_to_hi();
937 if self.has_where_clause_predicates {
938 self.predicates
939 .iter()
940 .rfind(|&p| p.kind.in_where_clause())
941 .map_or(end, |p| p.span)
942 .shrink_to_hi()
943 .to(end)
944 } else {
945 end
946 }
947 }
948
949 pub fn add_where_or_trailing_comma(&self) -> &'static str {
950 if self.has_where_clause_predicates {
951 ","
952 } else if self.where_clause_span.is_empty() {
953 " where"
954 } else {
955 ""
957 }
958 }
959
960 pub fn bounds_for_param(
961 &self,
962 param_def_id: LocalDefId,
963 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
964 self.predicates.iter().filter_map(move |pred| match pred.kind {
965 WherePredicateKind::BoundPredicate(bp)
966 if bp.is_param_bound(param_def_id.to_def_id()) =>
967 {
968 Some(bp)
969 }
970 _ => None,
971 })
972 }
973
974 pub fn outlives_for_param(
975 &self,
976 param_def_id: LocalDefId,
977 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
978 self.predicates.iter().filter_map(move |pred| match pred.kind {
979 WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
980 _ => None,
981 })
982 }
983
984 pub fn bounds_span_for_suggestions(
995 &self,
996 param_def_id: LocalDefId,
997 ) -> Option<(Span, Option<Span>)> {
998 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
999 |bound| {
1000 let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
1001 && let [.., segment] = trait_ref.path.segments
1002 && let Some(ret_ty) = segment.args().paren_sugar_output()
1003 && let ret_ty = ret_ty.peel_refs()
1004 && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
1005 && let TraitObjectSyntax::Dyn = tagged_ptr.tag()
1006 && ret_ty.span.can_be_used_for_suggestions()
1007 {
1008 Some(ret_ty.span)
1009 } else {
1010 None
1011 };
1012
1013 span_for_parentheses.map_or_else(
1014 || {
1015 let bs = bound.span();
1018 bs.can_be_used_for_suggestions().then(|| (bs.shrink_to_hi(), None))
1019 },
1020 |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
1021 )
1022 },
1023 )
1024 }
1025
1026 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
1027 let predicate = &self.predicates[pos];
1028 let span = predicate.span;
1029
1030 if !predicate.kind.in_where_clause() {
1031 return span;
1034 }
1035
1036 if pos < self.predicates.len() - 1 {
1038 let next_pred = &self.predicates[pos + 1];
1039 if next_pred.kind.in_where_clause() {
1040 return span.until(next_pred.span);
1043 }
1044 }
1045
1046 if pos > 0 {
1047 let prev_pred = &self.predicates[pos - 1];
1048 if prev_pred.kind.in_where_clause() {
1049 return prev_pred.span.shrink_to_hi().to(span);
1052 }
1053 }
1054
1055 self.where_clause_span
1059 }
1060
1061 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
1062 let predicate = &self.predicates[predicate_pos];
1063 let bounds = predicate.kind.bounds();
1064
1065 if bounds.len() == 1 {
1066 return self.span_for_predicate_removal(predicate_pos);
1067 }
1068
1069 let bound_span = bounds[bound_pos].span();
1070 if bound_pos < bounds.len() - 1 {
1071 bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
1077 } else {
1078 bound_span.with_lo(bounds[bound_pos - 1].span().hi())
1084 }
1085 }
1086}
1087
1088#[derive(Debug, Clone, Copy, HashStable_Generic)]
1090pub struct WherePredicate<'hir> {
1091 #[stable_hasher(ignore)]
1092 pub hir_id: HirId,
1093 pub span: Span,
1094 pub kind: &'hir WherePredicateKind<'hir>,
1095}
1096
1097#[derive(Debug, Clone, Copy, HashStable_Generic)]
1099pub enum WherePredicateKind<'hir> {
1100 BoundPredicate(WhereBoundPredicate<'hir>),
1102 RegionPredicate(WhereRegionPredicate<'hir>),
1104 EqPredicate(WhereEqPredicate<'hir>),
1106}
1107
1108impl<'hir> WherePredicateKind<'hir> {
1109 pub fn in_where_clause(&self) -> bool {
1110 match self {
1111 WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
1112 WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
1113 WherePredicateKind::EqPredicate(_) => false,
1114 }
1115 }
1116
1117 pub fn bounds(&self) -> GenericBounds<'hir> {
1118 match self {
1119 WherePredicateKind::BoundPredicate(p) => p.bounds,
1120 WherePredicateKind::RegionPredicate(p) => p.bounds,
1121 WherePredicateKind::EqPredicate(_) => &[],
1122 }
1123 }
1124}
1125
1126#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
1127pub enum PredicateOrigin {
1128 WhereClause,
1129 GenericParam,
1130 ImplTrait,
1131}
1132
1133#[derive(Debug, Clone, Copy, HashStable_Generic)]
1135pub struct WhereBoundPredicate<'hir> {
1136 pub origin: PredicateOrigin,
1138 pub bound_generic_params: &'hir [GenericParam<'hir>],
1140 pub bounded_ty: &'hir Ty<'hir>,
1142 pub bounds: GenericBounds<'hir>,
1144}
1145
1146impl<'hir> WhereBoundPredicate<'hir> {
1147 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
1149 self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
1150 }
1151}
1152
1153#[derive(Debug, Clone, Copy, HashStable_Generic)]
1155pub struct WhereRegionPredicate<'hir> {
1156 pub in_where_clause: bool,
1157 pub lifetime: &'hir Lifetime,
1158 pub bounds: GenericBounds<'hir>,
1159}
1160
1161impl<'hir> WhereRegionPredicate<'hir> {
1162 fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
1164 self.lifetime.kind == LifetimeKind::Param(param_def_id)
1165 }
1166}
1167
1168#[derive(Debug, Clone, Copy, HashStable_Generic)]
1170pub struct WhereEqPredicate<'hir> {
1171 pub lhs_ty: &'hir Ty<'hir>,
1172 pub rhs_ty: &'hir Ty<'hir>,
1173}
1174
1175#[derive(Clone, Copy, Debug)]
1179pub struct ParentedNode<'tcx> {
1180 pub parent: ItemLocalId,
1181 pub node: Node<'tcx>,
1182}
1183
1184#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1186pub enum AttrArgs {
1187 Empty,
1189 Delimited(DelimArgs),
1191 Eq {
1193 eq_span: Span,
1195 expr: MetaItemLit,
1197 },
1198}
1199
1200#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1201pub struct AttrPath {
1202 pub segments: Box<[Symbol]>,
1203 pub span: Span,
1204}
1205
1206impl IntoDiagArg for AttrPath {
1207 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> DiagArgValue {
1208 self.to_string().into_diag_arg(path)
1209 }
1210}
1211
1212impl AttrPath {
1213 pub fn from_ast(path: &ast::Path, lower_span: impl Copy + Fn(Span) -> Span) -> Self {
1214 AttrPath {
1215 segments: path
1216 .segments
1217 .iter()
1218 .map(|i| i.ident.name)
1219 .collect::<Vec<_>>()
1220 .into_boxed_slice(),
1221 span: lower_span(path.span),
1222 }
1223 }
1224}
1225
1226impl fmt::Display for AttrPath {
1227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1228 write!(
1229 f,
1230 "{}",
1231 join_path_idents(self.segments.iter().map(|i| Ident { name: *i, span: DUMMY_SP }))
1232 )
1233 }
1234}
1235
1236#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1237pub struct AttrItem {
1238 pub path: AttrPath,
1240 pub args: AttrArgs,
1241 pub id: HashIgnoredAttrId,
1242 pub style: AttrStyle,
1245 pub span: Span,
1247}
1248
1249#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1252pub struct HashIgnoredAttrId {
1253 pub attr_id: AttrId,
1254}
1255
1256#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1257pub enum Attribute {
1258 Parsed(AttributeKind),
1264
1265 Unparsed(Box<AttrItem>),
1268}
1269
1270impl Attribute {
1271 pub fn get_normal_item(&self) -> &AttrItem {
1272 match &self {
1273 Attribute::Unparsed(normal) => &normal,
1274 _ => panic!("unexpected parsed attribute"),
1275 }
1276 }
1277
1278 pub fn unwrap_normal_item(self) -> AttrItem {
1279 match self {
1280 Attribute::Unparsed(normal) => *normal,
1281 _ => panic!("unexpected parsed attribute"),
1282 }
1283 }
1284
1285 pub fn value_lit(&self) -> Option<&MetaItemLit> {
1286 match &self {
1287 Attribute::Unparsed(n) => match n.as_ref() {
1288 AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1289 _ => None,
1290 },
1291 _ => None,
1292 }
1293 }
1294
1295 pub fn is_parsed_attr(&self) -> bool {
1296 match self {
1297 Attribute::Parsed(_) => true,
1298 Attribute::Unparsed(_) => false,
1299 }
1300 }
1301}
1302
1303impl AttributeExt for Attribute {
1304 #[inline]
1305 fn id(&self) -> AttrId {
1306 match &self {
1307 Attribute::Unparsed(u) => u.id.attr_id,
1308 _ => panic!(),
1309 }
1310 }
1311
1312 #[inline]
1313 fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1314 match &self {
1315 Attribute::Unparsed(n) => match n.as_ref() {
1316 AttrItem { args: AttrArgs::Delimited(d), .. } => {
1317 ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1318 }
1319 _ => None,
1320 },
1321 _ => None,
1322 }
1323 }
1324
1325 #[inline]
1326 fn value_str(&self) -> Option<Symbol> {
1327 self.value_lit().and_then(|x| x.value_str())
1328 }
1329
1330 #[inline]
1331 fn value_span(&self) -> Option<Span> {
1332 self.value_lit().map(|i| i.span)
1333 }
1334
1335 #[inline]
1337 fn name(&self) -> Option<Symbol> {
1338 match &self {
1339 Attribute::Unparsed(n) => {
1340 if let [ident] = n.path.segments.as_ref() {
1341 Some(*ident)
1342 } else {
1343 None
1344 }
1345 }
1346 _ => None,
1347 }
1348 }
1349
1350 #[inline]
1351 fn path_matches(&self, name: &[Symbol]) -> bool {
1352 match &self {
1353 Attribute::Unparsed(n) => n.path.segments.iter().eq(name),
1354 _ => false,
1355 }
1356 }
1357
1358 #[inline]
1359 fn is_doc_comment(&self) -> Option<Span> {
1360 if let Attribute::Parsed(AttributeKind::DocComment { span, .. }) = self {
1361 Some(*span)
1362 } else {
1363 None
1364 }
1365 }
1366
1367 #[inline]
1368 fn span(&self) -> Span {
1369 match &self {
1370 Attribute::Unparsed(u) => u.span,
1371 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1373 Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1374 Attribute::Parsed(AttributeKind::CfgTrace(cfgs)) => cfgs[0].1,
1375 a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1376 }
1377 }
1378
1379 #[inline]
1380 fn is_word(&self) -> bool {
1381 match &self {
1382 Attribute::Unparsed(n) => {
1383 matches!(n.args, AttrArgs::Empty)
1384 }
1385 _ => false,
1386 }
1387 }
1388
1389 #[inline]
1390 fn symbol_path(&self) -> Option<SmallVec<[Symbol; 1]>> {
1391 match &self {
1392 Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1393 _ => None,
1394 }
1395 }
1396
1397 fn path_span(&self) -> Option<Span> {
1398 match &self {
1399 Attribute::Unparsed(attr) => Some(attr.path.span),
1400 Attribute::Parsed(_) => None,
1401 }
1402 }
1403
1404 #[inline]
1405 fn doc_str(&self) -> Option<Symbol> {
1406 match &self {
1407 Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1408 _ => None,
1409 }
1410 }
1411
1412 #[inline]
1413 fn deprecation_note(&self) -> Option<Symbol> {
1414 match &self {
1415 Attribute::Parsed(AttributeKind::Deprecation { deprecation, .. }) => deprecation.note,
1416 _ => None,
1417 }
1418 }
1419
1420 fn is_automatically_derived_attr(&self) -> bool {
1421 matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)))
1422 }
1423
1424 #[inline]
1425 fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)> {
1426 match &self {
1427 Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1428 Some((*comment, *kind))
1429 }
1430 _ => None,
1431 }
1432 }
1433
1434 fn doc_resolution_scope(&self) -> Option<AttrStyle> {
1435 match self {
1436 Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
1437 Attribute::Unparsed(attr) if self.has_name(sym::doc) && self.value_str().is_some() => {
1438 Some(attr.style)
1439 }
1440 _ => None,
1441 }
1442 }
1443
1444 fn is_proc_macro_attr(&self) -> bool {
1445 matches!(
1446 self,
1447 Attribute::Parsed(
1448 AttributeKind::ProcMacro(..)
1449 | AttributeKind::ProcMacroAttribute(..)
1450 | AttributeKind::ProcMacroDerive { .. }
1451 )
1452 )
1453 }
1454
1455 fn is_doc_hidden(&self) -> bool {
1456 matches!(self, Attribute::Parsed(AttributeKind::Doc(d)) if d.hidden.is_some())
1457 }
1458
1459 fn is_doc_keyword_or_attribute(&self) -> bool {
1460 matches!(self, Attribute::Parsed(AttributeKind::Doc(d)) if d.attribute.is_some() || d.keyword.is_some())
1461 }
1462}
1463
1464impl Attribute {
1466 #[inline]
1467 pub fn id(&self) -> AttrId {
1468 AttributeExt::id(self)
1469 }
1470
1471 #[inline]
1472 pub fn name(&self) -> Option<Symbol> {
1473 AttributeExt::name(self)
1474 }
1475
1476 #[inline]
1477 pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1478 AttributeExt::meta_item_list(self)
1479 }
1480
1481 #[inline]
1482 pub fn value_str(&self) -> Option<Symbol> {
1483 AttributeExt::value_str(self)
1484 }
1485
1486 #[inline]
1487 pub fn value_span(&self) -> Option<Span> {
1488 AttributeExt::value_span(self)
1489 }
1490
1491 #[inline]
1492 pub fn path_matches(&self, name: &[Symbol]) -> bool {
1493 AttributeExt::path_matches(self, name)
1494 }
1495
1496 #[inline]
1497 pub fn is_doc_comment(&self) -> Option<Span> {
1498 AttributeExt::is_doc_comment(self)
1499 }
1500
1501 #[inline]
1502 pub fn has_name(&self, name: Symbol) -> bool {
1503 AttributeExt::has_name(self, name)
1504 }
1505
1506 #[inline]
1507 pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1508 AttributeExt::has_any_name(self, names)
1509 }
1510
1511 #[inline]
1512 pub fn span(&self) -> Span {
1513 AttributeExt::span(self)
1514 }
1515
1516 #[inline]
1517 pub fn is_word(&self) -> bool {
1518 AttributeExt::is_word(self)
1519 }
1520
1521 #[inline]
1522 pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1523 AttributeExt::path(self)
1524 }
1525
1526 #[inline]
1527 pub fn doc_str(&self) -> Option<Symbol> {
1528 AttributeExt::doc_str(self)
1529 }
1530
1531 #[inline]
1532 pub fn is_proc_macro_attr(&self) -> bool {
1533 AttributeExt::is_proc_macro_attr(self)
1534 }
1535
1536 #[inline]
1537 pub fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)> {
1538 AttributeExt::doc_str_and_fragment_kind(self)
1539 }
1540}
1541
1542#[derive(Debug)]
1544pub struct AttributeMap<'tcx> {
1545 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1546 pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1548 pub opt_hash: Option<Fingerprint>,
1550}
1551
1552impl<'tcx> AttributeMap<'tcx> {
1553 pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1554 map: SortedMap::new(),
1555 opt_hash: Some(Fingerprint::ZERO),
1556 define_opaque: None,
1557 };
1558
1559 #[inline]
1560 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1561 self.map.get(&id).copied().unwrap_or(&[])
1562 }
1563}
1564
1565pub struct OwnerNodes<'tcx> {
1569 pub opt_hash_including_bodies: Option<Fingerprint>,
1572 pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1577 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1579}
1580
1581impl<'tcx> OwnerNodes<'tcx> {
1582 pub fn node(&self) -> OwnerNode<'tcx> {
1583 self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1585 }
1586}
1587
1588impl fmt::Debug for OwnerNodes<'_> {
1589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1590 f.debug_struct("OwnerNodes")
1591 .field("node", &self.nodes[ItemLocalId::ZERO])
1593 .field(
1594 "parents",
1595 &fmt::from_fn(|f| {
1596 f.debug_list()
1597 .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1598 fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1599 }))
1600 .finish()
1601 }),
1602 )
1603 .field("bodies", &self.bodies)
1604 .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1605 .finish()
1606 }
1607}
1608
1609#[derive(Debug, HashStable_Generic)]
1611pub struct OwnerInfo<'hir> {
1612 pub nodes: OwnerNodes<'hir>,
1614 pub parenting: LocalDefIdMap<ItemLocalId>,
1616 pub attrs: AttributeMap<'hir>,
1618 pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1621
1622 pub delayed_lints: DelayedLints,
1625}
1626
1627impl<'tcx> OwnerInfo<'tcx> {
1628 #[inline]
1629 pub fn node(&self) -> OwnerNode<'tcx> {
1630 self.nodes.node()
1631 }
1632}
1633
1634#[derive(Copy, Clone, Debug, HashStable_Generic)]
1635pub enum MaybeOwner<'tcx> {
1636 Owner(&'tcx OwnerInfo<'tcx>),
1637 NonOwner(HirId),
1638 Phantom,
1640}
1641
1642impl<'tcx> MaybeOwner<'tcx> {
1643 pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1644 match self {
1645 MaybeOwner::Owner(i) => Some(i),
1646 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1647 }
1648 }
1649
1650 pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1651 self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1652 }
1653}
1654
1655#[derive(Debug)]
1662pub struct Crate<'hir> {
1663 pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1664 pub opt_hir_hash: Option<Fingerprint>,
1666}
1667
1668#[derive(Debug, Clone, Copy, HashStable_Generic)]
1669pub struct Closure<'hir> {
1670 pub def_id: LocalDefId,
1671 pub binder: ClosureBinder,
1672 pub constness: Constness,
1673 pub capture_clause: CaptureBy,
1674 pub bound_generic_params: &'hir [GenericParam<'hir>],
1675 pub fn_decl: &'hir FnDecl<'hir>,
1676 pub body: BodyId,
1677 pub fn_decl_span: Span,
1679 pub fn_arg_span: Option<Span>,
1681 pub kind: ClosureKind,
1682}
1683
1684#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1685pub enum ClosureKind {
1686 Closure,
1688 Coroutine(CoroutineKind),
1693 CoroutineClosure(CoroutineDesugaring),
1698}
1699
1700#[derive(Debug, Clone, Copy, HashStable_Generic)]
1704pub struct Block<'hir> {
1705 pub stmts: &'hir [Stmt<'hir>],
1707 pub expr: Option<&'hir Expr<'hir>>,
1710 #[stable_hasher(ignore)]
1711 pub hir_id: HirId,
1712 pub rules: BlockCheckMode,
1714 pub span: Span,
1716 pub targeted_by_break: bool,
1720}
1721
1722impl<'hir> Block<'hir> {
1723 pub fn innermost_block(&self) -> &Block<'hir> {
1724 let mut block = self;
1725 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1726 block = inner_block;
1727 }
1728 block
1729 }
1730}
1731
1732#[derive(Debug, Clone, Copy, HashStable_Generic)]
1733pub struct TyPat<'hir> {
1734 #[stable_hasher(ignore)]
1735 pub hir_id: HirId,
1736 pub kind: TyPatKind<'hir>,
1737 pub span: Span,
1738}
1739
1740#[derive(Debug, Clone, Copy, HashStable_Generic)]
1741pub struct Pat<'hir> {
1742 #[stable_hasher(ignore)]
1743 pub hir_id: HirId,
1744 pub kind: PatKind<'hir>,
1745 pub span: Span,
1746 pub default_binding_modes: bool,
1749}
1750
1751impl<'hir> Pat<'hir> {
1752 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1753 if !it(self) {
1754 return false;
1755 }
1756
1757 use PatKind::*;
1758 match self.kind {
1759 Missing => unreachable!(),
1760 Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1761 Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => {
1762 s.walk_short_(it)
1763 }
1764 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1765 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1766 Slice(before, slice, after) => {
1767 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1768 }
1769 }
1770 }
1771
1772 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1779 self.walk_short_(&mut it)
1780 }
1781
1782 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1783 if !it(self) {
1784 return;
1785 }
1786
1787 use PatKind::*;
1788 match self.kind {
1789 Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1790 Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1791 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1792 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1793 Slice(before, slice, after) => {
1794 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1795 }
1796 }
1797 }
1798
1799 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1803 self.walk_(&mut it)
1804 }
1805
1806 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1810 self.walk(|p| {
1811 it(p);
1812 true
1813 })
1814 }
1815
1816 pub fn is_never_pattern(&self) -> bool {
1818 let mut is_never_pattern = false;
1819 self.walk(|pat| match &pat.kind {
1820 PatKind::Never => {
1821 is_never_pattern = true;
1822 false
1823 }
1824 PatKind::Or(s) => {
1825 is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1826 false
1827 }
1828 _ => true,
1829 });
1830 is_never_pattern
1831 }
1832
1833 pub fn is_guaranteed_to_constitute_read_for_never(&self) -> bool {
1842 match self.kind {
1843 PatKind::Wild => false,
1845
1846 PatKind::Guard(pat, _) => pat.is_guaranteed_to_constitute_read_for_never(),
1849
1850 PatKind::Or(subpats) => {
1859 subpats.iter().all(|pat| pat.is_guaranteed_to_constitute_read_for_never())
1860 }
1861
1862 PatKind::Never => true,
1864
1865 PatKind::Missing
1868 | PatKind::Binding(_, _, _, _)
1869 | PatKind::Struct(_, _, _)
1870 | PatKind::TupleStruct(_, _, _)
1871 | PatKind::Tuple(_, _)
1872 | PatKind::Box(_)
1873 | PatKind::Ref(_, _, _)
1874 | PatKind::Deref(_)
1875 | PatKind::Expr(_)
1876 | PatKind::Range(_, _, _)
1877 | PatKind::Slice(_, _, _)
1878 | PatKind::Err(_) => true,
1879 }
1880 }
1881}
1882
1883#[derive(Debug, Clone, Copy, HashStable_Generic)]
1889pub struct PatField<'hir> {
1890 #[stable_hasher(ignore)]
1891 pub hir_id: HirId,
1892 pub ident: Ident,
1894 pub pat: &'hir Pat<'hir>,
1896 pub is_shorthand: bool,
1897 pub span: Span,
1898}
1899
1900#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1901pub enum RangeEnd {
1902 Included,
1903 Excluded,
1904}
1905
1906impl fmt::Display for RangeEnd {
1907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1908 f.write_str(match self {
1909 RangeEnd::Included => "..=",
1910 RangeEnd::Excluded => "..",
1911 })
1912 }
1913}
1914
1915#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1919pub struct DotDotPos(u32);
1920
1921impl DotDotPos {
1922 pub fn new(n: Option<usize>) -> Self {
1924 match n {
1925 Some(n) => {
1926 assert!(n < u32::MAX as usize);
1927 Self(n as u32)
1928 }
1929 None => Self(u32::MAX),
1930 }
1931 }
1932
1933 pub fn as_opt_usize(&self) -> Option<usize> {
1934 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1935 }
1936}
1937
1938impl fmt::Debug for DotDotPos {
1939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1940 self.as_opt_usize().fmt(f)
1941 }
1942}
1943
1944#[derive(Debug, Clone, Copy, HashStable_Generic)]
1945pub struct PatExpr<'hir> {
1946 #[stable_hasher(ignore)]
1947 pub hir_id: HirId,
1948 pub span: Span,
1949 pub kind: PatExprKind<'hir>,
1950}
1951
1952#[derive(Debug, Clone, Copy, HashStable_Generic)]
1953pub enum PatExprKind<'hir> {
1954 Lit {
1955 lit: Lit,
1956 negated: bool,
1959 },
1960 Path(QPath<'hir>),
1962}
1963
1964#[derive(Debug, Clone, Copy, HashStable_Generic)]
1965pub enum TyPatKind<'hir> {
1966 Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1968
1969 NotNull,
1971
1972 Or(&'hir [TyPat<'hir>]),
1974
1975 Err(ErrorGuaranteed),
1977}
1978
1979#[derive(Debug, Clone, Copy, HashStable_Generic)]
1980pub enum PatKind<'hir> {
1981 Missing,
1983
1984 Wild,
1986
1987 Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1998
1999 Struct(QPath<'hir>, &'hir [PatField<'hir>], Option<Span>),
2002
2003 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
2007
2008 Or(&'hir [Pat<'hir>]),
2011
2012 Never,
2014
2015 Tuple(&'hir [Pat<'hir>], DotDotPos),
2019
2020 Box(&'hir Pat<'hir>),
2022
2023 Deref(&'hir Pat<'hir>),
2025
2026 Ref(&'hir Pat<'hir>, Pinnedness, Mutability),
2028
2029 Expr(&'hir PatExpr<'hir>),
2031
2032 Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
2034
2035 Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
2037
2038 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
2048
2049 Err(ErrorGuaranteed),
2051}
2052
2053#[derive(Debug, Clone, Copy, HashStable_Generic)]
2055pub struct Stmt<'hir> {
2056 #[stable_hasher(ignore)]
2057 pub hir_id: HirId,
2058 pub kind: StmtKind<'hir>,
2059 pub span: Span,
2060}
2061
2062#[derive(Debug, Clone, Copy, HashStable_Generic)]
2064pub enum StmtKind<'hir> {
2065 Let(&'hir LetStmt<'hir>),
2067
2068 Item(ItemId),
2070
2071 Expr(&'hir Expr<'hir>),
2073
2074 Semi(&'hir Expr<'hir>),
2076}
2077
2078#[derive(Debug, Clone, Copy, HashStable_Generic)]
2080pub struct LetStmt<'hir> {
2081 pub super_: Option<Span>,
2083 pub pat: &'hir Pat<'hir>,
2084 pub ty: Option<&'hir Ty<'hir>>,
2086 pub init: Option<&'hir Expr<'hir>>,
2088 pub els: Option<&'hir Block<'hir>>,
2090 #[stable_hasher(ignore)]
2091 pub hir_id: HirId,
2092 pub span: Span,
2093 pub source: LocalSource,
2097}
2098
2099#[derive(Debug, Clone, Copy, HashStable_Generic)]
2102pub struct Arm<'hir> {
2103 #[stable_hasher(ignore)]
2104 pub hir_id: HirId,
2105 pub span: Span,
2106 pub pat: &'hir Pat<'hir>,
2108 pub guard: Option<&'hir Expr<'hir>>,
2110 pub body: &'hir Expr<'hir>,
2112}
2113
2114#[derive(Debug, Clone, Copy, HashStable_Generic)]
2120pub struct LetExpr<'hir> {
2121 pub span: Span,
2122 pub pat: &'hir Pat<'hir>,
2123 pub ty: Option<&'hir Ty<'hir>>,
2124 pub init: &'hir Expr<'hir>,
2125 pub recovered: ast::Recovered,
2128}
2129
2130#[derive(Debug, Clone, Copy, HashStable_Generic)]
2131pub struct ExprField<'hir> {
2132 #[stable_hasher(ignore)]
2133 pub hir_id: HirId,
2134 pub ident: Ident,
2135 pub expr: &'hir Expr<'hir>,
2136 pub span: Span,
2137 pub is_shorthand: bool,
2138}
2139
2140#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2141pub enum BlockCheckMode {
2142 DefaultBlock,
2143 UnsafeBlock(UnsafeSource),
2144}
2145
2146#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2147pub enum UnsafeSource {
2148 CompilerGenerated,
2149 UserProvided,
2150}
2151
2152#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
2153pub struct BodyId {
2154 pub hir_id: HirId,
2155}
2156
2157#[derive(Debug, Clone, Copy, HashStable_Generic)]
2179pub struct Body<'hir> {
2180 pub params: &'hir [Param<'hir>],
2181 pub value: &'hir Expr<'hir>,
2182}
2183
2184impl<'hir> Body<'hir> {
2185 pub fn id(&self) -> BodyId {
2186 BodyId { hir_id: self.value.hir_id }
2187 }
2188}
2189
2190#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2192pub enum CoroutineKind {
2193 Desugared(CoroutineDesugaring, CoroutineSource),
2195
2196 Coroutine(Movability),
2198}
2199
2200impl CoroutineKind {
2201 pub fn movability(self) -> Movability {
2202 match self {
2203 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2204 | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2205 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2206 CoroutineKind::Coroutine(mov) => mov,
2207 }
2208 }
2209
2210 pub fn is_fn_like(self) -> bool {
2211 matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2212 }
2213
2214 pub fn to_plural_string(&self) -> String {
2215 match self {
2216 CoroutineKind::Desugared(d, CoroutineSource::Fn) => format!("{d:#}fn bodies"),
2217 CoroutineKind::Desugared(d, CoroutineSource::Block) => format!("{d:#}blocks"),
2218 CoroutineKind::Desugared(d, CoroutineSource::Closure) => format!("{d:#}closure bodies"),
2219 CoroutineKind::Coroutine(_) => "coroutines".to_string(),
2220 }
2221 }
2222}
2223
2224impl fmt::Display for CoroutineKind {
2225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2226 match self {
2227 CoroutineKind::Desugared(d, k) => {
2228 d.fmt(f)?;
2229 k.fmt(f)
2230 }
2231 CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2232 }
2233 }
2234}
2235
2236#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
2242pub enum CoroutineSource {
2243 Block,
2245
2246 Closure,
2248
2249 Fn,
2251}
2252
2253impl fmt::Display for CoroutineSource {
2254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2255 match self {
2256 CoroutineSource::Block => "block",
2257 CoroutineSource::Closure => "closure body",
2258 CoroutineSource::Fn => "fn body",
2259 }
2260 .fmt(f)
2261 }
2262}
2263
2264#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2265pub enum CoroutineDesugaring {
2266 Async,
2268
2269 Gen,
2271
2272 AsyncGen,
2275}
2276
2277impl fmt::Display for CoroutineDesugaring {
2278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2279 match self {
2280 CoroutineDesugaring::Async => {
2281 if f.alternate() {
2282 f.write_str("`async` ")?;
2283 } else {
2284 f.write_str("async ")?
2285 }
2286 }
2287 CoroutineDesugaring::Gen => {
2288 if f.alternate() {
2289 f.write_str("`gen` ")?;
2290 } else {
2291 f.write_str("gen ")?
2292 }
2293 }
2294 CoroutineDesugaring::AsyncGen => {
2295 if f.alternate() {
2296 f.write_str("`async gen` ")?;
2297 } else {
2298 f.write_str("async gen ")?
2299 }
2300 }
2301 }
2302
2303 Ok(())
2304 }
2305}
2306
2307#[derive(Copy, Clone, Debug)]
2308pub enum BodyOwnerKind {
2309 Fn,
2311
2312 Closure,
2314
2315 Const { inline: bool },
2317
2318 Static(Mutability),
2320
2321 GlobalAsm,
2323}
2324
2325impl BodyOwnerKind {
2326 pub fn is_fn_or_closure(self) -> bool {
2327 match self {
2328 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2329 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2330 false
2331 }
2332 }
2333 }
2334}
2335
2336#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2338pub enum ConstContext {
2339 ConstFn,
2341
2342 Static(Mutability),
2344
2345 Const { inline: bool },
2355}
2356
2357impl ConstContext {
2358 pub fn keyword_name(self) -> &'static str {
2362 match self {
2363 Self::Const { .. } => "const",
2364 Self::Static(Mutability::Not) => "static",
2365 Self::Static(Mutability::Mut) => "static mut",
2366 Self::ConstFn => "const fn",
2367 }
2368 }
2369}
2370
2371impl fmt::Display for ConstContext {
2374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2375 match *self {
2376 Self::Const { .. } => write!(f, "constant"),
2377 Self::Static(_) => write!(f, "static"),
2378 Self::ConstFn => write!(f, "constant function"),
2379 }
2380 }
2381}
2382
2383impl IntoDiagArg for ConstContext {
2384 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
2385 DiagArgValue::Str(Cow::Borrowed(match self {
2386 ConstContext::ConstFn => "const_fn",
2387 ConstContext::Static(_) => "static",
2388 ConstContext::Const { .. } => "const",
2389 }))
2390 }
2391}
2392
2393pub type Lit = Spanned<LitKind>;
2395
2396#[derive(Copy, Clone, Debug, HashStable_Generic)]
2405pub struct AnonConst {
2406 #[stable_hasher(ignore)]
2407 pub hir_id: HirId,
2408 pub def_id: LocalDefId,
2409 pub body: BodyId,
2410 pub span: Span,
2411}
2412
2413#[derive(Copy, Clone, Debug, HashStable_Generic)]
2415pub struct ConstBlock {
2416 #[stable_hasher(ignore)]
2417 pub hir_id: HirId,
2418 pub def_id: LocalDefId,
2419 pub body: BodyId,
2420}
2421
2422#[derive(Debug, Clone, Copy, HashStable_Generic)]
2431pub struct Expr<'hir> {
2432 #[stable_hasher(ignore)]
2433 pub hir_id: HirId,
2434 pub kind: ExprKind<'hir>,
2435 pub span: Span,
2436}
2437
2438impl Expr<'_> {
2439 pub fn precedence(&self, has_attr: &dyn Fn(HirId) -> bool) -> ExprPrecedence {
2440 let prefix_attrs_precedence = || -> ExprPrecedence {
2441 if has_attr(self.hir_id) { ExprPrecedence::Prefix } else { ExprPrecedence::Unambiguous }
2442 };
2443
2444 match &self.kind {
2445 ExprKind::Closure(closure) => {
2446 match closure.fn_decl.output {
2447 FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2448 FnRetTy::Return(_) => prefix_attrs_precedence(),
2449 }
2450 }
2451
2452 ExprKind::Break(..)
2453 | ExprKind::Ret(..)
2454 | ExprKind::Yield(..)
2455 | ExprKind::Become(..) => ExprPrecedence::Jump,
2456
2457 ExprKind::Binary(op, ..) => op.node.precedence(),
2459 ExprKind::Cast(..) => ExprPrecedence::Cast,
2460
2461 ExprKind::Assign(..) |
2462 ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2463
2464 ExprKind::AddrOf(..)
2466 | ExprKind::Let(..)
2471 | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2472
2473 ExprKind::Array(_)
2475 | ExprKind::Block(..)
2476 | ExprKind::Call(..)
2477 | ExprKind::ConstBlock(_)
2478 | ExprKind::Continue(..)
2479 | ExprKind::Field(..)
2480 | ExprKind::If(..)
2481 | ExprKind::Index(..)
2482 | ExprKind::InlineAsm(..)
2483 | ExprKind::Lit(_)
2484 | ExprKind::Loop(..)
2485 | ExprKind::Match(..)
2486 | ExprKind::MethodCall(..)
2487 | ExprKind::OffsetOf(..)
2488 | ExprKind::Path(..)
2489 | ExprKind::Repeat(..)
2490 | ExprKind::Struct(..)
2491 | ExprKind::Tup(_)
2492 | ExprKind::Type(..)
2493 | ExprKind::UnsafeBinderCast(..)
2494 | ExprKind::Use(..)
2495 | ExprKind::Err(_) => prefix_attrs_precedence(),
2496
2497 ExprKind::DropTemps(expr, ..) => expr.precedence(has_attr),
2498 }
2499 }
2500
2501 pub fn is_syntactic_place_expr(&self) -> bool {
2506 self.is_place_expr(|_| true)
2507 }
2508
2509 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2514 match self.kind {
2515 ExprKind::Path(QPath::Resolved(_, ref path)) => {
2516 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2517 }
2518
2519 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2523
2524 ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2526
2527 ExprKind::Unary(UnOp::Deref, _) => true,
2528
2529 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2530 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2531 }
2532
2533 ExprKind::Err(_guar)
2535 | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2536
2537 ExprKind::Path(QPath::TypeRelative(..))
2540 | ExprKind::Call(..)
2541 | ExprKind::MethodCall(..)
2542 | ExprKind::Use(..)
2543 | ExprKind::Struct(..)
2544 | ExprKind::Tup(..)
2545 | ExprKind::If(..)
2546 | ExprKind::Match(..)
2547 | ExprKind::Closure { .. }
2548 | ExprKind::Block(..)
2549 | ExprKind::Repeat(..)
2550 | ExprKind::Array(..)
2551 | ExprKind::Break(..)
2552 | ExprKind::Continue(..)
2553 | ExprKind::Ret(..)
2554 | ExprKind::Become(..)
2555 | ExprKind::Let(..)
2556 | ExprKind::Loop(..)
2557 | ExprKind::Assign(..)
2558 | ExprKind::InlineAsm(..)
2559 | ExprKind::OffsetOf(..)
2560 | ExprKind::AssignOp(..)
2561 | ExprKind::Lit(_)
2562 | ExprKind::ConstBlock(..)
2563 | ExprKind::Unary(..)
2564 | ExprKind::AddrOf(..)
2565 | ExprKind::Binary(..)
2566 | ExprKind::Yield(..)
2567 | ExprKind::Cast(..)
2568 | ExprKind::DropTemps(..) => false,
2569 }
2570 }
2571
2572 pub fn range_span(&self) -> Option<Span> {
2575 is_range_literal(self).then(|| self.span.parent_callsite().unwrap())
2576 }
2577
2578 pub fn is_size_lit(&self) -> bool {
2581 matches!(
2582 self.kind,
2583 ExprKind::Lit(Lit {
2584 node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2585 ..
2586 })
2587 )
2588 }
2589
2590 pub fn peel_drop_temps(&self) -> &Self {
2596 let mut expr = self;
2597 while let ExprKind::DropTemps(inner) = &expr.kind {
2598 expr = inner;
2599 }
2600 expr
2601 }
2602
2603 pub fn peel_blocks(&self) -> &Self {
2604 let mut expr = self;
2605 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2606 expr = inner;
2607 }
2608 expr
2609 }
2610
2611 pub fn peel_borrows(&self) -> &Self {
2612 let mut expr = self;
2613 while let ExprKind::AddrOf(.., inner) = &expr.kind {
2614 expr = inner;
2615 }
2616 expr
2617 }
2618
2619 pub fn can_have_side_effects(&self) -> bool {
2620 match self.peel_drop_temps().kind {
2621 ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2622 false
2623 }
2624 ExprKind::Type(base, _)
2625 | ExprKind::Unary(_, base)
2626 | ExprKind::Field(base, _)
2627 | ExprKind::Index(base, _, _)
2628 | ExprKind::AddrOf(.., base)
2629 | ExprKind::Cast(base, _)
2630 | ExprKind::UnsafeBinderCast(_, base, _) => {
2631 base.can_have_side_effects()
2635 }
2636 ExprKind::Binary(_, lhs, rhs) => {
2637 lhs.can_have_side_effects() || rhs.can_have_side_effects()
2641 }
2642 ExprKind::Struct(_, fields, init) => {
2643 let init_side_effects = match init {
2644 StructTailExpr::Base(init) => init.can_have_side_effects(),
2645 StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2646 };
2647 fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2648 || init_side_effects
2649 }
2650
2651 ExprKind::Array(args)
2652 | ExprKind::Tup(args)
2653 | ExprKind::Call(
2654 Expr {
2655 kind:
2656 ExprKind::Path(QPath::Resolved(
2657 None,
2658 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2659 )),
2660 ..
2661 },
2662 args,
2663 ) => args.iter().any(|arg| arg.can_have_side_effects()),
2664 ExprKind::Repeat(arg, _) => arg.can_have_side_effects(),
2665 ExprKind::If(..)
2666 | ExprKind::Match(..)
2667 | ExprKind::MethodCall(..)
2668 | ExprKind::Call(..)
2669 | ExprKind::Closure { .. }
2670 | ExprKind::Block(..)
2671 | ExprKind::Break(..)
2672 | ExprKind::Continue(..)
2673 | ExprKind::Ret(..)
2674 | ExprKind::Become(..)
2675 | ExprKind::Let(..)
2676 | ExprKind::Loop(..)
2677 | ExprKind::Assign(..)
2678 | ExprKind::InlineAsm(..)
2679 | ExprKind::AssignOp(..)
2680 | ExprKind::ConstBlock(..)
2681 | ExprKind::Yield(..)
2682 | ExprKind::DropTemps(..)
2683 | ExprKind::Err(_) => true,
2684 }
2685 }
2686
2687 pub fn is_approximately_pattern(&self) -> bool {
2689 match &self.kind {
2690 ExprKind::Array(_)
2691 | ExprKind::Call(..)
2692 | ExprKind::Tup(_)
2693 | ExprKind::Lit(_)
2694 | ExprKind::Path(_)
2695 | ExprKind::Struct(..) => true,
2696 _ => false,
2697 }
2698 }
2699
2700 pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2705 match (self.kind, other.kind) {
2706 (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2707 (
2708 ExprKind::Path(QPath::Resolved(None, path1)),
2709 ExprKind::Path(QPath::Resolved(None, path2)),
2710 ) => path1.res == path2.res,
2711 (
2712 ExprKind::Struct(
2713 &QPath::Resolved(None, &Path { res: Res::Def(_, path1_def_id), .. }),
2714 args1,
2715 StructTailExpr::None,
2716 ),
2717 ExprKind::Struct(
2718 &QPath::Resolved(None, &Path { res: Res::Def(_, path2_def_id), .. }),
2719 args2,
2720 StructTailExpr::None,
2721 ),
2722 ) => {
2723 path2_def_id == path1_def_id
2724 && is_range_literal(self)
2725 && is_range_literal(other)
2726 && std::iter::zip(args1, args2)
2727 .all(|(a, b)| a.expr.equivalent_for_indexing(b.expr))
2728 }
2729 _ => false,
2730 }
2731 }
2732
2733 pub fn method_ident(&self) -> Option<Ident> {
2734 match self.kind {
2735 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2736 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2737 _ => None,
2738 }
2739 }
2740}
2741
2742pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2745 if let ExprKind::Struct(QPath::Resolved(None, path), _, StructTailExpr::None) = expr.kind
2746 && let [.., segment] = path.segments
2747 && let sym::RangeFrom
2748 | sym::RangeFull
2749 | sym::Range
2750 | sym::RangeToInclusive
2751 | sym::RangeTo
2752 | sym::RangeFromCopy
2753 | sym::RangeCopy
2754 | sym::RangeInclusiveCopy
2755 | sym::RangeToInclusiveCopy = segment.ident.name
2756 && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2757 {
2758 true
2759 } else if let ExprKind::Call(func, _) = &expr.kind
2760 && let ExprKind::Path(QPath::Resolved(None, path)) = func.kind
2761 && let [.., segment] = path.segments
2762 && let sym::range_inclusive_new = segment.ident.name
2763 && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2764 {
2765 true
2766 } else {
2767 false
2768 }
2769}
2770
2771pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2778 match expr.kind {
2779 ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2781 _ if is_range_literal(expr) => true,
2783 _ => false,
2784 }
2785}
2786
2787#[derive(Debug, Clone, Copy, HashStable_Generic)]
2788pub enum ExprKind<'hir> {
2789 ConstBlock(ConstBlock),
2791 Array(&'hir [Expr<'hir>]),
2793 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2800 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2817 Use(&'hir Expr<'hir>, Span),
2819 Tup(&'hir [Expr<'hir>]),
2821 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2823 Unary(UnOp, &'hir Expr<'hir>),
2825 Lit(Lit),
2827 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2829 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2831 DropTemps(&'hir Expr<'hir>),
2837 Let(&'hir LetExpr<'hir>),
2842 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2851 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2857 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2860 Closure(&'hir Closure<'hir>),
2867 Block(&'hir Block<'hir>, Option<Label>),
2869
2870 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2872 AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2876 Field(&'hir Expr<'hir>, Ident),
2878 Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2882
2883 Path(QPath<'hir>),
2885
2886 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2888 Break(Destination, Option<&'hir Expr<'hir>>),
2890 Continue(Destination),
2892 Ret(Option<&'hir Expr<'hir>>),
2894 Become(&'hir Expr<'hir>),
2896
2897 InlineAsm(&'hir InlineAsm<'hir>),
2899
2900 OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2902
2903 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2908
2909 Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2914
2915 Yield(&'hir Expr<'hir>, YieldSource),
2917
2918 UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2921
2922 Err(rustc_span::ErrorGuaranteed),
2924}
2925
2926#[derive(Debug, Clone, Copy, HashStable_Generic)]
2927pub enum StructTailExpr<'hir> {
2928 None,
2930 Base(&'hir Expr<'hir>),
2933 DefaultFields(Span),
2937}
2938
2939#[derive(Debug, Clone, Copy, HashStable_Generic)]
2945pub enum QPath<'hir> {
2946 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2953
2954 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2961}
2962
2963impl<'hir> QPath<'hir> {
2964 pub fn span(&self) -> Span {
2966 match *self {
2967 QPath::Resolved(_, path) => path.span,
2968 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2969 }
2970 }
2971
2972 pub fn qself_span(&self) -> Span {
2975 match *self {
2976 QPath::Resolved(_, path) => path.span,
2977 QPath::TypeRelative(qself, _) => qself.span,
2978 }
2979 }
2980}
2981
2982#[derive(Copy, Clone, Debug, HashStable_Generic)]
2984pub enum LocalSource {
2985 Normal,
2987 AsyncFn,
2998 AwaitDesugar,
3000 AssignDesugar,
3002 Contract,
3004}
3005
3006#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
3008pub enum MatchSource {
3009 Normal,
3011 Postfix,
3013 ForLoopDesugar,
3015 TryDesugar(HirId),
3017 AwaitDesugar,
3019 FormatArgs,
3021}
3022
3023impl MatchSource {
3024 #[inline]
3025 pub const fn name(self) -> &'static str {
3026 use MatchSource::*;
3027 match self {
3028 Normal => "match",
3029 Postfix => ".match",
3030 ForLoopDesugar => "for",
3031 TryDesugar(_) => "?",
3032 AwaitDesugar => ".await",
3033 FormatArgs => "format_args!()",
3034 }
3035 }
3036}
3037
3038#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3040pub enum LoopSource {
3041 Loop,
3043 While,
3045 ForLoop,
3047}
3048
3049impl LoopSource {
3050 pub fn name(self) -> &'static str {
3051 match self {
3052 LoopSource::Loop => "loop",
3053 LoopSource::While => "while",
3054 LoopSource::ForLoop => "for",
3055 }
3056 }
3057}
3058
3059#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
3060pub enum LoopIdError {
3061 OutsideLoopScope,
3062 UnlabeledCfInWhileCondition,
3063 UnresolvedLabel,
3064}
3065
3066impl fmt::Display for LoopIdError {
3067 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3068 f.write_str(match self {
3069 LoopIdError::OutsideLoopScope => "not inside loop scope",
3070 LoopIdError::UnlabeledCfInWhileCondition => {
3071 "unlabeled control flow (break or continue) in while condition"
3072 }
3073 LoopIdError::UnresolvedLabel => "label not found",
3074 })
3075 }
3076}
3077
3078#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
3079pub struct Destination {
3080 pub label: Option<Label>,
3082
3083 pub target_id: Result<HirId, LoopIdError>,
3086}
3087
3088#[derive(Copy, Clone, Debug, HashStable_Generic)]
3090pub enum YieldSource {
3091 Await { expr: Option<HirId> },
3093 Yield,
3095}
3096
3097impl fmt::Display for YieldSource {
3098 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3099 f.write_str(match self {
3100 YieldSource::Await { .. } => "`await`",
3101 YieldSource::Yield => "`yield`",
3102 })
3103 }
3104}
3105
3106#[derive(Debug, Clone, Copy, HashStable_Generic)]
3109pub struct MutTy<'hir> {
3110 pub ty: &'hir Ty<'hir>,
3111 pub mutbl: Mutability,
3112}
3113
3114#[derive(Debug, Clone, Copy, HashStable_Generic)]
3117pub struct FnSig<'hir> {
3118 pub header: FnHeader,
3119 pub decl: &'hir FnDecl<'hir>,
3120 pub span: Span,
3121}
3122
3123#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3127pub struct TraitItemId {
3128 pub owner_id: OwnerId,
3129}
3130
3131impl TraitItemId {
3132 #[inline]
3133 pub fn hir_id(&self) -> HirId {
3134 HirId::make_owner(self.owner_id.def_id)
3136 }
3137}
3138
3139#[derive(Debug, Clone, Copy, HashStable_Generic)]
3144pub struct TraitItem<'hir> {
3145 pub ident: Ident,
3146 pub owner_id: OwnerId,
3147 pub generics: &'hir Generics<'hir>,
3148 pub kind: TraitItemKind<'hir>,
3149 pub span: Span,
3150 pub defaultness: Defaultness,
3151 pub has_delayed_lints: bool,
3152}
3153
3154macro_rules! expect_methods_self_kind {
3155 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3156 $(
3157 #[track_caller]
3158 pub fn $name(&self) -> $ret_ty {
3159 let $pat = &self.kind else { expect_failed(stringify!($name), self) };
3160 $ret_val
3161 }
3162 )*
3163 }
3164}
3165
3166macro_rules! expect_methods_self {
3167 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3168 $(
3169 #[track_caller]
3170 pub fn $name(&self) -> $ret_ty {
3171 let $pat = self else { expect_failed(stringify!($name), self) };
3172 $ret_val
3173 }
3174 )*
3175 }
3176}
3177
3178#[track_caller]
3179fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3180 panic!("{ident}: found {found:?}")
3181}
3182
3183impl<'hir> TraitItem<'hir> {
3184 #[inline]
3185 pub fn hir_id(&self) -> HirId {
3186 HirId::make_owner(self.owner_id.def_id)
3188 }
3189
3190 pub fn trait_item_id(&self) -> TraitItemId {
3191 TraitItemId { owner_id: self.owner_id }
3192 }
3193
3194 expect_methods_self_kind! {
3195 expect_const, (&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3196 TraitItemKind::Const(ty, rhs), (ty, *rhs);
3197
3198 expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3199 TraitItemKind::Fn(ty, trfn), (ty, trfn);
3200
3201 expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3202 TraitItemKind::Type(bounds, ty), (bounds, *ty);
3203 }
3204}
3205
3206#[derive(Debug, Clone, Copy, HashStable_Generic)]
3208pub enum TraitFn<'hir> {
3209 Required(&'hir [Option<Ident>]),
3211
3212 Provided(BodyId),
3214}
3215
3216#[derive(Debug, Clone, Copy, HashStable_Generic)]
3218pub enum TraitItemKind<'hir> {
3219 Const(&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3221 Fn(FnSig<'hir>, TraitFn<'hir>),
3223 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3226}
3227
3228#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3232pub struct ImplItemId {
3233 pub owner_id: OwnerId,
3234}
3235
3236impl ImplItemId {
3237 #[inline]
3238 pub fn hir_id(&self) -> HirId {
3239 HirId::make_owner(self.owner_id.def_id)
3241 }
3242}
3243
3244#[derive(Debug, Clone, Copy, HashStable_Generic)]
3248pub struct ImplItem<'hir> {
3249 pub ident: Ident,
3250 pub owner_id: OwnerId,
3251 pub generics: &'hir Generics<'hir>,
3252 pub kind: ImplItemKind<'hir>,
3253 pub impl_kind: ImplItemImplKind,
3254 pub span: Span,
3255 pub has_delayed_lints: bool,
3256}
3257
3258#[derive(Debug, Clone, Copy, HashStable_Generic)]
3259pub enum ImplItemImplKind {
3260 Inherent {
3261 vis_span: Span,
3262 },
3263 Trait {
3264 defaultness: Defaultness,
3265 trait_item_def_id: Result<DefId, ErrorGuaranteed>,
3267 },
3268}
3269
3270impl<'hir> ImplItem<'hir> {
3271 #[inline]
3272 pub fn hir_id(&self) -> HirId {
3273 HirId::make_owner(self.owner_id.def_id)
3275 }
3276
3277 pub fn impl_item_id(&self) -> ImplItemId {
3278 ImplItemId { owner_id: self.owner_id }
3279 }
3280
3281 pub fn vis_span(&self) -> Option<Span> {
3282 match self.impl_kind {
3283 ImplItemImplKind::Trait { .. } => None,
3284 ImplItemImplKind::Inherent { vis_span, .. } => Some(vis_span),
3285 }
3286 }
3287
3288 expect_methods_self_kind! {
3289 expect_const, (&'hir Ty<'hir>, ConstItemRhs<'hir>), ImplItemKind::Const(ty, rhs), (ty, *rhs);
3290 expect_fn, (&FnSig<'hir>, BodyId), ImplItemKind::Fn(ty, body), (ty, *body);
3291 expect_type, &'hir Ty<'hir>, ImplItemKind::Type(ty), ty;
3292 }
3293}
3294
3295#[derive(Debug, Clone, Copy, HashStable_Generic)]
3297pub enum ImplItemKind<'hir> {
3298 Const(&'hir Ty<'hir>, ConstItemRhs<'hir>),
3301 Fn(FnSig<'hir>, BodyId),
3303 Type(&'hir Ty<'hir>),
3305}
3306
3307#[derive(Debug, Clone, Copy, HashStable_Generic)]
3318pub struct AssocItemConstraint<'hir> {
3319 #[stable_hasher(ignore)]
3320 pub hir_id: HirId,
3321 pub ident: Ident,
3322 pub gen_args: &'hir GenericArgs<'hir>,
3323 pub kind: AssocItemConstraintKind<'hir>,
3324 pub span: Span,
3325}
3326
3327impl<'hir> AssocItemConstraint<'hir> {
3328 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3330 match self.kind {
3331 AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3332 _ => None,
3333 }
3334 }
3335
3336 pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3338 match self.kind {
3339 AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3340 _ => None,
3341 }
3342 }
3343}
3344
3345#[derive(Debug, Clone, Copy, HashStable_Generic)]
3346pub enum Term<'hir> {
3347 Ty(&'hir Ty<'hir>),
3348 Const(&'hir ConstArg<'hir>),
3349}
3350
3351impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3352 fn from(ty: &'hir Ty<'hir>) -> Self {
3353 Term::Ty(ty)
3354 }
3355}
3356
3357impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3358 fn from(c: &'hir ConstArg<'hir>) -> Self {
3359 Term::Const(c)
3360 }
3361}
3362
3363#[derive(Debug, Clone, Copy, HashStable_Generic)]
3365pub enum AssocItemConstraintKind<'hir> {
3366 Equality { term: Term<'hir> },
3373 Bound { bounds: &'hir [GenericBound<'hir>] },
3375}
3376
3377impl<'hir> AssocItemConstraintKind<'hir> {
3378 pub fn descr(&self) -> &'static str {
3379 match self {
3380 AssocItemConstraintKind::Equality { .. } => "binding",
3381 AssocItemConstraintKind::Bound { .. } => "constraint",
3382 }
3383 }
3384}
3385
3386#[derive(Debug, Clone, Copy, HashStable_Generic)]
3390pub enum AmbigArg {}
3391
3392#[derive(Debug, Clone, Copy, HashStable_Generic)]
3397#[repr(C)]
3398pub struct Ty<'hir, Unambig = ()> {
3399 #[stable_hasher(ignore)]
3400 pub hir_id: HirId,
3401 pub span: Span,
3402 pub kind: TyKind<'hir, Unambig>,
3403}
3404
3405impl<'hir> Ty<'hir, AmbigArg> {
3406 pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3417 let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3420 unsafe { &*ptr }
3421 }
3422}
3423
3424impl<'hir> Ty<'hir> {
3425 pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3431 if let TyKind::Infer(()) = self.kind {
3432 return None;
3433 }
3434
3435 let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3439 Some(unsafe { &*ptr })
3440 }
3441}
3442
3443impl<'hir> Ty<'hir, AmbigArg> {
3444 pub fn peel_refs(&self) -> &Ty<'hir> {
3445 let mut final_ty = self.as_unambig_ty();
3446 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3447 final_ty = ty;
3448 }
3449 final_ty
3450 }
3451}
3452
3453impl<'hir> Ty<'hir> {
3454 pub fn peel_refs(&self) -> &Self {
3455 let mut final_ty = self;
3456 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3457 final_ty = ty;
3458 }
3459 final_ty
3460 }
3461
3462 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3464 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3465 return None;
3466 };
3467 let [segment] = &path.segments else {
3468 return None;
3469 };
3470 match path.res {
3471 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3472 Some((def_id, segment.ident))
3473 }
3474 _ => None,
3475 }
3476 }
3477
3478 pub fn find_self_aliases(&self) -> Vec<Span> {
3479 use crate::intravisit::Visitor;
3480 struct MyVisitor(Vec<Span>);
3481 impl<'v> Visitor<'v> for MyVisitor {
3482 fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3483 if matches!(
3484 &t.kind,
3485 TyKind::Path(QPath::Resolved(
3486 _,
3487 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3488 ))
3489 ) {
3490 self.0.push(t.span);
3491 return;
3492 }
3493 crate::intravisit::walk_ty(self, t);
3494 }
3495 }
3496
3497 let mut my_visitor = MyVisitor(vec![]);
3498 my_visitor.visit_ty_unambig(self);
3499 my_visitor.0
3500 }
3501
3502 pub fn is_suggestable_infer_ty(&self) -> bool {
3505 fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3506 generic_args.iter().any(|arg| match arg {
3507 GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3508 GenericArg::Infer(_) => true,
3509 _ => false,
3510 })
3511 }
3512 debug!(?self);
3513 match &self.kind {
3514 TyKind::Infer(()) => true,
3515 TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3516 TyKind::Array(ty, length) => {
3517 ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3518 }
3519 TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3520 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3521 TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3522 ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3523 }
3524 TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3525 ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3526 || segments
3527 .iter()
3528 .any(|segment| are_suggestable_generic_args(segment.args().args))
3529 }
3530 _ => false,
3531 }
3532 }
3533}
3534
3535#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3537pub enum PrimTy {
3538 Int(IntTy),
3539 Uint(UintTy),
3540 Float(FloatTy),
3541 Str,
3542 Bool,
3543 Char,
3544}
3545
3546impl PrimTy {
3547 pub const ALL: [Self; 19] = [
3549 Self::Int(IntTy::I8),
3551 Self::Int(IntTy::I16),
3552 Self::Int(IntTy::I32),
3553 Self::Int(IntTy::I64),
3554 Self::Int(IntTy::I128),
3555 Self::Int(IntTy::Isize),
3556 Self::Uint(UintTy::U8),
3557 Self::Uint(UintTy::U16),
3558 Self::Uint(UintTy::U32),
3559 Self::Uint(UintTy::U64),
3560 Self::Uint(UintTy::U128),
3561 Self::Uint(UintTy::Usize),
3562 Self::Float(FloatTy::F16),
3563 Self::Float(FloatTy::F32),
3564 Self::Float(FloatTy::F64),
3565 Self::Float(FloatTy::F128),
3566 Self::Bool,
3567 Self::Char,
3568 Self::Str,
3569 ];
3570
3571 pub fn name_str(self) -> &'static str {
3575 match self {
3576 PrimTy::Int(i) => i.name_str(),
3577 PrimTy::Uint(u) => u.name_str(),
3578 PrimTy::Float(f) => f.name_str(),
3579 PrimTy::Str => "str",
3580 PrimTy::Bool => "bool",
3581 PrimTy::Char => "char",
3582 }
3583 }
3584
3585 pub fn name(self) -> Symbol {
3586 match self {
3587 PrimTy::Int(i) => i.name(),
3588 PrimTy::Uint(u) => u.name(),
3589 PrimTy::Float(f) => f.name(),
3590 PrimTy::Str => sym::str,
3591 PrimTy::Bool => sym::bool,
3592 PrimTy::Char => sym::char,
3593 }
3594 }
3595
3596 pub fn from_name(name: Symbol) -> Option<Self> {
3599 let ty = match name {
3600 sym::i8 => Self::Int(IntTy::I8),
3602 sym::i16 => Self::Int(IntTy::I16),
3603 sym::i32 => Self::Int(IntTy::I32),
3604 sym::i64 => Self::Int(IntTy::I64),
3605 sym::i128 => Self::Int(IntTy::I128),
3606 sym::isize => Self::Int(IntTy::Isize),
3607 sym::u8 => Self::Uint(UintTy::U8),
3608 sym::u16 => Self::Uint(UintTy::U16),
3609 sym::u32 => Self::Uint(UintTy::U32),
3610 sym::u64 => Self::Uint(UintTy::U64),
3611 sym::u128 => Self::Uint(UintTy::U128),
3612 sym::usize => Self::Uint(UintTy::Usize),
3613 sym::f16 => Self::Float(FloatTy::F16),
3614 sym::f32 => Self::Float(FloatTy::F32),
3615 sym::f64 => Self::Float(FloatTy::F64),
3616 sym::f128 => Self::Float(FloatTy::F128),
3617 sym::bool => Self::Bool,
3618 sym::char => Self::Char,
3619 sym::str => Self::Str,
3620 _ => return None,
3621 };
3622 Some(ty)
3623 }
3624}
3625
3626#[derive(Debug, Clone, Copy, HashStable_Generic)]
3627pub struct FnPtrTy<'hir> {
3628 pub safety: Safety,
3629 pub abi: ExternAbi,
3630 pub generic_params: &'hir [GenericParam<'hir>],
3631 pub decl: &'hir FnDecl<'hir>,
3632 pub param_idents: &'hir [Option<Ident>],
3635}
3636
3637#[derive(Debug, Clone, Copy, HashStable_Generic)]
3638pub struct UnsafeBinderTy<'hir> {
3639 pub generic_params: &'hir [GenericParam<'hir>],
3640 pub inner_ty: &'hir Ty<'hir>,
3641}
3642
3643#[derive(Debug, Clone, Copy, HashStable_Generic)]
3644pub struct OpaqueTy<'hir> {
3645 #[stable_hasher(ignore)]
3646 pub hir_id: HirId,
3647 pub def_id: LocalDefId,
3648 pub bounds: GenericBounds<'hir>,
3649 pub origin: OpaqueTyOrigin<LocalDefId>,
3650 pub span: Span,
3651}
3652
3653#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3654pub enum PreciseCapturingArgKind<T, U> {
3655 Lifetime(T),
3656 Param(U),
3658}
3659
3660pub type PreciseCapturingArg<'hir> =
3661 PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3662
3663impl PreciseCapturingArg<'_> {
3664 pub fn hir_id(self) -> HirId {
3665 match self {
3666 PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3667 PreciseCapturingArg::Param(param) => param.hir_id,
3668 }
3669 }
3670
3671 pub fn name(self) -> Symbol {
3672 match self {
3673 PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3674 PreciseCapturingArg::Param(param) => param.ident.name,
3675 }
3676 }
3677}
3678
3679#[derive(Debug, Clone, Copy, HashStable_Generic)]
3684pub struct PreciseCapturingNonLifetimeArg {
3685 #[stable_hasher(ignore)]
3686 pub hir_id: HirId,
3687 pub ident: Ident,
3688 pub res: Res,
3689}
3690
3691#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3692#[derive(HashStable_Generic, Encodable, Decodable)]
3693pub enum RpitContext {
3694 Trait,
3695 TraitImpl,
3696}
3697
3698#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3700#[derive(HashStable_Generic, Encodable, Decodable)]
3701pub enum OpaqueTyOrigin<D> {
3702 FnReturn {
3704 parent: D,
3706 in_trait_or_impl: Option<RpitContext>,
3708 },
3709 AsyncFn {
3711 parent: D,
3713 in_trait_or_impl: Option<RpitContext>,
3715 },
3716 TyAlias {
3718 parent: D,
3720 in_assoc_ty: bool,
3722 },
3723}
3724
3725#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3726pub enum InferDelegationKind {
3727 Input(usize),
3728 Output,
3729}
3730
3731#[repr(u8, C)]
3737#[derive(Debug, Clone, Copy, HashStable_Generic)]
3738pub enum TyKind<'hir, Unambig = ()> {
3739 InferDelegation(DefId, InferDelegationKind),
3741 Slice(&'hir Ty<'hir>),
3743 Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3745 Ptr(MutTy<'hir>),
3747 Ref(&'hir Lifetime, MutTy<'hir>),
3749 FnPtr(&'hir FnPtrTy<'hir>),
3751 UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3753 Never,
3755 Tup(&'hir [Ty<'hir>]),
3757 Path(QPath<'hir>),
3762 OpaqueDef(&'hir OpaqueTy<'hir>),
3764 TraitAscription(GenericBounds<'hir>),
3766 TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3772 Err(rustc_span::ErrorGuaranteed),
3774 Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3776 Infer(Unambig),
3782}
3783
3784#[derive(Debug, Clone, Copy, HashStable_Generic)]
3785pub enum InlineAsmOperand<'hir> {
3786 In {
3787 reg: InlineAsmRegOrRegClass,
3788 expr: &'hir Expr<'hir>,
3789 },
3790 Out {
3791 reg: InlineAsmRegOrRegClass,
3792 late: bool,
3793 expr: Option<&'hir Expr<'hir>>,
3794 },
3795 InOut {
3796 reg: InlineAsmRegOrRegClass,
3797 late: bool,
3798 expr: &'hir Expr<'hir>,
3799 },
3800 SplitInOut {
3801 reg: InlineAsmRegOrRegClass,
3802 late: bool,
3803 in_expr: &'hir Expr<'hir>,
3804 out_expr: Option<&'hir Expr<'hir>>,
3805 },
3806 Const {
3807 anon_const: ConstBlock,
3808 },
3809 SymFn {
3810 expr: &'hir Expr<'hir>,
3811 },
3812 SymStatic {
3813 path: QPath<'hir>,
3814 def_id: DefId,
3815 },
3816 Label {
3817 block: &'hir Block<'hir>,
3818 },
3819}
3820
3821impl<'hir> InlineAsmOperand<'hir> {
3822 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3823 match *self {
3824 Self::In { reg, .. }
3825 | Self::Out { reg, .. }
3826 | Self::InOut { reg, .. }
3827 | Self::SplitInOut { reg, .. } => Some(reg),
3828 Self::Const { .. }
3829 | Self::SymFn { .. }
3830 | Self::SymStatic { .. }
3831 | Self::Label { .. } => None,
3832 }
3833 }
3834
3835 pub fn is_clobber(&self) -> bool {
3836 matches!(
3837 self,
3838 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3839 )
3840 }
3841}
3842
3843#[derive(Debug, Clone, Copy, HashStable_Generic)]
3844pub struct InlineAsm<'hir> {
3845 pub asm_macro: ast::AsmMacro,
3846 pub template: &'hir [InlineAsmTemplatePiece],
3847 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3848 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3849 pub options: InlineAsmOptions,
3850 pub line_spans: &'hir [Span],
3851}
3852
3853impl InlineAsm<'_> {
3854 pub fn contains_label(&self) -> bool {
3855 self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3856 }
3857}
3858
3859#[derive(Debug, Clone, Copy, HashStable_Generic)]
3861pub struct Param<'hir> {
3862 #[stable_hasher(ignore)]
3863 pub hir_id: HirId,
3864 pub pat: &'hir Pat<'hir>,
3865 pub ty_span: Span,
3866 pub span: Span,
3867}
3868
3869#[derive(Debug, Clone, Copy, HashStable_Generic)]
3871pub struct FnDecl<'hir> {
3872 pub inputs: &'hir [Ty<'hir>],
3876 pub output: FnRetTy<'hir>,
3877 pub c_variadic: bool,
3878 pub implicit_self: ImplicitSelfKind,
3880 pub lifetime_elision_allowed: bool,
3882}
3883
3884impl<'hir> FnDecl<'hir> {
3885 pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3886 if let FnRetTy::Return(ty) = self.output
3887 && let TyKind::InferDelegation(sig_id, _) = ty.kind
3888 {
3889 return Some(sig_id);
3890 }
3891 None
3892 }
3893}
3894
3895#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3897pub enum ImplicitSelfKind {
3898 Imm,
3900 Mut,
3902 RefImm,
3904 RefMut,
3906 None,
3909}
3910
3911impl ImplicitSelfKind {
3912 pub fn has_implicit_self(&self) -> bool {
3914 !matches!(*self, ImplicitSelfKind::None)
3915 }
3916}
3917
3918#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3919pub enum IsAsync {
3920 Async(Span),
3921 NotAsync,
3922}
3923
3924impl IsAsync {
3925 pub fn is_async(self) -> bool {
3926 matches!(self, IsAsync::Async(_))
3927 }
3928}
3929
3930#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3931#[derive(Default)]
3932pub enum Defaultness {
3933 Default {
3934 has_value: bool,
3935 },
3936 #[default]
3937 Final,
3938}
3939
3940impl Defaultness {
3941 pub fn has_value(&self) -> bool {
3942 match *self {
3943 Defaultness::Default { has_value } => has_value,
3944 Defaultness::Final => true,
3945 }
3946 }
3947
3948 pub fn is_final(&self) -> bool {
3949 *self == Defaultness::Final
3950 }
3951
3952 pub fn is_default(&self) -> bool {
3953 matches!(*self, Defaultness::Default { .. })
3954 }
3955}
3956
3957#[derive(Debug, Clone, Copy, HashStable_Generic)]
3958pub enum FnRetTy<'hir> {
3959 DefaultReturn(Span),
3965 Return(&'hir Ty<'hir>),
3967}
3968
3969impl<'hir> FnRetTy<'hir> {
3970 #[inline]
3971 pub fn span(&self) -> Span {
3972 match *self {
3973 Self::DefaultReturn(span) => span,
3974 Self::Return(ref ty) => ty.span,
3975 }
3976 }
3977
3978 pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3979 if let Self::Return(ty) = self
3980 && ty.is_suggestable_infer_ty()
3981 {
3982 return Some(*ty);
3983 }
3984 None
3985 }
3986}
3987
3988#[derive(Copy, Clone, Debug, HashStable_Generic)]
3990pub enum ClosureBinder {
3991 Default,
3993 For { span: Span },
3997}
3998
3999#[derive(Debug, Clone, Copy, HashStable_Generic)]
4000pub struct Mod<'hir> {
4001 pub spans: ModSpans,
4002 pub item_ids: &'hir [ItemId],
4003}
4004
4005#[derive(Copy, Clone, Debug, HashStable_Generic)]
4006pub struct ModSpans {
4007 pub inner_span: Span,
4011 pub inject_use_span: Span,
4012}
4013
4014#[derive(Debug, Clone, Copy, HashStable_Generic)]
4015pub struct EnumDef<'hir> {
4016 pub variants: &'hir [Variant<'hir>],
4017}
4018
4019#[derive(Debug, Clone, Copy, HashStable_Generic)]
4020pub struct Variant<'hir> {
4021 pub ident: Ident,
4023 #[stable_hasher(ignore)]
4025 pub hir_id: HirId,
4026 pub def_id: LocalDefId,
4027 pub data: VariantData<'hir>,
4029 pub disr_expr: Option<&'hir AnonConst>,
4031 pub span: Span,
4033}
4034
4035#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
4036pub enum UseKind {
4037 Single(Ident),
4044
4045 Glob,
4047
4048 ListStem,
4052}
4053
4054#[derive(Clone, Debug, Copy, HashStable_Generic)]
4061pub struct TraitRef<'hir> {
4062 pub path: &'hir Path<'hir>,
4063 #[stable_hasher(ignore)]
4065 pub hir_ref_id: HirId,
4066}
4067
4068impl TraitRef<'_> {
4069 pub fn trait_def_id(&self) -> Option<DefId> {
4071 match self.path.res {
4072 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
4073 Res::Err => None,
4074 res => panic!("{res:?} did not resolve to a trait or trait alias"),
4075 }
4076 }
4077}
4078
4079#[derive(Clone, Debug, Copy, HashStable_Generic)]
4080pub struct PolyTraitRef<'hir> {
4081 pub bound_generic_params: &'hir [GenericParam<'hir>],
4083
4084 pub modifiers: TraitBoundModifiers,
4088
4089 pub trait_ref: TraitRef<'hir>,
4091
4092 pub span: Span,
4093}
4094
4095#[derive(Debug, Clone, Copy, HashStable_Generic)]
4096pub struct FieldDef<'hir> {
4097 pub span: Span,
4098 pub vis_span: Span,
4099 pub ident: Ident,
4100 #[stable_hasher(ignore)]
4101 pub hir_id: HirId,
4102 pub def_id: LocalDefId,
4103 pub ty: &'hir Ty<'hir>,
4104 pub safety: Safety,
4105 pub default: Option<&'hir AnonConst>,
4106}
4107
4108impl FieldDef<'_> {
4109 pub fn is_positional(&self) -> bool {
4111 self.ident.as_str().as_bytes()[0].is_ascii_digit()
4112 }
4113}
4114
4115#[derive(Debug, Clone, Copy, HashStable_Generic)]
4117pub enum VariantData<'hir> {
4118 Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4122 Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4126 Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4130}
4131
4132impl<'hir> VariantData<'hir> {
4133 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4135 match *self {
4136 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4137 _ => &[],
4138 }
4139 }
4140
4141 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4142 match *self {
4143 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4144 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4145 VariantData::Struct { .. } => None,
4146 }
4147 }
4148
4149 #[inline]
4150 pub fn ctor_kind(&self) -> Option<CtorKind> {
4151 self.ctor().map(|(kind, ..)| kind)
4152 }
4153
4154 #[inline]
4156 pub fn ctor_hir_id(&self) -> Option<HirId> {
4157 self.ctor().map(|(_, hir_id, _)| hir_id)
4158 }
4159
4160 #[inline]
4162 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4163 self.ctor().map(|(.., def_id)| def_id)
4164 }
4165}
4166
4167#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4171pub struct ItemId {
4172 pub owner_id: OwnerId,
4173}
4174
4175impl ItemId {
4176 #[inline]
4177 pub fn hir_id(&self) -> HirId {
4178 HirId::make_owner(self.owner_id.def_id)
4180 }
4181}
4182
4183#[derive(Debug, Clone, Copy, HashStable_Generic)]
4192pub struct Item<'hir> {
4193 pub owner_id: OwnerId,
4194 pub kind: ItemKind<'hir>,
4195 pub span: Span,
4196 pub vis_span: Span,
4197 pub has_delayed_lints: bool,
4198 pub eii: bool,
4201}
4202
4203impl<'hir> Item<'hir> {
4204 #[inline]
4205 pub fn hir_id(&self) -> HirId {
4206 HirId::make_owner(self.owner_id.def_id)
4208 }
4209
4210 pub fn item_id(&self) -> ItemId {
4211 ItemId { owner_id: self.owner_id }
4212 }
4213
4214 pub fn is_adt(&self) -> bool {
4217 matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4218 }
4219
4220 pub fn is_struct_or_union(&self) -> bool {
4222 matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4223 }
4224
4225 expect_methods_self_kind! {
4226 expect_extern_crate, (Option<Symbol>, Ident),
4227 ItemKind::ExternCrate(s, ident), (*s, *ident);
4228
4229 expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4230
4231 expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4232 ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4233
4234 expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4235 ItemKind::Const(ident, generics, ty, rhs), (*ident, generics, ty, *rhs);
4236
4237 expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4238 ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4239
4240 expect_macro, (Ident, &ast::MacroDef, MacroKinds),
4241 ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4242
4243 expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4244
4245 expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]),
4246 ItemKind::ForeignMod { abi, items }, (*abi, items);
4247
4248 expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4249
4250 expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4251 ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4252
4253 expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4254 ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4255
4256 expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4257 ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4258
4259 expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4260 ItemKind::Union(ident, generics, data), (*ident, generics, data);
4261
4262 expect_trait,
4263 (
4264 Constness,
4265 IsAuto,
4266 Safety,
4267 Ident,
4268 &'hir Generics<'hir>,
4269 GenericBounds<'hir>,
4270 &'hir [TraitItemId]
4271 ),
4272 ItemKind::Trait(constness, is_auto, safety, ident, generics, bounds, items),
4273 (*constness, *is_auto, *safety, *ident, generics, bounds, items);
4274
4275 expect_trait_alias, (Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4276 ItemKind::TraitAlias(constness, ident, generics, bounds), (*constness, *ident, generics, bounds);
4277
4278 expect_impl, &Impl<'hir>, ItemKind::Impl(imp), imp;
4279 }
4280}
4281
4282#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4283#[derive(Encodable, Decodable, HashStable_Generic, Default)]
4284pub enum Safety {
4285 #[default]
4290 Unsafe,
4291 Safe,
4292}
4293
4294impl Safety {
4295 pub fn prefix_str(self) -> &'static str {
4296 match self {
4297 Self::Unsafe => "unsafe ",
4298 Self::Safe => "",
4299 }
4300 }
4301
4302 #[inline]
4303 pub fn is_unsafe(self) -> bool {
4304 !self.is_safe()
4305 }
4306
4307 #[inline]
4308 pub fn is_safe(self) -> bool {
4309 match self {
4310 Self::Unsafe => false,
4311 Self::Safe => true,
4312 }
4313 }
4314}
4315
4316impl fmt::Display for Safety {
4317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4318 f.write_str(match *self {
4319 Self::Unsafe => "unsafe",
4320 Self::Safe => "safe",
4321 })
4322 }
4323}
4324
4325#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4326#[derive(Default)]
4327pub enum Constness {
4328 #[default]
4329 Const,
4330 NotConst,
4331}
4332
4333impl fmt::Display for Constness {
4334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4335 f.write_str(match *self {
4336 Self::Const => "const",
4337 Self::NotConst => "non-const",
4338 })
4339 }
4340}
4341
4342#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4347pub enum HeaderSafety {
4348 SafeTargetFeatures,
4354 Normal(Safety),
4355}
4356
4357impl From<Safety> for HeaderSafety {
4358 fn from(v: Safety) -> Self {
4359 Self::Normal(v)
4360 }
4361}
4362
4363#[derive(Copy, Clone, Debug, HashStable_Generic)]
4364pub struct FnHeader {
4365 pub safety: HeaderSafety,
4366 pub constness: Constness,
4367 pub asyncness: IsAsync,
4368 pub abi: ExternAbi,
4369}
4370
4371impl FnHeader {
4372 pub fn is_async(&self) -> bool {
4373 matches!(self.asyncness, IsAsync::Async(_))
4374 }
4375
4376 pub fn is_const(&self) -> bool {
4377 matches!(self.constness, Constness::Const)
4378 }
4379
4380 pub fn is_unsafe(&self) -> bool {
4381 self.safety().is_unsafe()
4382 }
4383
4384 pub fn is_safe(&self) -> bool {
4385 self.safety().is_safe()
4386 }
4387
4388 pub fn safety(&self) -> Safety {
4389 match self.safety {
4390 HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4391 HeaderSafety::Normal(safety) => safety,
4392 }
4393 }
4394}
4395
4396#[derive(Debug, Clone, Copy, HashStable_Generic)]
4397pub enum ItemKind<'hir> {
4398 ExternCrate(Option<Symbol>, Ident),
4402
4403 Use(&'hir UsePath<'hir>, UseKind),
4409
4410 Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4412 Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4414 Fn {
4416 sig: FnSig<'hir>,
4417 ident: Ident,
4418 generics: &'hir Generics<'hir>,
4419 body: BodyId,
4420 has_body: bool,
4424 },
4425 Macro(Ident, &'hir ast::MacroDef, MacroKinds),
4427 Mod(Ident, &'hir Mod<'hir>),
4429 ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] },
4431 GlobalAsm {
4433 asm: &'hir InlineAsm<'hir>,
4434 fake_body: BodyId,
4440 },
4441 TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4443 Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4445 Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4447 Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4449 Trait(
4451 Constness,
4452 IsAuto,
4453 Safety,
4454 Ident,
4455 &'hir Generics<'hir>,
4456 GenericBounds<'hir>,
4457 &'hir [TraitItemId],
4458 ),
4459 TraitAlias(Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4461
4462 Impl(Impl<'hir>),
4464}
4465
4466#[derive(Debug, Clone, Copy, HashStable_Generic)]
4471pub struct Impl<'hir> {
4472 pub generics: &'hir Generics<'hir>,
4473 pub of_trait: Option<&'hir TraitImplHeader<'hir>>,
4474 pub self_ty: &'hir Ty<'hir>,
4475 pub items: &'hir [ImplItemId],
4476 pub constness: Constness,
4477}
4478
4479#[derive(Debug, Clone, Copy, HashStable_Generic)]
4480pub struct TraitImplHeader<'hir> {
4481 pub safety: Safety,
4482 pub polarity: ImplPolarity,
4483 pub defaultness: Defaultness,
4484 pub defaultness_span: Option<Span>,
4487 pub trait_ref: TraitRef<'hir>,
4488}
4489
4490impl ItemKind<'_> {
4491 pub fn ident(&self) -> Option<Ident> {
4492 match *self {
4493 ItemKind::ExternCrate(_, ident)
4494 | ItemKind::Use(_, UseKind::Single(ident))
4495 | ItemKind::Static(_, ident, ..)
4496 | ItemKind::Const(ident, ..)
4497 | ItemKind::Fn { ident, .. }
4498 | ItemKind::Macro(ident, ..)
4499 | ItemKind::Mod(ident, ..)
4500 | ItemKind::TyAlias(ident, ..)
4501 | ItemKind::Enum(ident, ..)
4502 | ItemKind::Struct(ident, ..)
4503 | ItemKind::Union(ident, ..)
4504 | ItemKind::Trait(_, _, _, ident, ..)
4505 | ItemKind::TraitAlias(_, ident, ..) => Some(ident),
4506
4507 ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4508 | ItemKind::ForeignMod { .. }
4509 | ItemKind::GlobalAsm { .. }
4510 | ItemKind::Impl(_) => None,
4511 }
4512 }
4513
4514 pub fn generics(&self) -> Option<&Generics<'_>> {
4515 Some(match self {
4516 ItemKind::Fn { generics, .. }
4517 | ItemKind::TyAlias(_, generics, _)
4518 | ItemKind::Const(_, generics, _, _)
4519 | ItemKind::Enum(_, generics, _)
4520 | ItemKind::Struct(_, generics, _)
4521 | ItemKind::Union(_, generics, _)
4522 | ItemKind::Trait(_, _, _, _, generics, _, _)
4523 | ItemKind::TraitAlias(_, _, generics, _)
4524 | ItemKind::Impl(Impl { generics, .. }) => generics,
4525 _ => return None,
4526 })
4527 }
4528}
4529
4530#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4534pub struct ForeignItemId {
4535 pub owner_id: OwnerId,
4536}
4537
4538impl ForeignItemId {
4539 #[inline]
4540 pub fn hir_id(&self) -> HirId {
4541 HirId::make_owner(self.owner_id.def_id)
4543 }
4544}
4545
4546#[derive(Debug, Clone, Copy, HashStable_Generic)]
4547pub struct ForeignItem<'hir> {
4548 pub ident: Ident,
4549 pub kind: ForeignItemKind<'hir>,
4550 pub owner_id: OwnerId,
4551 pub span: Span,
4552 pub vis_span: Span,
4553 pub has_delayed_lints: bool,
4554}
4555
4556impl ForeignItem<'_> {
4557 #[inline]
4558 pub fn hir_id(&self) -> HirId {
4559 HirId::make_owner(self.owner_id.def_id)
4561 }
4562
4563 pub fn foreign_item_id(&self) -> ForeignItemId {
4564 ForeignItemId { owner_id: self.owner_id }
4565 }
4566}
4567
4568#[derive(Debug, Clone, Copy, HashStable_Generic)]
4570pub enum ForeignItemKind<'hir> {
4571 Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4578 Static(&'hir Ty<'hir>, Mutability, Safety),
4580 Type,
4582}
4583
4584#[derive(Debug, Copy, Clone, HashStable_Generic)]
4586pub struct Upvar {
4587 pub span: Span,
4589}
4590
4591#[derive(Debug, Clone, HashStable_Generic)]
4595pub struct TraitCandidate {
4596 pub def_id: DefId,
4597 pub import_ids: SmallVec<[LocalDefId; 1]>,
4598}
4599
4600#[derive(Copy, Clone, Debug, HashStable_Generic)]
4601pub enum OwnerNode<'hir> {
4602 Item(&'hir Item<'hir>),
4603 ForeignItem(&'hir ForeignItem<'hir>),
4604 TraitItem(&'hir TraitItem<'hir>),
4605 ImplItem(&'hir ImplItem<'hir>),
4606 Crate(&'hir Mod<'hir>),
4607 Synthetic,
4608}
4609
4610impl<'hir> OwnerNode<'hir> {
4611 pub fn span(&self) -> Span {
4612 match self {
4613 OwnerNode::Item(Item { span, .. })
4614 | OwnerNode::ForeignItem(ForeignItem { span, .. })
4615 | OwnerNode::ImplItem(ImplItem { span, .. })
4616 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4617 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4618 OwnerNode::Synthetic => unreachable!(),
4619 }
4620 }
4621
4622 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4623 match self {
4624 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4625 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4626 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4627 | OwnerNode::ForeignItem(ForeignItem {
4628 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4629 }) => Some(fn_sig),
4630 _ => None,
4631 }
4632 }
4633
4634 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4635 match self {
4636 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4637 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4638 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4639 | OwnerNode::ForeignItem(ForeignItem {
4640 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4641 }) => Some(fn_sig.decl),
4642 _ => None,
4643 }
4644 }
4645
4646 pub fn body_id(&self) -> Option<BodyId> {
4647 match self {
4648 OwnerNode::Item(Item {
4649 kind:
4650 ItemKind::Static(_, _, _, body)
4651 | ItemKind::Const(.., ConstItemRhs::Body(body))
4652 | ItemKind::Fn { body, .. },
4653 ..
4654 })
4655 | OwnerNode::TraitItem(TraitItem {
4656 kind:
4657 TraitItemKind::Fn(_, TraitFn::Provided(body))
4658 | TraitItemKind::Const(_, Some(ConstItemRhs::Body(body))),
4659 ..
4660 })
4661 | OwnerNode::ImplItem(ImplItem {
4662 kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, ConstItemRhs::Body(body)),
4663 ..
4664 }) => Some(*body),
4665 _ => None,
4666 }
4667 }
4668
4669 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4670 Node::generics(self.into())
4671 }
4672
4673 pub fn def_id(self) -> OwnerId {
4674 match self {
4675 OwnerNode::Item(Item { owner_id, .. })
4676 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4677 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4678 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4679 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4680 OwnerNode::Synthetic => unreachable!(),
4681 }
4682 }
4683
4684 pub fn is_impl_block(&self) -> bool {
4686 matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4687 }
4688
4689 expect_methods_self! {
4690 expect_item, &'hir Item<'hir>, OwnerNode::Item(n), n;
4691 expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4692 expect_impl_item, &'hir ImplItem<'hir>, OwnerNode::ImplItem(n), n;
4693 expect_trait_item, &'hir TraitItem<'hir>, OwnerNode::TraitItem(n), n;
4694 }
4695}
4696
4697impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4698 fn from(val: &'hir Item<'hir>) -> Self {
4699 OwnerNode::Item(val)
4700 }
4701}
4702
4703impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4704 fn from(val: &'hir ForeignItem<'hir>) -> Self {
4705 OwnerNode::ForeignItem(val)
4706 }
4707}
4708
4709impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4710 fn from(val: &'hir ImplItem<'hir>) -> Self {
4711 OwnerNode::ImplItem(val)
4712 }
4713}
4714
4715impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4716 fn from(val: &'hir TraitItem<'hir>) -> Self {
4717 OwnerNode::TraitItem(val)
4718 }
4719}
4720
4721impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4722 fn from(val: OwnerNode<'hir>) -> Self {
4723 match val {
4724 OwnerNode::Item(n) => Node::Item(n),
4725 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4726 OwnerNode::ImplItem(n) => Node::ImplItem(n),
4727 OwnerNode::TraitItem(n) => Node::TraitItem(n),
4728 OwnerNode::Crate(n) => Node::Crate(n),
4729 OwnerNode::Synthetic => Node::Synthetic,
4730 }
4731 }
4732}
4733
4734#[derive(Copy, Clone, Debug, HashStable_Generic)]
4735pub enum Node<'hir> {
4736 Param(&'hir Param<'hir>),
4737 Item(&'hir Item<'hir>),
4738 ForeignItem(&'hir ForeignItem<'hir>),
4739 TraitItem(&'hir TraitItem<'hir>),
4740 ImplItem(&'hir ImplItem<'hir>),
4741 Variant(&'hir Variant<'hir>),
4742 Field(&'hir FieldDef<'hir>),
4743 AnonConst(&'hir AnonConst),
4744 ConstBlock(&'hir ConstBlock),
4745 ConstArg(&'hir ConstArg<'hir>),
4746 Expr(&'hir Expr<'hir>),
4747 ExprField(&'hir ExprField<'hir>),
4748 ConstArgExprField(&'hir ConstArgExprField<'hir>),
4749 Stmt(&'hir Stmt<'hir>),
4750 PathSegment(&'hir PathSegment<'hir>),
4751 Ty(&'hir Ty<'hir>),
4752 AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4753 TraitRef(&'hir TraitRef<'hir>),
4754 OpaqueTy(&'hir OpaqueTy<'hir>),
4755 TyPat(&'hir TyPat<'hir>),
4756 Pat(&'hir Pat<'hir>),
4757 PatField(&'hir PatField<'hir>),
4758 PatExpr(&'hir PatExpr<'hir>),
4762 Arm(&'hir Arm<'hir>),
4763 Block(&'hir Block<'hir>),
4764 LetStmt(&'hir LetStmt<'hir>),
4765 Ctor(&'hir VariantData<'hir>),
4768 Lifetime(&'hir Lifetime),
4769 GenericParam(&'hir GenericParam<'hir>),
4770 Crate(&'hir Mod<'hir>),
4771 Infer(&'hir InferArg),
4772 WherePredicate(&'hir WherePredicate<'hir>),
4773 PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4774 Synthetic,
4776 Err(Span),
4777}
4778
4779impl<'hir> Node<'hir> {
4780 pub fn ident(&self) -> Option<Ident> {
4795 match self {
4796 Node::Item(item) => item.kind.ident(),
4797 Node::TraitItem(TraitItem { ident, .. })
4798 | Node::ImplItem(ImplItem { ident, .. })
4799 | Node::ForeignItem(ForeignItem { ident, .. })
4800 | Node::Field(FieldDef { ident, .. })
4801 | Node::Variant(Variant { ident, .. })
4802 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4803 Node::Lifetime(lt) => Some(lt.ident),
4804 Node::GenericParam(p) => Some(p.name.ident()),
4805 Node::AssocItemConstraint(c) => Some(c.ident),
4806 Node::PatField(f) => Some(f.ident),
4807 Node::ExprField(f) => Some(f.ident),
4808 Node::ConstArgExprField(f) => Some(f.field),
4809 Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4810 Node::Param(..)
4811 | Node::AnonConst(..)
4812 | Node::ConstBlock(..)
4813 | Node::ConstArg(..)
4814 | Node::Expr(..)
4815 | Node::Stmt(..)
4816 | Node::Block(..)
4817 | Node::Ctor(..)
4818 | Node::Pat(..)
4819 | Node::TyPat(..)
4820 | Node::PatExpr(..)
4821 | Node::Arm(..)
4822 | Node::LetStmt(..)
4823 | Node::Crate(..)
4824 | Node::Ty(..)
4825 | Node::TraitRef(..)
4826 | Node::OpaqueTy(..)
4827 | Node::Infer(..)
4828 | Node::WherePredicate(..)
4829 | Node::Synthetic
4830 | Node::Err(..) => None,
4831 }
4832 }
4833
4834 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4835 match self {
4836 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4837 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4838 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4839 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4840 Some(fn_sig.decl)
4841 }
4842 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4843 Some(fn_decl)
4844 }
4845 _ => None,
4846 }
4847 }
4848
4849 pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4851 if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4852 && let Some(of_trait) = impl_block.of_trait
4853 && let Some(trait_id) = of_trait.trait_ref.trait_def_id()
4854 && trait_id == trait_def_id
4855 {
4856 Some(impl_block)
4857 } else {
4858 None
4859 }
4860 }
4861
4862 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4863 match self {
4864 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4865 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4866 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4867 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4868 Some(fn_sig)
4869 }
4870 _ => None,
4871 }
4872 }
4873
4874 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4876 match self {
4877 Node::Item(it) => match it.kind {
4878 ItemKind::TyAlias(_, _, ty)
4879 | ItemKind::Static(_, _, ty, _)
4880 | ItemKind::Const(_, _, ty, _) => Some(ty),
4881 ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4882 _ => None,
4883 },
4884 Node::TraitItem(it) => match it.kind {
4885 TraitItemKind::Const(ty, _) => Some(ty),
4886 TraitItemKind::Type(_, ty) => ty,
4887 _ => None,
4888 },
4889 Node::ImplItem(it) => match it.kind {
4890 ImplItemKind::Const(ty, _) => Some(ty),
4891 ImplItemKind::Type(ty) => Some(ty),
4892 _ => None,
4893 },
4894 Node::ForeignItem(it) => match it.kind {
4895 ForeignItemKind::Static(ty, ..) => Some(ty),
4896 _ => None,
4897 },
4898 Node::GenericParam(param) => match param.kind {
4899 GenericParamKind::Lifetime { .. } => None,
4900 GenericParamKind::Type { default, .. } => default,
4901 GenericParamKind::Const { ty, .. } => Some(ty),
4902 },
4903 _ => None,
4904 }
4905 }
4906
4907 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4908 match self {
4909 Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
4910 _ => None,
4911 }
4912 }
4913
4914 #[inline]
4915 pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4916 match self {
4917 Node::Item(Item {
4918 owner_id,
4919 kind:
4920 ItemKind::Const(.., ConstItemRhs::Body(body))
4921 | ItemKind::Static(.., body)
4922 | ItemKind::Fn { body, .. },
4923 ..
4924 })
4925 | Node::TraitItem(TraitItem {
4926 owner_id,
4927 kind:
4928 TraitItemKind::Const(.., Some(ConstItemRhs::Body(body)))
4929 | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4930 ..
4931 })
4932 | Node::ImplItem(ImplItem {
4933 owner_id,
4934 kind: ImplItemKind::Const(.., ConstItemRhs::Body(body)) | ImplItemKind::Fn(_, body),
4935 ..
4936 }) => Some((owner_id.def_id, *body)),
4937
4938 Node::Item(Item {
4939 owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4940 }) => Some((owner_id.def_id, *fake_body)),
4941
4942 Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4943 Some((*def_id, *body))
4944 }
4945
4946 Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4947 Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4948
4949 _ => None,
4950 }
4951 }
4952
4953 pub fn body_id(&self) -> Option<BodyId> {
4954 Some(self.associated_body()?.1)
4955 }
4956
4957 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4958 match self {
4959 Node::ForeignItem(ForeignItem {
4960 kind: ForeignItemKind::Fn(_, _, generics), ..
4961 })
4962 | Node::TraitItem(TraitItem { generics, .. })
4963 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4964 Node::Item(item) => item.kind.generics(),
4965 _ => None,
4966 }
4967 }
4968
4969 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4970 match self {
4971 Node::Item(i) => Some(OwnerNode::Item(i)),
4972 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4973 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4974 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4975 Node::Crate(i) => Some(OwnerNode::Crate(i)),
4976 Node::Synthetic => Some(OwnerNode::Synthetic),
4977 _ => None,
4978 }
4979 }
4980
4981 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4982 match self {
4983 Node::Item(i) => match i.kind {
4984 ItemKind::Fn { ident, sig, generics, .. } => {
4985 Some(FnKind::ItemFn(ident, generics, sig.header))
4986 }
4987 _ => None,
4988 },
4989 Node::TraitItem(ti) => match ti.kind {
4990 TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4991 _ => None,
4992 },
4993 Node::ImplItem(ii) => match ii.kind {
4994 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4995 _ => None,
4996 },
4997 Node::Expr(e) => match e.kind {
4998 ExprKind::Closure { .. } => Some(FnKind::Closure),
4999 _ => None,
5000 },
5001 _ => None,
5002 }
5003 }
5004
5005 expect_methods_self! {
5006 expect_param, &'hir Param<'hir>, Node::Param(n), n;
5007 expect_item, &'hir Item<'hir>, Node::Item(n), n;
5008 expect_foreign_item, &'hir ForeignItem<'hir>, Node::ForeignItem(n), n;
5009 expect_trait_item, &'hir TraitItem<'hir>, Node::TraitItem(n), n;
5010 expect_impl_item, &'hir ImplItem<'hir>, Node::ImplItem(n), n;
5011 expect_variant, &'hir Variant<'hir>, Node::Variant(n), n;
5012 expect_field, &'hir FieldDef<'hir>, Node::Field(n), n;
5013 expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n;
5014 expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n;
5015 expect_expr, &'hir Expr<'hir>, Node::Expr(n), n;
5016 expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n;
5017 expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n;
5018 expect_path_segment, &'hir PathSegment<'hir>, Node::PathSegment(n), n;
5019 expect_ty, &'hir Ty<'hir>, Node::Ty(n), n;
5020 expect_assoc_item_constraint, &'hir AssocItemConstraint<'hir>, Node::AssocItemConstraint(n), n;
5021 expect_trait_ref, &'hir TraitRef<'hir>, Node::TraitRef(n), n;
5022 expect_opaque_ty, &'hir OpaqueTy<'hir>, Node::OpaqueTy(n), n;
5023 expect_pat, &'hir Pat<'hir>, Node::Pat(n), n;
5024 expect_pat_field, &'hir PatField<'hir>, Node::PatField(n), n;
5025 expect_arm, &'hir Arm<'hir>, Node::Arm(n), n;
5026 expect_block, &'hir Block<'hir>, Node::Block(n), n;
5027 expect_let_stmt, &'hir LetStmt<'hir>, Node::LetStmt(n), n;
5028 expect_ctor, &'hir VariantData<'hir>, Node::Ctor(n), n;
5029 expect_lifetime, &'hir Lifetime, Node::Lifetime(n), n;
5030 expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
5031 expect_crate, &'hir Mod<'hir>, Node::Crate(n), n;
5032 expect_infer, &'hir InferArg, Node::Infer(n), n;
5033 expect_closure, &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
5034 }
5035}
5036
5037#[cfg(target_pointer_width = "64")]
5039mod size_asserts {
5040 use rustc_data_structures::static_assert_size;
5041
5042 use super::*;
5043 static_assert_size!(Block<'_>, 48);
5045 static_assert_size!(Body<'_>, 24);
5046 static_assert_size!(Expr<'_>, 64);
5047 static_assert_size!(ExprKind<'_>, 48);
5048 static_assert_size!(FnDecl<'_>, 40);
5049 static_assert_size!(ForeignItem<'_>, 96);
5050 static_assert_size!(ForeignItemKind<'_>, 56);
5051 static_assert_size!(GenericArg<'_>, 16);
5052 static_assert_size!(GenericBound<'_>, 64);
5053 static_assert_size!(Generics<'_>, 56);
5054 static_assert_size!(Impl<'_>, 48);
5055 static_assert_size!(ImplItem<'_>, 88);
5056 static_assert_size!(ImplItemKind<'_>, 40);
5057 static_assert_size!(Item<'_>, 88);
5058 static_assert_size!(ItemKind<'_>, 64);
5059 static_assert_size!(LetStmt<'_>, 64);
5060 static_assert_size!(Param<'_>, 32);
5061 static_assert_size!(Pat<'_>, 80);
5062 static_assert_size!(PatKind<'_>, 56);
5063 static_assert_size!(Path<'_>, 40);
5064 static_assert_size!(PathSegment<'_>, 48);
5065 static_assert_size!(QPath<'_>, 24);
5066 static_assert_size!(Res, 12);
5067 static_assert_size!(Stmt<'_>, 32);
5068 static_assert_size!(StmtKind<'_>, 16);
5069 static_assert_size!(TraitImplHeader<'_>, 48);
5070 static_assert_size!(TraitItem<'_>, 88);
5071 static_assert_size!(TraitItemKind<'_>, 48);
5072 static_assert_size!(Ty<'_>, 48);
5073 static_assert_size!(TyKind<'_>, 32);
5074 }
5076
5077#[cfg(test)]
5078mod tests;