1use std::fmt;
3
4use rustc_abi::ExternAbi;
5use rustc_ast::attr::AttributeExt;
6use rustc_ast::token::CommentKind;
7use rustc_ast::util::parser::ExprPrecedence;
8use rustc_ast::{
9 self as ast, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitIntType,
10 LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind, join_path_idents,
11};
12pub use rustc_ast::{
13 AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
14 BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
15 MetaItemInner, MetaItemLit, Movability, Mutability, UnOp,
16};
17use rustc_data_structures::fingerprint::Fingerprint;
18use rustc_data_structures::sorted_map::SortedMap;
19use rustc_data_structures::tagged_ptr::TaggedRef;
20use rustc_index::IndexVec;
21use rustc_macros::{Decodable, Encodable, HashStable_Generic};
22use rustc_span::def_id::LocalDefId;
23use rustc_span::source_map::Spanned;
24use rustc_span::{BytePos, DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
25use rustc_target::asm::InlineAsmRegOrRegClass;
26use smallvec::SmallVec;
27use thin_vec::ThinVec;
28use tracing::debug;
29
30use crate::LangItem;
31use crate::attrs::AttributeKind;
32use crate::def::{CtorKind, DefKind, MacroKinds, PerNS, Res};
33use crate::def_id::{DefId, LocalDefIdMap};
34pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId};
35use crate::intravisit::{FnKind, VisitorExt};
36use crate::lints::DelayedLints;
37
38#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
39pub enum AngleBrackets {
40 Missing,
42 Empty,
44 Full,
46}
47
48#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
49pub enum LifetimeSource {
50 Reference,
52
53 Path { angle_brackets: AngleBrackets },
56
57 OutlivesBound,
59
60 PreciseCapturing,
62
63 Other,
70}
71
72#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
73pub enum LifetimeSyntax {
74 Implicit,
76
77 ExplicitAnonymous,
79
80 ExplicitBound,
82}
83
84impl From<Ident> for LifetimeSyntax {
85 fn from(ident: Ident) -> Self {
86 let name = ident.name;
87
88 if name == sym::empty {
89 unreachable!("A lifetime name should never be empty");
90 } else if name == kw::UnderscoreLifetime {
91 LifetimeSyntax::ExplicitAnonymous
92 } else {
93 debug_assert!(name.as_str().starts_with('\''));
94 LifetimeSyntax::ExplicitBound
95 }
96 }
97}
98
99#[derive(Debug, Copy, Clone, HashStable_Generic)]
150#[repr(align(4))]
155pub struct Lifetime {
156 #[stable_hasher(ignore)]
157 pub hir_id: HirId,
158
159 pub ident: Ident,
163
164 pub kind: LifetimeKind,
166
167 pub source: LifetimeSource,
170
171 pub syntax: LifetimeSyntax,
174}
175
176#[derive(Debug, Copy, Clone, HashStable_Generic)]
177pub enum ParamName {
178 Plain(Ident),
180
181 Error(Ident),
187
188 Fresh,
203}
204
205impl ParamName {
206 pub fn ident(&self) -> Ident {
207 match *self {
208 ParamName::Plain(ident) | ParamName::Error(ident) => ident,
209 ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
210 }
211 }
212}
213
214#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
215pub enum LifetimeKind {
216 Param(LocalDefId),
218
219 ImplicitObjectLifetimeDefault,
231
232 Error,
235
236 Infer,
240
241 Static,
243}
244
245impl LifetimeKind {
246 fn is_elided(&self) -> bool {
247 match self {
248 LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true,
249
250 LifetimeKind::Error | LifetimeKind::Param(..) | LifetimeKind::Static => false,
255 }
256 }
257}
258
259impl fmt::Display for Lifetime {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 self.ident.name.fmt(f)
262 }
263}
264
265impl Lifetime {
266 pub fn new(
267 hir_id: HirId,
268 ident: Ident,
269 kind: LifetimeKind,
270 source: LifetimeSource,
271 syntax: LifetimeSyntax,
272 ) -> Lifetime {
273 let lifetime = Lifetime { hir_id, ident, kind, source, syntax };
274
275 #[cfg(debug_assertions)]
277 match (lifetime.is_elided(), lifetime.is_anonymous()) {
278 (false, false) => {} (false, true) => {} (true, true) => {} (true, false) => panic!("bad Lifetime"),
282 }
283
284 lifetime
285 }
286
287 pub fn is_elided(&self) -> bool {
288 self.kind.is_elided()
289 }
290
291 pub fn is_anonymous(&self) -> bool {
292 self.ident.name == kw::UnderscoreLifetime
293 }
294
295 pub fn is_implicit(&self) -> bool {
296 matches!(self.syntax, LifetimeSyntax::Implicit)
297 }
298
299 pub fn is_static(&self) -> bool {
300 self.kind == LifetimeKind::Static
301 }
302
303 pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
304 use LifetimeSource::*;
305 use LifetimeSyntax::*;
306
307 debug_assert!(new_lifetime.starts_with('\''));
308
309 match (self.syntax, self.source) {
310 (ExplicitBound | ExplicitAnonymous, _) => (self.ident.span, format!("{new_lifetime}")),
312
313 (Implicit, Path { angle_brackets: AngleBrackets::Full }) => {
315 (self.ident.span, format!("{new_lifetime}, "))
316 }
317
318 (Implicit, Path { angle_brackets: AngleBrackets::Empty }) => {
320 (self.ident.span, format!("{new_lifetime}"))
321 }
322
323 (Implicit, Path { angle_brackets: AngleBrackets::Missing }) => {
325 (self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
326 }
327
328 (Implicit, Reference) => (self.ident.span, format!("{new_lifetime} ")),
330
331 (Implicit, source) => {
332 unreachable!("can't suggest for a implicit lifetime of {source:?}")
333 }
334 }
335 }
336}
337
338#[derive(Debug, Clone, Copy, HashStable_Generic)]
342pub struct Path<'hir, R = Res> {
343 pub span: Span,
344 pub res: R,
346 pub segments: &'hir [PathSegment<'hir>],
348}
349
350pub type UsePath<'hir> = Path<'hir, PerNS<Option<Res>>>;
352
353impl Path<'_> {
354 pub fn is_global(&self) -> bool {
355 self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
356 }
357}
358
359#[derive(Debug, Clone, Copy, HashStable_Generic)]
362pub struct PathSegment<'hir> {
363 pub ident: Ident,
365 #[stable_hasher(ignore)]
366 pub hir_id: HirId,
367 pub res: Res,
368
369 pub args: Option<&'hir GenericArgs<'hir>>,
375
376 pub infer_args: bool,
381}
382
383impl<'hir> PathSegment<'hir> {
384 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
386 PathSegment { ident, hir_id, res, infer_args: true, args: None }
387 }
388
389 pub fn invalid() -> Self {
390 Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
391 }
392
393 pub fn args(&self) -> &GenericArgs<'hir> {
394 if let Some(ref args) = self.args {
395 args
396 } else {
397 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
398 DUMMY
399 }
400 }
401}
402
403#[derive(Clone, Copy, Debug, HashStable_Generic)]
417#[repr(C)]
418pub struct ConstArg<'hir, Unambig = ()> {
419 #[stable_hasher(ignore)]
420 pub hir_id: HirId,
421 pub kind: ConstArgKind<'hir, Unambig>,
422}
423
424impl<'hir> ConstArg<'hir, AmbigArg> {
425 pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
436 let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
439 unsafe { &*ptr }
440 }
441}
442
443impl<'hir> ConstArg<'hir> {
444 pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
450 if let ConstArgKind::Infer(_, ()) = self.kind {
451 return None;
452 }
453
454 let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
458 Some(unsafe { &*ptr })
459 }
460}
461
462impl<'hir, Unambig> ConstArg<'hir, Unambig> {
463 pub fn anon_const_hir_id(&self) -> Option<HirId> {
464 match self.kind {
465 ConstArgKind::Anon(ac) => Some(ac.hir_id),
466 _ => None,
467 }
468 }
469
470 pub fn span(&self) -> Span {
471 match self.kind {
472 ConstArgKind::Path(path) => path.span(),
473 ConstArgKind::Anon(anon) => anon.span,
474 ConstArgKind::Infer(span, _) => span,
475 }
476 }
477}
478
479#[derive(Clone, Copy, Debug, HashStable_Generic)]
481#[repr(u8, C)]
482pub enum ConstArgKind<'hir, Unambig = ()> {
483 Path(QPath<'hir>),
489 Anon(&'hir AnonConst),
490 Infer(Span, Unambig),
493}
494
495#[derive(Clone, Copy, Debug, HashStable_Generic)]
496pub struct InferArg {
497 #[stable_hasher(ignore)]
498 pub hir_id: HirId,
499 pub span: Span,
500}
501
502impl InferArg {
503 pub fn to_ty(&self) -> Ty<'static> {
504 Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
505 }
506}
507
508#[derive(Debug, Clone, Copy, HashStable_Generic)]
509pub enum GenericArg<'hir> {
510 Lifetime(&'hir Lifetime),
511 Type(&'hir Ty<'hir, AmbigArg>),
512 Const(&'hir ConstArg<'hir, AmbigArg>),
513 Infer(InferArg),
523}
524
525impl GenericArg<'_> {
526 pub fn span(&self) -> Span {
527 match self {
528 GenericArg::Lifetime(l) => l.ident.span,
529 GenericArg::Type(t) => t.span,
530 GenericArg::Const(c) => c.span(),
531 GenericArg::Infer(i) => i.span,
532 }
533 }
534
535 pub fn hir_id(&self) -> HirId {
536 match self {
537 GenericArg::Lifetime(l) => l.hir_id,
538 GenericArg::Type(t) => t.hir_id,
539 GenericArg::Const(c) => c.hir_id,
540 GenericArg::Infer(i) => i.hir_id,
541 }
542 }
543
544 pub fn descr(&self) -> &'static str {
545 match self {
546 GenericArg::Lifetime(_) => "lifetime",
547 GenericArg::Type(_) => "type",
548 GenericArg::Const(_) => "constant",
549 GenericArg::Infer(_) => "placeholder",
550 }
551 }
552
553 pub fn to_ord(&self) -> ast::ParamKindOrd {
554 match self {
555 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
556 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
557 ast::ParamKindOrd::TypeOrConst
558 }
559 }
560 }
561
562 pub fn is_ty_or_const(&self) -> bool {
563 match self {
564 GenericArg::Lifetime(_) => false,
565 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
566 }
567 }
568}
569
570#[derive(Debug, Clone, Copy, HashStable_Generic)]
572pub struct GenericArgs<'hir> {
573 pub args: &'hir [GenericArg<'hir>],
575 pub constraints: &'hir [AssocItemConstraint<'hir>],
577 pub parenthesized: GenericArgsParentheses,
582 pub span_ext: Span,
595}
596
597impl<'hir> GenericArgs<'hir> {
598 pub const fn none() -> Self {
599 Self {
600 args: &[],
601 constraints: &[],
602 parenthesized: GenericArgsParentheses::No,
603 span_ext: DUMMY_SP,
604 }
605 }
606
607 pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
612 if self.parenthesized != GenericArgsParentheses::ParenSugar {
613 return None;
614 }
615
616 let inputs = self
617 .args
618 .iter()
619 .find_map(|arg| {
620 let GenericArg::Type(ty) = arg else { return None };
621 let TyKind::Tup(tys) = &ty.kind else { return None };
622 Some(tys)
623 })
624 .unwrap();
625
626 Some((inputs, self.paren_sugar_output_inner()))
627 }
628
629 pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
634 (self.parenthesized == GenericArgsParentheses::ParenSugar)
635 .then(|| self.paren_sugar_output_inner())
636 }
637
638 fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
639 let [constraint] = self.constraints.try_into().unwrap();
640 debug_assert_eq!(constraint.ident.name, sym::Output);
641 constraint.ty().unwrap()
642 }
643
644 pub fn has_err(&self) -> Option<ErrorGuaranteed> {
645 self.args
646 .iter()
647 .find_map(|arg| {
648 let GenericArg::Type(ty) = arg else { return None };
649 let TyKind::Err(guar) = ty.kind else { return None };
650 Some(guar)
651 })
652 .or_else(|| {
653 self.constraints.iter().find_map(|constraint| {
654 let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
655 Some(guar)
656 })
657 })
658 }
659
660 #[inline]
661 pub fn num_lifetime_params(&self) -> usize {
662 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
663 }
664
665 #[inline]
666 pub fn has_lifetime_params(&self) -> bool {
667 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
668 }
669
670 #[inline]
671 pub fn num_generic_params(&self) -> usize {
674 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
675 }
676
677 pub fn span(&self) -> Option<Span> {
683 let span_ext = self.span_ext()?;
684 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
685 }
686
687 pub fn span_ext(&self) -> Option<Span> {
689 Some(self.span_ext).filter(|span| !span.is_empty())
690 }
691
692 pub fn is_empty(&self) -> bool {
693 self.args.is_empty()
694 }
695}
696
697#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)]
698pub enum GenericArgsParentheses {
699 No,
700 ReturnTypeNotation,
703 ParenSugar,
705}
706
707#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
709pub struct TraitBoundModifiers {
710 pub constness: BoundConstness,
711 pub polarity: BoundPolarity,
712}
713
714impl TraitBoundModifiers {
715 pub const NONE: Self =
716 TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
717}
718
719#[derive(Clone, Copy, Debug, HashStable_Generic)]
720pub enum GenericBound<'hir> {
721 Trait(PolyTraitRef<'hir>),
722 Outlives(&'hir Lifetime),
723 Use(&'hir [PreciseCapturingArg<'hir>], Span),
724}
725
726impl GenericBound<'_> {
727 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
728 match self {
729 GenericBound::Trait(data) => Some(&data.trait_ref),
730 _ => None,
731 }
732 }
733
734 pub fn span(&self) -> Span {
735 match self {
736 GenericBound::Trait(t, ..) => t.span,
737 GenericBound::Outlives(l) => l.ident.span,
738 GenericBound::Use(_, span) => *span,
739 }
740 }
741}
742
743pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
744
745#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, Debug)]
746pub enum MissingLifetimeKind {
747 Underscore,
749 Ampersand,
751 Comma,
753 Brackets,
755}
756
757#[derive(Copy, Clone, Debug, HashStable_Generic)]
758pub enum LifetimeParamKind {
759 Explicit,
762
763 Elided(MissingLifetimeKind),
766
767 Error,
769}
770
771#[derive(Debug, Clone, Copy, HashStable_Generic)]
772pub enum GenericParamKind<'hir> {
773 Lifetime {
775 kind: LifetimeParamKind,
776 },
777 Type {
778 default: Option<&'hir Ty<'hir>>,
779 synthetic: bool,
780 },
781 Const {
782 ty: &'hir Ty<'hir>,
783 default: Option<&'hir ConstArg<'hir>>,
785 synthetic: bool,
786 },
787}
788
789#[derive(Debug, Clone, Copy, HashStable_Generic)]
790pub struct GenericParam<'hir> {
791 #[stable_hasher(ignore)]
792 pub hir_id: HirId,
793 pub def_id: LocalDefId,
794 pub name: ParamName,
795 pub span: Span,
796 pub pure_wrt_drop: bool,
797 pub kind: GenericParamKind<'hir>,
798 pub colon_span: Option<Span>,
799 pub source: GenericParamSource,
800}
801
802impl<'hir> GenericParam<'hir> {
803 pub fn is_impl_trait(&self) -> bool {
807 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
808 }
809
810 pub fn is_elided_lifetime(&self) -> bool {
814 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
815 }
816}
817
818#[derive(Debug, Clone, Copy, HashStable_Generic)]
825pub enum GenericParamSource {
826 Generics,
828 Binder,
830}
831
832#[derive(Default)]
833pub struct GenericParamCount {
834 pub lifetimes: usize,
835 pub types: usize,
836 pub consts: usize,
837 pub infer: usize,
838}
839
840#[derive(Debug, Clone, Copy, HashStable_Generic)]
843pub struct Generics<'hir> {
844 pub params: &'hir [GenericParam<'hir>],
845 pub predicates: &'hir [WherePredicate<'hir>],
846 pub has_where_clause_predicates: bool,
847 pub where_clause_span: Span,
848 pub span: Span,
849}
850
851impl<'hir> Generics<'hir> {
852 pub const fn empty() -> &'hir Generics<'hir> {
853 const NOPE: Generics<'_> = Generics {
854 params: &[],
855 predicates: &[],
856 has_where_clause_predicates: false,
857 where_clause_span: DUMMY_SP,
858 span: DUMMY_SP,
859 };
860 &NOPE
861 }
862
863 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
864 self.params.iter().find(|¶m| name == param.name.ident().name)
865 }
866
867 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
869 if let Some(first) = self.params.first()
870 && self.span.contains(first.span)
871 {
872 Some(first.span.shrink_to_lo())
875 } else {
876 None
877 }
878 }
879
880 pub fn span_for_param_suggestion(&self) -> Option<Span> {
882 self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
883 self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
886 })
887 }
888
889 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
892 let end = self.where_clause_span.shrink_to_hi();
893 if self.has_where_clause_predicates {
894 self.predicates
895 .iter()
896 .rfind(|&p| p.kind.in_where_clause())
897 .map_or(end, |p| p.span)
898 .shrink_to_hi()
899 .to(end)
900 } else {
901 end
902 }
903 }
904
905 pub fn add_where_or_trailing_comma(&self) -> &'static str {
906 if self.has_where_clause_predicates {
907 ","
908 } else if self.where_clause_span.is_empty() {
909 " where"
910 } else {
911 ""
913 }
914 }
915
916 pub fn bounds_for_param(
917 &self,
918 param_def_id: LocalDefId,
919 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
920 self.predicates.iter().filter_map(move |pred| match pred.kind {
921 WherePredicateKind::BoundPredicate(bp)
922 if bp.is_param_bound(param_def_id.to_def_id()) =>
923 {
924 Some(bp)
925 }
926 _ => None,
927 })
928 }
929
930 pub fn outlives_for_param(
931 &self,
932 param_def_id: LocalDefId,
933 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
934 self.predicates.iter().filter_map(move |pred| match pred.kind {
935 WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
936 _ => None,
937 })
938 }
939
940 pub fn bounds_span_for_suggestions(
951 &self,
952 param_def_id: LocalDefId,
953 ) -> Option<(Span, Option<Span>)> {
954 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
955 |bound| {
956 let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
957 && let [.., segment] = trait_ref.path.segments
958 && let Some(ret_ty) = segment.args().paren_sugar_output()
959 && let ret_ty = ret_ty.peel_refs()
960 && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
961 && let TraitObjectSyntax::Dyn = tagged_ptr.tag()
962 && ret_ty.span.can_be_used_for_suggestions()
963 {
964 Some(ret_ty.span)
965 } else {
966 None
967 };
968
969 span_for_parentheses.map_or_else(
970 || {
971 let bs = bound.span();
974 bs.can_be_used_for_suggestions().then(|| (bs.shrink_to_hi(), None))
975 },
976 |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
977 )
978 },
979 )
980 }
981
982 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
983 let predicate = &self.predicates[pos];
984 let span = predicate.span;
985
986 if !predicate.kind.in_where_clause() {
987 return span;
990 }
991
992 if pos < self.predicates.len() - 1 {
994 let next_pred = &self.predicates[pos + 1];
995 if next_pred.kind.in_where_clause() {
996 return span.until(next_pred.span);
999 }
1000 }
1001
1002 if pos > 0 {
1003 let prev_pred = &self.predicates[pos - 1];
1004 if prev_pred.kind.in_where_clause() {
1005 return prev_pred.span.shrink_to_hi().to(span);
1008 }
1009 }
1010
1011 self.where_clause_span
1015 }
1016
1017 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
1018 let predicate = &self.predicates[predicate_pos];
1019 let bounds = predicate.kind.bounds();
1020
1021 if bounds.len() == 1 {
1022 return self.span_for_predicate_removal(predicate_pos);
1023 }
1024
1025 let bound_span = bounds[bound_pos].span();
1026 if bound_pos < bounds.len() - 1 {
1027 bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
1033 } else {
1034 bound_span.with_lo(bounds[bound_pos - 1].span().hi())
1040 }
1041 }
1042}
1043
1044#[derive(Debug, Clone, Copy, HashStable_Generic)]
1046pub struct WherePredicate<'hir> {
1047 #[stable_hasher(ignore)]
1048 pub hir_id: HirId,
1049 pub span: Span,
1050 pub kind: &'hir WherePredicateKind<'hir>,
1051}
1052
1053#[derive(Debug, Clone, Copy, HashStable_Generic)]
1055pub enum WherePredicateKind<'hir> {
1056 BoundPredicate(WhereBoundPredicate<'hir>),
1058 RegionPredicate(WhereRegionPredicate<'hir>),
1060 EqPredicate(WhereEqPredicate<'hir>),
1062}
1063
1064impl<'hir> WherePredicateKind<'hir> {
1065 pub fn in_where_clause(&self) -> bool {
1066 match self {
1067 WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
1068 WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
1069 WherePredicateKind::EqPredicate(_) => false,
1070 }
1071 }
1072
1073 pub fn bounds(&self) -> GenericBounds<'hir> {
1074 match self {
1075 WherePredicateKind::BoundPredicate(p) => p.bounds,
1076 WherePredicateKind::RegionPredicate(p) => p.bounds,
1077 WherePredicateKind::EqPredicate(_) => &[],
1078 }
1079 }
1080}
1081
1082#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
1083pub enum PredicateOrigin {
1084 WhereClause,
1085 GenericParam,
1086 ImplTrait,
1087}
1088
1089#[derive(Debug, Clone, Copy, HashStable_Generic)]
1091pub struct WhereBoundPredicate<'hir> {
1092 pub origin: PredicateOrigin,
1094 pub bound_generic_params: &'hir [GenericParam<'hir>],
1096 pub bounded_ty: &'hir Ty<'hir>,
1098 pub bounds: GenericBounds<'hir>,
1100}
1101
1102impl<'hir> WhereBoundPredicate<'hir> {
1103 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
1105 self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
1106 }
1107}
1108
1109#[derive(Debug, Clone, Copy, HashStable_Generic)]
1111pub struct WhereRegionPredicate<'hir> {
1112 pub in_where_clause: bool,
1113 pub lifetime: &'hir Lifetime,
1114 pub bounds: GenericBounds<'hir>,
1115}
1116
1117impl<'hir> WhereRegionPredicate<'hir> {
1118 fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
1120 self.lifetime.kind == LifetimeKind::Param(param_def_id)
1121 }
1122}
1123
1124#[derive(Debug, Clone, Copy, HashStable_Generic)]
1126pub struct WhereEqPredicate<'hir> {
1127 pub lhs_ty: &'hir Ty<'hir>,
1128 pub rhs_ty: &'hir Ty<'hir>,
1129}
1130
1131#[derive(Clone, Copy, Debug)]
1135pub struct ParentedNode<'tcx> {
1136 pub parent: ItemLocalId,
1137 pub node: Node<'tcx>,
1138}
1139
1140#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1142pub enum AttrArgs {
1143 Empty,
1145 Delimited(DelimArgs),
1147 Eq {
1149 eq_span: Span,
1151 expr: MetaItemLit,
1153 },
1154}
1155
1156#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1157pub struct AttrPath {
1158 pub segments: Box<[Ident]>,
1159 pub span: Span,
1160}
1161
1162impl AttrPath {
1163 pub fn from_ast(path: &ast::Path) -> Self {
1164 AttrPath {
1165 segments: path.segments.iter().map(|i| i.ident).collect::<Vec<_>>().into_boxed_slice(),
1166 span: path.span,
1167 }
1168 }
1169}
1170
1171impl fmt::Display for AttrPath {
1172 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1173 write!(f, "{}", join_path_idents(&self.segments))
1174 }
1175}
1176
1177#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1178pub struct AttrItem {
1179 pub path: AttrPath,
1181 pub args: AttrArgs,
1182 pub id: HashIgnoredAttrId,
1183 pub style: AttrStyle,
1186 pub span: Span,
1188}
1189
1190#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1193pub struct HashIgnoredAttrId {
1194 pub attr_id: AttrId,
1195}
1196
1197#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1198pub enum Attribute {
1199 Parsed(AttributeKind),
1205
1206 Unparsed(Box<AttrItem>),
1209}
1210
1211impl Attribute {
1212 pub fn get_normal_item(&self) -> &AttrItem {
1213 match &self {
1214 Attribute::Unparsed(normal) => &normal,
1215 _ => panic!("unexpected parsed attribute"),
1216 }
1217 }
1218
1219 pub fn unwrap_normal_item(self) -> AttrItem {
1220 match self {
1221 Attribute::Unparsed(normal) => *normal,
1222 _ => panic!("unexpected parsed attribute"),
1223 }
1224 }
1225
1226 pub fn value_lit(&self) -> Option<&MetaItemLit> {
1227 match &self {
1228 Attribute::Unparsed(n) => match n.as_ref() {
1229 AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1230 _ => None,
1231 },
1232 _ => None,
1233 }
1234 }
1235
1236 pub fn is_parsed_attr(&self) -> bool {
1237 match self {
1238 Attribute::Parsed(_) => true,
1239 Attribute::Unparsed(_) => false,
1240 }
1241 }
1242}
1243
1244impl AttributeExt for Attribute {
1245 #[inline]
1246 fn id(&self) -> AttrId {
1247 match &self {
1248 Attribute::Unparsed(u) => u.id.attr_id,
1249 _ => panic!(),
1250 }
1251 }
1252
1253 #[inline]
1254 fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1255 match &self {
1256 Attribute::Unparsed(n) => match n.as_ref() {
1257 AttrItem { args: AttrArgs::Delimited(d), .. } => {
1258 ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1259 }
1260 _ => None,
1261 },
1262 _ => None,
1263 }
1264 }
1265
1266 #[inline]
1267 fn value_str(&self) -> Option<Symbol> {
1268 self.value_lit().and_then(|x| x.value_str())
1269 }
1270
1271 #[inline]
1272 fn value_span(&self) -> Option<Span> {
1273 self.value_lit().map(|i| i.span)
1274 }
1275
1276 #[inline]
1278 fn ident(&self) -> Option<Ident> {
1279 match &self {
1280 Attribute::Unparsed(n) => {
1281 if let [ident] = n.path.segments.as_ref() {
1282 Some(*ident)
1283 } else {
1284 None
1285 }
1286 }
1287 _ => None,
1288 }
1289 }
1290
1291 #[inline]
1292 fn path_matches(&self, name: &[Symbol]) -> bool {
1293 match &self {
1294 Attribute::Unparsed(n) => {
1295 n.path.segments.len() == name.len()
1296 && n.path.segments.iter().zip(name).all(|(s, n)| s.name == *n)
1297 }
1298 _ => false,
1299 }
1300 }
1301
1302 #[inline]
1303 fn is_doc_comment(&self) -> bool {
1304 matches!(self, Attribute::Parsed(AttributeKind::DocComment { .. }))
1305 }
1306
1307 #[inline]
1308 fn span(&self) -> Span {
1309 match &self {
1310 Attribute::Unparsed(u) => u.span,
1311 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1313 Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1314 Attribute::Parsed(AttributeKind::AllowInternalUnsafe(span)) => *span,
1315 Attribute::Parsed(AttributeKind::Linkage(_, span)) => *span,
1316 a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1317 }
1318 }
1319
1320 #[inline]
1321 fn is_word(&self) -> bool {
1322 match &self {
1323 Attribute::Unparsed(n) => {
1324 matches!(n.args, AttrArgs::Empty)
1325 }
1326 _ => false,
1327 }
1328 }
1329
1330 #[inline]
1331 fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1332 match &self {
1333 Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1334 _ => None,
1335 }
1336 }
1337
1338 #[inline]
1339 fn doc_str(&self) -> Option<Symbol> {
1340 match &self {
1341 Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1342 Attribute::Unparsed(_) if self.has_name(sym::doc) => self.value_str(),
1343 _ => None,
1344 }
1345 }
1346
1347 fn is_automatically_derived_attr(&self) -> bool {
1348 matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)))
1349 }
1350
1351 #[inline]
1352 fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1353 match &self {
1354 Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1355 Some((*comment, *kind))
1356 }
1357 Attribute::Unparsed(_) if self.has_name(sym::doc) => {
1358 self.value_str().map(|s| (s, CommentKind::Line))
1359 }
1360 _ => None,
1361 }
1362 }
1363
1364 fn doc_resolution_scope(&self) -> Option<AttrStyle> {
1365 match self {
1366 Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
1367 Attribute::Unparsed(attr) if self.has_name(sym::doc) && self.value_str().is_some() => {
1368 Some(attr.style)
1369 }
1370 _ => None,
1371 }
1372 }
1373
1374 fn is_proc_macro_attr(&self) -> bool {
1375 matches!(
1376 self,
1377 Attribute::Parsed(
1378 AttributeKind::ProcMacro(..)
1379 | AttributeKind::ProcMacroAttribute(..)
1380 | AttributeKind::ProcMacroDerive { .. }
1381 )
1382 )
1383 }
1384}
1385
1386impl Attribute {
1388 #[inline]
1389 pub fn id(&self) -> AttrId {
1390 AttributeExt::id(self)
1391 }
1392
1393 #[inline]
1394 pub fn name(&self) -> Option<Symbol> {
1395 AttributeExt::name(self)
1396 }
1397
1398 #[inline]
1399 pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1400 AttributeExt::meta_item_list(self)
1401 }
1402
1403 #[inline]
1404 pub fn value_str(&self) -> Option<Symbol> {
1405 AttributeExt::value_str(self)
1406 }
1407
1408 #[inline]
1409 pub fn value_span(&self) -> Option<Span> {
1410 AttributeExt::value_span(self)
1411 }
1412
1413 #[inline]
1414 pub fn ident(&self) -> Option<Ident> {
1415 AttributeExt::ident(self)
1416 }
1417
1418 #[inline]
1419 pub fn path_matches(&self, name: &[Symbol]) -> bool {
1420 AttributeExt::path_matches(self, name)
1421 }
1422
1423 #[inline]
1424 pub fn is_doc_comment(&self) -> bool {
1425 AttributeExt::is_doc_comment(self)
1426 }
1427
1428 #[inline]
1429 pub fn has_name(&self, name: Symbol) -> bool {
1430 AttributeExt::has_name(self, name)
1431 }
1432
1433 #[inline]
1434 pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1435 AttributeExt::has_any_name(self, names)
1436 }
1437
1438 #[inline]
1439 pub fn span(&self) -> Span {
1440 AttributeExt::span(self)
1441 }
1442
1443 #[inline]
1444 pub fn is_word(&self) -> bool {
1445 AttributeExt::is_word(self)
1446 }
1447
1448 #[inline]
1449 pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1450 AttributeExt::path(self)
1451 }
1452
1453 #[inline]
1454 pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1455 AttributeExt::ident_path(self)
1456 }
1457
1458 #[inline]
1459 pub fn doc_str(&self) -> Option<Symbol> {
1460 AttributeExt::doc_str(self)
1461 }
1462
1463 #[inline]
1464 pub fn is_proc_macro_attr(&self) -> bool {
1465 AttributeExt::is_proc_macro_attr(self)
1466 }
1467
1468 #[inline]
1469 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1470 AttributeExt::doc_str_and_comment_kind(self)
1471 }
1472}
1473
1474#[derive(Debug)]
1476pub struct AttributeMap<'tcx> {
1477 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1478 pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1480 pub opt_hash: Option<Fingerprint>,
1482}
1483
1484impl<'tcx> AttributeMap<'tcx> {
1485 pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1486 map: SortedMap::new(),
1487 opt_hash: Some(Fingerprint::ZERO),
1488 define_opaque: None,
1489 };
1490
1491 #[inline]
1492 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1493 self.map.get(&id).copied().unwrap_or(&[])
1494 }
1495}
1496
1497pub struct OwnerNodes<'tcx> {
1501 pub opt_hash_including_bodies: Option<Fingerprint>,
1504 pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1509 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1511}
1512
1513impl<'tcx> OwnerNodes<'tcx> {
1514 pub fn node(&self) -> OwnerNode<'tcx> {
1515 self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1517 }
1518}
1519
1520impl fmt::Debug for OwnerNodes<'_> {
1521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1522 f.debug_struct("OwnerNodes")
1523 .field("node", &self.nodes[ItemLocalId::ZERO])
1525 .field(
1526 "parents",
1527 &fmt::from_fn(|f| {
1528 f.debug_list()
1529 .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1530 fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1531 }))
1532 .finish()
1533 }),
1534 )
1535 .field("bodies", &self.bodies)
1536 .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1537 .finish()
1538 }
1539}
1540
1541#[derive(Debug, HashStable_Generic)]
1543pub struct OwnerInfo<'hir> {
1544 pub nodes: OwnerNodes<'hir>,
1546 pub parenting: LocalDefIdMap<ItemLocalId>,
1548 pub attrs: AttributeMap<'hir>,
1550 pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1553
1554 pub delayed_lints: DelayedLints,
1557}
1558
1559impl<'tcx> OwnerInfo<'tcx> {
1560 #[inline]
1561 pub fn node(&self) -> OwnerNode<'tcx> {
1562 self.nodes.node()
1563 }
1564}
1565
1566#[derive(Copy, Clone, Debug, HashStable_Generic)]
1567pub enum MaybeOwner<'tcx> {
1568 Owner(&'tcx OwnerInfo<'tcx>),
1569 NonOwner(HirId),
1570 Phantom,
1572}
1573
1574impl<'tcx> MaybeOwner<'tcx> {
1575 pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1576 match self {
1577 MaybeOwner::Owner(i) => Some(i),
1578 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1579 }
1580 }
1581
1582 pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1583 self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1584 }
1585}
1586
1587#[derive(Debug)]
1594pub struct Crate<'hir> {
1595 pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1596 pub opt_hir_hash: Option<Fingerprint>,
1598}
1599
1600#[derive(Debug, Clone, Copy, HashStable_Generic)]
1601pub struct Closure<'hir> {
1602 pub def_id: LocalDefId,
1603 pub binder: ClosureBinder,
1604 pub constness: Constness,
1605 pub capture_clause: CaptureBy,
1606 pub bound_generic_params: &'hir [GenericParam<'hir>],
1607 pub fn_decl: &'hir FnDecl<'hir>,
1608 pub body: BodyId,
1609 pub fn_decl_span: Span,
1611 pub fn_arg_span: Option<Span>,
1613 pub kind: ClosureKind,
1614}
1615
1616#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1617pub enum ClosureKind {
1618 Closure,
1620 Coroutine(CoroutineKind),
1625 CoroutineClosure(CoroutineDesugaring),
1630}
1631
1632#[derive(Debug, Clone, Copy, HashStable_Generic)]
1636pub struct Block<'hir> {
1637 pub stmts: &'hir [Stmt<'hir>],
1639 pub expr: Option<&'hir Expr<'hir>>,
1642 #[stable_hasher(ignore)]
1643 pub hir_id: HirId,
1644 pub rules: BlockCheckMode,
1646 pub span: Span,
1648 pub targeted_by_break: bool,
1652}
1653
1654impl<'hir> Block<'hir> {
1655 pub fn innermost_block(&self) -> &Block<'hir> {
1656 let mut block = self;
1657 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1658 block = inner_block;
1659 }
1660 block
1661 }
1662}
1663
1664#[derive(Debug, Clone, Copy, HashStable_Generic)]
1665pub struct TyPat<'hir> {
1666 #[stable_hasher(ignore)]
1667 pub hir_id: HirId,
1668 pub kind: TyPatKind<'hir>,
1669 pub span: Span,
1670}
1671
1672#[derive(Debug, Clone, Copy, HashStable_Generic)]
1673pub struct Pat<'hir> {
1674 #[stable_hasher(ignore)]
1675 pub hir_id: HirId,
1676 pub kind: PatKind<'hir>,
1677 pub span: Span,
1678 pub default_binding_modes: bool,
1681}
1682
1683impl<'hir> Pat<'hir> {
1684 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1685 if !it(self) {
1686 return false;
1687 }
1688
1689 use PatKind::*;
1690 match self.kind {
1691 Missing => unreachable!(),
1692 Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1693 Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_short_(it),
1694 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1695 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1696 Slice(before, slice, after) => {
1697 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1698 }
1699 }
1700 }
1701
1702 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1709 self.walk_short_(&mut it)
1710 }
1711
1712 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1713 if !it(self) {
1714 return;
1715 }
1716
1717 use PatKind::*;
1718 match self.kind {
1719 Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1720 Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1721 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1722 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1723 Slice(before, slice, after) => {
1724 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1725 }
1726 }
1727 }
1728
1729 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1733 self.walk_(&mut it)
1734 }
1735
1736 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1740 self.walk(|p| {
1741 it(p);
1742 true
1743 })
1744 }
1745
1746 pub fn is_never_pattern(&self) -> bool {
1748 let mut is_never_pattern = false;
1749 self.walk(|pat| match &pat.kind {
1750 PatKind::Never => {
1751 is_never_pattern = true;
1752 false
1753 }
1754 PatKind::Or(s) => {
1755 is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1756 false
1757 }
1758 _ => true,
1759 });
1760 is_never_pattern
1761 }
1762}
1763
1764#[derive(Debug, Clone, Copy, HashStable_Generic)]
1770pub struct PatField<'hir> {
1771 #[stable_hasher(ignore)]
1772 pub hir_id: HirId,
1773 pub ident: Ident,
1775 pub pat: &'hir Pat<'hir>,
1777 pub is_shorthand: bool,
1778 pub span: Span,
1779}
1780
1781#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1782pub enum RangeEnd {
1783 Included,
1784 Excluded,
1785}
1786
1787impl fmt::Display for RangeEnd {
1788 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1789 f.write_str(match self {
1790 RangeEnd::Included => "..=",
1791 RangeEnd::Excluded => "..",
1792 })
1793 }
1794}
1795
1796#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1800pub struct DotDotPos(u32);
1801
1802impl DotDotPos {
1803 pub fn new(n: Option<usize>) -> Self {
1805 match n {
1806 Some(n) => {
1807 assert!(n < u32::MAX as usize);
1808 Self(n as u32)
1809 }
1810 None => Self(u32::MAX),
1811 }
1812 }
1813
1814 pub fn as_opt_usize(&self) -> Option<usize> {
1815 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1816 }
1817}
1818
1819impl fmt::Debug for DotDotPos {
1820 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1821 self.as_opt_usize().fmt(f)
1822 }
1823}
1824
1825#[derive(Debug, Clone, Copy, HashStable_Generic)]
1826pub struct PatExpr<'hir> {
1827 #[stable_hasher(ignore)]
1828 pub hir_id: HirId,
1829 pub span: Span,
1830 pub kind: PatExprKind<'hir>,
1831}
1832
1833#[derive(Debug, Clone, Copy, HashStable_Generic)]
1834pub enum PatExprKind<'hir> {
1835 Lit {
1836 lit: Lit,
1837 negated: bool,
1840 },
1841 ConstBlock(ConstBlock),
1842 Path(QPath<'hir>),
1844}
1845
1846#[derive(Debug, Clone, Copy, HashStable_Generic)]
1847pub enum TyPatKind<'hir> {
1848 Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1850
1851 Or(&'hir [TyPat<'hir>]),
1853
1854 Err(ErrorGuaranteed),
1856}
1857
1858#[derive(Debug, Clone, Copy, HashStable_Generic)]
1859pub enum PatKind<'hir> {
1860 Missing,
1862
1863 Wild,
1865
1866 Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1877
1878 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1881
1882 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1886
1887 Or(&'hir [Pat<'hir>]),
1890
1891 Never,
1893
1894 Tuple(&'hir [Pat<'hir>], DotDotPos),
1898
1899 Box(&'hir Pat<'hir>),
1901
1902 Deref(&'hir Pat<'hir>),
1904
1905 Ref(&'hir Pat<'hir>, Mutability),
1907
1908 Expr(&'hir PatExpr<'hir>),
1910
1911 Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
1913
1914 Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
1916
1917 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1927
1928 Err(ErrorGuaranteed),
1930}
1931
1932#[derive(Debug, Clone, Copy, HashStable_Generic)]
1934pub struct Stmt<'hir> {
1935 #[stable_hasher(ignore)]
1936 pub hir_id: HirId,
1937 pub kind: StmtKind<'hir>,
1938 pub span: Span,
1939}
1940
1941#[derive(Debug, Clone, Copy, HashStable_Generic)]
1943pub enum StmtKind<'hir> {
1944 Let(&'hir LetStmt<'hir>),
1946
1947 Item(ItemId),
1949
1950 Expr(&'hir Expr<'hir>),
1952
1953 Semi(&'hir Expr<'hir>),
1955}
1956
1957#[derive(Debug, Clone, Copy, HashStable_Generic)]
1959pub struct LetStmt<'hir> {
1960 pub super_: Option<Span>,
1962 pub pat: &'hir Pat<'hir>,
1963 pub ty: Option<&'hir Ty<'hir>>,
1965 pub init: Option<&'hir Expr<'hir>>,
1967 pub els: Option<&'hir Block<'hir>>,
1969 #[stable_hasher(ignore)]
1970 pub hir_id: HirId,
1971 pub span: Span,
1972 pub source: LocalSource,
1976}
1977
1978#[derive(Debug, Clone, Copy, HashStable_Generic)]
1981pub struct Arm<'hir> {
1982 #[stable_hasher(ignore)]
1983 pub hir_id: HirId,
1984 pub span: Span,
1985 pub pat: &'hir Pat<'hir>,
1987 pub guard: Option<&'hir Expr<'hir>>,
1989 pub body: &'hir Expr<'hir>,
1991}
1992
1993#[derive(Debug, Clone, Copy, HashStable_Generic)]
1999pub struct LetExpr<'hir> {
2000 pub span: Span,
2001 pub pat: &'hir Pat<'hir>,
2002 pub ty: Option<&'hir Ty<'hir>>,
2003 pub init: &'hir Expr<'hir>,
2004 pub recovered: ast::Recovered,
2007}
2008
2009#[derive(Debug, Clone, Copy, HashStable_Generic)]
2010pub struct ExprField<'hir> {
2011 #[stable_hasher(ignore)]
2012 pub hir_id: HirId,
2013 pub ident: Ident,
2014 pub expr: &'hir Expr<'hir>,
2015 pub span: Span,
2016 pub is_shorthand: bool,
2017}
2018
2019#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2020pub enum BlockCheckMode {
2021 DefaultBlock,
2022 UnsafeBlock(UnsafeSource),
2023}
2024
2025#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2026pub enum UnsafeSource {
2027 CompilerGenerated,
2028 UserProvided,
2029}
2030
2031#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
2032pub struct BodyId {
2033 pub hir_id: HirId,
2034}
2035
2036#[derive(Debug, Clone, Copy, HashStable_Generic)]
2058pub struct Body<'hir> {
2059 pub params: &'hir [Param<'hir>],
2060 pub value: &'hir Expr<'hir>,
2061}
2062
2063impl<'hir> Body<'hir> {
2064 pub fn id(&self) -> BodyId {
2065 BodyId { hir_id: self.value.hir_id }
2066 }
2067}
2068
2069#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2071pub enum CoroutineKind {
2072 Desugared(CoroutineDesugaring, CoroutineSource),
2074
2075 Coroutine(Movability),
2077}
2078
2079impl CoroutineKind {
2080 pub fn movability(self) -> Movability {
2081 match self {
2082 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2083 | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2084 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2085 CoroutineKind::Coroutine(mov) => mov,
2086 }
2087 }
2088
2089 pub fn is_fn_like(self) -> bool {
2090 matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2091 }
2092
2093 pub fn to_plural_string(&self) -> String {
2094 match self {
2095 CoroutineKind::Desugared(d, CoroutineSource::Fn) => format!("{d:#}fn bodies"),
2096 CoroutineKind::Desugared(d, CoroutineSource::Block) => format!("{d:#}blocks"),
2097 CoroutineKind::Desugared(d, CoroutineSource::Closure) => format!("{d:#}closure bodies"),
2098 CoroutineKind::Coroutine(_) => "coroutines".to_string(),
2099 }
2100 }
2101}
2102
2103impl fmt::Display for CoroutineKind {
2104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2105 match self {
2106 CoroutineKind::Desugared(d, k) => {
2107 d.fmt(f)?;
2108 k.fmt(f)
2109 }
2110 CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2111 }
2112 }
2113}
2114
2115#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
2121pub enum CoroutineSource {
2122 Block,
2124
2125 Closure,
2127
2128 Fn,
2130}
2131
2132impl fmt::Display for CoroutineSource {
2133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2134 match self {
2135 CoroutineSource::Block => "block",
2136 CoroutineSource::Closure => "closure body",
2137 CoroutineSource::Fn => "fn body",
2138 }
2139 .fmt(f)
2140 }
2141}
2142
2143#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2144pub enum CoroutineDesugaring {
2145 Async,
2147
2148 Gen,
2150
2151 AsyncGen,
2154}
2155
2156impl fmt::Display for CoroutineDesugaring {
2157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2158 match self {
2159 CoroutineDesugaring::Async => {
2160 if f.alternate() {
2161 f.write_str("`async` ")?;
2162 } else {
2163 f.write_str("async ")?
2164 }
2165 }
2166 CoroutineDesugaring::Gen => {
2167 if f.alternate() {
2168 f.write_str("`gen` ")?;
2169 } else {
2170 f.write_str("gen ")?
2171 }
2172 }
2173 CoroutineDesugaring::AsyncGen => {
2174 if f.alternate() {
2175 f.write_str("`async gen` ")?;
2176 } else {
2177 f.write_str("async gen ")?
2178 }
2179 }
2180 }
2181
2182 Ok(())
2183 }
2184}
2185
2186#[derive(Copy, Clone, Debug)]
2187pub enum BodyOwnerKind {
2188 Fn,
2190
2191 Closure,
2193
2194 Const { inline: bool },
2196
2197 Static(Mutability),
2199
2200 GlobalAsm,
2202}
2203
2204impl BodyOwnerKind {
2205 pub fn is_fn_or_closure(self) -> bool {
2206 match self {
2207 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2208 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2209 false
2210 }
2211 }
2212 }
2213}
2214
2215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2217pub enum ConstContext {
2218 ConstFn,
2220
2221 Static(Mutability),
2223
2224 Const { inline: bool },
2234}
2235
2236impl ConstContext {
2237 pub fn keyword_name(self) -> &'static str {
2241 match self {
2242 Self::Const { .. } => "const",
2243 Self::Static(Mutability::Not) => "static",
2244 Self::Static(Mutability::Mut) => "static mut",
2245 Self::ConstFn => "const fn",
2246 }
2247 }
2248}
2249
2250impl fmt::Display for ConstContext {
2253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2254 match *self {
2255 Self::Const { .. } => write!(f, "constant"),
2256 Self::Static(_) => write!(f, "static"),
2257 Self::ConstFn => write!(f, "constant function"),
2258 }
2259 }
2260}
2261
2262pub type Lit = Spanned<LitKind>;
2267
2268#[derive(Copy, Clone, Debug, HashStable_Generic)]
2277pub struct AnonConst {
2278 #[stable_hasher(ignore)]
2279 pub hir_id: HirId,
2280 pub def_id: LocalDefId,
2281 pub body: BodyId,
2282 pub span: Span,
2283}
2284
2285#[derive(Copy, Clone, Debug, HashStable_Generic)]
2287pub struct ConstBlock {
2288 #[stable_hasher(ignore)]
2289 pub hir_id: HirId,
2290 pub def_id: LocalDefId,
2291 pub body: BodyId,
2292}
2293
2294#[derive(Debug, Clone, Copy, HashStable_Generic)]
2303pub struct Expr<'hir> {
2304 #[stable_hasher(ignore)]
2305 pub hir_id: HirId,
2306 pub kind: ExprKind<'hir>,
2307 pub span: Span,
2308}
2309
2310impl Expr<'_> {
2311 pub fn precedence(&self, has_attr: &dyn Fn(HirId) -> bool) -> ExprPrecedence {
2312 let prefix_attrs_precedence = || -> ExprPrecedence {
2313 if has_attr(self.hir_id) { ExprPrecedence::Prefix } else { ExprPrecedence::Unambiguous }
2314 };
2315
2316 match &self.kind {
2317 ExprKind::Closure(closure) => {
2318 match closure.fn_decl.output {
2319 FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2320 FnRetTy::Return(_) => prefix_attrs_precedence(),
2321 }
2322 }
2323
2324 ExprKind::Break(..)
2325 | ExprKind::Ret(..)
2326 | ExprKind::Yield(..)
2327 | ExprKind::Become(..) => ExprPrecedence::Jump,
2328
2329 ExprKind::Binary(op, ..) => op.node.precedence(),
2331 ExprKind::Cast(..) => ExprPrecedence::Cast,
2332
2333 ExprKind::Assign(..) |
2334 ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2335
2336 ExprKind::AddrOf(..)
2338 | ExprKind::Let(..)
2343 | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2344
2345 ExprKind::Array(_)
2347 | ExprKind::Block(..)
2348 | ExprKind::Call(..)
2349 | ExprKind::ConstBlock(_)
2350 | ExprKind::Continue(..)
2351 | ExprKind::Field(..)
2352 | ExprKind::If(..)
2353 | ExprKind::Index(..)
2354 | ExprKind::InlineAsm(..)
2355 | ExprKind::Lit(_)
2356 | ExprKind::Loop(..)
2357 | ExprKind::Match(..)
2358 | ExprKind::MethodCall(..)
2359 | ExprKind::OffsetOf(..)
2360 | ExprKind::Path(..)
2361 | ExprKind::Repeat(..)
2362 | ExprKind::Struct(..)
2363 | ExprKind::Tup(_)
2364 | ExprKind::Type(..)
2365 | ExprKind::UnsafeBinderCast(..)
2366 | ExprKind::Use(..)
2367 | ExprKind::Err(_) => prefix_attrs_precedence(),
2368
2369 ExprKind::DropTemps(expr, ..) => expr.precedence(has_attr),
2370 }
2371 }
2372
2373 pub fn is_syntactic_place_expr(&self) -> bool {
2378 self.is_place_expr(|_| true)
2379 }
2380
2381 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2386 match self.kind {
2387 ExprKind::Path(QPath::Resolved(_, ref path)) => {
2388 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2389 }
2390
2391 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2395
2396 ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2398
2399 ExprKind::Unary(UnOp::Deref, _) => true,
2400
2401 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2402 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2403 }
2404
2405 ExprKind::Path(QPath::LangItem(..)) => false,
2407
2408 ExprKind::Err(_guar)
2410 | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2411
2412 ExprKind::Path(QPath::TypeRelative(..))
2415 | ExprKind::Call(..)
2416 | ExprKind::MethodCall(..)
2417 | ExprKind::Use(..)
2418 | ExprKind::Struct(..)
2419 | ExprKind::Tup(..)
2420 | ExprKind::If(..)
2421 | ExprKind::Match(..)
2422 | ExprKind::Closure { .. }
2423 | ExprKind::Block(..)
2424 | ExprKind::Repeat(..)
2425 | ExprKind::Array(..)
2426 | ExprKind::Break(..)
2427 | ExprKind::Continue(..)
2428 | ExprKind::Ret(..)
2429 | ExprKind::Become(..)
2430 | ExprKind::Let(..)
2431 | ExprKind::Loop(..)
2432 | ExprKind::Assign(..)
2433 | ExprKind::InlineAsm(..)
2434 | ExprKind::OffsetOf(..)
2435 | ExprKind::AssignOp(..)
2436 | ExprKind::Lit(_)
2437 | ExprKind::ConstBlock(..)
2438 | ExprKind::Unary(..)
2439 | ExprKind::AddrOf(..)
2440 | ExprKind::Binary(..)
2441 | ExprKind::Yield(..)
2442 | ExprKind::Cast(..)
2443 | ExprKind::DropTemps(..) => false,
2444 }
2445 }
2446
2447 pub fn is_size_lit(&self) -> bool {
2450 matches!(
2451 self.kind,
2452 ExprKind::Lit(Lit {
2453 node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2454 ..
2455 })
2456 )
2457 }
2458
2459 pub fn peel_drop_temps(&self) -> &Self {
2465 let mut expr = self;
2466 while let ExprKind::DropTemps(inner) = &expr.kind {
2467 expr = inner;
2468 }
2469 expr
2470 }
2471
2472 pub fn peel_blocks(&self) -> &Self {
2473 let mut expr = self;
2474 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2475 expr = inner;
2476 }
2477 expr
2478 }
2479
2480 pub fn peel_borrows(&self) -> &Self {
2481 let mut expr = self;
2482 while let ExprKind::AddrOf(.., inner) = &expr.kind {
2483 expr = inner;
2484 }
2485 expr
2486 }
2487
2488 pub fn can_have_side_effects(&self) -> bool {
2489 match self.peel_drop_temps().kind {
2490 ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2491 false
2492 }
2493 ExprKind::Type(base, _)
2494 | ExprKind::Unary(_, base)
2495 | ExprKind::Field(base, _)
2496 | ExprKind::Index(base, _, _)
2497 | ExprKind::AddrOf(.., base)
2498 | ExprKind::Cast(base, _)
2499 | ExprKind::UnsafeBinderCast(_, base, _) => {
2500 base.can_have_side_effects()
2504 }
2505 ExprKind::Struct(_, fields, init) => {
2506 let init_side_effects = match init {
2507 StructTailExpr::Base(init) => init.can_have_side_effects(),
2508 StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2509 };
2510 fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2511 || init_side_effects
2512 }
2513
2514 ExprKind::Array(args)
2515 | ExprKind::Tup(args)
2516 | ExprKind::Call(
2517 Expr {
2518 kind:
2519 ExprKind::Path(QPath::Resolved(
2520 None,
2521 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2522 )),
2523 ..
2524 },
2525 args,
2526 ) => args.iter().any(|arg| arg.can_have_side_effects()),
2527 ExprKind::If(..)
2528 | ExprKind::Match(..)
2529 | ExprKind::MethodCall(..)
2530 | ExprKind::Call(..)
2531 | ExprKind::Closure { .. }
2532 | ExprKind::Block(..)
2533 | ExprKind::Repeat(..)
2534 | ExprKind::Break(..)
2535 | ExprKind::Continue(..)
2536 | ExprKind::Ret(..)
2537 | ExprKind::Become(..)
2538 | ExprKind::Let(..)
2539 | ExprKind::Loop(..)
2540 | ExprKind::Assign(..)
2541 | ExprKind::InlineAsm(..)
2542 | ExprKind::AssignOp(..)
2543 | ExprKind::ConstBlock(..)
2544 | ExprKind::Binary(..)
2545 | ExprKind::Yield(..)
2546 | ExprKind::DropTemps(..)
2547 | ExprKind::Err(_) => true,
2548 }
2549 }
2550
2551 pub fn is_approximately_pattern(&self) -> bool {
2553 match &self.kind {
2554 ExprKind::Array(_)
2555 | ExprKind::Call(..)
2556 | ExprKind::Tup(_)
2557 | ExprKind::Lit(_)
2558 | ExprKind::Path(_)
2559 | ExprKind::Struct(..) => true,
2560 _ => false,
2561 }
2562 }
2563
2564 pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2569 match (self.kind, other.kind) {
2570 (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2571 (
2572 ExprKind::Path(QPath::LangItem(item1, _)),
2573 ExprKind::Path(QPath::LangItem(item2, _)),
2574 ) => item1 == item2,
2575 (
2576 ExprKind::Path(QPath::Resolved(None, path1)),
2577 ExprKind::Path(QPath::Resolved(None, path2)),
2578 ) => path1.res == path2.res,
2579 (
2580 ExprKind::Struct(
2581 QPath::LangItem(LangItem::RangeTo, _),
2582 [val1],
2583 StructTailExpr::None,
2584 ),
2585 ExprKind::Struct(
2586 QPath::LangItem(LangItem::RangeTo, _),
2587 [val2],
2588 StructTailExpr::None,
2589 ),
2590 )
2591 | (
2592 ExprKind::Struct(
2593 QPath::LangItem(LangItem::RangeToInclusive, _),
2594 [val1],
2595 StructTailExpr::None,
2596 ),
2597 ExprKind::Struct(
2598 QPath::LangItem(LangItem::RangeToInclusive, _),
2599 [val2],
2600 StructTailExpr::None,
2601 ),
2602 )
2603 | (
2604 ExprKind::Struct(
2605 QPath::LangItem(LangItem::RangeFrom, _),
2606 [val1],
2607 StructTailExpr::None,
2608 ),
2609 ExprKind::Struct(
2610 QPath::LangItem(LangItem::RangeFrom, _),
2611 [val2],
2612 StructTailExpr::None,
2613 ),
2614 )
2615 | (
2616 ExprKind::Struct(
2617 QPath::LangItem(LangItem::RangeFromCopy, _),
2618 [val1],
2619 StructTailExpr::None,
2620 ),
2621 ExprKind::Struct(
2622 QPath::LangItem(LangItem::RangeFromCopy, _),
2623 [val2],
2624 StructTailExpr::None,
2625 ),
2626 ) => val1.expr.equivalent_for_indexing(val2.expr),
2627 (
2628 ExprKind::Struct(
2629 QPath::LangItem(LangItem::Range, _),
2630 [val1, val3],
2631 StructTailExpr::None,
2632 ),
2633 ExprKind::Struct(
2634 QPath::LangItem(LangItem::Range, _),
2635 [val2, val4],
2636 StructTailExpr::None,
2637 ),
2638 )
2639 | (
2640 ExprKind::Struct(
2641 QPath::LangItem(LangItem::RangeCopy, _),
2642 [val1, val3],
2643 StructTailExpr::None,
2644 ),
2645 ExprKind::Struct(
2646 QPath::LangItem(LangItem::RangeCopy, _),
2647 [val2, val4],
2648 StructTailExpr::None,
2649 ),
2650 )
2651 | (
2652 ExprKind::Struct(
2653 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2654 [val1, val3],
2655 StructTailExpr::None,
2656 ),
2657 ExprKind::Struct(
2658 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2659 [val2, val4],
2660 StructTailExpr::None,
2661 ),
2662 ) => {
2663 val1.expr.equivalent_for_indexing(val2.expr)
2664 && val3.expr.equivalent_for_indexing(val4.expr)
2665 }
2666 _ => false,
2667 }
2668 }
2669
2670 pub fn method_ident(&self) -> Option<Ident> {
2671 match self.kind {
2672 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2673 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2674 _ => None,
2675 }
2676 }
2677}
2678
2679pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2682 match expr.kind {
2683 ExprKind::Struct(ref qpath, _, _) => matches!(
2685 **qpath,
2686 QPath::LangItem(
2687 LangItem::Range
2688 | LangItem::RangeTo
2689 | LangItem::RangeFrom
2690 | LangItem::RangeFull
2691 | LangItem::RangeToInclusive
2692 | LangItem::RangeCopy
2693 | LangItem::RangeFromCopy
2694 | LangItem::RangeInclusiveCopy,
2695 ..
2696 )
2697 ),
2698
2699 ExprKind::Call(ref func, _) => {
2701 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
2702 }
2703
2704 _ => false,
2705 }
2706}
2707
2708pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2715 match expr.kind {
2716 ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2718 _ if is_range_literal(expr) => true,
2720 _ => false,
2721 }
2722}
2723
2724#[derive(Debug, Clone, Copy, HashStable_Generic)]
2725pub enum ExprKind<'hir> {
2726 ConstBlock(ConstBlock),
2728 Array(&'hir [Expr<'hir>]),
2730 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2737 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2754 Use(&'hir Expr<'hir>, Span),
2756 Tup(&'hir [Expr<'hir>]),
2758 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2760 Unary(UnOp, &'hir Expr<'hir>),
2762 Lit(Lit),
2764 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2766 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2768 DropTemps(&'hir Expr<'hir>),
2774 Let(&'hir LetExpr<'hir>),
2779 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2788 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2794 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2797 Closure(&'hir Closure<'hir>),
2804 Block(&'hir Block<'hir>, Option<Label>),
2806
2807 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2809 AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2813 Field(&'hir Expr<'hir>, Ident),
2815 Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2819
2820 Path(QPath<'hir>),
2822
2823 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2825 Break(Destination, Option<&'hir Expr<'hir>>),
2827 Continue(Destination),
2829 Ret(Option<&'hir Expr<'hir>>),
2831 Become(&'hir Expr<'hir>),
2833
2834 InlineAsm(&'hir InlineAsm<'hir>),
2836
2837 OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2839
2840 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2845
2846 Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2851
2852 Yield(&'hir Expr<'hir>, YieldSource),
2854
2855 UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2858
2859 Err(rustc_span::ErrorGuaranteed),
2861}
2862
2863#[derive(Debug, Clone, Copy, HashStable_Generic)]
2864pub enum StructTailExpr<'hir> {
2865 None,
2867 Base(&'hir Expr<'hir>),
2870 DefaultFields(Span),
2874}
2875
2876#[derive(Debug, Clone, Copy, HashStable_Generic)]
2882pub enum QPath<'hir> {
2883 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2890
2891 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2898
2899 LangItem(LangItem, Span),
2901}
2902
2903impl<'hir> QPath<'hir> {
2904 pub fn span(&self) -> Span {
2906 match *self {
2907 QPath::Resolved(_, path) => path.span,
2908 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2909 QPath::LangItem(_, span) => span,
2910 }
2911 }
2912
2913 pub fn qself_span(&self) -> Span {
2916 match *self {
2917 QPath::Resolved(_, path) => path.span,
2918 QPath::TypeRelative(qself, _) => qself.span,
2919 QPath::LangItem(_, span) => span,
2920 }
2921 }
2922}
2923
2924#[derive(Copy, Clone, Debug, HashStable_Generic)]
2926pub enum LocalSource {
2927 Normal,
2929 AsyncFn,
2940 AwaitDesugar,
2942 AssignDesugar(Span),
2945 Contract,
2947}
2948
2949#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2951pub enum MatchSource {
2952 Normal,
2954 Postfix,
2956 ForLoopDesugar,
2958 TryDesugar(HirId),
2960 AwaitDesugar,
2962 FormatArgs,
2964}
2965
2966impl MatchSource {
2967 #[inline]
2968 pub const fn name(self) -> &'static str {
2969 use MatchSource::*;
2970 match self {
2971 Normal => "match",
2972 Postfix => ".match",
2973 ForLoopDesugar => "for",
2974 TryDesugar(_) => "?",
2975 AwaitDesugar => ".await",
2976 FormatArgs => "format_args!()",
2977 }
2978 }
2979}
2980
2981#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2983pub enum LoopSource {
2984 Loop,
2986 While,
2988 ForLoop,
2990}
2991
2992impl LoopSource {
2993 pub fn name(self) -> &'static str {
2994 match self {
2995 LoopSource::Loop => "loop",
2996 LoopSource::While => "while",
2997 LoopSource::ForLoop => "for",
2998 }
2999 }
3000}
3001
3002#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
3003pub enum LoopIdError {
3004 OutsideLoopScope,
3005 UnlabeledCfInWhileCondition,
3006 UnresolvedLabel,
3007}
3008
3009impl fmt::Display for LoopIdError {
3010 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3011 f.write_str(match self {
3012 LoopIdError::OutsideLoopScope => "not inside loop scope",
3013 LoopIdError::UnlabeledCfInWhileCondition => {
3014 "unlabeled control flow (break or continue) in while condition"
3015 }
3016 LoopIdError::UnresolvedLabel => "label not found",
3017 })
3018 }
3019}
3020
3021#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
3022pub struct Destination {
3023 pub label: Option<Label>,
3025
3026 pub target_id: Result<HirId, LoopIdError>,
3029}
3030
3031#[derive(Copy, Clone, Debug, HashStable_Generic)]
3033pub enum YieldSource {
3034 Await { expr: Option<HirId> },
3036 Yield,
3038}
3039
3040impl fmt::Display for YieldSource {
3041 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3042 f.write_str(match self {
3043 YieldSource::Await { .. } => "`await`",
3044 YieldSource::Yield => "`yield`",
3045 })
3046 }
3047}
3048
3049#[derive(Debug, Clone, Copy, HashStable_Generic)]
3052pub struct MutTy<'hir> {
3053 pub ty: &'hir Ty<'hir>,
3054 pub mutbl: Mutability,
3055}
3056
3057#[derive(Debug, Clone, Copy, HashStable_Generic)]
3060pub struct FnSig<'hir> {
3061 pub header: FnHeader,
3062 pub decl: &'hir FnDecl<'hir>,
3063 pub span: Span,
3064}
3065
3066#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3070pub struct TraitItemId {
3071 pub owner_id: OwnerId,
3072}
3073
3074impl TraitItemId {
3075 #[inline]
3076 pub fn hir_id(&self) -> HirId {
3077 HirId::make_owner(self.owner_id.def_id)
3079 }
3080}
3081
3082#[derive(Debug, Clone, Copy, HashStable_Generic)]
3087pub struct TraitItem<'hir> {
3088 pub ident: Ident,
3089 pub owner_id: OwnerId,
3090 pub generics: &'hir Generics<'hir>,
3091 pub kind: TraitItemKind<'hir>,
3092 pub span: Span,
3093 pub defaultness: Defaultness,
3094 pub has_delayed_lints: bool,
3095}
3096
3097macro_rules! expect_methods_self_kind {
3098 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3099 $(
3100 #[track_caller]
3101 pub fn $name(&self) -> $ret_ty {
3102 let $pat = &self.kind else { expect_failed(stringify!($ident), self) };
3103 $ret_val
3104 }
3105 )*
3106 }
3107}
3108
3109macro_rules! expect_methods_self {
3110 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3111 $(
3112 #[track_caller]
3113 pub fn $name(&self) -> $ret_ty {
3114 let $pat = self else { expect_failed(stringify!($ident), self) };
3115 $ret_val
3116 }
3117 )*
3118 }
3119}
3120
3121#[track_caller]
3122fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3123 panic!("{ident}: found {found:?}")
3124}
3125
3126impl<'hir> TraitItem<'hir> {
3127 #[inline]
3128 pub fn hir_id(&self) -> HirId {
3129 HirId::make_owner(self.owner_id.def_id)
3131 }
3132
3133 pub fn trait_item_id(&self) -> TraitItemId {
3134 TraitItemId { owner_id: self.owner_id }
3135 }
3136
3137 expect_methods_self_kind! {
3138 expect_const, (&'hir Ty<'hir>, Option<BodyId>),
3139 TraitItemKind::Const(ty, body), (ty, *body);
3140
3141 expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3142 TraitItemKind::Fn(ty, trfn), (ty, trfn);
3143
3144 expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3145 TraitItemKind::Type(bounds, ty), (bounds, *ty);
3146 }
3147}
3148
3149#[derive(Debug, Clone, Copy, HashStable_Generic)]
3151pub enum TraitFn<'hir> {
3152 Required(&'hir [Option<Ident>]),
3154
3155 Provided(BodyId),
3157}
3158
3159#[derive(Debug, Clone, Copy, HashStable_Generic)]
3161pub enum TraitItemKind<'hir> {
3162 Const(&'hir Ty<'hir>, Option<BodyId>),
3164 Fn(FnSig<'hir>, TraitFn<'hir>),
3166 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3169}
3170
3171#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3175pub struct ImplItemId {
3176 pub owner_id: OwnerId,
3177}
3178
3179impl ImplItemId {
3180 #[inline]
3181 pub fn hir_id(&self) -> HirId {
3182 HirId::make_owner(self.owner_id.def_id)
3184 }
3185}
3186
3187#[derive(Debug, Clone, Copy, HashStable_Generic)]
3191pub struct ImplItem<'hir> {
3192 pub ident: Ident,
3193 pub owner_id: OwnerId,
3194 pub generics: &'hir Generics<'hir>,
3195 pub kind: ImplItemKind<'hir>,
3196 pub defaultness: Defaultness,
3197 pub span: Span,
3198 pub vis_span: Span,
3199 pub has_delayed_lints: bool,
3200 pub trait_item_def_id: Option<DefId>,
3202}
3203
3204impl<'hir> ImplItem<'hir> {
3205 #[inline]
3206 pub fn hir_id(&self) -> HirId {
3207 HirId::make_owner(self.owner_id.def_id)
3209 }
3210
3211 pub fn impl_item_id(&self) -> ImplItemId {
3212 ImplItemId { owner_id: self.owner_id }
3213 }
3214
3215 expect_methods_self_kind! {
3216 expect_const, (&'hir Ty<'hir>, BodyId), ImplItemKind::Const(ty, body), (ty, *body);
3217 expect_fn, (&FnSig<'hir>, BodyId), ImplItemKind::Fn(ty, body), (ty, *body);
3218 expect_type, &'hir Ty<'hir>, ImplItemKind::Type(ty), ty;
3219 }
3220}
3221
3222#[derive(Debug, Clone, Copy, HashStable_Generic)]
3224pub enum ImplItemKind<'hir> {
3225 Const(&'hir Ty<'hir>, BodyId),
3228 Fn(FnSig<'hir>, BodyId),
3230 Type(&'hir Ty<'hir>),
3232}
3233
3234#[derive(Debug, Clone, Copy, HashStable_Generic)]
3245pub struct AssocItemConstraint<'hir> {
3246 #[stable_hasher(ignore)]
3247 pub hir_id: HirId,
3248 pub ident: Ident,
3249 pub gen_args: &'hir GenericArgs<'hir>,
3250 pub kind: AssocItemConstraintKind<'hir>,
3251 pub span: Span,
3252}
3253
3254impl<'hir> AssocItemConstraint<'hir> {
3255 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3257 match self.kind {
3258 AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3259 _ => None,
3260 }
3261 }
3262
3263 pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3265 match self.kind {
3266 AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3267 _ => None,
3268 }
3269 }
3270}
3271
3272#[derive(Debug, Clone, Copy, HashStable_Generic)]
3273pub enum Term<'hir> {
3274 Ty(&'hir Ty<'hir>),
3275 Const(&'hir ConstArg<'hir>),
3276}
3277
3278impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3279 fn from(ty: &'hir Ty<'hir>) -> Self {
3280 Term::Ty(ty)
3281 }
3282}
3283
3284impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3285 fn from(c: &'hir ConstArg<'hir>) -> Self {
3286 Term::Const(c)
3287 }
3288}
3289
3290#[derive(Debug, Clone, Copy, HashStable_Generic)]
3292pub enum AssocItemConstraintKind<'hir> {
3293 Equality { term: Term<'hir> },
3300 Bound { bounds: &'hir [GenericBound<'hir>] },
3302}
3303
3304impl<'hir> AssocItemConstraintKind<'hir> {
3305 pub fn descr(&self) -> &'static str {
3306 match self {
3307 AssocItemConstraintKind::Equality { .. } => "binding",
3308 AssocItemConstraintKind::Bound { .. } => "constraint",
3309 }
3310 }
3311}
3312
3313#[derive(Debug, Clone, Copy, HashStable_Generic)]
3317pub enum AmbigArg {}
3318
3319#[derive(Debug, Clone, Copy, HashStable_Generic)]
3324#[repr(C)]
3325pub struct Ty<'hir, Unambig = ()> {
3326 #[stable_hasher(ignore)]
3327 pub hir_id: HirId,
3328 pub span: Span,
3329 pub kind: TyKind<'hir, Unambig>,
3330}
3331
3332impl<'hir> Ty<'hir, AmbigArg> {
3333 pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3344 let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3347 unsafe { &*ptr }
3348 }
3349}
3350
3351impl<'hir> Ty<'hir> {
3352 pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3358 if let TyKind::Infer(()) = self.kind {
3359 return None;
3360 }
3361
3362 let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3366 Some(unsafe { &*ptr })
3367 }
3368}
3369
3370impl<'hir> Ty<'hir, AmbigArg> {
3371 pub fn peel_refs(&self) -> &Ty<'hir> {
3372 let mut final_ty = self.as_unambig_ty();
3373 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3374 final_ty = ty;
3375 }
3376 final_ty
3377 }
3378}
3379
3380impl<'hir> Ty<'hir> {
3381 pub fn peel_refs(&self) -> &Self {
3382 let mut final_ty = self;
3383 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3384 final_ty = ty;
3385 }
3386 final_ty
3387 }
3388
3389 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3391 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3392 return None;
3393 };
3394 let [segment] = &path.segments else {
3395 return None;
3396 };
3397 match path.res {
3398 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3399 Some((def_id, segment.ident))
3400 }
3401 _ => None,
3402 }
3403 }
3404
3405 pub fn find_self_aliases(&self) -> Vec<Span> {
3406 use crate::intravisit::Visitor;
3407 struct MyVisitor(Vec<Span>);
3408 impl<'v> Visitor<'v> for MyVisitor {
3409 fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3410 if matches!(
3411 &t.kind,
3412 TyKind::Path(QPath::Resolved(
3413 _,
3414 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3415 ))
3416 ) {
3417 self.0.push(t.span);
3418 return;
3419 }
3420 crate::intravisit::walk_ty(self, t);
3421 }
3422 }
3423
3424 let mut my_visitor = MyVisitor(vec![]);
3425 my_visitor.visit_ty_unambig(self);
3426 my_visitor.0
3427 }
3428
3429 pub fn is_suggestable_infer_ty(&self) -> bool {
3432 fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3433 generic_args.iter().any(|arg| match arg {
3434 GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3435 GenericArg::Infer(_) => true,
3436 _ => false,
3437 })
3438 }
3439 debug!(?self);
3440 match &self.kind {
3441 TyKind::Infer(()) => true,
3442 TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3443 TyKind::Array(ty, length) => {
3444 ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3445 }
3446 TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3447 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3448 TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3449 ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3450 }
3451 TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3452 ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3453 || segments
3454 .iter()
3455 .any(|segment| are_suggestable_generic_args(segment.args().args))
3456 }
3457 _ => false,
3458 }
3459 }
3460}
3461
3462#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3464pub enum PrimTy {
3465 Int(IntTy),
3466 Uint(UintTy),
3467 Float(FloatTy),
3468 Str,
3469 Bool,
3470 Char,
3471}
3472
3473impl PrimTy {
3474 pub const ALL: [Self; 19] = [
3476 Self::Int(IntTy::I8),
3478 Self::Int(IntTy::I16),
3479 Self::Int(IntTy::I32),
3480 Self::Int(IntTy::I64),
3481 Self::Int(IntTy::I128),
3482 Self::Int(IntTy::Isize),
3483 Self::Uint(UintTy::U8),
3484 Self::Uint(UintTy::U16),
3485 Self::Uint(UintTy::U32),
3486 Self::Uint(UintTy::U64),
3487 Self::Uint(UintTy::U128),
3488 Self::Uint(UintTy::Usize),
3489 Self::Float(FloatTy::F16),
3490 Self::Float(FloatTy::F32),
3491 Self::Float(FloatTy::F64),
3492 Self::Float(FloatTy::F128),
3493 Self::Bool,
3494 Self::Char,
3495 Self::Str,
3496 ];
3497
3498 pub fn name_str(self) -> &'static str {
3502 match self {
3503 PrimTy::Int(i) => i.name_str(),
3504 PrimTy::Uint(u) => u.name_str(),
3505 PrimTy::Float(f) => f.name_str(),
3506 PrimTy::Str => "str",
3507 PrimTy::Bool => "bool",
3508 PrimTy::Char => "char",
3509 }
3510 }
3511
3512 pub fn name(self) -> Symbol {
3513 match self {
3514 PrimTy::Int(i) => i.name(),
3515 PrimTy::Uint(u) => u.name(),
3516 PrimTy::Float(f) => f.name(),
3517 PrimTy::Str => sym::str,
3518 PrimTy::Bool => sym::bool,
3519 PrimTy::Char => sym::char,
3520 }
3521 }
3522
3523 pub fn from_name(name: Symbol) -> Option<Self> {
3526 let ty = match name {
3527 sym::i8 => Self::Int(IntTy::I8),
3529 sym::i16 => Self::Int(IntTy::I16),
3530 sym::i32 => Self::Int(IntTy::I32),
3531 sym::i64 => Self::Int(IntTy::I64),
3532 sym::i128 => Self::Int(IntTy::I128),
3533 sym::isize => Self::Int(IntTy::Isize),
3534 sym::u8 => Self::Uint(UintTy::U8),
3535 sym::u16 => Self::Uint(UintTy::U16),
3536 sym::u32 => Self::Uint(UintTy::U32),
3537 sym::u64 => Self::Uint(UintTy::U64),
3538 sym::u128 => Self::Uint(UintTy::U128),
3539 sym::usize => Self::Uint(UintTy::Usize),
3540 sym::f16 => Self::Float(FloatTy::F16),
3541 sym::f32 => Self::Float(FloatTy::F32),
3542 sym::f64 => Self::Float(FloatTy::F64),
3543 sym::f128 => Self::Float(FloatTy::F128),
3544 sym::bool => Self::Bool,
3545 sym::char => Self::Char,
3546 sym::str => Self::Str,
3547 _ => return None,
3548 };
3549 Some(ty)
3550 }
3551}
3552
3553#[derive(Debug, Clone, Copy, HashStable_Generic)]
3554pub struct FnPtrTy<'hir> {
3555 pub safety: Safety,
3556 pub abi: ExternAbi,
3557 pub generic_params: &'hir [GenericParam<'hir>],
3558 pub decl: &'hir FnDecl<'hir>,
3559 pub param_idents: &'hir [Option<Ident>],
3562}
3563
3564#[derive(Debug, Clone, Copy, HashStable_Generic)]
3565pub struct UnsafeBinderTy<'hir> {
3566 pub generic_params: &'hir [GenericParam<'hir>],
3567 pub inner_ty: &'hir Ty<'hir>,
3568}
3569
3570#[derive(Debug, Clone, Copy, HashStable_Generic)]
3571pub struct OpaqueTy<'hir> {
3572 #[stable_hasher(ignore)]
3573 pub hir_id: HirId,
3574 pub def_id: LocalDefId,
3575 pub bounds: GenericBounds<'hir>,
3576 pub origin: OpaqueTyOrigin<LocalDefId>,
3577 pub span: Span,
3578}
3579
3580#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3581pub enum PreciseCapturingArgKind<T, U> {
3582 Lifetime(T),
3583 Param(U),
3585}
3586
3587pub type PreciseCapturingArg<'hir> =
3588 PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3589
3590impl PreciseCapturingArg<'_> {
3591 pub fn hir_id(self) -> HirId {
3592 match self {
3593 PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3594 PreciseCapturingArg::Param(param) => param.hir_id,
3595 }
3596 }
3597
3598 pub fn name(self) -> Symbol {
3599 match self {
3600 PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3601 PreciseCapturingArg::Param(param) => param.ident.name,
3602 }
3603 }
3604}
3605
3606#[derive(Debug, Clone, Copy, HashStable_Generic)]
3611pub struct PreciseCapturingNonLifetimeArg {
3612 #[stable_hasher(ignore)]
3613 pub hir_id: HirId,
3614 pub ident: Ident,
3615 pub res: Res,
3616}
3617
3618#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3619#[derive(HashStable_Generic, Encodable, Decodable)]
3620pub enum RpitContext {
3621 Trait,
3622 TraitImpl,
3623}
3624
3625#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3627#[derive(HashStable_Generic, Encodable, Decodable)]
3628pub enum OpaqueTyOrigin<D> {
3629 FnReturn {
3631 parent: D,
3633 in_trait_or_impl: Option<RpitContext>,
3635 },
3636 AsyncFn {
3638 parent: D,
3640 in_trait_or_impl: Option<RpitContext>,
3642 },
3643 TyAlias {
3645 parent: D,
3647 in_assoc_ty: bool,
3649 },
3650}
3651
3652#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3653pub enum InferDelegationKind {
3654 Input(usize),
3655 Output,
3656}
3657
3658#[repr(u8, C)]
3664#[derive(Debug, Clone, Copy, HashStable_Generic)]
3665pub enum TyKind<'hir, Unambig = ()> {
3666 InferDelegation(DefId, InferDelegationKind),
3668 Slice(&'hir Ty<'hir>),
3670 Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3672 Ptr(MutTy<'hir>),
3674 Ref(&'hir Lifetime, MutTy<'hir>),
3676 FnPtr(&'hir FnPtrTy<'hir>),
3678 UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3680 Never,
3682 Tup(&'hir [Ty<'hir>]),
3684 Path(QPath<'hir>),
3689 OpaqueDef(&'hir OpaqueTy<'hir>),
3691 TraitAscription(GenericBounds<'hir>),
3693 TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3699 Typeof(&'hir AnonConst),
3701 Err(rustc_span::ErrorGuaranteed),
3703 Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3705 Infer(Unambig),
3711}
3712
3713#[derive(Debug, Clone, Copy, HashStable_Generic)]
3714pub enum InlineAsmOperand<'hir> {
3715 In {
3716 reg: InlineAsmRegOrRegClass,
3717 expr: &'hir Expr<'hir>,
3718 },
3719 Out {
3720 reg: InlineAsmRegOrRegClass,
3721 late: bool,
3722 expr: Option<&'hir Expr<'hir>>,
3723 },
3724 InOut {
3725 reg: InlineAsmRegOrRegClass,
3726 late: bool,
3727 expr: &'hir Expr<'hir>,
3728 },
3729 SplitInOut {
3730 reg: InlineAsmRegOrRegClass,
3731 late: bool,
3732 in_expr: &'hir Expr<'hir>,
3733 out_expr: Option<&'hir Expr<'hir>>,
3734 },
3735 Const {
3736 anon_const: ConstBlock,
3737 },
3738 SymFn {
3739 expr: &'hir Expr<'hir>,
3740 },
3741 SymStatic {
3742 path: QPath<'hir>,
3743 def_id: DefId,
3744 },
3745 Label {
3746 block: &'hir Block<'hir>,
3747 },
3748}
3749
3750impl<'hir> InlineAsmOperand<'hir> {
3751 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3752 match *self {
3753 Self::In { reg, .. }
3754 | Self::Out { reg, .. }
3755 | Self::InOut { reg, .. }
3756 | Self::SplitInOut { reg, .. } => Some(reg),
3757 Self::Const { .. }
3758 | Self::SymFn { .. }
3759 | Self::SymStatic { .. }
3760 | Self::Label { .. } => None,
3761 }
3762 }
3763
3764 pub fn is_clobber(&self) -> bool {
3765 matches!(
3766 self,
3767 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3768 )
3769 }
3770}
3771
3772#[derive(Debug, Clone, Copy, HashStable_Generic)]
3773pub struct InlineAsm<'hir> {
3774 pub asm_macro: ast::AsmMacro,
3775 pub template: &'hir [InlineAsmTemplatePiece],
3776 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3777 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3778 pub options: InlineAsmOptions,
3779 pub line_spans: &'hir [Span],
3780}
3781
3782impl InlineAsm<'_> {
3783 pub fn contains_label(&self) -> bool {
3784 self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3785 }
3786}
3787
3788#[derive(Debug, Clone, Copy, HashStable_Generic)]
3790pub struct Param<'hir> {
3791 #[stable_hasher(ignore)]
3792 pub hir_id: HirId,
3793 pub pat: &'hir Pat<'hir>,
3794 pub ty_span: Span,
3795 pub span: Span,
3796}
3797
3798#[derive(Debug, Clone, Copy, HashStable_Generic)]
3800pub struct FnDecl<'hir> {
3801 pub inputs: &'hir [Ty<'hir>],
3805 pub output: FnRetTy<'hir>,
3806 pub c_variadic: bool,
3807 pub implicit_self: ImplicitSelfKind,
3809 pub lifetime_elision_allowed: bool,
3811}
3812
3813impl<'hir> FnDecl<'hir> {
3814 pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3815 if let FnRetTy::Return(ty) = self.output
3816 && let TyKind::InferDelegation(sig_id, _) = ty.kind
3817 {
3818 return Some(sig_id);
3819 }
3820 None
3821 }
3822}
3823
3824#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3826pub enum ImplicitSelfKind {
3827 Imm,
3829 Mut,
3831 RefImm,
3833 RefMut,
3835 None,
3838}
3839
3840impl ImplicitSelfKind {
3841 pub fn has_implicit_self(&self) -> bool {
3843 !matches!(*self, ImplicitSelfKind::None)
3844 }
3845}
3846
3847#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3848pub enum IsAsync {
3849 Async(Span),
3850 NotAsync,
3851}
3852
3853impl IsAsync {
3854 pub fn is_async(self) -> bool {
3855 matches!(self, IsAsync::Async(_))
3856 }
3857}
3858
3859#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3860pub enum Defaultness {
3861 Default { has_value: bool },
3862 Final,
3863}
3864
3865impl Defaultness {
3866 pub fn has_value(&self) -> bool {
3867 match *self {
3868 Defaultness::Default { has_value } => has_value,
3869 Defaultness::Final => true,
3870 }
3871 }
3872
3873 pub fn is_final(&self) -> bool {
3874 *self == Defaultness::Final
3875 }
3876
3877 pub fn is_default(&self) -> bool {
3878 matches!(*self, Defaultness::Default { .. })
3879 }
3880}
3881
3882#[derive(Debug, Clone, Copy, HashStable_Generic)]
3883pub enum FnRetTy<'hir> {
3884 DefaultReturn(Span),
3890 Return(&'hir Ty<'hir>),
3892}
3893
3894impl<'hir> FnRetTy<'hir> {
3895 #[inline]
3896 pub fn span(&self) -> Span {
3897 match *self {
3898 Self::DefaultReturn(span) => span,
3899 Self::Return(ref ty) => ty.span,
3900 }
3901 }
3902
3903 pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3904 if let Self::Return(ty) = self
3905 && ty.is_suggestable_infer_ty()
3906 {
3907 return Some(*ty);
3908 }
3909 None
3910 }
3911}
3912
3913#[derive(Copy, Clone, Debug, HashStable_Generic)]
3915pub enum ClosureBinder {
3916 Default,
3918 For { span: Span },
3922}
3923
3924#[derive(Debug, Clone, Copy, HashStable_Generic)]
3925pub struct Mod<'hir> {
3926 pub spans: ModSpans,
3927 pub item_ids: &'hir [ItemId],
3928}
3929
3930#[derive(Copy, Clone, Debug, HashStable_Generic)]
3931pub struct ModSpans {
3932 pub inner_span: Span,
3936 pub inject_use_span: Span,
3937}
3938
3939#[derive(Debug, Clone, Copy, HashStable_Generic)]
3940pub struct EnumDef<'hir> {
3941 pub variants: &'hir [Variant<'hir>],
3942}
3943
3944#[derive(Debug, Clone, Copy, HashStable_Generic)]
3945pub struct Variant<'hir> {
3946 pub ident: Ident,
3948 #[stable_hasher(ignore)]
3950 pub hir_id: HirId,
3951 pub def_id: LocalDefId,
3952 pub data: VariantData<'hir>,
3954 pub disr_expr: Option<&'hir AnonConst>,
3956 pub span: Span,
3958}
3959
3960#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3961pub enum UseKind {
3962 Single(Ident),
3969
3970 Glob,
3972
3973 ListStem,
3977}
3978
3979#[derive(Clone, Debug, Copy, HashStable_Generic)]
3986pub struct TraitRef<'hir> {
3987 pub path: &'hir Path<'hir>,
3988 #[stable_hasher(ignore)]
3990 pub hir_ref_id: HirId,
3991}
3992
3993impl TraitRef<'_> {
3994 pub fn trait_def_id(&self) -> Option<DefId> {
3996 match self.path.res {
3997 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3998 Res::Err => None,
3999 res => panic!("{res:?} did not resolve to a trait or trait alias"),
4000 }
4001 }
4002}
4003
4004#[derive(Clone, Debug, Copy, HashStable_Generic)]
4005pub struct PolyTraitRef<'hir> {
4006 pub bound_generic_params: &'hir [GenericParam<'hir>],
4008
4009 pub modifiers: TraitBoundModifiers,
4013
4014 pub trait_ref: TraitRef<'hir>,
4016
4017 pub span: Span,
4018}
4019
4020#[derive(Debug, Clone, Copy, HashStable_Generic)]
4021pub struct FieldDef<'hir> {
4022 pub span: Span,
4023 pub vis_span: Span,
4024 pub ident: Ident,
4025 #[stable_hasher(ignore)]
4026 pub hir_id: HirId,
4027 pub def_id: LocalDefId,
4028 pub ty: &'hir Ty<'hir>,
4029 pub safety: Safety,
4030 pub default: Option<&'hir AnonConst>,
4031}
4032
4033impl FieldDef<'_> {
4034 pub fn is_positional(&self) -> bool {
4036 self.ident.as_str().as_bytes()[0].is_ascii_digit()
4037 }
4038}
4039
4040#[derive(Debug, Clone, Copy, HashStable_Generic)]
4042pub enum VariantData<'hir> {
4043 Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4047 Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4051 Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4055}
4056
4057impl<'hir> VariantData<'hir> {
4058 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4060 match *self {
4061 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4062 _ => &[],
4063 }
4064 }
4065
4066 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4067 match *self {
4068 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4069 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4070 VariantData::Struct { .. } => None,
4071 }
4072 }
4073
4074 #[inline]
4075 pub fn ctor_kind(&self) -> Option<CtorKind> {
4076 self.ctor().map(|(kind, ..)| kind)
4077 }
4078
4079 #[inline]
4081 pub fn ctor_hir_id(&self) -> Option<HirId> {
4082 self.ctor().map(|(_, hir_id, _)| hir_id)
4083 }
4084
4085 #[inline]
4087 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4088 self.ctor().map(|(.., def_id)| def_id)
4089 }
4090}
4091
4092#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4096pub struct ItemId {
4097 pub owner_id: OwnerId,
4098}
4099
4100impl ItemId {
4101 #[inline]
4102 pub fn hir_id(&self) -> HirId {
4103 HirId::make_owner(self.owner_id.def_id)
4105 }
4106}
4107
4108#[derive(Debug, Clone, Copy, HashStable_Generic)]
4117pub struct Item<'hir> {
4118 pub owner_id: OwnerId,
4119 pub kind: ItemKind<'hir>,
4120 pub span: Span,
4121 pub vis_span: Span,
4122 pub has_delayed_lints: bool,
4123}
4124
4125impl<'hir> Item<'hir> {
4126 #[inline]
4127 pub fn hir_id(&self) -> HirId {
4128 HirId::make_owner(self.owner_id.def_id)
4130 }
4131
4132 pub fn item_id(&self) -> ItemId {
4133 ItemId { owner_id: self.owner_id }
4134 }
4135
4136 pub fn is_adt(&self) -> bool {
4139 matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4140 }
4141
4142 pub fn is_struct_or_union(&self) -> bool {
4144 matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4145 }
4146
4147 expect_methods_self_kind! {
4148 expect_extern_crate, (Option<Symbol>, Ident),
4149 ItemKind::ExternCrate(s, ident), (*s, *ident);
4150
4151 expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4152
4153 expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4154 ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4155
4156 expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, BodyId),
4157 ItemKind::Const(ident, generics, ty, body), (*ident, generics, ty, *body);
4158
4159 expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4160 ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4161
4162 expect_macro, (Ident, &ast::MacroDef, MacroKinds),
4163 ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4164
4165 expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4166
4167 expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]),
4168 ItemKind::ForeignMod { abi, items }, (*abi, items);
4169
4170 expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4171
4172 expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4173 ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4174
4175 expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4176 ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4177
4178 expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4179 ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4180
4181 expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4182 ItemKind::Union(ident, generics, data), (*ident, generics, data);
4183
4184 expect_trait,
4185 (
4186 Constness,
4187 IsAuto,
4188 Safety,
4189 Ident,
4190 &'hir Generics<'hir>,
4191 GenericBounds<'hir>,
4192 &'hir [TraitItemId]
4193 ),
4194 ItemKind::Trait(constness, is_auto, safety, ident, generics, bounds, items),
4195 (*constness, *is_auto, *safety, *ident, generics, bounds, items);
4196
4197 expect_trait_alias, (Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4198 ItemKind::TraitAlias(ident, generics, bounds), (*ident, generics, bounds);
4199
4200 expect_impl, &Impl<'hir>, ItemKind::Impl(imp), imp;
4201 }
4202}
4203
4204#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4205#[derive(Encodable, Decodable, HashStable_Generic)]
4206pub enum Safety {
4207 Unsafe,
4208 Safe,
4209}
4210
4211impl Safety {
4212 pub fn prefix_str(self) -> &'static str {
4213 match self {
4214 Self::Unsafe => "unsafe ",
4215 Self::Safe => "",
4216 }
4217 }
4218
4219 #[inline]
4220 pub fn is_unsafe(self) -> bool {
4221 !self.is_safe()
4222 }
4223
4224 #[inline]
4225 pub fn is_safe(self) -> bool {
4226 match self {
4227 Self::Unsafe => false,
4228 Self::Safe => true,
4229 }
4230 }
4231}
4232
4233impl fmt::Display for Safety {
4234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4235 f.write_str(match *self {
4236 Self::Unsafe => "unsafe",
4237 Self::Safe => "safe",
4238 })
4239 }
4240}
4241
4242#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4243pub enum Constness {
4244 Const,
4245 NotConst,
4246}
4247
4248impl fmt::Display for Constness {
4249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4250 f.write_str(match *self {
4251 Self::Const => "const",
4252 Self::NotConst => "non-const",
4253 })
4254 }
4255}
4256
4257#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4262pub enum HeaderSafety {
4263 SafeTargetFeatures,
4269 Normal(Safety),
4270}
4271
4272impl From<Safety> for HeaderSafety {
4273 fn from(v: Safety) -> Self {
4274 Self::Normal(v)
4275 }
4276}
4277
4278#[derive(Copy, Clone, Debug, HashStable_Generic)]
4279pub struct FnHeader {
4280 pub safety: HeaderSafety,
4281 pub constness: Constness,
4282 pub asyncness: IsAsync,
4283 pub abi: ExternAbi,
4284}
4285
4286impl FnHeader {
4287 pub fn is_async(&self) -> bool {
4288 matches!(self.asyncness, IsAsync::Async(_))
4289 }
4290
4291 pub fn is_const(&self) -> bool {
4292 matches!(self.constness, Constness::Const)
4293 }
4294
4295 pub fn is_unsafe(&self) -> bool {
4296 self.safety().is_unsafe()
4297 }
4298
4299 pub fn is_safe(&self) -> bool {
4300 self.safety().is_safe()
4301 }
4302
4303 pub fn safety(&self) -> Safety {
4304 match self.safety {
4305 HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4306 HeaderSafety::Normal(safety) => safety,
4307 }
4308 }
4309}
4310
4311#[derive(Debug, Clone, Copy, HashStable_Generic)]
4312pub enum ItemKind<'hir> {
4313 ExternCrate(Option<Symbol>, Ident),
4317
4318 Use(&'hir UsePath<'hir>, UseKind),
4324
4325 Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4327 Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, BodyId),
4329 Fn {
4331 sig: FnSig<'hir>,
4332 ident: Ident,
4333 generics: &'hir Generics<'hir>,
4334 body: BodyId,
4335 has_body: bool,
4339 },
4340 Macro(Ident, &'hir ast::MacroDef, MacroKinds),
4342 Mod(Ident, &'hir Mod<'hir>),
4344 ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] },
4346 GlobalAsm {
4348 asm: &'hir InlineAsm<'hir>,
4349 fake_body: BodyId,
4355 },
4356 TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4358 Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4360 Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4362 Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4364 Trait(
4366 Constness,
4367 IsAuto,
4368 Safety,
4369 Ident,
4370 &'hir Generics<'hir>,
4371 GenericBounds<'hir>,
4372 &'hir [TraitItemId],
4373 ),
4374 TraitAlias(Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4376
4377 Impl(Impl<'hir>),
4379}
4380
4381#[derive(Debug, Clone, Copy, HashStable_Generic)]
4386pub struct Impl<'hir> {
4387 pub generics: &'hir Generics<'hir>,
4388 pub of_trait: Option<&'hir TraitImplHeader<'hir>>,
4389 pub self_ty: &'hir Ty<'hir>,
4390 pub items: &'hir [ImplItemId],
4391}
4392
4393#[derive(Debug, Clone, Copy, HashStable_Generic)]
4394pub struct TraitImplHeader<'hir> {
4395 pub constness: Constness,
4396 pub safety: Safety,
4397 pub polarity: ImplPolarity,
4398 pub defaultness: Defaultness,
4399 pub defaultness_span: Option<Span>,
4402 pub trait_ref: TraitRef<'hir>,
4403}
4404
4405impl ItemKind<'_> {
4406 pub fn ident(&self) -> Option<Ident> {
4407 match *self {
4408 ItemKind::ExternCrate(_, ident)
4409 | ItemKind::Use(_, UseKind::Single(ident))
4410 | ItemKind::Static(_, ident, ..)
4411 | ItemKind::Const(ident, ..)
4412 | ItemKind::Fn { ident, .. }
4413 | ItemKind::Macro(ident, ..)
4414 | ItemKind::Mod(ident, ..)
4415 | ItemKind::TyAlias(ident, ..)
4416 | ItemKind::Enum(ident, ..)
4417 | ItemKind::Struct(ident, ..)
4418 | ItemKind::Union(ident, ..)
4419 | ItemKind::Trait(_, _, _, ident, ..)
4420 | ItemKind::TraitAlias(ident, ..) => Some(ident),
4421
4422 ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4423 | ItemKind::ForeignMod { .. }
4424 | ItemKind::GlobalAsm { .. }
4425 | ItemKind::Impl(_) => None,
4426 }
4427 }
4428
4429 pub fn generics(&self) -> Option<&Generics<'_>> {
4430 Some(match self {
4431 ItemKind::Fn { generics, .. }
4432 | ItemKind::TyAlias(_, generics, _)
4433 | ItemKind::Const(_, generics, _, _)
4434 | ItemKind::Enum(_, generics, _)
4435 | ItemKind::Struct(_, generics, _)
4436 | ItemKind::Union(_, generics, _)
4437 | ItemKind::Trait(_, _, _, _, generics, _, _)
4438 | ItemKind::TraitAlias(_, generics, _)
4439 | ItemKind::Impl(Impl { generics, .. }) => generics,
4440 _ => return None,
4441 })
4442 }
4443}
4444
4445#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4449pub struct ForeignItemId {
4450 pub owner_id: OwnerId,
4451}
4452
4453impl ForeignItemId {
4454 #[inline]
4455 pub fn hir_id(&self) -> HirId {
4456 HirId::make_owner(self.owner_id.def_id)
4458 }
4459}
4460
4461#[derive(Debug, Clone, Copy, HashStable_Generic)]
4462pub struct ForeignItem<'hir> {
4463 pub ident: Ident,
4464 pub kind: ForeignItemKind<'hir>,
4465 pub owner_id: OwnerId,
4466 pub span: Span,
4467 pub vis_span: Span,
4468 pub has_delayed_lints: bool,
4469}
4470
4471impl ForeignItem<'_> {
4472 #[inline]
4473 pub fn hir_id(&self) -> HirId {
4474 HirId::make_owner(self.owner_id.def_id)
4476 }
4477
4478 pub fn foreign_item_id(&self) -> ForeignItemId {
4479 ForeignItemId { owner_id: self.owner_id }
4480 }
4481}
4482
4483#[derive(Debug, Clone, Copy, HashStable_Generic)]
4485pub enum ForeignItemKind<'hir> {
4486 Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4493 Static(&'hir Ty<'hir>, Mutability, Safety),
4495 Type,
4497}
4498
4499#[derive(Debug, Copy, Clone, HashStable_Generic)]
4501pub struct Upvar {
4502 pub span: Span,
4504}
4505
4506#[derive(Debug, Clone, HashStable_Generic)]
4510pub struct TraitCandidate {
4511 pub def_id: DefId,
4512 pub import_ids: SmallVec<[LocalDefId; 1]>,
4513}
4514
4515#[derive(Copy, Clone, Debug, HashStable_Generic)]
4516pub enum OwnerNode<'hir> {
4517 Item(&'hir Item<'hir>),
4518 ForeignItem(&'hir ForeignItem<'hir>),
4519 TraitItem(&'hir TraitItem<'hir>),
4520 ImplItem(&'hir ImplItem<'hir>),
4521 Crate(&'hir Mod<'hir>),
4522 Synthetic,
4523}
4524
4525impl<'hir> OwnerNode<'hir> {
4526 pub fn span(&self) -> Span {
4527 match self {
4528 OwnerNode::Item(Item { span, .. })
4529 | OwnerNode::ForeignItem(ForeignItem { span, .. })
4530 | OwnerNode::ImplItem(ImplItem { span, .. })
4531 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4532 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4533 OwnerNode::Synthetic => unreachable!(),
4534 }
4535 }
4536
4537 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4538 match self {
4539 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4540 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4541 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4542 | OwnerNode::ForeignItem(ForeignItem {
4543 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4544 }) => Some(fn_sig),
4545 _ => None,
4546 }
4547 }
4548
4549 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4550 match self {
4551 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4552 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4553 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4554 | OwnerNode::ForeignItem(ForeignItem {
4555 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4556 }) => Some(fn_sig.decl),
4557 _ => None,
4558 }
4559 }
4560
4561 pub fn body_id(&self) -> Option<BodyId> {
4562 match self {
4563 OwnerNode::Item(Item {
4564 kind:
4565 ItemKind::Static(_, _, _, body)
4566 | ItemKind::Const(_, _, _, body)
4567 | ItemKind::Fn { body, .. },
4568 ..
4569 })
4570 | OwnerNode::TraitItem(TraitItem {
4571 kind:
4572 TraitItemKind::Fn(_, TraitFn::Provided(body)) | TraitItemKind::Const(_, Some(body)),
4573 ..
4574 })
4575 | OwnerNode::ImplItem(ImplItem {
4576 kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, body),
4577 ..
4578 }) => Some(*body),
4579 _ => None,
4580 }
4581 }
4582
4583 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4584 Node::generics(self.into())
4585 }
4586
4587 pub fn def_id(self) -> OwnerId {
4588 match self {
4589 OwnerNode::Item(Item { owner_id, .. })
4590 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4591 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4592 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4593 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4594 OwnerNode::Synthetic => unreachable!(),
4595 }
4596 }
4597
4598 pub fn is_impl_block(&self) -> bool {
4600 matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4601 }
4602
4603 expect_methods_self! {
4604 expect_item, &'hir Item<'hir>, OwnerNode::Item(n), n;
4605 expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4606 expect_impl_item, &'hir ImplItem<'hir>, OwnerNode::ImplItem(n), n;
4607 expect_trait_item, &'hir TraitItem<'hir>, OwnerNode::TraitItem(n), n;
4608 }
4609}
4610
4611impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4612 fn from(val: &'hir Item<'hir>) -> Self {
4613 OwnerNode::Item(val)
4614 }
4615}
4616
4617impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4618 fn from(val: &'hir ForeignItem<'hir>) -> Self {
4619 OwnerNode::ForeignItem(val)
4620 }
4621}
4622
4623impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4624 fn from(val: &'hir ImplItem<'hir>) -> Self {
4625 OwnerNode::ImplItem(val)
4626 }
4627}
4628
4629impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4630 fn from(val: &'hir TraitItem<'hir>) -> Self {
4631 OwnerNode::TraitItem(val)
4632 }
4633}
4634
4635impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4636 fn from(val: OwnerNode<'hir>) -> Self {
4637 match val {
4638 OwnerNode::Item(n) => Node::Item(n),
4639 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4640 OwnerNode::ImplItem(n) => Node::ImplItem(n),
4641 OwnerNode::TraitItem(n) => Node::TraitItem(n),
4642 OwnerNode::Crate(n) => Node::Crate(n),
4643 OwnerNode::Synthetic => Node::Synthetic,
4644 }
4645 }
4646}
4647
4648#[derive(Copy, Clone, Debug, HashStable_Generic)]
4649pub enum Node<'hir> {
4650 Param(&'hir Param<'hir>),
4651 Item(&'hir Item<'hir>),
4652 ForeignItem(&'hir ForeignItem<'hir>),
4653 TraitItem(&'hir TraitItem<'hir>),
4654 ImplItem(&'hir ImplItem<'hir>),
4655 Variant(&'hir Variant<'hir>),
4656 Field(&'hir FieldDef<'hir>),
4657 AnonConst(&'hir AnonConst),
4658 ConstBlock(&'hir ConstBlock),
4659 ConstArg(&'hir ConstArg<'hir>),
4660 Expr(&'hir Expr<'hir>),
4661 ExprField(&'hir ExprField<'hir>),
4662 Stmt(&'hir Stmt<'hir>),
4663 PathSegment(&'hir PathSegment<'hir>),
4664 Ty(&'hir Ty<'hir>),
4665 AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4666 TraitRef(&'hir TraitRef<'hir>),
4667 OpaqueTy(&'hir OpaqueTy<'hir>),
4668 TyPat(&'hir TyPat<'hir>),
4669 Pat(&'hir Pat<'hir>),
4670 PatField(&'hir PatField<'hir>),
4671 PatExpr(&'hir PatExpr<'hir>),
4675 Arm(&'hir Arm<'hir>),
4676 Block(&'hir Block<'hir>),
4677 LetStmt(&'hir LetStmt<'hir>),
4678 Ctor(&'hir VariantData<'hir>),
4681 Lifetime(&'hir Lifetime),
4682 GenericParam(&'hir GenericParam<'hir>),
4683 Crate(&'hir Mod<'hir>),
4684 Infer(&'hir InferArg),
4685 WherePredicate(&'hir WherePredicate<'hir>),
4686 PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4687 Synthetic,
4689 Err(Span),
4690}
4691
4692impl<'hir> Node<'hir> {
4693 pub fn ident(&self) -> Option<Ident> {
4708 match self {
4709 Node::Item(item) => item.kind.ident(),
4710 Node::TraitItem(TraitItem { ident, .. })
4711 | Node::ImplItem(ImplItem { ident, .. })
4712 | Node::ForeignItem(ForeignItem { ident, .. })
4713 | Node::Field(FieldDef { ident, .. })
4714 | Node::Variant(Variant { ident, .. })
4715 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4716 Node::Lifetime(lt) => Some(lt.ident),
4717 Node::GenericParam(p) => Some(p.name.ident()),
4718 Node::AssocItemConstraint(c) => Some(c.ident),
4719 Node::PatField(f) => Some(f.ident),
4720 Node::ExprField(f) => Some(f.ident),
4721 Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4722 Node::Param(..)
4723 | Node::AnonConst(..)
4724 | Node::ConstBlock(..)
4725 | Node::ConstArg(..)
4726 | Node::Expr(..)
4727 | Node::Stmt(..)
4728 | Node::Block(..)
4729 | Node::Ctor(..)
4730 | Node::Pat(..)
4731 | Node::TyPat(..)
4732 | Node::PatExpr(..)
4733 | Node::Arm(..)
4734 | Node::LetStmt(..)
4735 | Node::Crate(..)
4736 | Node::Ty(..)
4737 | Node::TraitRef(..)
4738 | Node::OpaqueTy(..)
4739 | Node::Infer(..)
4740 | Node::WherePredicate(..)
4741 | Node::Synthetic
4742 | Node::Err(..) => None,
4743 }
4744 }
4745
4746 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4747 match self {
4748 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4749 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4750 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4751 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4752 Some(fn_sig.decl)
4753 }
4754 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4755 Some(fn_decl)
4756 }
4757 _ => None,
4758 }
4759 }
4760
4761 pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4763 if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4764 && let Some(of_trait) = impl_block.of_trait
4765 && let Some(trait_id) = of_trait.trait_ref.trait_def_id()
4766 && trait_id == trait_def_id
4767 {
4768 Some(impl_block)
4769 } else {
4770 None
4771 }
4772 }
4773
4774 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4775 match self {
4776 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4777 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4778 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4779 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4780 Some(fn_sig)
4781 }
4782 _ => None,
4783 }
4784 }
4785
4786 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4788 match self {
4789 Node::Item(it) => match it.kind {
4790 ItemKind::TyAlias(_, _, ty)
4791 | ItemKind::Static(_, _, ty, _)
4792 | ItemKind::Const(_, _, ty, _) => Some(ty),
4793 ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4794 _ => None,
4795 },
4796 Node::TraitItem(it) => match it.kind {
4797 TraitItemKind::Const(ty, _) => Some(ty),
4798 TraitItemKind::Type(_, ty) => ty,
4799 _ => None,
4800 },
4801 Node::ImplItem(it) => match it.kind {
4802 ImplItemKind::Const(ty, _) => Some(ty),
4803 ImplItemKind::Type(ty) => Some(ty),
4804 _ => None,
4805 },
4806 Node::ForeignItem(it) => match it.kind {
4807 ForeignItemKind::Static(ty, ..) => Some(ty),
4808 _ => None,
4809 },
4810 _ => None,
4811 }
4812 }
4813
4814 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4815 match self {
4816 Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
4817 _ => None,
4818 }
4819 }
4820
4821 #[inline]
4822 pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4823 match self {
4824 Node::Item(Item {
4825 owner_id,
4826 kind:
4827 ItemKind::Const(_, _, _, body)
4828 | ItemKind::Static(.., body)
4829 | ItemKind::Fn { body, .. },
4830 ..
4831 })
4832 | Node::TraitItem(TraitItem {
4833 owner_id,
4834 kind:
4835 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4836 ..
4837 })
4838 | Node::ImplItem(ImplItem {
4839 owner_id,
4840 kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
4841 ..
4842 }) => Some((owner_id.def_id, *body)),
4843
4844 Node::Item(Item {
4845 owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4846 }) => Some((owner_id.def_id, *fake_body)),
4847
4848 Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4849 Some((*def_id, *body))
4850 }
4851
4852 Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4853 Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4854
4855 _ => None,
4856 }
4857 }
4858
4859 pub fn body_id(&self) -> Option<BodyId> {
4860 Some(self.associated_body()?.1)
4861 }
4862
4863 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4864 match self {
4865 Node::ForeignItem(ForeignItem {
4866 kind: ForeignItemKind::Fn(_, _, generics), ..
4867 })
4868 | Node::TraitItem(TraitItem { generics, .. })
4869 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4870 Node::Item(item) => item.kind.generics(),
4871 _ => None,
4872 }
4873 }
4874
4875 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4876 match self {
4877 Node::Item(i) => Some(OwnerNode::Item(i)),
4878 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4879 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4880 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4881 Node::Crate(i) => Some(OwnerNode::Crate(i)),
4882 Node::Synthetic => Some(OwnerNode::Synthetic),
4883 _ => None,
4884 }
4885 }
4886
4887 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4888 match self {
4889 Node::Item(i) => match i.kind {
4890 ItemKind::Fn { ident, sig, generics, .. } => {
4891 Some(FnKind::ItemFn(ident, generics, sig.header))
4892 }
4893 _ => None,
4894 },
4895 Node::TraitItem(ti) => match ti.kind {
4896 TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4897 _ => None,
4898 },
4899 Node::ImplItem(ii) => match ii.kind {
4900 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4901 _ => None,
4902 },
4903 Node::Expr(e) => match e.kind {
4904 ExprKind::Closure { .. } => Some(FnKind::Closure),
4905 _ => None,
4906 },
4907 _ => None,
4908 }
4909 }
4910
4911 expect_methods_self! {
4912 expect_param, &'hir Param<'hir>, Node::Param(n), n;
4913 expect_item, &'hir Item<'hir>, Node::Item(n), n;
4914 expect_foreign_item, &'hir ForeignItem<'hir>, Node::ForeignItem(n), n;
4915 expect_trait_item, &'hir TraitItem<'hir>, Node::TraitItem(n), n;
4916 expect_impl_item, &'hir ImplItem<'hir>, Node::ImplItem(n), n;
4917 expect_variant, &'hir Variant<'hir>, Node::Variant(n), n;
4918 expect_field, &'hir FieldDef<'hir>, Node::Field(n), n;
4919 expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n;
4920 expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n;
4921 expect_expr, &'hir Expr<'hir>, Node::Expr(n), n;
4922 expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n;
4923 expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n;
4924 expect_path_segment, &'hir PathSegment<'hir>, Node::PathSegment(n), n;
4925 expect_ty, &'hir Ty<'hir>, Node::Ty(n), n;
4926 expect_assoc_item_constraint, &'hir AssocItemConstraint<'hir>, Node::AssocItemConstraint(n), n;
4927 expect_trait_ref, &'hir TraitRef<'hir>, Node::TraitRef(n), n;
4928 expect_opaque_ty, &'hir OpaqueTy<'hir>, Node::OpaqueTy(n), n;
4929 expect_pat, &'hir Pat<'hir>, Node::Pat(n), n;
4930 expect_pat_field, &'hir PatField<'hir>, Node::PatField(n), n;
4931 expect_arm, &'hir Arm<'hir>, Node::Arm(n), n;
4932 expect_block, &'hir Block<'hir>, Node::Block(n), n;
4933 expect_let_stmt, &'hir LetStmt<'hir>, Node::LetStmt(n), n;
4934 expect_ctor, &'hir VariantData<'hir>, Node::Ctor(n), n;
4935 expect_lifetime, &'hir Lifetime, Node::Lifetime(n), n;
4936 expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4937 expect_crate, &'hir Mod<'hir>, Node::Crate(n), n;
4938 expect_infer, &'hir InferArg, Node::Infer(n), n;
4939 expect_closure, &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4940 }
4941}
4942
4943#[cfg(target_pointer_width = "64")]
4945mod size_asserts {
4946 use rustc_data_structures::static_assert_size;
4947
4948 use super::*;
4949 static_assert_size!(Block<'_>, 48);
4951 static_assert_size!(Body<'_>, 24);
4952 static_assert_size!(Expr<'_>, 64);
4953 static_assert_size!(ExprKind<'_>, 48);
4954 static_assert_size!(FnDecl<'_>, 40);
4955 static_assert_size!(ForeignItem<'_>, 96);
4956 static_assert_size!(ForeignItemKind<'_>, 56);
4957 static_assert_size!(GenericArg<'_>, 16);
4958 static_assert_size!(GenericBound<'_>, 64);
4959 static_assert_size!(Generics<'_>, 56);
4960 static_assert_size!(Impl<'_>, 40);
4961 static_assert_size!(ImplItem<'_>, 96);
4962 static_assert_size!(ImplItemKind<'_>, 40);
4963 static_assert_size!(Item<'_>, 88);
4964 static_assert_size!(ItemKind<'_>, 64);
4965 static_assert_size!(LetStmt<'_>, 72);
4966 static_assert_size!(Param<'_>, 32);
4967 static_assert_size!(Pat<'_>, 72);
4968 static_assert_size!(PatKind<'_>, 48);
4969 static_assert_size!(Path<'_>, 40);
4970 static_assert_size!(PathSegment<'_>, 48);
4971 static_assert_size!(QPath<'_>, 24);
4972 static_assert_size!(Res, 12);
4973 static_assert_size!(Stmt<'_>, 32);
4974 static_assert_size!(StmtKind<'_>, 16);
4975 static_assert_size!(TraitImplHeader<'_>, 48);
4976 static_assert_size!(TraitItem<'_>, 88);
4977 static_assert_size!(TraitItemKind<'_>, 48);
4978 static_assert_size!(Ty<'_>, 48);
4979 static_assert_size!(TyKind<'_>, 32);
4980 }
4982
4983#[cfg(test)]
4984mod tests;