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