1use std::borrow::Cow;
3use std::fmt;
4
5use rustc_abi::ExternAbi;
6use rustc_ast::attr::AttributeExt;
7use rustc_ast::token::CommentKind;
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))]
158pub struct Lifetime {
159 #[stable_hasher(ignore)]
160 pub hir_id: HirId,
161
162 pub ident: Ident,
166
167 pub kind: LifetimeKind,
169
170 pub source: LifetimeSource,
173
174 pub syntax: LifetimeSyntax,
177}
178
179#[derive(Debug, Copy, Clone, HashStable_Generic)]
180pub enum ParamName {
181 Plain(Ident),
183
184 Error(Ident),
190
191 Fresh,
206}
207
208impl ParamName {
209 pub fn ident(&self) -> Ident {
210 match *self {
211 ParamName::Plain(ident) | ParamName::Error(ident) => ident,
212 ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
213 }
214 }
215}
216
217#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
218pub enum LifetimeKind {
219 Param(LocalDefId),
221
222 ImplicitObjectLifetimeDefault,
234
235 Error,
238
239 Infer,
243
244 Static,
246}
247
248impl LifetimeKind {
249 fn is_elided(&self) -> bool {
250 match self {
251 LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true,
252
253 LifetimeKind::Error | LifetimeKind::Param(..) | LifetimeKind::Static => false,
258 }
259 }
260}
261
262impl fmt::Display for Lifetime {
263 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264 self.ident.name.fmt(f)
265 }
266}
267
268impl Lifetime {
269 pub fn new(
270 hir_id: HirId,
271 ident: Ident,
272 kind: LifetimeKind,
273 source: LifetimeSource,
274 syntax: LifetimeSyntax,
275 ) -> Lifetime {
276 let lifetime = Lifetime { hir_id, ident, kind, source, syntax };
277
278 #[cfg(debug_assertions)]
280 match (lifetime.is_elided(), lifetime.is_anonymous()) {
281 (false, false) => {} (false, true) => {} (true, true) => {} (true, false) => panic!("bad Lifetime"),
285 }
286
287 lifetime
288 }
289
290 pub fn is_elided(&self) -> bool {
291 self.kind.is_elided()
292 }
293
294 pub fn is_anonymous(&self) -> bool {
295 self.ident.name == kw::UnderscoreLifetime
296 }
297
298 pub fn is_implicit(&self) -> bool {
299 matches!(self.syntax, LifetimeSyntax::Implicit)
300 }
301
302 pub fn is_static(&self) -> bool {
303 self.kind == LifetimeKind::Static
304 }
305
306 pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
307 use LifetimeSource::*;
308 use LifetimeSyntax::*;
309
310 debug_assert!(new_lifetime.starts_with('\''));
311
312 match (self.syntax, self.source) {
313 (ExplicitBound | ExplicitAnonymous, _) => (self.ident.span, format!("{new_lifetime}")),
315
316 (Implicit, Path { angle_brackets: AngleBrackets::Full }) => {
318 (self.ident.span, format!("{new_lifetime}, "))
319 }
320
321 (Implicit, Path { angle_brackets: AngleBrackets::Empty }) => {
323 (self.ident.span, format!("{new_lifetime}"))
324 }
325
326 (Implicit, Path { angle_brackets: AngleBrackets::Missing }) => {
328 (self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
329 }
330
331 (Implicit, Reference) => (self.ident.span, format!("{new_lifetime} ")),
333
334 (Implicit, source) => {
335 unreachable!("can't suggest for a implicit lifetime of {source:?}")
336 }
337 }
338 }
339}
340
341#[derive(Debug, Clone, Copy, HashStable_Generic)]
345pub struct Path<'hir, R = Res> {
346 pub span: Span,
347 pub res: R,
349 pub segments: &'hir [PathSegment<'hir>],
351}
352
353pub type UsePath<'hir> = Path<'hir, PerNS<Option<Res>>>;
355
356impl Path<'_> {
357 pub fn is_global(&self) -> bool {
358 self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
359 }
360}
361
362#[derive(Debug, Clone, Copy, HashStable_Generic)]
365pub struct PathSegment<'hir> {
366 pub ident: Ident,
368 #[stable_hasher(ignore)]
369 pub hir_id: HirId,
370 pub res: Res,
371
372 pub args: Option<&'hir GenericArgs<'hir>>,
378
379 pub infer_args: bool,
384}
385
386impl<'hir> PathSegment<'hir> {
387 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
389 PathSegment { ident, hir_id, res, infer_args: true, args: None }
390 }
391
392 pub fn invalid() -> Self {
393 Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
394 }
395
396 pub fn args(&self) -> &GenericArgs<'hir> {
397 if let Some(ref args) = self.args {
398 args
399 } else {
400 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
401 DUMMY
402 }
403 }
404}
405
406#[derive(Clone, Copy, Debug, HashStable_Generic)]
407pub enum ConstItemRhs<'hir> {
408 Body(BodyId),
409 TypeConst(&'hir ConstArg<'hir>),
410}
411
412impl<'hir> ConstItemRhs<'hir> {
413 pub fn hir_id(&self) -> HirId {
414 match self {
415 ConstItemRhs::Body(body_id) => body_id.hir_id,
416 ConstItemRhs::TypeConst(ct_arg) => ct_arg.hir_id,
417 }
418 }
419
420 pub fn span<'tcx>(&self, tcx: impl crate::intravisit::HirTyCtxt<'tcx>) -> Span {
421 match self {
422 ConstItemRhs::Body(body_id) => tcx.hir_body(*body_id).value.span,
423 ConstItemRhs::TypeConst(ct_arg) => ct_arg.span(),
424 }
425 }
426}
427
428#[derive(Clone, Copy, Debug, HashStable_Generic)]
442#[repr(C)]
443pub struct ConstArg<'hir, Unambig = ()> {
444 #[stable_hasher(ignore)]
445 pub hir_id: HirId,
446 pub kind: ConstArgKind<'hir, Unambig>,
447}
448
449impl<'hir> ConstArg<'hir, AmbigArg> {
450 pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
461 let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
464 unsafe { &*ptr }
465 }
466}
467
468impl<'hir> ConstArg<'hir> {
469 pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
475 if let ConstArgKind::Infer(_, ()) = self.kind {
476 return None;
477 }
478
479 let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
483 Some(unsafe { &*ptr })
484 }
485}
486
487impl<'hir, Unambig> ConstArg<'hir, Unambig> {
488 pub fn anon_const_hir_id(&self) -> Option<HirId> {
489 match self.kind {
490 ConstArgKind::Anon(ac) => Some(ac.hir_id),
491 _ => None,
492 }
493 }
494
495 pub fn span(&self) -> Span {
496 match self.kind {
497 ConstArgKind::Path(path) => path.span(),
498 ConstArgKind::Anon(anon) => anon.span,
499 ConstArgKind::Error(span, _) => span,
500 ConstArgKind::Infer(span, _) => span,
501 }
502 }
503}
504
505#[derive(Clone, Copy, Debug, HashStable_Generic)]
507#[repr(u8, C)]
508pub enum ConstArgKind<'hir, Unambig = ()> {
509 Path(QPath<'hir>),
515 Anon(&'hir AnonConst),
516 Error(Span, ErrorGuaranteed),
518 Infer(Span, Unambig),
521}
522
523#[derive(Clone, Copy, Debug, HashStable_Generic)]
524pub struct InferArg {
525 #[stable_hasher(ignore)]
526 pub hir_id: HirId,
527 pub span: Span,
528}
529
530impl InferArg {
531 pub fn to_ty(&self) -> Ty<'static> {
532 Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
533 }
534}
535
536#[derive(Debug, Clone, Copy, HashStable_Generic)]
537pub enum GenericArg<'hir> {
538 Lifetime(&'hir Lifetime),
539 Type(&'hir Ty<'hir, AmbigArg>),
540 Const(&'hir ConstArg<'hir, AmbigArg>),
541 Infer(InferArg),
551}
552
553impl GenericArg<'_> {
554 pub fn span(&self) -> Span {
555 match self {
556 GenericArg::Lifetime(l) => l.ident.span,
557 GenericArg::Type(t) => t.span,
558 GenericArg::Const(c) => c.span(),
559 GenericArg::Infer(i) => i.span,
560 }
561 }
562
563 pub fn hir_id(&self) -> HirId {
564 match self {
565 GenericArg::Lifetime(l) => l.hir_id,
566 GenericArg::Type(t) => t.hir_id,
567 GenericArg::Const(c) => c.hir_id,
568 GenericArg::Infer(i) => i.hir_id,
569 }
570 }
571
572 pub fn descr(&self) -> &'static str {
573 match self {
574 GenericArg::Lifetime(_) => "lifetime",
575 GenericArg::Type(_) => "type",
576 GenericArg::Const(_) => "constant",
577 GenericArg::Infer(_) => "placeholder",
578 }
579 }
580
581 pub fn to_ord(&self) -> ast::ParamKindOrd {
582 match self {
583 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
584 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
585 ast::ParamKindOrd::TypeOrConst
586 }
587 }
588 }
589
590 pub fn is_ty_or_const(&self) -> bool {
591 match self {
592 GenericArg::Lifetime(_) => false,
593 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
594 }
595 }
596}
597
598#[derive(Debug, Clone, Copy, HashStable_Generic)]
600pub struct GenericArgs<'hir> {
601 pub args: &'hir [GenericArg<'hir>],
603 pub constraints: &'hir [AssocItemConstraint<'hir>],
605 pub parenthesized: GenericArgsParentheses,
610 pub span_ext: Span,
623}
624
625impl<'hir> GenericArgs<'hir> {
626 pub const fn none() -> Self {
627 Self {
628 args: &[],
629 constraints: &[],
630 parenthesized: GenericArgsParentheses::No,
631 span_ext: DUMMY_SP,
632 }
633 }
634
635 pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
640 if self.parenthesized != GenericArgsParentheses::ParenSugar {
641 return None;
642 }
643
644 let inputs = self
645 .args
646 .iter()
647 .find_map(|arg| {
648 let GenericArg::Type(ty) = arg else { return None };
649 let TyKind::Tup(tys) = &ty.kind else { return None };
650 Some(tys)
651 })
652 .unwrap();
653
654 Some((inputs, self.paren_sugar_output_inner()))
655 }
656
657 pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
662 (self.parenthesized == GenericArgsParentheses::ParenSugar)
663 .then(|| self.paren_sugar_output_inner())
664 }
665
666 fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
667 let [constraint] = self.constraints.try_into().unwrap();
668 debug_assert_eq!(constraint.ident.name, sym::Output);
669 constraint.ty().unwrap()
670 }
671
672 pub fn has_err(&self) -> Option<ErrorGuaranteed> {
673 self.args
674 .iter()
675 .find_map(|arg| {
676 let GenericArg::Type(ty) = arg else { return None };
677 let TyKind::Err(guar) = ty.kind else { return None };
678 Some(guar)
679 })
680 .or_else(|| {
681 self.constraints.iter().find_map(|constraint| {
682 let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
683 Some(guar)
684 })
685 })
686 }
687
688 #[inline]
689 pub fn num_lifetime_params(&self) -> usize {
690 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
691 }
692
693 #[inline]
694 pub fn has_lifetime_params(&self) -> bool {
695 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
696 }
697
698 #[inline]
699 pub fn num_generic_params(&self) -> usize {
702 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
703 }
704
705 pub fn span(&self) -> Option<Span> {
711 let span_ext = self.span_ext()?;
712 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
713 }
714
715 pub fn span_ext(&self) -> Option<Span> {
717 Some(self.span_ext).filter(|span| !span.is_empty())
718 }
719
720 pub fn is_empty(&self) -> bool {
721 self.args.is_empty()
722 }
723}
724
725#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)]
726pub enum GenericArgsParentheses {
727 No,
728 ReturnTypeNotation,
731 ParenSugar,
733}
734
735#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
737pub struct TraitBoundModifiers {
738 pub constness: BoundConstness,
739 pub polarity: BoundPolarity,
740}
741
742impl TraitBoundModifiers {
743 pub const NONE: Self =
744 TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
745}
746
747#[derive(Clone, Copy, Debug, HashStable_Generic)]
748pub enum GenericBound<'hir> {
749 Trait(PolyTraitRef<'hir>),
750 Outlives(&'hir Lifetime),
751 Use(&'hir [PreciseCapturingArg<'hir>], Span),
752}
753
754impl GenericBound<'_> {
755 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
756 match self {
757 GenericBound::Trait(data) => Some(&data.trait_ref),
758 _ => None,
759 }
760 }
761
762 pub fn span(&self) -> Span {
763 match self {
764 GenericBound::Trait(t, ..) => t.span,
765 GenericBound::Outlives(l) => l.ident.span,
766 GenericBound::Use(_, span) => *span,
767 }
768 }
769}
770
771pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
772
773#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, Debug)]
774pub enum MissingLifetimeKind {
775 Underscore,
777 Ampersand,
779 Comma,
781 Brackets,
783}
784
785#[derive(Copy, Clone, Debug, HashStable_Generic)]
786pub enum LifetimeParamKind {
787 Explicit,
790
791 Elided(MissingLifetimeKind),
794
795 Error,
797}
798
799#[derive(Debug, Clone, Copy, HashStable_Generic)]
800pub enum GenericParamKind<'hir> {
801 Lifetime {
803 kind: LifetimeParamKind,
804 },
805 Type {
806 default: Option<&'hir Ty<'hir>>,
807 synthetic: bool,
808 },
809 Const {
810 ty: &'hir Ty<'hir>,
811 default: Option<&'hir ConstArg<'hir>>,
813 },
814}
815
816#[derive(Debug, Clone, Copy, HashStable_Generic)]
817pub struct GenericParam<'hir> {
818 #[stable_hasher(ignore)]
819 pub hir_id: HirId,
820 pub def_id: LocalDefId,
821 pub name: ParamName,
822 pub span: Span,
823 pub pure_wrt_drop: bool,
824 pub kind: GenericParamKind<'hir>,
825 pub colon_span: Option<Span>,
826 pub source: GenericParamSource,
827}
828
829impl<'hir> GenericParam<'hir> {
830 pub fn is_impl_trait(&self) -> bool {
834 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
835 }
836
837 pub fn is_elided_lifetime(&self) -> bool {
841 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
842 }
843}
844
845#[derive(Debug, Clone, Copy, HashStable_Generic)]
852pub enum GenericParamSource {
853 Generics,
855 Binder,
857}
858
859#[derive(Default)]
860pub struct GenericParamCount {
861 pub lifetimes: usize,
862 pub types: usize,
863 pub consts: usize,
864 pub infer: usize,
865}
866
867#[derive(Debug, Clone, Copy, HashStable_Generic)]
870pub struct Generics<'hir> {
871 pub params: &'hir [GenericParam<'hir>],
872 pub predicates: &'hir [WherePredicate<'hir>],
873 pub has_where_clause_predicates: bool,
874 pub where_clause_span: Span,
875 pub span: Span,
876}
877
878impl<'hir> Generics<'hir> {
879 pub const fn empty() -> &'hir Generics<'hir> {
880 const NOPE: Generics<'_> = Generics {
881 params: &[],
882 predicates: &[],
883 has_where_clause_predicates: false,
884 where_clause_span: DUMMY_SP,
885 span: DUMMY_SP,
886 };
887 &NOPE
888 }
889
890 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
891 self.params.iter().find(|¶m| name == param.name.ident().name)
892 }
893
894 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
896 if let Some(first) = self.params.first()
897 && self.span.contains(first.span)
898 {
899 Some(first.span.shrink_to_lo())
902 } else {
903 None
904 }
905 }
906
907 pub fn span_for_param_suggestion(&self) -> Option<Span> {
909 self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
910 self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
913 })
914 }
915
916 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
919 let end = self.where_clause_span.shrink_to_hi();
920 if self.has_where_clause_predicates {
921 self.predicates
922 .iter()
923 .rfind(|&p| p.kind.in_where_clause())
924 .map_or(end, |p| p.span)
925 .shrink_to_hi()
926 .to(end)
927 } else {
928 end
929 }
930 }
931
932 pub fn add_where_or_trailing_comma(&self) -> &'static str {
933 if self.has_where_clause_predicates {
934 ","
935 } else if self.where_clause_span.is_empty() {
936 " where"
937 } else {
938 ""
940 }
941 }
942
943 pub fn bounds_for_param(
944 &self,
945 param_def_id: LocalDefId,
946 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
947 self.predicates.iter().filter_map(move |pred| match pred.kind {
948 WherePredicateKind::BoundPredicate(bp)
949 if bp.is_param_bound(param_def_id.to_def_id()) =>
950 {
951 Some(bp)
952 }
953 _ => None,
954 })
955 }
956
957 pub fn outlives_for_param(
958 &self,
959 param_def_id: LocalDefId,
960 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
961 self.predicates.iter().filter_map(move |pred| match pred.kind {
962 WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
963 _ => None,
964 })
965 }
966
967 pub fn bounds_span_for_suggestions(
978 &self,
979 param_def_id: LocalDefId,
980 ) -> Option<(Span, Option<Span>)> {
981 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
982 |bound| {
983 let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
984 && let [.., segment] = trait_ref.path.segments
985 && let Some(ret_ty) = segment.args().paren_sugar_output()
986 && let ret_ty = ret_ty.peel_refs()
987 && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
988 && let TraitObjectSyntax::Dyn = tagged_ptr.tag()
989 && ret_ty.span.can_be_used_for_suggestions()
990 {
991 Some(ret_ty.span)
992 } else {
993 None
994 };
995
996 span_for_parentheses.map_or_else(
997 || {
998 let bs = bound.span();
1001 bs.can_be_used_for_suggestions().then(|| (bs.shrink_to_hi(), None))
1002 },
1003 |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
1004 )
1005 },
1006 )
1007 }
1008
1009 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
1010 let predicate = &self.predicates[pos];
1011 let span = predicate.span;
1012
1013 if !predicate.kind.in_where_clause() {
1014 return span;
1017 }
1018
1019 if pos < self.predicates.len() - 1 {
1021 let next_pred = &self.predicates[pos + 1];
1022 if next_pred.kind.in_where_clause() {
1023 return span.until(next_pred.span);
1026 }
1027 }
1028
1029 if pos > 0 {
1030 let prev_pred = &self.predicates[pos - 1];
1031 if prev_pred.kind.in_where_clause() {
1032 return prev_pred.span.shrink_to_hi().to(span);
1035 }
1036 }
1037
1038 self.where_clause_span
1042 }
1043
1044 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
1045 let predicate = &self.predicates[predicate_pos];
1046 let bounds = predicate.kind.bounds();
1047
1048 if bounds.len() == 1 {
1049 return self.span_for_predicate_removal(predicate_pos);
1050 }
1051
1052 let bound_span = bounds[bound_pos].span();
1053 if bound_pos < bounds.len() - 1 {
1054 bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
1060 } else {
1061 bound_span.with_lo(bounds[bound_pos - 1].span().hi())
1067 }
1068 }
1069}
1070
1071#[derive(Debug, Clone, Copy, HashStable_Generic)]
1073pub struct WherePredicate<'hir> {
1074 #[stable_hasher(ignore)]
1075 pub hir_id: HirId,
1076 pub span: Span,
1077 pub kind: &'hir WherePredicateKind<'hir>,
1078}
1079
1080#[derive(Debug, Clone, Copy, HashStable_Generic)]
1082pub enum WherePredicateKind<'hir> {
1083 BoundPredicate(WhereBoundPredicate<'hir>),
1085 RegionPredicate(WhereRegionPredicate<'hir>),
1087 EqPredicate(WhereEqPredicate<'hir>),
1089}
1090
1091impl<'hir> WherePredicateKind<'hir> {
1092 pub fn in_where_clause(&self) -> bool {
1093 match self {
1094 WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
1095 WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
1096 WherePredicateKind::EqPredicate(_) => false,
1097 }
1098 }
1099
1100 pub fn bounds(&self) -> GenericBounds<'hir> {
1101 match self {
1102 WherePredicateKind::BoundPredicate(p) => p.bounds,
1103 WherePredicateKind::RegionPredicate(p) => p.bounds,
1104 WherePredicateKind::EqPredicate(_) => &[],
1105 }
1106 }
1107}
1108
1109#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
1110pub enum PredicateOrigin {
1111 WhereClause,
1112 GenericParam,
1113 ImplTrait,
1114}
1115
1116#[derive(Debug, Clone, Copy, HashStable_Generic)]
1118pub struct WhereBoundPredicate<'hir> {
1119 pub origin: PredicateOrigin,
1121 pub bound_generic_params: &'hir [GenericParam<'hir>],
1123 pub bounded_ty: &'hir Ty<'hir>,
1125 pub bounds: GenericBounds<'hir>,
1127}
1128
1129impl<'hir> WhereBoundPredicate<'hir> {
1130 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
1132 self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
1133 }
1134}
1135
1136#[derive(Debug, Clone, Copy, HashStable_Generic)]
1138pub struct WhereRegionPredicate<'hir> {
1139 pub in_where_clause: bool,
1140 pub lifetime: &'hir Lifetime,
1141 pub bounds: GenericBounds<'hir>,
1142}
1143
1144impl<'hir> WhereRegionPredicate<'hir> {
1145 fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
1147 self.lifetime.kind == LifetimeKind::Param(param_def_id)
1148 }
1149}
1150
1151#[derive(Debug, Clone, Copy, HashStable_Generic)]
1153pub struct WhereEqPredicate<'hir> {
1154 pub lhs_ty: &'hir Ty<'hir>,
1155 pub rhs_ty: &'hir Ty<'hir>,
1156}
1157
1158#[derive(Clone, Copy, Debug)]
1162pub struct ParentedNode<'tcx> {
1163 pub parent: ItemLocalId,
1164 pub node: Node<'tcx>,
1165}
1166
1167#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1169pub enum AttrArgs {
1170 Empty,
1172 Delimited(DelimArgs),
1174 Eq {
1176 eq_span: Span,
1178 expr: MetaItemLit,
1180 },
1181}
1182
1183#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1184pub struct AttrPath {
1185 pub segments: Box<[Ident]>,
1186 pub span: Span,
1187}
1188
1189impl IntoDiagArg for AttrPath {
1190 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> DiagArgValue {
1191 self.to_string().into_diag_arg(path)
1192 }
1193}
1194
1195impl AttrPath {
1196 pub fn from_ast(path: &ast::Path) -> Self {
1197 AttrPath {
1198 segments: path.segments.iter().map(|i| i.ident).collect::<Vec<_>>().into_boxed_slice(),
1199 span: path.span,
1200 }
1201 }
1202}
1203
1204impl fmt::Display for AttrPath {
1205 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1206 write!(f, "{}", join_path_idents(&self.segments))
1207 }
1208}
1209
1210#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1211pub struct AttrItem {
1212 pub path: AttrPath,
1214 pub args: AttrArgs,
1215 pub id: HashIgnoredAttrId,
1216 pub style: AttrStyle,
1219 pub span: Span,
1221}
1222
1223#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1226pub struct HashIgnoredAttrId {
1227 pub attr_id: AttrId,
1228}
1229
1230#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1231pub enum Attribute {
1232 Parsed(AttributeKind),
1238
1239 Unparsed(Box<AttrItem>),
1242}
1243
1244impl Attribute {
1245 pub fn get_normal_item(&self) -> &AttrItem {
1246 match &self {
1247 Attribute::Unparsed(normal) => &normal,
1248 _ => panic!("unexpected parsed attribute"),
1249 }
1250 }
1251
1252 pub fn unwrap_normal_item(self) -> AttrItem {
1253 match self {
1254 Attribute::Unparsed(normal) => *normal,
1255 _ => panic!("unexpected parsed attribute"),
1256 }
1257 }
1258
1259 pub fn value_lit(&self) -> Option<&MetaItemLit> {
1260 match &self {
1261 Attribute::Unparsed(n) => match n.as_ref() {
1262 AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1263 _ => None,
1264 },
1265 _ => None,
1266 }
1267 }
1268
1269 pub fn is_parsed_attr(&self) -> bool {
1270 match self {
1271 Attribute::Parsed(_) => true,
1272 Attribute::Unparsed(_) => false,
1273 }
1274 }
1275}
1276
1277impl AttributeExt for Attribute {
1278 #[inline]
1279 fn id(&self) -> AttrId {
1280 match &self {
1281 Attribute::Unparsed(u) => u.id.attr_id,
1282 _ => panic!(),
1283 }
1284 }
1285
1286 #[inline]
1287 fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1288 match &self {
1289 Attribute::Unparsed(n) => match n.as_ref() {
1290 AttrItem { args: AttrArgs::Delimited(d), .. } => {
1291 ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1292 }
1293 _ => None,
1294 },
1295 _ => None,
1296 }
1297 }
1298
1299 #[inline]
1300 fn value_str(&self) -> Option<Symbol> {
1301 self.value_lit().and_then(|x| x.value_str())
1302 }
1303
1304 #[inline]
1305 fn value_span(&self) -> Option<Span> {
1306 self.value_lit().map(|i| i.span)
1307 }
1308
1309 #[inline]
1311 fn ident(&self) -> Option<Ident> {
1312 match &self {
1313 Attribute::Unparsed(n) => {
1314 if let [ident] = n.path.segments.as_ref() {
1315 Some(*ident)
1316 } else {
1317 None
1318 }
1319 }
1320 _ => None,
1321 }
1322 }
1323
1324 #[inline]
1325 fn path_matches(&self, name: &[Symbol]) -> bool {
1326 match &self {
1327 Attribute::Unparsed(n) => n.path.segments.iter().map(|ident| &ident.name).eq(name),
1328 _ => false,
1329 }
1330 }
1331
1332 #[inline]
1333 fn is_doc_comment(&self) -> Option<Span> {
1334 if let Attribute::Parsed(AttributeKind::DocComment { span, .. }) = self {
1335 Some(*span)
1336 } else {
1337 None
1338 }
1339 }
1340
1341 #[inline]
1342 fn span(&self) -> Span {
1343 match &self {
1344 Attribute::Unparsed(u) => u.span,
1345 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1347 Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1348 a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1349 }
1350 }
1351
1352 #[inline]
1353 fn is_word(&self) -> bool {
1354 match &self {
1355 Attribute::Unparsed(n) => {
1356 matches!(n.args, AttrArgs::Empty)
1357 }
1358 _ => false,
1359 }
1360 }
1361
1362 #[inline]
1363 fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1364 match &self {
1365 Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1366 _ => None,
1367 }
1368 }
1369
1370 #[inline]
1371 fn doc_str(&self) -> Option<Symbol> {
1372 match &self {
1373 Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1374 Attribute::Unparsed(_) if self.has_name(sym::doc) => self.value_str(),
1375 _ => None,
1376 }
1377 }
1378
1379 fn is_automatically_derived_attr(&self) -> bool {
1380 matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)))
1381 }
1382
1383 #[inline]
1384 fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1385 match &self {
1386 Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1387 Some((*comment, *kind))
1388 }
1389 Attribute::Unparsed(_) if self.has_name(sym::doc) => {
1390 self.value_str().map(|s| (s, CommentKind::Line))
1391 }
1392 _ => None,
1393 }
1394 }
1395
1396 fn doc_resolution_scope(&self) -> Option<AttrStyle> {
1397 match self {
1398 Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
1399 Attribute::Unparsed(attr) if self.has_name(sym::doc) && self.value_str().is_some() => {
1400 Some(attr.style)
1401 }
1402 _ => None,
1403 }
1404 }
1405
1406 fn is_proc_macro_attr(&self) -> bool {
1407 matches!(
1408 self,
1409 Attribute::Parsed(
1410 AttributeKind::ProcMacro(..)
1411 | AttributeKind::ProcMacroAttribute(..)
1412 | AttributeKind::ProcMacroDerive { .. }
1413 )
1414 )
1415 }
1416}
1417
1418impl Attribute {
1420 #[inline]
1421 pub fn id(&self) -> AttrId {
1422 AttributeExt::id(self)
1423 }
1424
1425 #[inline]
1426 pub fn name(&self) -> Option<Symbol> {
1427 AttributeExt::name(self)
1428 }
1429
1430 #[inline]
1431 pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1432 AttributeExt::meta_item_list(self)
1433 }
1434
1435 #[inline]
1436 pub fn value_str(&self) -> Option<Symbol> {
1437 AttributeExt::value_str(self)
1438 }
1439
1440 #[inline]
1441 pub fn value_span(&self) -> Option<Span> {
1442 AttributeExt::value_span(self)
1443 }
1444
1445 #[inline]
1446 pub fn ident(&self) -> Option<Ident> {
1447 AttributeExt::ident(self)
1448 }
1449
1450 #[inline]
1451 pub fn path_matches(&self, name: &[Symbol]) -> bool {
1452 AttributeExt::path_matches(self, name)
1453 }
1454
1455 #[inline]
1456 pub fn is_doc_comment(&self) -> Option<Span> {
1457 AttributeExt::is_doc_comment(self)
1458 }
1459
1460 #[inline]
1461 pub fn has_name(&self, name: Symbol) -> bool {
1462 AttributeExt::has_name(self, name)
1463 }
1464
1465 #[inline]
1466 pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1467 AttributeExt::has_any_name(self, names)
1468 }
1469
1470 #[inline]
1471 pub fn span(&self) -> Span {
1472 AttributeExt::span(self)
1473 }
1474
1475 #[inline]
1476 pub fn is_word(&self) -> bool {
1477 AttributeExt::is_word(self)
1478 }
1479
1480 #[inline]
1481 pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1482 AttributeExt::path(self)
1483 }
1484
1485 #[inline]
1486 pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1487 AttributeExt::ident_path(self)
1488 }
1489
1490 #[inline]
1491 pub fn doc_str(&self) -> Option<Symbol> {
1492 AttributeExt::doc_str(self)
1493 }
1494
1495 #[inline]
1496 pub fn is_proc_macro_attr(&self) -> bool {
1497 AttributeExt::is_proc_macro_attr(self)
1498 }
1499
1500 #[inline]
1501 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1502 AttributeExt::doc_str_and_comment_kind(self)
1503 }
1504}
1505
1506#[derive(Debug)]
1508pub struct AttributeMap<'tcx> {
1509 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1510 pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1512 pub opt_hash: Option<Fingerprint>,
1514}
1515
1516impl<'tcx> AttributeMap<'tcx> {
1517 pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1518 map: SortedMap::new(),
1519 opt_hash: Some(Fingerprint::ZERO),
1520 define_opaque: None,
1521 };
1522
1523 #[inline]
1524 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1525 self.map.get(&id).copied().unwrap_or(&[])
1526 }
1527}
1528
1529pub struct OwnerNodes<'tcx> {
1533 pub opt_hash_including_bodies: Option<Fingerprint>,
1536 pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1541 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1543}
1544
1545impl<'tcx> OwnerNodes<'tcx> {
1546 pub fn node(&self) -> OwnerNode<'tcx> {
1547 self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1549 }
1550}
1551
1552impl fmt::Debug for OwnerNodes<'_> {
1553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1554 f.debug_struct("OwnerNodes")
1555 .field("node", &self.nodes[ItemLocalId::ZERO])
1557 .field(
1558 "parents",
1559 &fmt::from_fn(|f| {
1560 f.debug_list()
1561 .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1562 fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1563 }))
1564 .finish()
1565 }),
1566 )
1567 .field("bodies", &self.bodies)
1568 .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1569 .finish()
1570 }
1571}
1572
1573#[derive(Debug, HashStable_Generic)]
1575pub struct OwnerInfo<'hir> {
1576 pub nodes: OwnerNodes<'hir>,
1578 pub parenting: LocalDefIdMap<ItemLocalId>,
1580 pub attrs: AttributeMap<'hir>,
1582 pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1585
1586 pub delayed_lints: DelayedLints,
1589}
1590
1591impl<'tcx> OwnerInfo<'tcx> {
1592 #[inline]
1593 pub fn node(&self) -> OwnerNode<'tcx> {
1594 self.nodes.node()
1595 }
1596}
1597
1598#[derive(Copy, Clone, Debug, HashStable_Generic)]
1599pub enum MaybeOwner<'tcx> {
1600 Owner(&'tcx OwnerInfo<'tcx>),
1601 NonOwner(HirId),
1602 Phantom,
1604}
1605
1606impl<'tcx> MaybeOwner<'tcx> {
1607 pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1608 match self {
1609 MaybeOwner::Owner(i) => Some(i),
1610 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1611 }
1612 }
1613
1614 pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1615 self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1616 }
1617}
1618
1619#[derive(Debug)]
1626pub struct Crate<'hir> {
1627 pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1628 pub opt_hir_hash: Option<Fingerprint>,
1630}
1631
1632#[derive(Debug, Clone, Copy, HashStable_Generic)]
1633pub struct Closure<'hir> {
1634 pub def_id: LocalDefId,
1635 pub binder: ClosureBinder,
1636 pub constness: Constness,
1637 pub capture_clause: CaptureBy,
1638 pub bound_generic_params: &'hir [GenericParam<'hir>],
1639 pub fn_decl: &'hir FnDecl<'hir>,
1640 pub body: BodyId,
1641 pub fn_decl_span: Span,
1643 pub fn_arg_span: Option<Span>,
1645 pub kind: ClosureKind,
1646}
1647
1648#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1649pub enum ClosureKind {
1650 Closure,
1652 Coroutine(CoroutineKind),
1657 CoroutineClosure(CoroutineDesugaring),
1662}
1663
1664#[derive(Debug, Clone, Copy, HashStable_Generic)]
1668pub struct Block<'hir> {
1669 pub stmts: &'hir [Stmt<'hir>],
1671 pub expr: Option<&'hir Expr<'hir>>,
1674 #[stable_hasher(ignore)]
1675 pub hir_id: HirId,
1676 pub rules: BlockCheckMode,
1678 pub span: Span,
1680 pub targeted_by_break: bool,
1684}
1685
1686impl<'hir> Block<'hir> {
1687 pub fn innermost_block(&self) -> &Block<'hir> {
1688 let mut block = self;
1689 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1690 block = inner_block;
1691 }
1692 block
1693 }
1694}
1695
1696#[derive(Debug, Clone, Copy, HashStable_Generic)]
1697pub struct TyPat<'hir> {
1698 #[stable_hasher(ignore)]
1699 pub hir_id: HirId,
1700 pub kind: TyPatKind<'hir>,
1701 pub span: Span,
1702}
1703
1704#[derive(Debug, Clone, Copy, HashStable_Generic)]
1705pub struct Pat<'hir> {
1706 #[stable_hasher(ignore)]
1707 pub hir_id: HirId,
1708 pub kind: PatKind<'hir>,
1709 pub span: Span,
1710 pub default_binding_modes: bool,
1713}
1714
1715impl<'hir> Pat<'hir> {
1716 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1717 if !it(self) {
1718 return false;
1719 }
1720
1721 use PatKind::*;
1722 match self.kind {
1723 Missing => unreachable!(),
1724 Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1725 Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => {
1726 s.walk_short_(it)
1727 }
1728 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1729 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1730 Slice(before, slice, after) => {
1731 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1732 }
1733 }
1734 }
1735
1736 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1743 self.walk_short_(&mut it)
1744 }
1745
1746 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1747 if !it(self) {
1748 return;
1749 }
1750
1751 use PatKind::*;
1752 match self.kind {
1753 Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1754 Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1755 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1756 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1757 Slice(before, slice, after) => {
1758 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1759 }
1760 }
1761 }
1762
1763 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1767 self.walk_(&mut it)
1768 }
1769
1770 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1774 self.walk(|p| {
1775 it(p);
1776 true
1777 })
1778 }
1779
1780 pub fn is_never_pattern(&self) -> bool {
1782 let mut is_never_pattern = false;
1783 self.walk(|pat| match &pat.kind {
1784 PatKind::Never => {
1785 is_never_pattern = true;
1786 false
1787 }
1788 PatKind::Or(s) => {
1789 is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1790 false
1791 }
1792 _ => true,
1793 });
1794 is_never_pattern
1795 }
1796}
1797
1798#[derive(Debug, Clone, Copy, HashStable_Generic)]
1804pub struct PatField<'hir> {
1805 #[stable_hasher(ignore)]
1806 pub hir_id: HirId,
1807 pub ident: Ident,
1809 pub pat: &'hir Pat<'hir>,
1811 pub is_shorthand: bool,
1812 pub span: Span,
1813}
1814
1815#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1816pub enum RangeEnd {
1817 Included,
1818 Excluded,
1819}
1820
1821impl fmt::Display for RangeEnd {
1822 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1823 f.write_str(match self {
1824 RangeEnd::Included => "..=",
1825 RangeEnd::Excluded => "..",
1826 })
1827 }
1828}
1829
1830#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1834pub struct DotDotPos(u32);
1835
1836impl DotDotPos {
1837 pub fn new(n: Option<usize>) -> Self {
1839 match n {
1840 Some(n) => {
1841 assert!(n < u32::MAX as usize);
1842 Self(n as u32)
1843 }
1844 None => Self(u32::MAX),
1845 }
1846 }
1847
1848 pub fn as_opt_usize(&self) -> Option<usize> {
1849 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1850 }
1851}
1852
1853impl fmt::Debug for DotDotPos {
1854 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1855 self.as_opt_usize().fmt(f)
1856 }
1857}
1858
1859#[derive(Debug, Clone, Copy, HashStable_Generic)]
1860pub struct PatExpr<'hir> {
1861 #[stable_hasher(ignore)]
1862 pub hir_id: HirId,
1863 pub span: Span,
1864 pub kind: PatExprKind<'hir>,
1865}
1866
1867#[derive(Debug, Clone, Copy, HashStable_Generic)]
1868pub enum PatExprKind<'hir> {
1869 Lit {
1870 lit: Lit,
1871 negated: bool,
1874 },
1875 ConstBlock(ConstBlock),
1876 Path(QPath<'hir>),
1878}
1879
1880#[derive(Debug, Clone, Copy, HashStable_Generic)]
1881pub enum TyPatKind<'hir> {
1882 Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1884
1885 NotNull,
1887
1888 Or(&'hir [TyPat<'hir>]),
1890
1891 Err(ErrorGuaranteed),
1893}
1894
1895#[derive(Debug, Clone, Copy, HashStable_Generic)]
1896pub enum PatKind<'hir> {
1897 Missing,
1899
1900 Wild,
1902
1903 Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1914
1915 Struct(QPath<'hir>, &'hir [PatField<'hir>], Option<Span>),
1918
1919 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1923
1924 Or(&'hir [Pat<'hir>]),
1927
1928 Never,
1930
1931 Tuple(&'hir [Pat<'hir>], DotDotPos),
1935
1936 Box(&'hir Pat<'hir>),
1938
1939 Deref(&'hir Pat<'hir>),
1941
1942 Ref(&'hir Pat<'hir>, Pinnedness, Mutability),
1944
1945 Expr(&'hir PatExpr<'hir>),
1947
1948 Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
1950
1951 Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
1953
1954 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1964
1965 Err(ErrorGuaranteed),
1967}
1968
1969#[derive(Debug, Clone, Copy, HashStable_Generic)]
1971pub struct Stmt<'hir> {
1972 #[stable_hasher(ignore)]
1973 pub hir_id: HirId,
1974 pub kind: StmtKind<'hir>,
1975 pub span: Span,
1976}
1977
1978#[derive(Debug, Clone, Copy, HashStable_Generic)]
1980pub enum StmtKind<'hir> {
1981 Let(&'hir LetStmt<'hir>),
1983
1984 Item(ItemId),
1986
1987 Expr(&'hir Expr<'hir>),
1989
1990 Semi(&'hir Expr<'hir>),
1992}
1993
1994#[derive(Debug, Clone, Copy, HashStable_Generic)]
1996pub struct LetStmt<'hir> {
1997 pub super_: Option<Span>,
1999 pub pat: &'hir Pat<'hir>,
2000 pub ty: Option<&'hir Ty<'hir>>,
2002 pub init: Option<&'hir Expr<'hir>>,
2004 pub els: Option<&'hir Block<'hir>>,
2006 #[stable_hasher(ignore)]
2007 pub hir_id: HirId,
2008 pub span: Span,
2009 pub source: LocalSource,
2013}
2014
2015#[derive(Debug, Clone, Copy, HashStable_Generic)]
2018pub struct Arm<'hir> {
2019 #[stable_hasher(ignore)]
2020 pub hir_id: HirId,
2021 pub span: Span,
2022 pub pat: &'hir Pat<'hir>,
2024 pub guard: Option<&'hir Expr<'hir>>,
2026 pub body: &'hir Expr<'hir>,
2028}
2029
2030#[derive(Debug, Clone, Copy, HashStable_Generic)]
2036pub struct LetExpr<'hir> {
2037 pub span: Span,
2038 pub pat: &'hir Pat<'hir>,
2039 pub ty: Option<&'hir Ty<'hir>>,
2040 pub init: &'hir Expr<'hir>,
2041 pub recovered: ast::Recovered,
2044}
2045
2046#[derive(Debug, Clone, Copy, HashStable_Generic)]
2047pub struct ExprField<'hir> {
2048 #[stable_hasher(ignore)]
2049 pub hir_id: HirId,
2050 pub ident: Ident,
2051 pub expr: &'hir Expr<'hir>,
2052 pub span: Span,
2053 pub is_shorthand: bool,
2054}
2055
2056#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2057pub enum BlockCheckMode {
2058 DefaultBlock,
2059 UnsafeBlock(UnsafeSource),
2060}
2061
2062#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2063pub enum UnsafeSource {
2064 CompilerGenerated,
2065 UserProvided,
2066}
2067
2068#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
2069pub struct BodyId {
2070 pub hir_id: HirId,
2071}
2072
2073#[derive(Debug, Clone, Copy, HashStable_Generic)]
2095pub struct Body<'hir> {
2096 pub params: &'hir [Param<'hir>],
2097 pub value: &'hir Expr<'hir>,
2098}
2099
2100impl<'hir> Body<'hir> {
2101 pub fn id(&self) -> BodyId {
2102 BodyId { hir_id: self.value.hir_id }
2103 }
2104}
2105
2106#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2108pub enum CoroutineKind {
2109 Desugared(CoroutineDesugaring, CoroutineSource),
2111
2112 Coroutine(Movability),
2114}
2115
2116impl CoroutineKind {
2117 pub fn movability(self) -> Movability {
2118 match self {
2119 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2120 | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2121 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2122 CoroutineKind::Coroutine(mov) => mov,
2123 }
2124 }
2125
2126 pub fn is_fn_like(self) -> bool {
2127 matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2128 }
2129
2130 pub fn to_plural_string(&self) -> String {
2131 match self {
2132 CoroutineKind::Desugared(d, CoroutineSource::Fn) => format!("{d:#}fn bodies"),
2133 CoroutineKind::Desugared(d, CoroutineSource::Block) => format!("{d:#}blocks"),
2134 CoroutineKind::Desugared(d, CoroutineSource::Closure) => format!("{d:#}closure bodies"),
2135 CoroutineKind::Coroutine(_) => "coroutines".to_string(),
2136 }
2137 }
2138}
2139
2140impl fmt::Display for CoroutineKind {
2141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2142 match self {
2143 CoroutineKind::Desugared(d, k) => {
2144 d.fmt(f)?;
2145 k.fmt(f)
2146 }
2147 CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2148 }
2149 }
2150}
2151
2152#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
2158pub enum CoroutineSource {
2159 Block,
2161
2162 Closure,
2164
2165 Fn,
2167}
2168
2169impl fmt::Display for CoroutineSource {
2170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2171 match self {
2172 CoroutineSource::Block => "block",
2173 CoroutineSource::Closure => "closure body",
2174 CoroutineSource::Fn => "fn body",
2175 }
2176 .fmt(f)
2177 }
2178}
2179
2180#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2181pub enum CoroutineDesugaring {
2182 Async,
2184
2185 Gen,
2187
2188 AsyncGen,
2191}
2192
2193impl fmt::Display for CoroutineDesugaring {
2194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2195 match self {
2196 CoroutineDesugaring::Async => {
2197 if f.alternate() {
2198 f.write_str("`async` ")?;
2199 } else {
2200 f.write_str("async ")?
2201 }
2202 }
2203 CoroutineDesugaring::Gen => {
2204 if f.alternate() {
2205 f.write_str("`gen` ")?;
2206 } else {
2207 f.write_str("gen ")?
2208 }
2209 }
2210 CoroutineDesugaring::AsyncGen => {
2211 if f.alternate() {
2212 f.write_str("`async gen` ")?;
2213 } else {
2214 f.write_str("async gen ")?
2215 }
2216 }
2217 }
2218
2219 Ok(())
2220 }
2221}
2222
2223#[derive(Copy, Clone, Debug)]
2224pub enum BodyOwnerKind {
2225 Fn,
2227
2228 Closure,
2230
2231 Const { inline: bool },
2233
2234 Static(Mutability),
2236
2237 GlobalAsm,
2239}
2240
2241impl BodyOwnerKind {
2242 pub fn is_fn_or_closure(self) -> bool {
2243 match self {
2244 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2245 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2246 false
2247 }
2248 }
2249 }
2250}
2251
2252#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2254pub enum ConstContext {
2255 ConstFn,
2257
2258 Static(Mutability),
2260
2261 Const { inline: bool },
2271}
2272
2273impl ConstContext {
2274 pub fn keyword_name(self) -> &'static str {
2278 match self {
2279 Self::Const { .. } => "const",
2280 Self::Static(Mutability::Not) => "static",
2281 Self::Static(Mutability::Mut) => "static mut",
2282 Self::ConstFn => "const fn",
2283 }
2284 }
2285}
2286
2287impl fmt::Display for ConstContext {
2290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2291 match *self {
2292 Self::Const { .. } => write!(f, "constant"),
2293 Self::Static(_) => write!(f, "static"),
2294 Self::ConstFn => write!(f, "constant function"),
2295 }
2296 }
2297}
2298
2299impl IntoDiagArg for ConstContext {
2300 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
2301 DiagArgValue::Str(Cow::Borrowed(match self {
2302 ConstContext::ConstFn => "const_fn",
2303 ConstContext::Static(_) => "static",
2304 ConstContext::Const { .. } => "const",
2305 }))
2306 }
2307}
2308
2309pub type Lit = Spanned<LitKind>;
2311
2312#[derive(Copy, Clone, Debug, HashStable_Generic)]
2321pub struct AnonConst {
2322 #[stable_hasher(ignore)]
2323 pub hir_id: HirId,
2324 pub def_id: LocalDefId,
2325 pub body: BodyId,
2326 pub span: Span,
2327}
2328
2329#[derive(Copy, Clone, Debug, HashStable_Generic)]
2331pub struct ConstBlock {
2332 #[stable_hasher(ignore)]
2333 pub hir_id: HirId,
2334 pub def_id: LocalDefId,
2335 pub body: BodyId,
2336}
2337
2338#[derive(Debug, Clone, Copy, HashStable_Generic)]
2347pub struct Expr<'hir> {
2348 #[stable_hasher(ignore)]
2349 pub hir_id: HirId,
2350 pub kind: ExprKind<'hir>,
2351 pub span: Span,
2352}
2353
2354impl Expr<'_> {
2355 pub fn precedence(&self, has_attr: &dyn Fn(HirId) -> bool) -> ExprPrecedence {
2356 let prefix_attrs_precedence = || -> ExprPrecedence {
2357 if has_attr(self.hir_id) { ExprPrecedence::Prefix } else { ExprPrecedence::Unambiguous }
2358 };
2359
2360 match &self.kind {
2361 ExprKind::Closure(closure) => {
2362 match closure.fn_decl.output {
2363 FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2364 FnRetTy::Return(_) => prefix_attrs_precedence(),
2365 }
2366 }
2367
2368 ExprKind::Break(..)
2369 | ExprKind::Ret(..)
2370 | ExprKind::Yield(..)
2371 | ExprKind::Become(..) => ExprPrecedence::Jump,
2372
2373 ExprKind::Binary(op, ..) => op.node.precedence(),
2375 ExprKind::Cast(..) => ExprPrecedence::Cast,
2376
2377 ExprKind::Assign(..) |
2378 ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2379
2380 ExprKind::AddrOf(..)
2382 | ExprKind::Let(..)
2387 | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2388
2389 ExprKind::Array(_)
2391 | ExprKind::Block(..)
2392 | ExprKind::Call(..)
2393 | ExprKind::ConstBlock(_)
2394 | ExprKind::Continue(..)
2395 | ExprKind::Field(..)
2396 | ExprKind::If(..)
2397 | ExprKind::Index(..)
2398 | ExprKind::InlineAsm(..)
2399 | ExprKind::Lit(_)
2400 | ExprKind::Loop(..)
2401 | ExprKind::Match(..)
2402 | ExprKind::MethodCall(..)
2403 | ExprKind::OffsetOf(..)
2404 | ExprKind::Path(..)
2405 | ExprKind::Repeat(..)
2406 | ExprKind::Struct(..)
2407 | ExprKind::Tup(_)
2408 | ExprKind::Type(..)
2409 | ExprKind::UnsafeBinderCast(..)
2410 | ExprKind::Use(..)
2411 | ExprKind::Err(_) => prefix_attrs_precedence(),
2412
2413 ExprKind::DropTemps(expr, ..) => expr.precedence(has_attr),
2414 }
2415 }
2416
2417 pub fn is_syntactic_place_expr(&self) -> bool {
2422 self.is_place_expr(|_| true)
2423 }
2424
2425 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2430 match self.kind {
2431 ExprKind::Path(QPath::Resolved(_, ref path)) => {
2432 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2433 }
2434
2435 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2439
2440 ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2442
2443 ExprKind::Unary(UnOp::Deref, _) => true,
2444
2445 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2446 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2447 }
2448
2449 ExprKind::Err(_guar)
2451 | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2452
2453 ExprKind::Path(QPath::TypeRelative(..))
2456 | ExprKind::Call(..)
2457 | ExprKind::MethodCall(..)
2458 | ExprKind::Use(..)
2459 | ExprKind::Struct(..)
2460 | ExprKind::Tup(..)
2461 | ExprKind::If(..)
2462 | ExprKind::Match(..)
2463 | ExprKind::Closure { .. }
2464 | ExprKind::Block(..)
2465 | ExprKind::Repeat(..)
2466 | ExprKind::Array(..)
2467 | ExprKind::Break(..)
2468 | ExprKind::Continue(..)
2469 | ExprKind::Ret(..)
2470 | ExprKind::Become(..)
2471 | ExprKind::Let(..)
2472 | ExprKind::Loop(..)
2473 | ExprKind::Assign(..)
2474 | ExprKind::InlineAsm(..)
2475 | ExprKind::OffsetOf(..)
2476 | ExprKind::AssignOp(..)
2477 | ExprKind::Lit(_)
2478 | ExprKind::ConstBlock(..)
2479 | ExprKind::Unary(..)
2480 | ExprKind::AddrOf(..)
2481 | ExprKind::Binary(..)
2482 | ExprKind::Yield(..)
2483 | ExprKind::Cast(..)
2484 | ExprKind::DropTemps(..) => false,
2485 }
2486 }
2487
2488 pub fn range_span(&self) -> Option<Span> {
2491 is_range_literal(self).then(|| self.span.parent_callsite().unwrap())
2492 }
2493
2494 pub fn is_size_lit(&self) -> bool {
2497 matches!(
2498 self.kind,
2499 ExprKind::Lit(Lit {
2500 node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2501 ..
2502 })
2503 )
2504 }
2505
2506 pub fn peel_drop_temps(&self) -> &Self {
2512 let mut expr = self;
2513 while let ExprKind::DropTemps(inner) = &expr.kind {
2514 expr = inner;
2515 }
2516 expr
2517 }
2518
2519 pub fn peel_blocks(&self) -> &Self {
2520 let mut expr = self;
2521 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2522 expr = inner;
2523 }
2524 expr
2525 }
2526
2527 pub fn peel_borrows(&self) -> &Self {
2528 let mut expr = self;
2529 while let ExprKind::AddrOf(.., inner) = &expr.kind {
2530 expr = inner;
2531 }
2532 expr
2533 }
2534
2535 pub fn can_have_side_effects(&self) -> bool {
2536 match self.peel_drop_temps().kind {
2537 ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2538 false
2539 }
2540 ExprKind::Type(base, _)
2541 | ExprKind::Unary(_, base)
2542 | ExprKind::Field(base, _)
2543 | ExprKind::Index(base, _, _)
2544 | ExprKind::AddrOf(.., base)
2545 | ExprKind::Cast(base, _)
2546 | ExprKind::UnsafeBinderCast(_, base, _) => {
2547 base.can_have_side_effects()
2551 }
2552 ExprKind::Struct(_, fields, init) => {
2553 let init_side_effects = match init {
2554 StructTailExpr::Base(init) => init.can_have_side_effects(),
2555 StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2556 };
2557 fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2558 || init_side_effects
2559 }
2560
2561 ExprKind::Array(args)
2562 | ExprKind::Tup(args)
2563 | ExprKind::Call(
2564 Expr {
2565 kind:
2566 ExprKind::Path(QPath::Resolved(
2567 None,
2568 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2569 )),
2570 ..
2571 },
2572 args,
2573 ) => args.iter().any(|arg| arg.can_have_side_effects()),
2574 ExprKind::If(..)
2575 | ExprKind::Match(..)
2576 | ExprKind::MethodCall(..)
2577 | ExprKind::Call(..)
2578 | ExprKind::Closure { .. }
2579 | ExprKind::Block(..)
2580 | ExprKind::Repeat(..)
2581 | ExprKind::Break(..)
2582 | ExprKind::Continue(..)
2583 | ExprKind::Ret(..)
2584 | ExprKind::Become(..)
2585 | ExprKind::Let(..)
2586 | ExprKind::Loop(..)
2587 | ExprKind::Assign(..)
2588 | ExprKind::InlineAsm(..)
2589 | ExprKind::AssignOp(..)
2590 | ExprKind::ConstBlock(..)
2591 | ExprKind::Binary(..)
2592 | ExprKind::Yield(..)
2593 | ExprKind::DropTemps(..)
2594 | ExprKind::Err(_) => true,
2595 }
2596 }
2597
2598 pub fn is_approximately_pattern(&self) -> bool {
2600 match &self.kind {
2601 ExprKind::Array(_)
2602 | ExprKind::Call(..)
2603 | ExprKind::Tup(_)
2604 | ExprKind::Lit(_)
2605 | ExprKind::Path(_)
2606 | ExprKind::Struct(..) => true,
2607 _ => false,
2608 }
2609 }
2610
2611 pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2616 match (self.kind, other.kind) {
2617 (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2618 (
2619 ExprKind::Path(QPath::Resolved(None, path1)),
2620 ExprKind::Path(QPath::Resolved(None, path2)),
2621 ) => path1.res == path2.res,
2622 (
2623 ExprKind::Struct(
2624 &QPath::Resolved(None, &Path { res: Res::Def(_, path1_def_id), .. }),
2625 args1,
2626 StructTailExpr::None,
2627 ),
2628 ExprKind::Struct(
2629 &QPath::Resolved(None, &Path { res: Res::Def(_, path2_def_id), .. }),
2630 args2,
2631 StructTailExpr::None,
2632 ),
2633 ) => {
2634 path2_def_id == path1_def_id
2635 && is_range_literal(self)
2636 && is_range_literal(other)
2637 && std::iter::zip(args1, args2)
2638 .all(|(a, b)| a.expr.equivalent_for_indexing(b.expr))
2639 }
2640 _ => false,
2641 }
2642 }
2643
2644 pub fn method_ident(&self) -> Option<Ident> {
2645 match self.kind {
2646 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2647 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2648 _ => None,
2649 }
2650 }
2651}
2652
2653pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2656 if let ExprKind::Struct(QPath::Resolved(None, path), _, StructTailExpr::None) = expr.kind
2657 && let [.., segment] = path.segments
2658 && let sym::RangeFrom
2659 | sym::RangeFull
2660 | sym::Range
2661 | sym::RangeToInclusive
2662 | sym::RangeTo
2663 | sym::RangeFromCopy
2664 | sym::RangeCopy
2665 | sym::RangeInclusiveCopy
2666 | sym::RangeToInclusiveCopy = segment.ident.name
2667 && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2668 {
2669 true
2670 } else if let ExprKind::Call(func, _) = &expr.kind
2671 && let ExprKind::Path(QPath::Resolved(None, path)) = func.kind
2672 && let [.., segment] = path.segments
2673 && let sym::range_inclusive_new = segment.ident.name
2674 && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2675 {
2676 true
2677 } else {
2678 false
2679 }
2680}
2681
2682pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2689 match expr.kind {
2690 ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2692 _ if is_range_literal(expr) => true,
2694 _ => false,
2695 }
2696}
2697
2698#[derive(Debug, Clone, Copy, HashStable_Generic)]
2699pub enum ExprKind<'hir> {
2700 ConstBlock(ConstBlock),
2702 Array(&'hir [Expr<'hir>]),
2704 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2711 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2728 Use(&'hir Expr<'hir>, Span),
2730 Tup(&'hir [Expr<'hir>]),
2732 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2734 Unary(UnOp, &'hir Expr<'hir>),
2736 Lit(Lit),
2738 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2740 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2742 DropTemps(&'hir Expr<'hir>),
2748 Let(&'hir LetExpr<'hir>),
2753 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2762 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2768 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2771 Closure(&'hir Closure<'hir>),
2778 Block(&'hir Block<'hir>, Option<Label>),
2780
2781 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2783 AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2787 Field(&'hir Expr<'hir>, Ident),
2789 Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2793
2794 Path(QPath<'hir>),
2796
2797 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2799 Break(Destination, Option<&'hir Expr<'hir>>),
2801 Continue(Destination),
2803 Ret(Option<&'hir Expr<'hir>>),
2805 Become(&'hir Expr<'hir>),
2807
2808 InlineAsm(&'hir InlineAsm<'hir>),
2810
2811 OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2813
2814 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2819
2820 Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2825
2826 Yield(&'hir Expr<'hir>, YieldSource),
2828
2829 UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2832
2833 Err(rustc_span::ErrorGuaranteed),
2835}
2836
2837#[derive(Debug, Clone, Copy, HashStable_Generic)]
2838pub enum StructTailExpr<'hir> {
2839 None,
2841 Base(&'hir Expr<'hir>),
2844 DefaultFields(Span),
2848}
2849
2850#[derive(Debug, Clone, Copy, HashStable_Generic)]
2856pub enum QPath<'hir> {
2857 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2864
2865 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2872}
2873
2874impl<'hir> QPath<'hir> {
2875 pub fn span(&self) -> Span {
2877 match *self {
2878 QPath::Resolved(_, path) => path.span,
2879 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2880 }
2881 }
2882
2883 pub fn qself_span(&self) -> Span {
2886 match *self {
2887 QPath::Resolved(_, path) => path.span,
2888 QPath::TypeRelative(qself, _) => qself.span,
2889 }
2890 }
2891}
2892
2893#[derive(Copy, Clone, Debug, HashStable_Generic)]
2895pub enum LocalSource {
2896 Normal,
2898 AsyncFn,
2909 AwaitDesugar,
2911 AssignDesugar,
2913 Contract,
2915}
2916
2917#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2919pub enum MatchSource {
2920 Normal,
2922 Postfix,
2924 ForLoopDesugar,
2926 TryDesugar(HirId),
2928 AwaitDesugar,
2930 FormatArgs,
2932}
2933
2934impl MatchSource {
2935 #[inline]
2936 pub const fn name(self) -> &'static str {
2937 use MatchSource::*;
2938 match self {
2939 Normal => "match",
2940 Postfix => ".match",
2941 ForLoopDesugar => "for",
2942 TryDesugar(_) => "?",
2943 AwaitDesugar => ".await",
2944 FormatArgs => "format_args!()",
2945 }
2946 }
2947}
2948
2949#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2951pub enum LoopSource {
2952 Loop,
2954 While,
2956 ForLoop,
2958}
2959
2960impl LoopSource {
2961 pub fn name(self) -> &'static str {
2962 match self {
2963 LoopSource::Loop => "loop",
2964 LoopSource::While => "while",
2965 LoopSource::ForLoop => "for",
2966 }
2967 }
2968}
2969
2970#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2971pub enum LoopIdError {
2972 OutsideLoopScope,
2973 UnlabeledCfInWhileCondition,
2974 UnresolvedLabel,
2975}
2976
2977impl fmt::Display for LoopIdError {
2978 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2979 f.write_str(match self {
2980 LoopIdError::OutsideLoopScope => "not inside loop scope",
2981 LoopIdError::UnlabeledCfInWhileCondition => {
2982 "unlabeled control flow (break or continue) in while condition"
2983 }
2984 LoopIdError::UnresolvedLabel => "label not found",
2985 })
2986 }
2987}
2988
2989#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2990pub struct Destination {
2991 pub label: Option<Label>,
2993
2994 pub target_id: Result<HirId, LoopIdError>,
2997}
2998
2999#[derive(Copy, Clone, Debug, HashStable_Generic)]
3001pub enum YieldSource {
3002 Await { expr: Option<HirId> },
3004 Yield,
3006}
3007
3008impl fmt::Display for YieldSource {
3009 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3010 f.write_str(match self {
3011 YieldSource::Await { .. } => "`await`",
3012 YieldSource::Yield => "`yield`",
3013 })
3014 }
3015}
3016
3017#[derive(Debug, Clone, Copy, HashStable_Generic)]
3020pub struct MutTy<'hir> {
3021 pub ty: &'hir Ty<'hir>,
3022 pub mutbl: Mutability,
3023}
3024
3025#[derive(Debug, Clone, Copy, HashStable_Generic)]
3028pub struct FnSig<'hir> {
3029 pub header: FnHeader,
3030 pub decl: &'hir FnDecl<'hir>,
3031 pub span: Span,
3032}
3033
3034#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3038pub struct TraitItemId {
3039 pub owner_id: OwnerId,
3040}
3041
3042impl TraitItemId {
3043 #[inline]
3044 pub fn hir_id(&self) -> HirId {
3045 HirId::make_owner(self.owner_id.def_id)
3047 }
3048}
3049
3050#[derive(Debug, Clone, Copy, HashStable_Generic)]
3055pub struct TraitItem<'hir> {
3056 pub ident: Ident,
3057 pub owner_id: OwnerId,
3058 pub generics: &'hir Generics<'hir>,
3059 pub kind: TraitItemKind<'hir>,
3060 pub span: Span,
3061 pub defaultness: Defaultness,
3062 pub has_delayed_lints: bool,
3063}
3064
3065macro_rules! expect_methods_self_kind {
3066 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3067 $(
3068 #[track_caller]
3069 pub fn $name(&self) -> $ret_ty {
3070 let $pat = &self.kind else { expect_failed(stringify!($name), self) };
3071 $ret_val
3072 }
3073 )*
3074 }
3075}
3076
3077macro_rules! expect_methods_self {
3078 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3079 $(
3080 #[track_caller]
3081 pub fn $name(&self) -> $ret_ty {
3082 let $pat = self else { expect_failed(stringify!($name), self) };
3083 $ret_val
3084 }
3085 )*
3086 }
3087}
3088
3089#[track_caller]
3090fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3091 panic!("{ident}: found {found:?}")
3092}
3093
3094impl<'hir> TraitItem<'hir> {
3095 #[inline]
3096 pub fn hir_id(&self) -> HirId {
3097 HirId::make_owner(self.owner_id.def_id)
3099 }
3100
3101 pub fn trait_item_id(&self) -> TraitItemId {
3102 TraitItemId { owner_id: self.owner_id }
3103 }
3104
3105 expect_methods_self_kind! {
3106 expect_const, (&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3107 TraitItemKind::Const(ty, rhs), (ty, *rhs);
3108
3109 expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3110 TraitItemKind::Fn(ty, trfn), (ty, trfn);
3111
3112 expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3113 TraitItemKind::Type(bounds, ty), (bounds, *ty);
3114 }
3115}
3116
3117#[derive(Debug, Clone, Copy, HashStable_Generic)]
3119pub enum TraitFn<'hir> {
3120 Required(&'hir [Option<Ident>]),
3122
3123 Provided(BodyId),
3125}
3126
3127#[derive(Debug, Clone, Copy, HashStable_Generic)]
3129pub enum TraitItemKind<'hir> {
3130 Const(&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3132 Fn(FnSig<'hir>, TraitFn<'hir>),
3134 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3137}
3138
3139#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3143pub struct ImplItemId {
3144 pub owner_id: OwnerId,
3145}
3146
3147impl ImplItemId {
3148 #[inline]
3149 pub fn hir_id(&self) -> HirId {
3150 HirId::make_owner(self.owner_id.def_id)
3152 }
3153}
3154
3155#[derive(Debug, Clone, Copy, HashStable_Generic)]
3159pub struct ImplItem<'hir> {
3160 pub ident: Ident,
3161 pub owner_id: OwnerId,
3162 pub generics: &'hir Generics<'hir>,
3163 pub kind: ImplItemKind<'hir>,
3164 pub impl_kind: ImplItemImplKind,
3165 pub span: Span,
3166 pub has_delayed_lints: bool,
3167}
3168
3169#[derive(Debug, Clone, Copy, HashStable_Generic)]
3170pub enum ImplItemImplKind {
3171 Inherent {
3172 vis_span: Span,
3173 },
3174 Trait {
3175 defaultness: Defaultness,
3176 trait_item_def_id: Result<DefId, ErrorGuaranteed>,
3178 },
3179}
3180
3181impl<'hir> ImplItem<'hir> {
3182 #[inline]
3183 pub fn hir_id(&self) -> HirId {
3184 HirId::make_owner(self.owner_id.def_id)
3186 }
3187
3188 pub fn impl_item_id(&self) -> ImplItemId {
3189 ImplItemId { owner_id: self.owner_id }
3190 }
3191
3192 pub fn vis_span(&self) -> Option<Span> {
3193 match self.impl_kind {
3194 ImplItemImplKind::Trait { .. } => None,
3195 ImplItemImplKind::Inherent { vis_span, .. } => Some(vis_span),
3196 }
3197 }
3198
3199 expect_methods_self_kind! {
3200 expect_const, (&'hir Ty<'hir>, ConstItemRhs<'hir>), ImplItemKind::Const(ty, rhs), (ty, *rhs);
3201 expect_fn, (&FnSig<'hir>, BodyId), ImplItemKind::Fn(ty, body), (ty, *body);
3202 expect_type, &'hir Ty<'hir>, ImplItemKind::Type(ty), ty;
3203 }
3204}
3205
3206#[derive(Debug, Clone, Copy, HashStable_Generic)]
3208pub enum ImplItemKind<'hir> {
3209 Const(&'hir Ty<'hir>, ConstItemRhs<'hir>),
3212 Fn(FnSig<'hir>, BodyId),
3214 Type(&'hir Ty<'hir>),
3216}
3217
3218#[derive(Debug, Clone, Copy, HashStable_Generic)]
3229pub struct AssocItemConstraint<'hir> {
3230 #[stable_hasher(ignore)]
3231 pub hir_id: HirId,
3232 pub ident: Ident,
3233 pub gen_args: &'hir GenericArgs<'hir>,
3234 pub kind: AssocItemConstraintKind<'hir>,
3235 pub span: Span,
3236}
3237
3238impl<'hir> AssocItemConstraint<'hir> {
3239 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3241 match self.kind {
3242 AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3243 _ => None,
3244 }
3245 }
3246
3247 pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3249 match self.kind {
3250 AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3251 _ => None,
3252 }
3253 }
3254}
3255
3256#[derive(Debug, Clone, Copy, HashStable_Generic)]
3257pub enum Term<'hir> {
3258 Ty(&'hir Ty<'hir>),
3259 Const(&'hir ConstArg<'hir>),
3260}
3261
3262impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3263 fn from(ty: &'hir Ty<'hir>) -> Self {
3264 Term::Ty(ty)
3265 }
3266}
3267
3268impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3269 fn from(c: &'hir ConstArg<'hir>) -> Self {
3270 Term::Const(c)
3271 }
3272}
3273
3274#[derive(Debug, Clone, Copy, HashStable_Generic)]
3276pub enum AssocItemConstraintKind<'hir> {
3277 Equality { term: Term<'hir> },
3284 Bound { bounds: &'hir [GenericBound<'hir>] },
3286}
3287
3288impl<'hir> AssocItemConstraintKind<'hir> {
3289 pub fn descr(&self) -> &'static str {
3290 match self {
3291 AssocItemConstraintKind::Equality { .. } => "binding",
3292 AssocItemConstraintKind::Bound { .. } => "constraint",
3293 }
3294 }
3295}
3296
3297#[derive(Debug, Clone, Copy, HashStable_Generic)]
3301pub enum AmbigArg {}
3302
3303#[derive(Debug, Clone, Copy, HashStable_Generic)]
3308#[repr(C)]
3309pub struct Ty<'hir, Unambig = ()> {
3310 #[stable_hasher(ignore)]
3311 pub hir_id: HirId,
3312 pub span: Span,
3313 pub kind: TyKind<'hir, Unambig>,
3314}
3315
3316impl<'hir> Ty<'hir, AmbigArg> {
3317 pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3328 let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3331 unsafe { &*ptr }
3332 }
3333}
3334
3335impl<'hir> Ty<'hir> {
3336 pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3342 if let TyKind::Infer(()) = self.kind {
3343 return None;
3344 }
3345
3346 let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3350 Some(unsafe { &*ptr })
3351 }
3352}
3353
3354impl<'hir> Ty<'hir, AmbigArg> {
3355 pub fn peel_refs(&self) -> &Ty<'hir> {
3356 let mut final_ty = self.as_unambig_ty();
3357 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3358 final_ty = ty;
3359 }
3360 final_ty
3361 }
3362}
3363
3364impl<'hir> Ty<'hir> {
3365 pub fn peel_refs(&self) -> &Self {
3366 let mut final_ty = self;
3367 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3368 final_ty = ty;
3369 }
3370 final_ty
3371 }
3372
3373 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3375 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3376 return None;
3377 };
3378 let [segment] = &path.segments else {
3379 return None;
3380 };
3381 match path.res {
3382 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3383 Some((def_id, segment.ident))
3384 }
3385 _ => None,
3386 }
3387 }
3388
3389 pub fn find_self_aliases(&self) -> Vec<Span> {
3390 use crate::intravisit::Visitor;
3391 struct MyVisitor(Vec<Span>);
3392 impl<'v> Visitor<'v> for MyVisitor {
3393 fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3394 if matches!(
3395 &t.kind,
3396 TyKind::Path(QPath::Resolved(
3397 _,
3398 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3399 ))
3400 ) {
3401 self.0.push(t.span);
3402 return;
3403 }
3404 crate::intravisit::walk_ty(self, t);
3405 }
3406 }
3407
3408 let mut my_visitor = MyVisitor(vec![]);
3409 my_visitor.visit_ty_unambig(self);
3410 my_visitor.0
3411 }
3412
3413 pub fn is_suggestable_infer_ty(&self) -> bool {
3416 fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3417 generic_args.iter().any(|arg| match arg {
3418 GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3419 GenericArg::Infer(_) => true,
3420 _ => false,
3421 })
3422 }
3423 debug!(?self);
3424 match &self.kind {
3425 TyKind::Infer(()) => true,
3426 TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3427 TyKind::Array(ty, length) => {
3428 ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3429 }
3430 TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3431 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3432 TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3433 ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3434 }
3435 TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3436 ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3437 || segments
3438 .iter()
3439 .any(|segment| are_suggestable_generic_args(segment.args().args))
3440 }
3441 _ => false,
3442 }
3443 }
3444}
3445
3446#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3448pub enum PrimTy {
3449 Int(IntTy),
3450 Uint(UintTy),
3451 Float(FloatTy),
3452 Str,
3453 Bool,
3454 Char,
3455}
3456
3457impl PrimTy {
3458 pub const ALL: [Self; 19] = [
3460 Self::Int(IntTy::I8),
3462 Self::Int(IntTy::I16),
3463 Self::Int(IntTy::I32),
3464 Self::Int(IntTy::I64),
3465 Self::Int(IntTy::I128),
3466 Self::Int(IntTy::Isize),
3467 Self::Uint(UintTy::U8),
3468 Self::Uint(UintTy::U16),
3469 Self::Uint(UintTy::U32),
3470 Self::Uint(UintTy::U64),
3471 Self::Uint(UintTy::U128),
3472 Self::Uint(UintTy::Usize),
3473 Self::Float(FloatTy::F16),
3474 Self::Float(FloatTy::F32),
3475 Self::Float(FloatTy::F64),
3476 Self::Float(FloatTy::F128),
3477 Self::Bool,
3478 Self::Char,
3479 Self::Str,
3480 ];
3481
3482 pub fn name_str(self) -> &'static str {
3486 match self {
3487 PrimTy::Int(i) => i.name_str(),
3488 PrimTy::Uint(u) => u.name_str(),
3489 PrimTy::Float(f) => f.name_str(),
3490 PrimTy::Str => "str",
3491 PrimTy::Bool => "bool",
3492 PrimTy::Char => "char",
3493 }
3494 }
3495
3496 pub fn name(self) -> Symbol {
3497 match self {
3498 PrimTy::Int(i) => i.name(),
3499 PrimTy::Uint(u) => u.name(),
3500 PrimTy::Float(f) => f.name(),
3501 PrimTy::Str => sym::str,
3502 PrimTy::Bool => sym::bool,
3503 PrimTy::Char => sym::char,
3504 }
3505 }
3506
3507 pub fn from_name(name: Symbol) -> Option<Self> {
3510 let ty = match name {
3511 sym::i8 => Self::Int(IntTy::I8),
3513 sym::i16 => Self::Int(IntTy::I16),
3514 sym::i32 => Self::Int(IntTy::I32),
3515 sym::i64 => Self::Int(IntTy::I64),
3516 sym::i128 => Self::Int(IntTy::I128),
3517 sym::isize => Self::Int(IntTy::Isize),
3518 sym::u8 => Self::Uint(UintTy::U8),
3519 sym::u16 => Self::Uint(UintTy::U16),
3520 sym::u32 => Self::Uint(UintTy::U32),
3521 sym::u64 => Self::Uint(UintTy::U64),
3522 sym::u128 => Self::Uint(UintTy::U128),
3523 sym::usize => Self::Uint(UintTy::Usize),
3524 sym::f16 => Self::Float(FloatTy::F16),
3525 sym::f32 => Self::Float(FloatTy::F32),
3526 sym::f64 => Self::Float(FloatTy::F64),
3527 sym::f128 => Self::Float(FloatTy::F128),
3528 sym::bool => Self::Bool,
3529 sym::char => Self::Char,
3530 sym::str => Self::Str,
3531 _ => return None,
3532 };
3533 Some(ty)
3534 }
3535}
3536
3537#[derive(Debug, Clone, Copy, HashStable_Generic)]
3538pub struct FnPtrTy<'hir> {
3539 pub safety: Safety,
3540 pub abi: ExternAbi,
3541 pub generic_params: &'hir [GenericParam<'hir>],
3542 pub decl: &'hir FnDecl<'hir>,
3543 pub param_idents: &'hir [Option<Ident>],
3546}
3547
3548#[derive(Debug, Clone, Copy, HashStable_Generic)]
3549pub struct UnsafeBinderTy<'hir> {
3550 pub generic_params: &'hir [GenericParam<'hir>],
3551 pub inner_ty: &'hir Ty<'hir>,
3552}
3553
3554#[derive(Debug, Clone, Copy, HashStable_Generic)]
3555pub struct OpaqueTy<'hir> {
3556 #[stable_hasher(ignore)]
3557 pub hir_id: HirId,
3558 pub def_id: LocalDefId,
3559 pub bounds: GenericBounds<'hir>,
3560 pub origin: OpaqueTyOrigin<LocalDefId>,
3561 pub span: Span,
3562}
3563
3564#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3565pub enum PreciseCapturingArgKind<T, U> {
3566 Lifetime(T),
3567 Param(U),
3569}
3570
3571pub type PreciseCapturingArg<'hir> =
3572 PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3573
3574impl PreciseCapturingArg<'_> {
3575 pub fn hir_id(self) -> HirId {
3576 match self {
3577 PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3578 PreciseCapturingArg::Param(param) => param.hir_id,
3579 }
3580 }
3581
3582 pub fn name(self) -> Symbol {
3583 match self {
3584 PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3585 PreciseCapturingArg::Param(param) => param.ident.name,
3586 }
3587 }
3588}
3589
3590#[derive(Debug, Clone, Copy, HashStable_Generic)]
3595pub struct PreciseCapturingNonLifetimeArg {
3596 #[stable_hasher(ignore)]
3597 pub hir_id: HirId,
3598 pub ident: Ident,
3599 pub res: Res,
3600}
3601
3602#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3603#[derive(HashStable_Generic, Encodable, Decodable)]
3604pub enum RpitContext {
3605 Trait,
3606 TraitImpl,
3607}
3608
3609#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3611#[derive(HashStable_Generic, Encodable, Decodable)]
3612pub enum OpaqueTyOrigin<D> {
3613 FnReturn {
3615 parent: D,
3617 in_trait_or_impl: Option<RpitContext>,
3619 },
3620 AsyncFn {
3622 parent: D,
3624 in_trait_or_impl: Option<RpitContext>,
3626 },
3627 TyAlias {
3629 parent: D,
3631 in_assoc_ty: bool,
3633 },
3634}
3635
3636#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3637pub enum InferDelegationKind {
3638 Input(usize),
3639 Output,
3640}
3641
3642#[repr(u8, C)]
3648#[derive(Debug, Clone, Copy, HashStable_Generic)]
3649pub enum TyKind<'hir, Unambig = ()> {
3650 InferDelegation(DefId, InferDelegationKind),
3652 Slice(&'hir Ty<'hir>),
3654 Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3656 Ptr(MutTy<'hir>),
3658 Ref(&'hir Lifetime, MutTy<'hir>),
3660 FnPtr(&'hir FnPtrTy<'hir>),
3662 UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3664 Never,
3666 Tup(&'hir [Ty<'hir>]),
3668 Path(QPath<'hir>),
3673 OpaqueDef(&'hir OpaqueTy<'hir>),
3675 TraitAscription(GenericBounds<'hir>),
3677 TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3683 Typeof(&'hir AnonConst),
3685 Err(rustc_span::ErrorGuaranteed),
3687 Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3689 Infer(Unambig),
3695}
3696
3697#[derive(Debug, Clone, Copy, HashStable_Generic)]
3698pub enum InlineAsmOperand<'hir> {
3699 In {
3700 reg: InlineAsmRegOrRegClass,
3701 expr: &'hir Expr<'hir>,
3702 },
3703 Out {
3704 reg: InlineAsmRegOrRegClass,
3705 late: bool,
3706 expr: Option<&'hir Expr<'hir>>,
3707 },
3708 InOut {
3709 reg: InlineAsmRegOrRegClass,
3710 late: bool,
3711 expr: &'hir Expr<'hir>,
3712 },
3713 SplitInOut {
3714 reg: InlineAsmRegOrRegClass,
3715 late: bool,
3716 in_expr: &'hir Expr<'hir>,
3717 out_expr: Option<&'hir Expr<'hir>>,
3718 },
3719 Const {
3720 anon_const: ConstBlock,
3721 },
3722 SymFn {
3723 expr: &'hir Expr<'hir>,
3724 },
3725 SymStatic {
3726 path: QPath<'hir>,
3727 def_id: DefId,
3728 },
3729 Label {
3730 block: &'hir Block<'hir>,
3731 },
3732}
3733
3734impl<'hir> InlineAsmOperand<'hir> {
3735 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3736 match *self {
3737 Self::In { reg, .. }
3738 | Self::Out { reg, .. }
3739 | Self::InOut { reg, .. }
3740 | Self::SplitInOut { reg, .. } => Some(reg),
3741 Self::Const { .. }
3742 | Self::SymFn { .. }
3743 | Self::SymStatic { .. }
3744 | Self::Label { .. } => None,
3745 }
3746 }
3747
3748 pub fn is_clobber(&self) -> bool {
3749 matches!(
3750 self,
3751 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3752 )
3753 }
3754}
3755
3756#[derive(Debug, Clone, Copy, HashStable_Generic)]
3757pub struct InlineAsm<'hir> {
3758 pub asm_macro: ast::AsmMacro,
3759 pub template: &'hir [InlineAsmTemplatePiece],
3760 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3761 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3762 pub options: InlineAsmOptions,
3763 pub line_spans: &'hir [Span],
3764}
3765
3766impl InlineAsm<'_> {
3767 pub fn contains_label(&self) -> bool {
3768 self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3769 }
3770}
3771
3772#[derive(Debug, Clone, Copy, HashStable_Generic)]
3774pub struct Param<'hir> {
3775 #[stable_hasher(ignore)]
3776 pub hir_id: HirId,
3777 pub pat: &'hir Pat<'hir>,
3778 pub ty_span: Span,
3779 pub span: Span,
3780}
3781
3782#[derive(Debug, Clone, Copy, HashStable_Generic)]
3784pub struct FnDecl<'hir> {
3785 pub inputs: &'hir [Ty<'hir>],
3789 pub output: FnRetTy<'hir>,
3790 pub c_variadic: bool,
3791 pub implicit_self: ImplicitSelfKind,
3793 pub lifetime_elision_allowed: bool,
3795}
3796
3797impl<'hir> FnDecl<'hir> {
3798 pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3799 if let FnRetTy::Return(ty) = self.output
3800 && let TyKind::InferDelegation(sig_id, _) = ty.kind
3801 {
3802 return Some(sig_id);
3803 }
3804 None
3805 }
3806}
3807
3808#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3810pub enum ImplicitSelfKind {
3811 Imm,
3813 Mut,
3815 RefImm,
3817 RefMut,
3819 None,
3822}
3823
3824impl ImplicitSelfKind {
3825 pub fn has_implicit_self(&self) -> bool {
3827 !matches!(*self, ImplicitSelfKind::None)
3828 }
3829}
3830
3831#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3832pub enum IsAsync {
3833 Async(Span),
3834 NotAsync,
3835}
3836
3837impl IsAsync {
3838 pub fn is_async(self) -> bool {
3839 matches!(self, IsAsync::Async(_))
3840 }
3841}
3842
3843#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3844pub enum Defaultness {
3845 Default { has_value: bool },
3846 Final,
3847}
3848
3849impl Defaultness {
3850 pub fn has_value(&self) -> bool {
3851 match *self {
3852 Defaultness::Default { has_value } => has_value,
3853 Defaultness::Final => true,
3854 }
3855 }
3856
3857 pub fn is_final(&self) -> bool {
3858 *self == Defaultness::Final
3859 }
3860
3861 pub fn is_default(&self) -> bool {
3862 matches!(*self, Defaultness::Default { .. })
3863 }
3864}
3865
3866#[derive(Debug, Clone, Copy, HashStable_Generic)]
3867pub enum FnRetTy<'hir> {
3868 DefaultReturn(Span),
3874 Return(&'hir Ty<'hir>),
3876}
3877
3878impl<'hir> FnRetTy<'hir> {
3879 #[inline]
3880 pub fn span(&self) -> Span {
3881 match *self {
3882 Self::DefaultReturn(span) => span,
3883 Self::Return(ref ty) => ty.span,
3884 }
3885 }
3886
3887 pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3888 if let Self::Return(ty) = self
3889 && ty.is_suggestable_infer_ty()
3890 {
3891 return Some(*ty);
3892 }
3893 None
3894 }
3895}
3896
3897#[derive(Copy, Clone, Debug, HashStable_Generic)]
3899pub enum ClosureBinder {
3900 Default,
3902 For { span: Span },
3906}
3907
3908#[derive(Debug, Clone, Copy, HashStable_Generic)]
3909pub struct Mod<'hir> {
3910 pub spans: ModSpans,
3911 pub item_ids: &'hir [ItemId],
3912}
3913
3914#[derive(Copy, Clone, Debug, HashStable_Generic)]
3915pub struct ModSpans {
3916 pub inner_span: Span,
3920 pub inject_use_span: Span,
3921}
3922
3923#[derive(Debug, Clone, Copy, HashStable_Generic)]
3924pub struct EnumDef<'hir> {
3925 pub variants: &'hir [Variant<'hir>],
3926}
3927
3928#[derive(Debug, Clone, Copy, HashStable_Generic)]
3929pub struct Variant<'hir> {
3930 pub ident: Ident,
3932 #[stable_hasher(ignore)]
3934 pub hir_id: HirId,
3935 pub def_id: LocalDefId,
3936 pub data: VariantData<'hir>,
3938 pub disr_expr: Option<&'hir AnonConst>,
3940 pub span: Span,
3942}
3943
3944#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3945pub enum UseKind {
3946 Single(Ident),
3953
3954 Glob,
3956
3957 ListStem,
3961}
3962
3963#[derive(Clone, Debug, Copy, HashStable_Generic)]
3970pub struct TraitRef<'hir> {
3971 pub path: &'hir Path<'hir>,
3972 #[stable_hasher(ignore)]
3974 pub hir_ref_id: HirId,
3975}
3976
3977impl TraitRef<'_> {
3978 pub fn trait_def_id(&self) -> Option<DefId> {
3980 match self.path.res {
3981 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3982 Res::Err => None,
3983 res => panic!("{res:?} did not resolve to a trait or trait alias"),
3984 }
3985 }
3986}
3987
3988#[derive(Clone, Debug, Copy, HashStable_Generic)]
3989pub struct PolyTraitRef<'hir> {
3990 pub bound_generic_params: &'hir [GenericParam<'hir>],
3992
3993 pub modifiers: TraitBoundModifiers,
3997
3998 pub trait_ref: TraitRef<'hir>,
4000
4001 pub span: Span,
4002}
4003
4004#[derive(Debug, Clone, Copy, HashStable_Generic)]
4005pub struct FieldDef<'hir> {
4006 pub span: Span,
4007 pub vis_span: Span,
4008 pub ident: Ident,
4009 #[stable_hasher(ignore)]
4010 pub hir_id: HirId,
4011 pub def_id: LocalDefId,
4012 pub ty: &'hir Ty<'hir>,
4013 pub safety: Safety,
4014 pub default: Option<&'hir AnonConst>,
4015}
4016
4017impl FieldDef<'_> {
4018 pub fn is_positional(&self) -> bool {
4020 self.ident.as_str().as_bytes()[0].is_ascii_digit()
4021 }
4022}
4023
4024#[derive(Debug, Clone, Copy, HashStable_Generic)]
4026pub enum VariantData<'hir> {
4027 Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4031 Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4035 Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4039}
4040
4041impl<'hir> VariantData<'hir> {
4042 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4044 match *self {
4045 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4046 _ => &[],
4047 }
4048 }
4049
4050 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4051 match *self {
4052 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4053 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4054 VariantData::Struct { .. } => None,
4055 }
4056 }
4057
4058 #[inline]
4059 pub fn ctor_kind(&self) -> Option<CtorKind> {
4060 self.ctor().map(|(kind, ..)| kind)
4061 }
4062
4063 #[inline]
4065 pub fn ctor_hir_id(&self) -> Option<HirId> {
4066 self.ctor().map(|(_, hir_id, _)| hir_id)
4067 }
4068
4069 #[inline]
4071 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4072 self.ctor().map(|(.., def_id)| def_id)
4073 }
4074}
4075
4076#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4080pub struct ItemId {
4081 pub owner_id: OwnerId,
4082}
4083
4084impl ItemId {
4085 #[inline]
4086 pub fn hir_id(&self) -> HirId {
4087 HirId::make_owner(self.owner_id.def_id)
4089 }
4090}
4091
4092#[derive(Debug, Clone, Copy, HashStable_Generic)]
4101pub struct Item<'hir> {
4102 pub owner_id: OwnerId,
4103 pub kind: ItemKind<'hir>,
4104 pub span: Span,
4105 pub vis_span: Span,
4106 pub has_delayed_lints: bool,
4107}
4108
4109impl<'hir> Item<'hir> {
4110 #[inline]
4111 pub fn hir_id(&self) -> HirId {
4112 HirId::make_owner(self.owner_id.def_id)
4114 }
4115
4116 pub fn item_id(&self) -> ItemId {
4117 ItemId { owner_id: self.owner_id }
4118 }
4119
4120 pub fn is_adt(&self) -> bool {
4123 matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4124 }
4125
4126 pub fn is_struct_or_union(&self) -> bool {
4128 matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4129 }
4130
4131 expect_methods_self_kind! {
4132 expect_extern_crate, (Option<Symbol>, Ident),
4133 ItemKind::ExternCrate(s, ident), (*s, *ident);
4134
4135 expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4136
4137 expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4138 ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4139
4140 expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4141 ItemKind::Const(ident, generics, ty, rhs), (*ident, generics, ty, *rhs);
4142
4143 expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4144 ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4145
4146 expect_macro, (Ident, &ast::MacroDef, MacroKinds),
4147 ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4148
4149 expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4150
4151 expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]),
4152 ItemKind::ForeignMod { abi, items }, (*abi, items);
4153
4154 expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4155
4156 expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4157 ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4158
4159 expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4160 ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4161
4162 expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4163 ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4164
4165 expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4166 ItemKind::Union(ident, generics, data), (*ident, generics, data);
4167
4168 expect_trait,
4169 (
4170 Constness,
4171 IsAuto,
4172 Safety,
4173 Ident,
4174 &'hir Generics<'hir>,
4175 GenericBounds<'hir>,
4176 &'hir [TraitItemId]
4177 ),
4178 ItemKind::Trait(constness, is_auto, safety, ident, generics, bounds, items),
4179 (*constness, *is_auto, *safety, *ident, generics, bounds, items);
4180
4181 expect_trait_alias, (Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4182 ItemKind::TraitAlias(constness, ident, generics, bounds), (*constness, *ident, generics, bounds);
4183
4184 expect_impl, &Impl<'hir>, ItemKind::Impl(imp), imp;
4185 }
4186}
4187
4188#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4189#[derive(Encodable, Decodable, HashStable_Generic)]
4190pub enum Safety {
4191 Unsafe,
4192 Safe,
4193}
4194
4195impl Safety {
4196 pub fn prefix_str(self) -> &'static str {
4197 match self {
4198 Self::Unsafe => "unsafe ",
4199 Self::Safe => "",
4200 }
4201 }
4202
4203 #[inline]
4204 pub fn is_unsafe(self) -> bool {
4205 !self.is_safe()
4206 }
4207
4208 #[inline]
4209 pub fn is_safe(self) -> bool {
4210 match self {
4211 Self::Unsafe => false,
4212 Self::Safe => true,
4213 }
4214 }
4215}
4216
4217impl fmt::Display for Safety {
4218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4219 f.write_str(match *self {
4220 Self::Unsafe => "unsafe",
4221 Self::Safe => "safe",
4222 })
4223 }
4224}
4225
4226#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4227pub enum Constness {
4228 Const,
4229 NotConst,
4230}
4231
4232impl fmt::Display for Constness {
4233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4234 f.write_str(match *self {
4235 Self::Const => "const",
4236 Self::NotConst => "non-const",
4237 })
4238 }
4239}
4240
4241#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4246pub enum HeaderSafety {
4247 SafeTargetFeatures,
4253 Normal(Safety),
4254}
4255
4256impl From<Safety> for HeaderSafety {
4257 fn from(v: Safety) -> Self {
4258 Self::Normal(v)
4259 }
4260}
4261
4262#[derive(Copy, Clone, Debug, HashStable_Generic)]
4263pub struct FnHeader {
4264 pub safety: HeaderSafety,
4265 pub constness: Constness,
4266 pub asyncness: IsAsync,
4267 pub abi: ExternAbi,
4268}
4269
4270impl FnHeader {
4271 pub fn is_async(&self) -> bool {
4272 matches!(self.asyncness, IsAsync::Async(_))
4273 }
4274
4275 pub fn is_const(&self) -> bool {
4276 matches!(self.constness, Constness::Const)
4277 }
4278
4279 pub fn is_unsafe(&self) -> bool {
4280 self.safety().is_unsafe()
4281 }
4282
4283 pub fn is_safe(&self) -> bool {
4284 self.safety().is_safe()
4285 }
4286
4287 pub fn safety(&self) -> Safety {
4288 match self.safety {
4289 HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4290 HeaderSafety::Normal(safety) => safety,
4291 }
4292 }
4293}
4294
4295#[derive(Debug, Clone, Copy, HashStable_Generic)]
4296pub enum ItemKind<'hir> {
4297 ExternCrate(Option<Symbol>, Ident),
4301
4302 Use(&'hir UsePath<'hir>, UseKind),
4308
4309 Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4311 Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4313 Fn {
4315 sig: FnSig<'hir>,
4316 ident: Ident,
4317 generics: &'hir Generics<'hir>,
4318 body: BodyId,
4319 has_body: bool,
4323 },
4324 Macro(Ident, &'hir ast::MacroDef, MacroKinds),
4326 Mod(Ident, &'hir Mod<'hir>),
4328 ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] },
4330 GlobalAsm {
4332 asm: &'hir InlineAsm<'hir>,
4333 fake_body: BodyId,
4339 },
4340 TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4342 Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4344 Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4346 Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4348 Trait(
4350 Constness,
4351 IsAuto,
4352 Safety,
4353 Ident,
4354 &'hir Generics<'hir>,
4355 GenericBounds<'hir>,
4356 &'hir [TraitItemId],
4357 ),
4358 TraitAlias(Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4360
4361 Impl(Impl<'hir>),
4363}
4364
4365#[derive(Debug, Clone, Copy, HashStable_Generic)]
4370pub struct Impl<'hir> {
4371 pub generics: &'hir Generics<'hir>,
4372 pub of_trait: Option<&'hir TraitImplHeader<'hir>>,
4373 pub self_ty: &'hir Ty<'hir>,
4374 pub items: &'hir [ImplItemId],
4375}
4376
4377#[derive(Debug, Clone, Copy, HashStable_Generic)]
4378pub struct TraitImplHeader<'hir> {
4379 pub constness: Constness,
4380 pub safety: Safety,
4381 pub polarity: ImplPolarity,
4382 pub defaultness: Defaultness,
4383 pub defaultness_span: Option<Span>,
4386 pub trait_ref: TraitRef<'hir>,
4387}
4388
4389impl ItemKind<'_> {
4390 pub fn ident(&self) -> Option<Ident> {
4391 match *self {
4392 ItemKind::ExternCrate(_, ident)
4393 | ItemKind::Use(_, UseKind::Single(ident))
4394 | ItemKind::Static(_, ident, ..)
4395 | ItemKind::Const(ident, ..)
4396 | ItemKind::Fn { ident, .. }
4397 | ItemKind::Macro(ident, ..)
4398 | ItemKind::Mod(ident, ..)
4399 | ItemKind::TyAlias(ident, ..)
4400 | ItemKind::Enum(ident, ..)
4401 | ItemKind::Struct(ident, ..)
4402 | ItemKind::Union(ident, ..)
4403 | ItemKind::Trait(_, _, _, ident, ..)
4404 | ItemKind::TraitAlias(_, ident, ..) => Some(ident),
4405
4406 ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4407 | ItemKind::ForeignMod { .. }
4408 | ItemKind::GlobalAsm { .. }
4409 | ItemKind::Impl(_) => None,
4410 }
4411 }
4412
4413 pub fn generics(&self) -> Option<&Generics<'_>> {
4414 Some(match self {
4415 ItemKind::Fn { generics, .. }
4416 | ItemKind::TyAlias(_, generics, _)
4417 | ItemKind::Const(_, generics, _, _)
4418 | ItemKind::Enum(_, generics, _)
4419 | ItemKind::Struct(_, generics, _)
4420 | ItemKind::Union(_, generics, _)
4421 | ItemKind::Trait(_, _, _, _, generics, _, _)
4422 | ItemKind::TraitAlias(_, _, generics, _)
4423 | ItemKind::Impl(Impl { generics, .. }) => generics,
4424 _ => return None,
4425 })
4426 }
4427}
4428
4429#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4433pub struct ForeignItemId {
4434 pub owner_id: OwnerId,
4435}
4436
4437impl ForeignItemId {
4438 #[inline]
4439 pub fn hir_id(&self) -> HirId {
4440 HirId::make_owner(self.owner_id.def_id)
4442 }
4443}
4444
4445#[derive(Debug, Clone, Copy, HashStable_Generic)]
4446pub struct ForeignItem<'hir> {
4447 pub ident: Ident,
4448 pub kind: ForeignItemKind<'hir>,
4449 pub owner_id: OwnerId,
4450 pub span: Span,
4451 pub vis_span: Span,
4452 pub has_delayed_lints: bool,
4453}
4454
4455impl ForeignItem<'_> {
4456 #[inline]
4457 pub fn hir_id(&self) -> HirId {
4458 HirId::make_owner(self.owner_id.def_id)
4460 }
4461
4462 pub fn foreign_item_id(&self) -> ForeignItemId {
4463 ForeignItemId { owner_id: self.owner_id }
4464 }
4465}
4466
4467#[derive(Debug, Clone, Copy, HashStable_Generic)]
4469pub enum ForeignItemKind<'hir> {
4470 Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4477 Static(&'hir Ty<'hir>, Mutability, Safety),
4479 Type,
4481}
4482
4483#[derive(Debug, Copy, Clone, HashStable_Generic)]
4485pub struct Upvar {
4486 pub span: Span,
4488}
4489
4490#[derive(Debug, Clone, HashStable_Generic)]
4494pub struct TraitCandidate {
4495 pub def_id: DefId,
4496 pub import_ids: SmallVec<[LocalDefId; 1]>,
4497}
4498
4499#[derive(Copy, Clone, Debug, HashStable_Generic)]
4500pub enum OwnerNode<'hir> {
4501 Item(&'hir Item<'hir>),
4502 ForeignItem(&'hir ForeignItem<'hir>),
4503 TraitItem(&'hir TraitItem<'hir>),
4504 ImplItem(&'hir ImplItem<'hir>),
4505 Crate(&'hir Mod<'hir>),
4506 Synthetic,
4507}
4508
4509impl<'hir> OwnerNode<'hir> {
4510 pub fn span(&self) -> Span {
4511 match self {
4512 OwnerNode::Item(Item { span, .. })
4513 | OwnerNode::ForeignItem(ForeignItem { span, .. })
4514 | OwnerNode::ImplItem(ImplItem { span, .. })
4515 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4516 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4517 OwnerNode::Synthetic => unreachable!(),
4518 }
4519 }
4520
4521 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4522 match self {
4523 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4524 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4525 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4526 | OwnerNode::ForeignItem(ForeignItem {
4527 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4528 }) => Some(fn_sig),
4529 _ => None,
4530 }
4531 }
4532
4533 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4534 match self {
4535 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4536 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4537 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4538 | OwnerNode::ForeignItem(ForeignItem {
4539 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4540 }) => Some(fn_sig.decl),
4541 _ => None,
4542 }
4543 }
4544
4545 pub fn body_id(&self) -> Option<BodyId> {
4546 match self {
4547 OwnerNode::Item(Item {
4548 kind:
4549 ItemKind::Static(_, _, _, body)
4550 | ItemKind::Const(.., ConstItemRhs::Body(body))
4551 | ItemKind::Fn { body, .. },
4552 ..
4553 })
4554 | OwnerNode::TraitItem(TraitItem {
4555 kind:
4556 TraitItemKind::Fn(_, TraitFn::Provided(body))
4557 | TraitItemKind::Const(_, Some(ConstItemRhs::Body(body))),
4558 ..
4559 })
4560 | OwnerNode::ImplItem(ImplItem {
4561 kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, ConstItemRhs::Body(body)),
4562 ..
4563 }) => Some(*body),
4564 _ => None,
4565 }
4566 }
4567
4568 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4569 Node::generics(self.into())
4570 }
4571
4572 pub fn def_id(self) -> OwnerId {
4573 match self {
4574 OwnerNode::Item(Item { owner_id, .. })
4575 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4576 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4577 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4578 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4579 OwnerNode::Synthetic => unreachable!(),
4580 }
4581 }
4582
4583 pub fn is_impl_block(&self) -> bool {
4585 matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4586 }
4587
4588 expect_methods_self! {
4589 expect_item, &'hir Item<'hir>, OwnerNode::Item(n), n;
4590 expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4591 expect_impl_item, &'hir ImplItem<'hir>, OwnerNode::ImplItem(n), n;
4592 expect_trait_item, &'hir TraitItem<'hir>, OwnerNode::TraitItem(n), n;
4593 }
4594}
4595
4596impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4597 fn from(val: &'hir Item<'hir>) -> Self {
4598 OwnerNode::Item(val)
4599 }
4600}
4601
4602impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4603 fn from(val: &'hir ForeignItem<'hir>) -> Self {
4604 OwnerNode::ForeignItem(val)
4605 }
4606}
4607
4608impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4609 fn from(val: &'hir ImplItem<'hir>) -> Self {
4610 OwnerNode::ImplItem(val)
4611 }
4612}
4613
4614impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4615 fn from(val: &'hir TraitItem<'hir>) -> Self {
4616 OwnerNode::TraitItem(val)
4617 }
4618}
4619
4620impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4621 fn from(val: OwnerNode<'hir>) -> Self {
4622 match val {
4623 OwnerNode::Item(n) => Node::Item(n),
4624 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4625 OwnerNode::ImplItem(n) => Node::ImplItem(n),
4626 OwnerNode::TraitItem(n) => Node::TraitItem(n),
4627 OwnerNode::Crate(n) => Node::Crate(n),
4628 OwnerNode::Synthetic => Node::Synthetic,
4629 }
4630 }
4631}
4632
4633#[derive(Copy, Clone, Debug, HashStable_Generic)]
4634pub enum Node<'hir> {
4635 Param(&'hir Param<'hir>),
4636 Item(&'hir Item<'hir>),
4637 ForeignItem(&'hir ForeignItem<'hir>),
4638 TraitItem(&'hir TraitItem<'hir>),
4639 ImplItem(&'hir ImplItem<'hir>),
4640 Variant(&'hir Variant<'hir>),
4641 Field(&'hir FieldDef<'hir>),
4642 AnonConst(&'hir AnonConst),
4643 ConstBlock(&'hir ConstBlock),
4644 ConstArg(&'hir ConstArg<'hir>),
4645 Expr(&'hir Expr<'hir>),
4646 ExprField(&'hir ExprField<'hir>),
4647 Stmt(&'hir Stmt<'hir>),
4648 PathSegment(&'hir PathSegment<'hir>),
4649 Ty(&'hir Ty<'hir>),
4650 AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4651 TraitRef(&'hir TraitRef<'hir>),
4652 OpaqueTy(&'hir OpaqueTy<'hir>),
4653 TyPat(&'hir TyPat<'hir>),
4654 Pat(&'hir Pat<'hir>),
4655 PatField(&'hir PatField<'hir>),
4656 PatExpr(&'hir PatExpr<'hir>),
4660 Arm(&'hir Arm<'hir>),
4661 Block(&'hir Block<'hir>),
4662 LetStmt(&'hir LetStmt<'hir>),
4663 Ctor(&'hir VariantData<'hir>),
4666 Lifetime(&'hir Lifetime),
4667 GenericParam(&'hir GenericParam<'hir>),
4668 Crate(&'hir Mod<'hir>),
4669 Infer(&'hir InferArg),
4670 WherePredicate(&'hir WherePredicate<'hir>),
4671 PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4672 Synthetic,
4674 Err(Span),
4675}
4676
4677impl<'hir> Node<'hir> {
4678 pub fn ident(&self) -> Option<Ident> {
4693 match self {
4694 Node::Item(item) => item.kind.ident(),
4695 Node::TraitItem(TraitItem { ident, .. })
4696 | Node::ImplItem(ImplItem { ident, .. })
4697 | Node::ForeignItem(ForeignItem { ident, .. })
4698 | Node::Field(FieldDef { ident, .. })
4699 | Node::Variant(Variant { ident, .. })
4700 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4701 Node::Lifetime(lt) => Some(lt.ident),
4702 Node::GenericParam(p) => Some(p.name.ident()),
4703 Node::AssocItemConstraint(c) => Some(c.ident),
4704 Node::PatField(f) => Some(f.ident),
4705 Node::ExprField(f) => Some(f.ident),
4706 Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4707 Node::Param(..)
4708 | Node::AnonConst(..)
4709 | Node::ConstBlock(..)
4710 | Node::ConstArg(..)
4711 | Node::Expr(..)
4712 | Node::Stmt(..)
4713 | Node::Block(..)
4714 | Node::Ctor(..)
4715 | Node::Pat(..)
4716 | Node::TyPat(..)
4717 | Node::PatExpr(..)
4718 | Node::Arm(..)
4719 | Node::LetStmt(..)
4720 | Node::Crate(..)
4721 | Node::Ty(..)
4722 | Node::TraitRef(..)
4723 | Node::OpaqueTy(..)
4724 | Node::Infer(..)
4725 | Node::WherePredicate(..)
4726 | Node::Synthetic
4727 | Node::Err(..) => None,
4728 }
4729 }
4730
4731 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4732 match self {
4733 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4734 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4735 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4736 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4737 Some(fn_sig.decl)
4738 }
4739 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4740 Some(fn_decl)
4741 }
4742 _ => None,
4743 }
4744 }
4745
4746 pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4748 if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4749 && let Some(of_trait) = impl_block.of_trait
4750 && let Some(trait_id) = of_trait.trait_ref.trait_def_id()
4751 && trait_id == trait_def_id
4752 {
4753 Some(impl_block)
4754 } else {
4755 None
4756 }
4757 }
4758
4759 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4760 match self {
4761 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4762 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4763 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4764 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4765 Some(fn_sig)
4766 }
4767 _ => None,
4768 }
4769 }
4770
4771 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4773 match self {
4774 Node::Item(it) => match it.kind {
4775 ItemKind::TyAlias(_, _, ty)
4776 | ItemKind::Static(_, _, ty, _)
4777 | ItemKind::Const(_, _, ty, _) => Some(ty),
4778 ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4779 _ => None,
4780 },
4781 Node::TraitItem(it) => match it.kind {
4782 TraitItemKind::Const(ty, _) => Some(ty),
4783 TraitItemKind::Type(_, ty) => ty,
4784 _ => None,
4785 },
4786 Node::ImplItem(it) => match it.kind {
4787 ImplItemKind::Const(ty, _) => Some(ty),
4788 ImplItemKind::Type(ty) => Some(ty),
4789 _ => None,
4790 },
4791 Node::ForeignItem(it) => match it.kind {
4792 ForeignItemKind::Static(ty, ..) => Some(ty),
4793 _ => None,
4794 },
4795 Node::GenericParam(param) => match param.kind {
4796 GenericParamKind::Lifetime { .. } => None,
4797 GenericParamKind::Type { default, .. } => default,
4798 GenericParamKind::Const { ty, .. } => Some(ty),
4799 },
4800 _ => None,
4801 }
4802 }
4803
4804 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4805 match self {
4806 Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
4807 _ => None,
4808 }
4809 }
4810
4811 #[inline]
4812 pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4813 match self {
4814 Node::Item(Item {
4815 owner_id,
4816 kind:
4817 ItemKind::Const(.., ConstItemRhs::Body(body))
4818 | ItemKind::Static(.., body)
4819 | ItemKind::Fn { body, .. },
4820 ..
4821 })
4822 | Node::TraitItem(TraitItem {
4823 owner_id,
4824 kind:
4825 TraitItemKind::Const(.., Some(ConstItemRhs::Body(body)))
4826 | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4827 ..
4828 })
4829 | Node::ImplItem(ImplItem {
4830 owner_id,
4831 kind: ImplItemKind::Const(.., ConstItemRhs::Body(body)) | ImplItemKind::Fn(_, body),
4832 ..
4833 }) => Some((owner_id.def_id, *body)),
4834
4835 Node::Item(Item {
4836 owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4837 }) => Some((owner_id.def_id, *fake_body)),
4838
4839 Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4840 Some((*def_id, *body))
4841 }
4842
4843 Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4844 Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4845
4846 _ => None,
4847 }
4848 }
4849
4850 pub fn body_id(&self) -> Option<BodyId> {
4851 Some(self.associated_body()?.1)
4852 }
4853
4854 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4855 match self {
4856 Node::ForeignItem(ForeignItem {
4857 kind: ForeignItemKind::Fn(_, _, generics), ..
4858 })
4859 | Node::TraitItem(TraitItem { generics, .. })
4860 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4861 Node::Item(item) => item.kind.generics(),
4862 _ => None,
4863 }
4864 }
4865
4866 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4867 match self {
4868 Node::Item(i) => Some(OwnerNode::Item(i)),
4869 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4870 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4871 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4872 Node::Crate(i) => Some(OwnerNode::Crate(i)),
4873 Node::Synthetic => Some(OwnerNode::Synthetic),
4874 _ => None,
4875 }
4876 }
4877
4878 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4879 match self {
4880 Node::Item(i) => match i.kind {
4881 ItemKind::Fn { ident, sig, generics, .. } => {
4882 Some(FnKind::ItemFn(ident, generics, sig.header))
4883 }
4884 _ => None,
4885 },
4886 Node::TraitItem(ti) => match ti.kind {
4887 TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4888 _ => None,
4889 },
4890 Node::ImplItem(ii) => match ii.kind {
4891 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4892 _ => None,
4893 },
4894 Node::Expr(e) => match e.kind {
4895 ExprKind::Closure { .. } => Some(FnKind::Closure),
4896 _ => None,
4897 },
4898 _ => None,
4899 }
4900 }
4901
4902 expect_methods_self! {
4903 expect_param, &'hir Param<'hir>, Node::Param(n), n;
4904 expect_item, &'hir Item<'hir>, Node::Item(n), n;
4905 expect_foreign_item, &'hir ForeignItem<'hir>, Node::ForeignItem(n), n;
4906 expect_trait_item, &'hir TraitItem<'hir>, Node::TraitItem(n), n;
4907 expect_impl_item, &'hir ImplItem<'hir>, Node::ImplItem(n), n;
4908 expect_variant, &'hir Variant<'hir>, Node::Variant(n), n;
4909 expect_field, &'hir FieldDef<'hir>, Node::Field(n), n;
4910 expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n;
4911 expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n;
4912 expect_expr, &'hir Expr<'hir>, Node::Expr(n), n;
4913 expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n;
4914 expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n;
4915 expect_path_segment, &'hir PathSegment<'hir>, Node::PathSegment(n), n;
4916 expect_ty, &'hir Ty<'hir>, Node::Ty(n), n;
4917 expect_assoc_item_constraint, &'hir AssocItemConstraint<'hir>, Node::AssocItemConstraint(n), n;
4918 expect_trait_ref, &'hir TraitRef<'hir>, Node::TraitRef(n), n;
4919 expect_opaque_ty, &'hir OpaqueTy<'hir>, Node::OpaqueTy(n), n;
4920 expect_pat, &'hir Pat<'hir>, Node::Pat(n), n;
4921 expect_pat_field, &'hir PatField<'hir>, Node::PatField(n), n;
4922 expect_arm, &'hir Arm<'hir>, Node::Arm(n), n;
4923 expect_block, &'hir Block<'hir>, Node::Block(n), n;
4924 expect_let_stmt, &'hir LetStmt<'hir>, Node::LetStmt(n), n;
4925 expect_ctor, &'hir VariantData<'hir>, Node::Ctor(n), n;
4926 expect_lifetime, &'hir Lifetime, Node::Lifetime(n), n;
4927 expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4928 expect_crate, &'hir Mod<'hir>, Node::Crate(n), n;
4929 expect_infer, &'hir InferArg, Node::Infer(n), n;
4930 expect_closure, &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4931 }
4932}
4933
4934#[cfg(target_pointer_width = "64")]
4936mod size_asserts {
4937 use rustc_data_structures::static_assert_size;
4938
4939 use super::*;
4940 static_assert_size!(Block<'_>, 48);
4942 static_assert_size!(Body<'_>, 24);
4943 static_assert_size!(Expr<'_>, 64);
4944 static_assert_size!(ExprKind<'_>, 48);
4945 static_assert_size!(FnDecl<'_>, 40);
4946 static_assert_size!(ForeignItem<'_>, 96);
4947 static_assert_size!(ForeignItemKind<'_>, 56);
4948 static_assert_size!(GenericArg<'_>, 16);
4949 static_assert_size!(GenericBound<'_>, 64);
4950 static_assert_size!(Generics<'_>, 56);
4951 static_assert_size!(Impl<'_>, 40);
4952 static_assert_size!(ImplItem<'_>, 88);
4953 static_assert_size!(ImplItemKind<'_>, 40);
4954 static_assert_size!(Item<'_>, 88);
4955 static_assert_size!(ItemKind<'_>, 64);
4956 static_assert_size!(LetStmt<'_>, 64);
4957 static_assert_size!(Param<'_>, 32);
4958 static_assert_size!(Pat<'_>, 80);
4959 static_assert_size!(PatKind<'_>, 56);
4960 static_assert_size!(Path<'_>, 40);
4961 static_assert_size!(PathSegment<'_>, 48);
4962 static_assert_size!(QPath<'_>, 24);
4963 static_assert_size!(Res, 12);
4964 static_assert_size!(Stmt<'_>, 32);
4965 static_assert_size!(StmtKind<'_>, 16);
4966 static_assert_size!(TraitImplHeader<'_>, 48);
4967 static_assert_size!(TraitItem<'_>, 88);
4968 static_assert_size!(TraitItemKind<'_>, 48);
4969 static_assert_size!(Ty<'_>, 48);
4970 static_assert_size!(TyKind<'_>, 32);
4971 }
4973
4974#[cfg(test)]
4975mod tests;