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