1use std::fmt;
3
4use rustc_abi::ExternAbi;
5use rustc_ast::attr::AttributeExt;
6use rustc_ast::token::CommentKind;
7use rustc_ast::util::parser::ExprPrecedence;
8use rustc_ast::{
9 self as ast, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitIntType,
10 LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind, join_path_idents,
11};
12pub use rustc_ast::{
13 AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
14 BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
15 MetaItemInner, MetaItemLit, Movability, Mutability, UnOp,
16};
17use rustc_data_structures::fingerprint::Fingerprint;
18use rustc_data_structures::sorted_map::SortedMap;
19use rustc_data_structures::tagged_ptr::TaggedRef;
20use rustc_index::IndexVec;
21use rustc_macros::{Decodable, Encodable, HashStable_Generic};
22use rustc_span::def_id::LocalDefId;
23use rustc_span::hygiene::MacroKind;
24use rustc_span::source_map::Spanned;
25use rustc_span::{BytePos, DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
26use rustc_target::asm::InlineAsmRegOrRegClass;
27use smallvec::SmallVec;
28use thin_vec::ThinVec;
29use tracing::debug;
30
31use crate::LangItem;
32use crate::attrs::AttributeKind;
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)]
151#[repr(align(4))]
156pub struct Lifetime {
157 #[stable_hasher(ignore)]
158 pub hir_id: HirId,
159
160 pub ident: Ident,
164
165 pub kind: LifetimeKind,
167
168 pub source: LifetimeSource,
171
172 pub syntax: LifetimeSyntax,
175}
176
177#[derive(Debug, Copy, Clone, HashStable_Generic)]
178pub enum ParamName {
179 Plain(Ident),
181
182 Error(Ident),
188
189 Fresh,
204}
205
206impl ParamName {
207 pub fn ident(&self) -> Ident {
208 match *self {
209 ParamName::Plain(ident) | ParamName::Error(ident) => ident,
210 ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
211 }
212 }
213}
214
215#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
216pub enum LifetimeKind {
217 Param(LocalDefId),
219
220 ImplicitObjectLifetimeDefault,
232
233 Error,
236
237 Infer,
241
242 Static,
244}
245
246impl LifetimeKind {
247 fn is_elided(&self) -> bool {
248 match self {
249 LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true,
250
251 LifetimeKind::Error | LifetimeKind::Param(..) | LifetimeKind::Static => false,
256 }
257 }
258}
259
260impl fmt::Display for Lifetime {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 self.ident.name.fmt(f)
263 }
264}
265
266impl Lifetime {
267 pub fn new(
268 hir_id: HirId,
269 ident: Ident,
270 kind: LifetimeKind,
271 source: LifetimeSource,
272 syntax: LifetimeSyntax,
273 ) -> Lifetime {
274 let lifetime = Lifetime { hir_id, ident, kind, source, syntax };
275
276 #[cfg(debug_assertions)]
278 match (lifetime.is_elided(), lifetime.is_anonymous()) {
279 (false, false) => {} (false, true) => {} (true, true) => {} (true, false) => panic!("bad Lifetime"),
283 }
284
285 lifetime
286 }
287
288 pub fn is_elided(&self) -> bool {
289 self.kind.is_elided()
290 }
291
292 pub fn is_anonymous(&self) -> bool {
293 self.ident.name == kw::UnderscoreLifetime
294 }
295
296 pub fn is_implicit(&self) -> bool {
297 matches!(self.syntax, LifetimeSyntax::Implicit)
298 }
299
300 pub fn is_static(&self) -> bool {
301 self.kind == LifetimeKind::Static
302 }
303
304 pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
305 use LifetimeSource::*;
306 use LifetimeSyntax::*;
307
308 debug_assert!(new_lifetime.starts_with('\''));
309
310 match (self.syntax, self.source) {
311 (ExplicitBound | ExplicitAnonymous, _) => (self.ident.span, format!("{new_lifetime}")),
313
314 (Implicit, Path { angle_brackets: AngleBrackets::Full }) => {
316 (self.ident.span, format!("{new_lifetime}, "))
317 }
318
319 (Implicit, Path { angle_brackets: AngleBrackets::Empty }) => {
321 (self.ident.span, format!("{new_lifetime}"))
322 }
323
324 (Implicit, Path { angle_brackets: AngleBrackets::Missing }) => {
326 (self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
327 }
328
329 (Implicit, Reference) => (self.ident.span, format!("{new_lifetime} ")),
331
332 (Implicit, source) => {
333 unreachable!("can't suggest for a implicit lifetime of {source:?}")
334 }
335 }
336 }
337}
338
339#[derive(Debug, Clone, Copy, HashStable_Generic)]
343pub struct Path<'hir, R = Res> {
344 pub span: Span,
345 pub res: R,
347 pub segments: &'hir [PathSegment<'hir>],
349}
350
351pub type UsePath<'hir> = Path<'hir, PerNS<Option<Res>>>;
353
354impl Path<'_> {
355 pub fn is_global(&self) -> bool {
356 self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
357 }
358}
359
360#[derive(Debug, Clone, Copy, HashStable_Generic)]
363pub struct PathSegment<'hir> {
364 pub ident: Ident,
366 #[stable_hasher(ignore)]
367 pub hir_id: HirId,
368 pub res: Res,
369
370 pub args: Option<&'hir GenericArgs<'hir>>,
376
377 pub infer_args: bool,
382}
383
384impl<'hir> PathSegment<'hir> {
385 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
387 PathSegment { ident, hir_id, res, infer_args: true, args: None }
388 }
389
390 pub fn invalid() -> Self {
391 Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
392 }
393
394 pub fn args(&self) -> &GenericArgs<'hir> {
395 if let Some(ref args) = self.args {
396 args
397 } else {
398 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
399 DUMMY
400 }
401 }
402}
403
404#[derive(Clone, Copy, Debug, HashStable_Generic)]
420#[repr(C)]
421pub struct ConstArg<'hir, Unambig = ()> {
422 #[stable_hasher(ignore)]
423 pub hir_id: HirId,
424 pub kind: ConstArgKind<'hir, Unambig>,
425}
426
427impl<'hir> ConstArg<'hir, AmbigArg> {
428 pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
439 let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
442 unsafe { &*ptr }
443 }
444}
445
446impl<'hir> ConstArg<'hir> {
447 pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
453 if let ConstArgKind::Infer(_, ()) = self.kind {
454 return None;
455 }
456
457 let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
461 Some(unsafe { &*ptr })
462 }
463}
464
465impl<'hir, Unambig> ConstArg<'hir, Unambig> {
466 pub fn anon_const_hir_id(&self) -> Option<HirId> {
467 match self.kind {
468 ConstArgKind::Anon(ac) => Some(ac.hir_id),
469 _ => None,
470 }
471 }
472
473 pub fn span(&self) -> Span {
474 match self.kind {
475 ConstArgKind::Path(path) => path.span(),
476 ConstArgKind::Anon(anon) => anon.span,
477 ConstArgKind::Infer(span, _) => span,
478 }
479 }
480}
481
482#[derive(Clone, Copy, Debug, HashStable_Generic)]
484#[repr(u8, C)]
485pub enum ConstArgKind<'hir, Unambig = ()> {
486 Path(QPath<'hir>),
492 Anon(&'hir AnonConst),
493 Infer(Span, Unambig),
496}
497
498#[derive(Clone, Copy, Debug, HashStable_Generic)]
499pub struct InferArg {
500 #[stable_hasher(ignore)]
501 pub hir_id: HirId,
502 pub span: Span,
503}
504
505impl InferArg {
506 pub fn to_ty(&self) -> Ty<'static> {
507 Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
508 }
509}
510
511#[derive(Debug, Clone, Copy, HashStable_Generic)]
512pub enum GenericArg<'hir> {
513 Lifetime(&'hir Lifetime),
514 Type(&'hir Ty<'hir, AmbigArg>),
515 Const(&'hir ConstArg<'hir, AmbigArg>),
516 Infer(InferArg),
526}
527
528impl GenericArg<'_> {
529 pub fn span(&self) -> Span {
530 match self {
531 GenericArg::Lifetime(l) => l.ident.span,
532 GenericArg::Type(t) => t.span,
533 GenericArg::Const(c) => c.span(),
534 GenericArg::Infer(i) => i.span,
535 }
536 }
537
538 pub fn hir_id(&self) -> HirId {
539 match self {
540 GenericArg::Lifetime(l) => l.hir_id,
541 GenericArg::Type(t) => t.hir_id,
542 GenericArg::Const(c) => c.hir_id,
543 GenericArg::Infer(i) => i.hir_id,
544 }
545 }
546
547 pub fn descr(&self) -> &'static str {
548 match self {
549 GenericArg::Lifetime(_) => "lifetime",
550 GenericArg::Type(_) => "type",
551 GenericArg::Const(_) => "constant",
552 GenericArg::Infer(_) => "placeholder",
553 }
554 }
555
556 pub fn to_ord(&self) -> ast::ParamKindOrd {
557 match self {
558 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
559 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
560 ast::ParamKindOrd::TypeOrConst
561 }
562 }
563 }
564
565 pub fn is_ty_or_const(&self) -> bool {
566 match self {
567 GenericArg::Lifetime(_) => false,
568 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
569 }
570 }
571}
572
573#[derive(Debug, Clone, Copy, HashStable_Generic)]
575pub struct GenericArgs<'hir> {
576 pub args: &'hir [GenericArg<'hir>],
578 pub constraints: &'hir [AssocItemConstraint<'hir>],
580 pub parenthesized: GenericArgsParentheses,
585 pub span_ext: Span,
598}
599
600impl<'hir> GenericArgs<'hir> {
601 pub const fn none() -> Self {
602 Self {
603 args: &[],
604 constraints: &[],
605 parenthesized: GenericArgsParentheses::No,
606 span_ext: DUMMY_SP,
607 }
608 }
609
610 pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
615 if self.parenthesized != GenericArgsParentheses::ParenSugar {
616 return None;
617 }
618
619 let inputs = self
620 .args
621 .iter()
622 .find_map(|arg| {
623 let GenericArg::Type(ty) = arg else { return None };
624 let TyKind::Tup(tys) = &ty.kind else { return None };
625 Some(tys)
626 })
627 .unwrap();
628
629 Some((inputs, self.paren_sugar_output_inner()))
630 }
631
632 pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
637 (self.parenthesized == GenericArgsParentheses::ParenSugar)
638 .then(|| self.paren_sugar_output_inner())
639 }
640
641 fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
642 let [constraint] = self.constraints.try_into().unwrap();
643 debug_assert_eq!(constraint.ident.name, sym::Output);
644 constraint.ty().unwrap()
645 }
646
647 pub fn has_err(&self) -> Option<ErrorGuaranteed> {
648 self.args
649 .iter()
650 .find_map(|arg| {
651 let GenericArg::Type(ty) = arg else { return None };
652 let TyKind::Err(guar) = ty.kind else { return None };
653 Some(guar)
654 })
655 .or_else(|| {
656 self.constraints.iter().find_map(|constraint| {
657 let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
658 Some(guar)
659 })
660 })
661 }
662
663 #[inline]
664 pub fn num_lifetime_params(&self) -> usize {
665 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
666 }
667
668 #[inline]
669 pub fn has_lifetime_params(&self) -> bool {
670 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
671 }
672
673 #[inline]
674 pub fn num_generic_params(&self) -> usize {
677 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
678 }
679
680 pub fn span(&self) -> Option<Span> {
686 let span_ext = self.span_ext()?;
687 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
688 }
689
690 pub fn span_ext(&self) -> Option<Span> {
692 Some(self.span_ext).filter(|span| !span.is_empty())
693 }
694
695 pub fn is_empty(&self) -> bool {
696 self.args.is_empty()
697 }
698}
699
700#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)]
701pub enum GenericArgsParentheses {
702 No,
703 ReturnTypeNotation,
706 ParenSugar,
708}
709
710#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
712pub struct TraitBoundModifiers {
713 pub constness: BoundConstness,
714 pub polarity: BoundPolarity,
715}
716
717impl TraitBoundModifiers {
718 pub const NONE: Self =
719 TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
720}
721
722#[derive(Clone, Copy, Debug, HashStable_Generic)]
723pub enum GenericBound<'hir> {
724 Trait(PolyTraitRef<'hir>),
725 Outlives(&'hir Lifetime),
726 Use(&'hir [PreciseCapturingArg<'hir>], Span),
727}
728
729impl GenericBound<'_> {
730 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
731 match self {
732 GenericBound::Trait(data) => Some(&data.trait_ref),
733 _ => None,
734 }
735 }
736
737 pub fn span(&self) -> Span {
738 match self {
739 GenericBound::Trait(t, ..) => t.span,
740 GenericBound::Outlives(l) => l.ident.span,
741 GenericBound::Use(_, span) => *span,
742 }
743 }
744}
745
746pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
747
748#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, Debug)]
749pub enum MissingLifetimeKind {
750 Underscore,
752 Ampersand,
754 Comma,
756 Brackets,
758}
759
760#[derive(Copy, Clone, Debug, HashStable_Generic)]
761pub enum LifetimeParamKind {
762 Explicit,
765
766 Elided(MissingLifetimeKind),
769
770 Error,
772}
773
774#[derive(Debug, Clone, Copy, HashStable_Generic)]
775pub enum GenericParamKind<'hir> {
776 Lifetime {
778 kind: LifetimeParamKind,
779 },
780 Type {
781 default: Option<&'hir Ty<'hir>>,
782 synthetic: bool,
783 },
784 Const {
785 ty: &'hir Ty<'hir>,
786 default: Option<&'hir ConstArg<'hir>>,
788 synthetic: bool,
789 },
790}
791
792#[derive(Debug, Clone, Copy, HashStable_Generic)]
793pub struct GenericParam<'hir> {
794 #[stable_hasher(ignore)]
795 pub hir_id: HirId,
796 pub def_id: LocalDefId,
797 pub name: ParamName,
798 pub span: Span,
799 pub pure_wrt_drop: bool,
800 pub kind: GenericParamKind<'hir>,
801 pub colon_span: Option<Span>,
802 pub source: GenericParamSource,
803}
804
805impl<'hir> GenericParam<'hir> {
806 pub fn is_impl_trait(&self) -> bool {
810 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
811 }
812
813 pub fn is_elided_lifetime(&self) -> bool {
817 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
818 }
819}
820
821#[derive(Debug, Clone, Copy, HashStable_Generic)]
828pub enum GenericParamSource {
829 Generics,
831 Binder,
833}
834
835#[derive(Default)]
836pub struct GenericParamCount {
837 pub lifetimes: usize,
838 pub types: usize,
839 pub consts: usize,
840 pub infer: usize,
841}
842
843#[derive(Debug, Clone, Copy, HashStable_Generic)]
846pub struct Generics<'hir> {
847 pub params: &'hir [GenericParam<'hir>],
848 pub predicates: &'hir [WherePredicate<'hir>],
849 pub has_where_clause_predicates: bool,
850 pub where_clause_span: Span,
851 pub span: Span,
852}
853
854impl<'hir> Generics<'hir> {
855 pub const fn empty() -> &'hir Generics<'hir> {
856 const NOPE: Generics<'_> = Generics {
857 params: &[],
858 predicates: &[],
859 has_where_clause_predicates: false,
860 where_clause_span: DUMMY_SP,
861 span: DUMMY_SP,
862 };
863 &NOPE
864 }
865
866 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
867 self.params.iter().find(|¶m| name == param.name.ident().name)
868 }
869
870 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
872 if let Some(first) = self.params.first()
873 && self.span.contains(first.span)
874 {
875 Some(first.span.shrink_to_lo())
878 } else {
879 None
880 }
881 }
882
883 pub fn span_for_param_suggestion(&self) -> Option<Span> {
885 self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
886 self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
889 })
890 }
891
892 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
895 let end = self.where_clause_span.shrink_to_hi();
896 if self.has_where_clause_predicates {
897 self.predicates
898 .iter()
899 .rfind(|&p| p.kind.in_where_clause())
900 .map_or(end, |p| p.span)
901 .shrink_to_hi()
902 .to(end)
903 } else {
904 end
905 }
906 }
907
908 pub fn add_where_or_trailing_comma(&self) -> &'static str {
909 if self.has_where_clause_predicates {
910 ","
911 } else if self.where_clause_span.is_empty() {
912 " where"
913 } else {
914 ""
916 }
917 }
918
919 pub fn bounds_for_param(
920 &self,
921 param_def_id: LocalDefId,
922 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
923 self.predicates.iter().filter_map(move |pred| match pred.kind {
924 WherePredicateKind::BoundPredicate(bp)
925 if bp.is_param_bound(param_def_id.to_def_id()) =>
926 {
927 Some(bp)
928 }
929 _ => None,
930 })
931 }
932
933 pub fn outlives_for_param(
934 &self,
935 param_def_id: LocalDefId,
936 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
937 self.predicates.iter().filter_map(move |pred| match pred.kind {
938 WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
939 _ => None,
940 })
941 }
942
943 pub fn bounds_span_for_suggestions(
954 &self,
955 param_def_id: LocalDefId,
956 ) -> Option<(Span, Option<Span>)> {
957 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
958 |bound| {
959 let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
960 && let [.., segment] = trait_ref.path.segments
961 && let Some(ret_ty) = segment.args().paren_sugar_output()
962 && let ret_ty = ret_ty.peel_refs()
963 && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
964 && let TraitObjectSyntax::Dyn = tagged_ptr.tag()
965 && ret_ty.span.can_be_used_for_suggestions()
966 {
967 Some(ret_ty.span)
968 } else {
969 None
970 };
971
972 span_for_parentheses.map_or_else(
973 || {
974 let bs = bound.span();
977 bs.can_be_used_for_suggestions().then(|| (bs.shrink_to_hi(), None))
978 },
979 |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
980 )
981 },
982 )
983 }
984
985 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
986 let predicate = &self.predicates[pos];
987 let span = predicate.span;
988
989 if !predicate.kind.in_where_clause() {
990 return span;
993 }
994
995 if pos < self.predicates.len() - 1 {
997 let next_pred = &self.predicates[pos + 1];
998 if next_pred.kind.in_where_clause() {
999 return span.until(next_pred.span);
1002 }
1003 }
1004
1005 if pos > 0 {
1006 let prev_pred = &self.predicates[pos - 1];
1007 if prev_pred.kind.in_where_clause() {
1008 return prev_pred.span.shrink_to_hi().to(span);
1011 }
1012 }
1013
1014 self.where_clause_span
1018 }
1019
1020 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
1021 let predicate = &self.predicates[predicate_pos];
1022 let bounds = predicate.kind.bounds();
1023
1024 if bounds.len() == 1 {
1025 return self.span_for_predicate_removal(predicate_pos);
1026 }
1027
1028 let bound_span = bounds[bound_pos].span();
1029 if bound_pos < bounds.len() - 1 {
1030 bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
1036 } else {
1037 bound_span.with_lo(bounds[bound_pos - 1].span().hi())
1043 }
1044 }
1045}
1046
1047#[derive(Debug, Clone, Copy, HashStable_Generic)]
1049pub struct WherePredicate<'hir> {
1050 #[stable_hasher(ignore)]
1051 pub hir_id: HirId,
1052 pub span: Span,
1053 pub kind: &'hir WherePredicateKind<'hir>,
1054}
1055
1056#[derive(Debug, Clone, Copy, HashStable_Generic)]
1058pub enum WherePredicateKind<'hir> {
1059 BoundPredicate(WhereBoundPredicate<'hir>),
1061 RegionPredicate(WhereRegionPredicate<'hir>),
1063 EqPredicate(WhereEqPredicate<'hir>),
1065}
1066
1067impl<'hir> WherePredicateKind<'hir> {
1068 pub fn in_where_clause(&self) -> bool {
1069 match self {
1070 WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
1071 WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
1072 WherePredicateKind::EqPredicate(_) => false,
1073 }
1074 }
1075
1076 pub fn bounds(&self) -> GenericBounds<'hir> {
1077 match self {
1078 WherePredicateKind::BoundPredicate(p) => p.bounds,
1079 WherePredicateKind::RegionPredicate(p) => p.bounds,
1080 WherePredicateKind::EqPredicate(_) => &[],
1081 }
1082 }
1083}
1084
1085#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
1086pub enum PredicateOrigin {
1087 WhereClause,
1088 GenericParam,
1089 ImplTrait,
1090}
1091
1092#[derive(Debug, Clone, Copy, HashStable_Generic)]
1094pub struct WhereBoundPredicate<'hir> {
1095 pub origin: PredicateOrigin,
1097 pub bound_generic_params: &'hir [GenericParam<'hir>],
1099 pub bounded_ty: &'hir Ty<'hir>,
1101 pub bounds: GenericBounds<'hir>,
1103}
1104
1105impl<'hir> WhereBoundPredicate<'hir> {
1106 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
1108 self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
1109 }
1110}
1111
1112#[derive(Debug, Clone, Copy, HashStable_Generic)]
1114pub struct WhereRegionPredicate<'hir> {
1115 pub in_where_clause: bool,
1116 pub lifetime: &'hir Lifetime,
1117 pub bounds: GenericBounds<'hir>,
1118}
1119
1120impl<'hir> WhereRegionPredicate<'hir> {
1121 fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
1123 self.lifetime.kind == LifetimeKind::Param(param_def_id)
1124 }
1125}
1126
1127#[derive(Debug, Clone, Copy, HashStable_Generic)]
1129pub struct WhereEqPredicate<'hir> {
1130 pub lhs_ty: &'hir Ty<'hir>,
1131 pub rhs_ty: &'hir Ty<'hir>,
1132}
1133
1134#[derive(Clone, Copy, Debug)]
1138pub struct ParentedNode<'tcx> {
1139 pub parent: ItemLocalId,
1140 pub node: Node<'tcx>,
1141}
1142
1143#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1145pub enum AttrArgs {
1146 Empty,
1148 Delimited(DelimArgs),
1150 Eq {
1152 eq_span: Span,
1154 expr: MetaItemLit,
1156 },
1157}
1158
1159#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1160pub struct AttrPath {
1161 pub segments: Box<[Ident]>,
1162 pub span: Span,
1163}
1164
1165impl AttrPath {
1166 pub fn from_ast(path: &ast::Path) -> Self {
1167 AttrPath {
1168 segments: path.segments.iter().map(|i| i.ident).collect::<Vec<_>>().into_boxed_slice(),
1169 span: path.span,
1170 }
1171 }
1172}
1173
1174impl fmt::Display for AttrPath {
1175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1176 write!(f, "{}", join_path_idents(&self.segments))
1177 }
1178}
1179
1180#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1181pub struct AttrItem {
1182 pub path: AttrPath,
1184 pub args: AttrArgs,
1185 pub id: HashIgnoredAttrId,
1186 pub style: AttrStyle,
1189 pub span: Span,
1191}
1192
1193#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1196pub struct HashIgnoredAttrId {
1197 pub attr_id: AttrId,
1198}
1199
1200#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1201pub enum Attribute {
1202 Parsed(AttributeKind),
1208
1209 Unparsed(Box<AttrItem>),
1212}
1213
1214impl Attribute {
1215 pub fn get_normal_item(&self) -> &AttrItem {
1216 match &self {
1217 Attribute::Unparsed(normal) => &normal,
1218 _ => panic!("unexpected parsed attribute"),
1219 }
1220 }
1221
1222 pub fn unwrap_normal_item(self) -> AttrItem {
1223 match self {
1224 Attribute::Unparsed(normal) => *normal,
1225 _ => panic!("unexpected parsed attribute"),
1226 }
1227 }
1228
1229 pub fn value_lit(&self) -> Option<&MetaItemLit> {
1230 match &self {
1231 Attribute::Unparsed(n) => match n.as_ref() {
1232 AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1233 _ => None,
1234 },
1235 _ => None,
1236 }
1237 }
1238}
1239
1240impl AttributeExt for Attribute {
1241 #[inline]
1242 fn id(&self) -> AttrId {
1243 match &self {
1244 Attribute::Unparsed(u) => u.id.attr_id,
1245 _ => panic!(),
1246 }
1247 }
1248
1249 #[inline]
1250 fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1251 match &self {
1252 Attribute::Unparsed(n) => match n.as_ref() {
1253 AttrItem { args: AttrArgs::Delimited(d), .. } => {
1254 ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1255 }
1256 _ => None,
1257 },
1258 _ => None,
1259 }
1260 }
1261
1262 #[inline]
1263 fn value_str(&self) -> Option<Symbol> {
1264 self.value_lit().and_then(|x| x.value_str())
1265 }
1266
1267 #[inline]
1268 fn value_span(&self) -> Option<Span> {
1269 self.value_lit().map(|i| i.span)
1270 }
1271
1272 #[inline]
1274 fn ident(&self) -> Option<Ident> {
1275 match &self {
1276 Attribute::Unparsed(n) => {
1277 if let [ident] = n.path.segments.as_ref() {
1278 Some(*ident)
1279 } else {
1280 None
1281 }
1282 }
1283 _ => None,
1284 }
1285 }
1286
1287 #[inline]
1288 fn path_matches(&self, name: &[Symbol]) -> bool {
1289 match &self {
1290 Attribute::Unparsed(n) => {
1291 n.path.segments.len() == name.len()
1292 && n.path.segments.iter().zip(name).all(|(s, n)| s.name == *n)
1293 }
1294 _ => false,
1295 }
1296 }
1297
1298 #[inline]
1299 fn is_doc_comment(&self) -> bool {
1300 matches!(self, Attribute::Parsed(AttributeKind::DocComment { .. }))
1301 }
1302
1303 #[inline]
1304 fn span(&self) -> Span {
1305 match &self {
1306 Attribute::Unparsed(u) => u.span,
1307 Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1309 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1310 Attribute::Parsed(AttributeKind::MacroUse { span, .. }) => *span,
1311 Attribute::Parsed(AttributeKind::MayDangle(span)) => *span,
1312 Attribute::Parsed(AttributeKind::Ignore { span, .. }) => *span,
1313 Attribute::Parsed(AttributeKind::AutomaticallyDerived(span)) => *span,
1314 a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1315 }
1316 }
1317
1318 #[inline]
1319 fn is_word(&self) -> bool {
1320 match &self {
1321 Attribute::Unparsed(n) => {
1322 matches!(n.args, AttrArgs::Empty)
1323 }
1324 _ => false,
1325 }
1326 }
1327
1328 #[inline]
1329 fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1330 match &self {
1331 Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1332 _ => None,
1333 }
1334 }
1335
1336 #[inline]
1337 fn doc_str(&self) -> Option<Symbol> {
1338 match &self {
1339 Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1340 Attribute::Unparsed(_) if self.has_name(sym::doc) => self.value_str(),
1341 _ => None,
1342 }
1343 }
1344
1345 fn is_automatically_derived_attr(&self) -> bool {
1346 matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..)))
1347 }
1348
1349 #[inline]
1350 fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1351 match &self {
1352 Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1353 Some((*comment, *kind))
1354 }
1355 Attribute::Unparsed(_) if self.has_name(sym::doc) => {
1356 self.value_str().map(|s| (s, CommentKind::Line))
1357 }
1358 _ => None,
1359 }
1360 }
1361
1362 fn doc_resolution_scope(&self) -> Option<AttrStyle> {
1363 match self {
1364 Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
1365 Attribute::Unparsed(attr) if self.has_name(sym::doc) && self.value_str().is_some() => {
1366 Some(attr.style)
1367 }
1368 _ => None,
1369 }
1370 }
1371
1372 fn is_proc_macro_attr(&self) -> bool {
1373 matches!(
1374 self,
1375 Attribute::Parsed(
1376 AttributeKind::ProcMacro(..)
1377 | AttributeKind::ProcMacroAttribute(..)
1378 | AttributeKind::ProcMacroDerive { .. }
1379 )
1380 )
1381 }
1382}
1383
1384impl Attribute {
1386 #[inline]
1387 pub fn id(&self) -> AttrId {
1388 AttributeExt::id(self)
1389 }
1390
1391 #[inline]
1392 pub fn name(&self) -> Option<Symbol> {
1393 AttributeExt::name(self)
1394 }
1395
1396 #[inline]
1397 pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1398 AttributeExt::meta_item_list(self)
1399 }
1400
1401 #[inline]
1402 pub fn value_str(&self) -> Option<Symbol> {
1403 AttributeExt::value_str(self)
1404 }
1405
1406 #[inline]
1407 pub fn value_span(&self) -> Option<Span> {
1408 AttributeExt::value_span(self)
1409 }
1410
1411 #[inline]
1412 pub fn ident(&self) -> Option<Ident> {
1413 AttributeExt::ident(self)
1414 }
1415
1416 #[inline]
1417 pub fn path_matches(&self, name: &[Symbol]) -> bool {
1418 AttributeExt::path_matches(self, name)
1419 }
1420
1421 #[inline]
1422 pub fn is_doc_comment(&self) -> bool {
1423 AttributeExt::is_doc_comment(self)
1424 }
1425
1426 #[inline]
1427 pub fn has_name(&self, name: Symbol) -> bool {
1428 AttributeExt::has_name(self, name)
1429 }
1430
1431 #[inline]
1432 pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1433 AttributeExt::has_any_name(self, names)
1434 }
1435
1436 #[inline]
1437 pub fn span(&self) -> Span {
1438 AttributeExt::span(self)
1439 }
1440
1441 #[inline]
1442 pub fn is_word(&self) -> bool {
1443 AttributeExt::is_word(self)
1444 }
1445
1446 #[inline]
1447 pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1448 AttributeExt::path(self)
1449 }
1450
1451 #[inline]
1452 pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1453 AttributeExt::ident_path(self)
1454 }
1455
1456 #[inline]
1457 pub fn doc_str(&self) -> Option<Symbol> {
1458 AttributeExt::doc_str(self)
1459 }
1460
1461 #[inline]
1462 pub fn is_proc_macro_attr(&self) -> bool {
1463 AttributeExt::is_proc_macro_attr(self)
1464 }
1465
1466 #[inline]
1467 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1468 AttributeExt::doc_str_and_comment_kind(self)
1469 }
1470}
1471
1472#[derive(Debug)]
1474pub struct AttributeMap<'tcx> {
1475 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1476 pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1478 pub opt_hash: Option<Fingerprint>,
1480}
1481
1482impl<'tcx> AttributeMap<'tcx> {
1483 pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1484 map: SortedMap::new(),
1485 opt_hash: Some(Fingerprint::ZERO),
1486 define_opaque: None,
1487 };
1488
1489 #[inline]
1490 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1491 self.map.get(&id).copied().unwrap_or(&[])
1492 }
1493}
1494
1495pub struct OwnerNodes<'tcx> {
1499 pub opt_hash_including_bodies: Option<Fingerprint>,
1502 pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1507 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1509}
1510
1511impl<'tcx> OwnerNodes<'tcx> {
1512 pub fn node(&self) -> OwnerNode<'tcx> {
1513 self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1515 }
1516}
1517
1518impl fmt::Debug for OwnerNodes<'_> {
1519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1520 f.debug_struct("OwnerNodes")
1521 .field("node", &self.nodes[ItemLocalId::ZERO])
1523 .field(
1524 "parents",
1525 &fmt::from_fn(|f| {
1526 f.debug_list()
1527 .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1528 fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1529 }))
1530 .finish()
1531 }),
1532 )
1533 .field("bodies", &self.bodies)
1534 .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1535 .finish()
1536 }
1537}
1538
1539#[derive(Debug, HashStable_Generic)]
1541pub struct OwnerInfo<'hir> {
1542 pub nodes: OwnerNodes<'hir>,
1544 pub parenting: LocalDefIdMap<ItemLocalId>,
1546 pub attrs: AttributeMap<'hir>,
1548 pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1551
1552 pub delayed_lints: DelayedLints,
1555}
1556
1557impl<'tcx> OwnerInfo<'tcx> {
1558 #[inline]
1559 pub fn node(&self) -> OwnerNode<'tcx> {
1560 self.nodes.node()
1561 }
1562}
1563
1564#[derive(Copy, Clone, Debug, HashStable_Generic)]
1565pub enum MaybeOwner<'tcx> {
1566 Owner(&'tcx OwnerInfo<'tcx>),
1567 NonOwner(HirId),
1568 Phantom,
1570}
1571
1572impl<'tcx> MaybeOwner<'tcx> {
1573 pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1574 match self {
1575 MaybeOwner::Owner(i) => Some(i),
1576 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1577 }
1578 }
1579
1580 pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1581 self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1582 }
1583}
1584
1585#[derive(Debug)]
1592pub struct Crate<'hir> {
1593 pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1594 pub opt_hir_hash: Option<Fingerprint>,
1596}
1597
1598#[derive(Debug, Clone, Copy, HashStable_Generic)]
1599pub struct Closure<'hir> {
1600 pub def_id: LocalDefId,
1601 pub binder: ClosureBinder,
1602 pub constness: Constness,
1603 pub capture_clause: CaptureBy,
1604 pub bound_generic_params: &'hir [GenericParam<'hir>],
1605 pub fn_decl: &'hir FnDecl<'hir>,
1606 pub body: BodyId,
1607 pub fn_decl_span: Span,
1609 pub fn_arg_span: Option<Span>,
1611 pub kind: ClosureKind,
1612}
1613
1614#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1615pub enum ClosureKind {
1616 Closure,
1618 Coroutine(CoroutineKind),
1623 CoroutineClosure(CoroutineDesugaring),
1628}
1629
1630#[derive(Debug, Clone, Copy, HashStable_Generic)]
1634pub struct Block<'hir> {
1635 pub stmts: &'hir [Stmt<'hir>],
1637 pub expr: Option<&'hir Expr<'hir>>,
1640 #[stable_hasher(ignore)]
1641 pub hir_id: HirId,
1642 pub rules: BlockCheckMode,
1644 pub span: Span,
1646 pub targeted_by_break: bool,
1650}
1651
1652impl<'hir> Block<'hir> {
1653 pub fn innermost_block(&self) -> &Block<'hir> {
1654 let mut block = self;
1655 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1656 block = inner_block;
1657 }
1658 block
1659 }
1660}
1661
1662#[derive(Debug, Clone, Copy, HashStable_Generic)]
1663pub struct TyPat<'hir> {
1664 #[stable_hasher(ignore)]
1665 pub hir_id: HirId,
1666 pub kind: TyPatKind<'hir>,
1667 pub span: Span,
1668}
1669
1670#[derive(Debug, Clone, Copy, HashStable_Generic)]
1671pub struct Pat<'hir> {
1672 #[stable_hasher(ignore)]
1673 pub hir_id: HirId,
1674 pub kind: PatKind<'hir>,
1675 pub span: Span,
1676 pub default_binding_modes: bool,
1679}
1680
1681impl<'hir> Pat<'hir> {
1682 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1683 if !it(self) {
1684 return false;
1685 }
1686
1687 use PatKind::*;
1688 match self.kind {
1689 Missing => unreachable!(),
1690 Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1691 Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_short_(it),
1692 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1693 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1694 Slice(before, slice, after) => {
1695 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1696 }
1697 }
1698 }
1699
1700 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1707 self.walk_short_(&mut it)
1708 }
1709
1710 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1711 if !it(self) {
1712 return;
1713 }
1714
1715 use PatKind::*;
1716 match self.kind {
1717 Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1718 Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1719 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1720 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1721 Slice(before, slice, after) => {
1722 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1723 }
1724 }
1725 }
1726
1727 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1731 self.walk_(&mut it)
1732 }
1733
1734 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1738 self.walk(|p| {
1739 it(p);
1740 true
1741 })
1742 }
1743
1744 pub fn is_never_pattern(&self) -> bool {
1746 let mut is_never_pattern = false;
1747 self.walk(|pat| match &pat.kind {
1748 PatKind::Never => {
1749 is_never_pattern = true;
1750 false
1751 }
1752 PatKind::Or(s) => {
1753 is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1754 false
1755 }
1756 _ => true,
1757 });
1758 is_never_pattern
1759 }
1760}
1761
1762#[derive(Debug, Clone, Copy, HashStable_Generic)]
1768pub struct PatField<'hir> {
1769 #[stable_hasher(ignore)]
1770 pub hir_id: HirId,
1771 pub ident: Ident,
1773 pub pat: &'hir Pat<'hir>,
1775 pub is_shorthand: bool,
1776 pub span: Span,
1777}
1778
1779#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1780pub enum RangeEnd {
1781 Included,
1782 Excluded,
1783}
1784
1785impl fmt::Display for RangeEnd {
1786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1787 f.write_str(match self {
1788 RangeEnd::Included => "..=",
1789 RangeEnd::Excluded => "..",
1790 })
1791 }
1792}
1793
1794#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1798pub struct DotDotPos(u32);
1799
1800impl DotDotPos {
1801 pub fn new(n: Option<usize>) -> Self {
1803 match n {
1804 Some(n) => {
1805 assert!(n < u32::MAX as usize);
1806 Self(n as u32)
1807 }
1808 None => Self(u32::MAX),
1809 }
1810 }
1811
1812 pub fn as_opt_usize(&self) -> Option<usize> {
1813 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1814 }
1815}
1816
1817impl fmt::Debug for DotDotPos {
1818 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1819 self.as_opt_usize().fmt(f)
1820 }
1821}
1822
1823#[derive(Debug, Clone, Copy, HashStable_Generic)]
1824pub struct PatExpr<'hir> {
1825 #[stable_hasher(ignore)]
1826 pub hir_id: HirId,
1827 pub span: Span,
1828 pub kind: PatExprKind<'hir>,
1829}
1830
1831#[derive(Debug, Clone, Copy, HashStable_Generic)]
1832pub enum PatExprKind<'hir> {
1833 Lit {
1834 lit: Lit,
1835 negated: bool,
1838 },
1839 ConstBlock(ConstBlock),
1840 Path(QPath<'hir>),
1842}
1843
1844#[derive(Debug, Clone, Copy, HashStable_Generic)]
1845pub enum TyPatKind<'hir> {
1846 Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1848
1849 Or(&'hir [TyPat<'hir>]),
1851
1852 Err(ErrorGuaranteed),
1854}
1855
1856#[derive(Debug, Clone, Copy, HashStable_Generic)]
1857pub enum PatKind<'hir> {
1858 Missing,
1860
1861 Wild,
1863
1864 Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1875
1876 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1879
1880 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1884
1885 Or(&'hir [Pat<'hir>]),
1888
1889 Never,
1891
1892 Tuple(&'hir [Pat<'hir>], DotDotPos),
1896
1897 Box(&'hir Pat<'hir>),
1899
1900 Deref(&'hir Pat<'hir>),
1902
1903 Ref(&'hir Pat<'hir>, Mutability),
1905
1906 Expr(&'hir PatExpr<'hir>),
1908
1909 Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
1911
1912 Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
1914
1915 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1925
1926 Err(ErrorGuaranteed),
1928}
1929
1930#[derive(Debug, Clone, Copy, HashStable_Generic)]
1932pub struct Stmt<'hir> {
1933 #[stable_hasher(ignore)]
1934 pub hir_id: HirId,
1935 pub kind: StmtKind<'hir>,
1936 pub span: Span,
1937}
1938
1939#[derive(Debug, Clone, Copy, HashStable_Generic)]
1941pub enum StmtKind<'hir> {
1942 Let(&'hir LetStmt<'hir>),
1944
1945 Item(ItemId),
1947
1948 Expr(&'hir Expr<'hir>),
1950
1951 Semi(&'hir Expr<'hir>),
1953}
1954
1955#[derive(Debug, Clone, Copy, HashStable_Generic)]
1957pub struct LetStmt<'hir> {
1958 pub super_: Option<Span>,
1960 pub pat: &'hir Pat<'hir>,
1961 pub ty: Option<&'hir Ty<'hir>>,
1963 pub init: Option<&'hir Expr<'hir>>,
1965 pub els: Option<&'hir Block<'hir>>,
1967 #[stable_hasher(ignore)]
1968 pub hir_id: HirId,
1969 pub span: Span,
1970 pub source: LocalSource,
1974}
1975
1976#[derive(Debug, Clone, Copy, HashStable_Generic)]
1979pub struct Arm<'hir> {
1980 #[stable_hasher(ignore)]
1981 pub hir_id: HirId,
1982 pub span: Span,
1983 pub pat: &'hir Pat<'hir>,
1985 pub guard: Option<&'hir Expr<'hir>>,
1987 pub body: &'hir Expr<'hir>,
1989}
1990
1991#[derive(Debug, Clone, Copy, HashStable_Generic)]
1997pub struct LetExpr<'hir> {
1998 pub span: Span,
1999 pub pat: &'hir Pat<'hir>,
2000 pub ty: Option<&'hir Ty<'hir>>,
2001 pub init: &'hir Expr<'hir>,
2002 pub recovered: ast::Recovered,
2005}
2006
2007#[derive(Debug, Clone, Copy, HashStable_Generic)]
2008pub struct ExprField<'hir> {
2009 #[stable_hasher(ignore)]
2010 pub hir_id: HirId,
2011 pub ident: Ident,
2012 pub expr: &'hir Expr<'hir>,
2013 pub span: Span,
2014 pub is_shorthand: bool,
2015}
2016
2017#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2018pub enum BlockCheckMode {
2019 DefaultBlock,
2020 UnsafeBlock(UnsafeSource),
2021}
2022
2023#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2024pub enum UnsafeSource {
2025 CompilerGenerated,
2026 UserProvided,
2027}
2028
2029#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
2030pub struct BodyId {
2031 pub hir_id: HirId,
2032}
2033
2034#[derive(Debug, Clone, Copy, HashStable_Generic)]
2056pub struct Body<'hir> {
2057 pub params: &'hir [Param<'hir>],
2058 pub value: &'hir Expr<'hir>,
2059}
2060
2061impl<'hir> Body<'hir> {
2062 pub fn id(&self) -> BodyId {
2063 BodyId { hir_id: self.value.hir_id }
2064 }
2065}
2066
2067#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2069pub enum CoroutineKind {
2070 Desugared(CoroutineDesugaring, CoroutineSource),
2072
2073 Coroutine(Movability),
2075}
2076
2077impl CoroutineKind {
2078 pub fn movability(self) -> Movability {
2079 match self {
2080 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2081 | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2082 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2083 CoroutineKind::Coroutine(mov) => mov,
2084 }
2085 }
2086
2087 pub fn is_fn_like(self) -> bool {
2088 matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2089 }
2090
2091 pub fn to_plural_string(&self) -> String {
2092 match self {
2093 CoroutineKind::Desugared(d, CoroutineSource::Fn) => format!("{d:#}fn bodies"),
2094 CoroutineKind::Desugared(d, CoroutineSource::Block) => format!("{d:#}blocks"),
2095 CoroutineKind::Desugared(d, CoroutineSource::Closure) => format!("{d:#}closure bodies"),
2096 CoroutineKind::Coroutine(_) => "coroutines".to_string(),
2097 }
2098 }
2099}
2100
2101impl fmt::Display for CoroutineKind {
2102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2103 match self {
2104 CoroutineKind::Desugared(d, k) => {
2105 d.fmt(f)?;
2106 k.fmt(f)
2107 }
2108 CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2109 }
2110 }
2111}
2112
2113#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
2119pub enum CoroutineSource {
2120 Block,
2122
2123 Closure,
2125
2126 Fn,
2128}
2129
2130impl fmt::Display for CoroutineSource {
2131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2132 match self {
2133 CoroutineSource::Block => "block",
2134 CoroutineSource::Closure => "closure body",
2135 CoroutineSource::Fn => "fn body",
2136 }
2137 .fmt(f)
2138 }
2139}
2140
2141#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2142pub enum CoroutineDesugaring {
2143 Async,
2145
2146 Gen,
2148
2149 AsyncGen,
2152}
2153
2154impl fmt::Display for CoroutineDesugaring {
2155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2156 match self {
2157 CoroutineDesugaring::Async => {
2158 if f.alternate() {
2159 f.write_str("`async` ")?;
2160 } else {
2161 f.write_str("async ")?
2162 }
2163 }
2164 CoroutineDesugaring::Gen => {
2165 if f.alternate() {
2166 f.write_str("`gen` ")?;
2167 } else {
2168 f.write_str("gen ")?
2169 }
2170 }
2171 CoroutineDesugaring::AsyncGen => {
2172 if f.alternate() {
2173 f.write_str("`async gen` ")?;
2174 } else {
2175 f.write_str("async gen ")?
2176 }
2177 }
2178 }
2179
2180 Ok(())
2181 }
2182}
2183
2184#[derive(Copy, Clone, Debug)]
2185pub enum BodyOwnerKind {
2186 Fn,
2188
2189 Closure,
2191
2192 Const { inline: bool },
2194
2195 Static(Mutability),
2197
2198 GlobalAsm,
2200}
2201
2202impl BodyOwnerKind {
2203 pub fn is_fn_or_closure(self) -> bool {
2204 match self {
2205 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2206 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2207 false
2208 }
2209 }
2210 }
2211}
2212
2213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2215pub enum ConstContext {
2216 ConstFn,
2218
2219 Static(Mutability),
2221
2222 Const { inline: bool },
2232}
2233
2234impl ConstContext {
2235 pub fn keyword_name(self) -> &'static str {
2239 match self {
2240 Self::Const { .. } => "const",
2241 Self::Static(Mutability::Not) => "static",
2242 Self::Static(Mutability::Mut) => "static mut",
2243 Self::ConstFn => "const fn",
2244 }
2245 }
2246}
2247
2248impl fmt::Display for ConstContext {
2251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2252 match *self {
2253 Self::Const { .. } => write!(f, "constant"),
2254 Self::Static(_) => write!(f, "static"),
2255 Self::ConstFn => write!(f, "constant function"),
2256 }
2257 }
2258}
2259
2260pub type Lit = Spanned<LitKind>;
2265
2266#[derive(Copy, Clone, Debug, HashStable_Generic)]
2275pub struct AnonConst {
2276 #[stable_hasher(ignore)]
2277 pub hir_id: HirId,
2278 pub def_id: LocalDefId,
2279 pub body: BodyId,
2280 pub span: Span,
2281}
2282
2283#[derive(Copy, Clone, Debug, HashStable_Generic)]
2285pub struct ConstBlock {
2286 #[stable_hasher(ignore)]
2287 pub hir_id: HirId,
2288 pub def_id: LocalDefId,
2289 pub body: BodyId,
2290}
2291
2292#[derive(Debug, Clone, Copy, HashStable_Generic)]
2301pub struct Expr<'hir> {
2302 #[stable_hasher(ignore)]
2303 pub hir_id: HirId,
2304 pub kind: ExprKind<'hir>,
2305 pub span: Span,
2306}
2307
2308impl Expr<'_> {
2309 pub fn precedence(&self, has_attr: &dyn Fn(HirId) -> bool) -> ExprPrecedence {
2310 let prefix_attrs_precedence = || -> ExprPrecedence {
2311 if has_attr(self.hir_id) { ExprPrecedence::Prefix } else { ExprPrecedence::Unambiguous }
2312 };
2313
2314 match &self.kind {
2315 ExprKind::Closure(closure) => {
2316 match closure.fn_decl.output {
2317 FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2318 FnRetTy::Return(_) => prefix_attrs_precedence(),
2319 }
2320 }
2321
2322 ExprKind::Break(..)
2323 | ExprKind::Ret(..)
2324 | ExprKind::Yield(..)
2325 | ExprKind::Become(..) => ExprPrecedence::Jump,
2326
2327 ExprKind::Binary(op, ..) => op.node.precedence(),
2329 ExprKind::Cast(..) => ExprPrecedence::Cast,
2330
2331 ExprKind::Assign(..) |
2332 ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2333
2334 ExprKind::AddrOf(..)
2336 | ExprKind::Let(..)
2341 | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2342
2343 ExprKind::Array(_)
2345 | ExprKind::Block(..)
2346 | ExprKind::Call(..)
2347 | ExprKind::ConstBlock(_)
2348 | ExprKind::Continue(..)
2349 | ExprKind::Field(..)
2350 | ExprKind::If(..)
2351 | ExprKind::Index(..)
2352 | ExprKind::InlineAsm(..)
2353 | ExprKind::Lit(_)
2354 | ExprKind::Loop(..)
2355 | ExprKind::Match(..)
2356 | ExprKind::MethodCall(..)
2357 | ExprKind::OffsetOf(..)
2358 | ExprKind::Path(..)
2359 | ExprKind::Repeat(..)
2360 | ExprKind::Struct(..)
2361 | ExprKind::Tup(_)
2362 | ExprKind::Type(..)
2363 | ExprKind::UnsafeBinderCast(..)
2364 | ExprKind::Use(..)
2365 | ExprKind::Err(_) => prefix_attrs_precedence(),
2366
2367 ExprKind::DropTemps(expr, ..) => expr.precedence(has_attr),
2368 }
2369 }
2370
2371 pub fn is_syntactic_place_expr(&self) -> bool {
2376 self.is_place_expr(|_| true)
2377 }
2378
2379 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2384 match self.kind {
2385 ExprKind::Path(QPath::Resolved(_, ref path)) => {
2386 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2387 }
2388
2389 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2393
2394 ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2396
2397 ExprKind::Unary(UnOp::Deref, _) => true,
2398
2399 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2400 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2401 }
2402
2403 ExprKind::Path(QPath::LangItem(..)) => false,
2405
2406 ExprKind::Err(_guar)
2408 | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2409
2410 ExprKind::Path(QPath::TypeRelative(..))
2413 | ExprKind::Call(..)
2414 | ExprKind::MethodCall(..)
2415 | ExprKind::Use(..)
2416 | ExprKind::Struct(..)
2417 | ExprKind::Tup(..)
2418 | ExprKind::If(..)
2419 | ExprKind::Match(..)
2420 | ExprKind::Closure { .. }
2421 | ExprKind::Block(..)
2422 | ExprKind::Repeat(..)
2423 | ExprKind::Array(..)
2424 | ExprKind::Break(..)
2425 | ExprKind::Continue(..)
2426 | ExprKind::Ret(..)
2427 | ExprKind::Become(..)
2428 | ExprKind::Let(..)
2429 | ExprKind::Loop(..)
2430 | ExprKind::Assign(..)
2431 | ExprKind::InlineAsm(..)
2432 | ExprKind::OffsetOf(..)
2433 | ExprKind::AssignOp(..)
2434 | ExprKind::Lit(_)
2435 | ExprKind::ConstBlock(..)
2436 | ExprKind::Unary(..)
2437 | ExprKind::AddrOf(..)
2438 | ExprKind::Binary(..)
2439 | ExprKind::Yield(..)
2440 | ExprKind::Cast(..)
2441 | ExprKind::DropTemps(..) => false,
2442 }
2443 }
2444
2445 pub fn is_size_lit(&self) -> bool {
2448 matches!(
2449 self.kind,
2450 ExprKind::Lit(Lit {
2451 node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2452 ..
2453 })
2454 )
2455 }
2456
2457 pub fn peel_drop_temps(&self) -> &Self {
2463 let mut expr = self;
2464 while let ExprKind::DropTemps(inner) = &expr.kind {
2465 expr = inner;
2466 }
2467 expr
2468 }
2469
2470 pub fn peel_blocks(&self) -> &Self {
2471 let mut expr = self;
2472 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2473 expr = inner;
2474 }
2475 expr
2476 }
2477
2478 pub fn peel_borrows(&self) -> &Self {
2479 let mut expr = self;
2480 while let ExprKind::AddrOf(.., inner) = &expr.kind {
2481 expr = inner;
2482 }
2483 expr
2484 }
2485
2486 pub fn can_have_side_effects(&self) -> bool {
2487 match self.peel_drop_temps().kind {
2488 ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2489 false
2490 }
2491 ExprKind::Type(base, _)
2492 | ExprKind::Unary(_, base)
2493 | ExprKind::Field(base, _)
2494 | ExprKind::Index(base, _, _)
2495 | ExprKind::AddrOf(.., base)
2496 | ExprKind::Cast(base, _)
2497 | ExprKind::UnsafeBinderCast(_, base, _) => {
2498 base.can_have_side_effects()
2502 }
2503 ExprKind::Struct(_, fields, init) => {
2504 let init_side_effects = match init {
2505 StructTailExpr::Base(init) => init.can_have_side_effects(),
2506 StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2507 };
2508 fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2509 || init_side_effects
2510 }
2511
2512 ExprKind::Array(args)
2513 | ExprKind::Tup(args)
2514 | ExprKind::Call(
2515 Expr {
2516 kind:
2517 ExprKind::Path(QPath::Resolved(
2518 None,
2519 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2520 )),
2521 ..
2522 },
2523 args,
2524 ) => args.iter().any(|arg| arg.can_have_side_effects()),
2525 ExprKind::If(..)
2526 | ExprKind::Match(..)
2527 | ExprKind::MethodCall(..)
2528 | ExprKind::Call(..)
2529 | ExprKind::Closure { .. }
2530 | ExprKind::Block(..)
2531 | ExprKind::Repeat(..)
2532 | ExprKind::Break(..)
2533 | ExprKind::Continue(..)
2534 | ExprKind::Ret(..)
2535 | ExprKind::Become(..)
2536 | ExprKind::Let(..)
2537 | ExprKind::Loop(..)
2538 | ExprKind::Assign(..)
2539 | ExprKind::InlineAsm(..)
2540 | ExprKind::AssignOp(..)
2541 | ExprKind::ConstBlock(..)
2542 | ExprKind::Binary(..)
2543 | ExprKind::Yield(..)
2544 | ExprKind::DropTemps(..)
2545 | ExprKind::Err(_) => true,
2546 }
2547 }
2548
2549 pub fn is_approximately_pattern(&self) -> bool {
2551 match &self.kind {
2552 ExprKind::Array(_)
2553 | ExprKind::Call(..)
2554 | ExprKind::Tup(_)
2555 | ExprKind::Lit(_)
2556 | ExprKind::Path(_)
2557 | ExprKind::Struct(..) => true,
2558 _ => false,
2559 }
2560 }
2561
2562 pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2567 match (self.kind, other.kind) {
2568 (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2569 (
2570 ExprKind::Path(QPath::LangItem(item1, _)),
2571 ExprKind::Path(QPath::LangItem(item2, _)),
2572 ) => item1 == item2,
2573 (
2574 ExprKind::Path(QPath::Resolved(None, path1)),
2575 ExprKind::Path(QPath::Resolved(None, path2)),
2576 ) => path1.res == path2.res,
2577 (
2578 ExprKind::Struct(
2579 QPath::LangItem(LangItem::RangeTo, _),
2580 [val1],
2581 StructTailExpr::None,
2582 ),
2583 ExprKind::Struct(
2584 QPath::LangItem(LangItem::RangeTo, _),
2585 [val2],
2586 StructTailExpr::None,
2587 ),
2588 )
2589 | (
2590 ExprKind::Struct(
2591 QPath::LangItem(LangItem::RangeToInclusive, _),
2592 [val1],
2593 StructTailExpr::None,
2594 ),
2595 ExprKind::Struct(
2596 QPath::LangItem(LangItem::RangeToInclusive, _),
2597 [val2],
2598 StructTailExpr::None,
2599 ),
2600 )
2601 | (
2602 ExprKind::Struct(
2603 QPath::LangItem(LangItem::RangeFrom, _),
2604 [val1],
2605 StructTailExpr::None,
2606 ),
2607 ExprKind::Struct(
2608 QPath::LangItem(LangItem::RangeFrom, _),
2609 [val2],
2610 StructTailExpr::None,
2611 ),
2612 )
2613 | (
2614 ExprKind::Struct(
2615 QPath::LangItem(LangItem::RangeFromCopy, _),
2616 [val1],
2617 StructTailExpr::None,
2618 ),
2619 ExprKind::Struct(
2620 QPath::LangItem(LangItem::RangeFromCopy, _),
2621 [val2],
2622 StructTailExpr::None,
2623 ),
2624 ) => val1.expr.equivalent_for_indexing(val2.expr),
2625 (
2626 ExprKind::Struct(
2627 QPath::LangItem(LangItem::Range, _),
2628 [val1, val3],
2629 StructTailExpr::None,
2630 ),
2631 ExprKind::Struct(
2632 QPath::LangItem(LangItem::Range, _),
2633 [val2, val4],
2634 StructTailExpr::None,
2635 ),
2636 )
2637 | (
2638 ExprKind::Struct(
2639 QPath::LangItem(LangItem::RangeCopy, _),
2640 [val1, val3],
2641 StructTailExpr::None,
2642 ),
2643 ExprKind::Struct(
2644 QPath::LangItem(LangItem::RangeCopy, _),
2645 [val2, val4],
2646 StructTailExpr::None,
2647 ),
2648 )
2649 | (
2650 ExprKind::Struct(
2651 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2652 [val1, val3],
2653 StructTailExpr::None,
2654 ),
2655 ExprKind::Struct(
2656 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2657 [val2, val4],
2658 StructTailExpr::None,
2659 ),
2660 ) => {
2661 val1.expr.equivalent_for_indexing(val2.expr)
2662 && val3.expr.equivalent_for_indexing(val4.expr)
2663 }
2664 _ => false,
2665 }
2666 }
2667
2668 pub fn method_ident(&self) -> Option<Ident> {
2669 match self.kind {
2670 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2671 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2672 _ => None,
2673 }
2674 }
2675}
2676
2677pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2680 match expr.kind {
2681 ExprKind::Struct(ref qpath, _, _) => matches!(
2683 **qpath,
2684 QPath::LangItem(
2685 LangItem::Range
2686 | LangItem::RangeTo
2687 | LangItem::RangeFrom
2688 | LangItem::RangeFull
2689 | LangItem::RangeToInclusive
2690 | LangItem::RangeCopy
2691 | LangItem::RangeFromCopy
2692 | LangItem::RangeInclusiveCopy,
2693 ..
2694 )
2695 ),
2696
2697 ExprKind::Call(ref func, _) => {
2699 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
2700 }
2701
2702 _ => false,
2703 }
2704}
2705
2706pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2713 match expr.kind {
2714 ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2716 _ if is_range_literal(expr) => true,
2718 _ => false,
2719 }
2720}
2721
2722#[derive(Debug, Clone, Copy, HashStable_Generic)]
2723pub enum ExprKind<'hir> {
2724 ConstBlock(ConstBlock),
2726 Array(&'hir [Expr<'hir>]),
2728 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2735 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2752 Use(&'hir Expr<'hir>, Span),
2754 Tup(&'hir [Expr<'hir>]),
2756 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2758 Unary(UnOp, &'hir Expr<'hir>),
2760 Lit(Lit),
2762 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2764 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2766 DropTemps(&'hir Expr<'hir>),
2772 Let(&'hir LetExpr<'hir>),
2777 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2786 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2792 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2795 Closure(&'hir Closure<'hir>),
2802 Block(&'hir Block<'hir>, Option<Label>),
2804
2805 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2807 AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2811 Field(&'hir Expr<'hir>, Ident),
2813 Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2817
2818 Path(QPath<'hir>),
2820
2821 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2823 Break(Destination, Option<&'hir Expr<'hir>>),
2825 Continue(Destination),
2827 Ret(Option<&'hir Expr<'hir>>),
2829 Become(&'hir Expr<'hir>),
2831
2832 InlineAsm(&'hir InlineAsm<'hir>),
2834
2835 OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2837
2838 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2843
2844 Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2849
2850 Yield(&'hir Expr<'hir>, YieldSource),
2852
2853 UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2856
2857 Err(rustc_span::ErrorGuaranteed),
2859}
2860
2861#[derive(Debug, Clone, Copy, HashStable_Generic)]
2862pub enum StructTailExpr<'hir> {
2863 None,
2865 Base(&'hir Expr<'hir>),
2868 DefaultFields(Span),
2872}
2873
2874#[derive(Debug, Clone, Copy, HashStable_Generic)]
2880pub enum QPath<'hir> {
2881 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2888
2889 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2896
2897 LangItem(LangItem, Span),
2899}
2900
2901impl<'hir> QPath<'hir> {
2902 pub fn span(&self) -> Span {
2904 match *self {
2905 QPath::Resolved(_, path) => path.span,
2906 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2907 QPath::LangItem(_, span) => span,
2908 }
2909 }
2910
2911 pub fn qself_span(&self) -> Span {
2914 match *self {
2915 QPath::Resolved(_, path) => path.span,
2916 QPath::TypeRelative(qself, _) => qself.span,
2917 QPath::LangItem(_, span) => span,
2918 }
2919 }
2920}
2921
2922#[derive(Copy, Clone, Debug, HashStable_Generic)]
2924pub enum LocalSource {
2925 Normal,
2927 AsyncFn,
2938 AwaitDesugar,
2940 AssignDesugar(Span),
2943 Contract,
2945}
2946
2947#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2949pub enum MatchSource {
2950 Normal,
2952 Postfix,
2954 ForLoopDesugar,
2956 TryDesugar(HirId),
2958 AwaitDesugar,
2960 FormatArgs,
2962}
2963
2964impl MatchSource {
2965 #[inline]
2966 pub const fn name(self) -> &'static str {
2967 use MatchSource::*;
2968 match self {
2969 Normal => "match",
2970 Postfix => ".match",
2971 ForLoopDesugar => "for",
2972 TryDesugar(_) => "?",
2973 AwaitDesugar => ".await",
2974 FormatArgs => "format_args!()",
2975 }
2976 }
2977}
2978
2979#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2981pub enum LoopSource {
2982 Loop,
2984 While,
2986 ForLoop,
2988}
2989
2990impl LoopSource {
2991 pub fn name(self) -> &'static str {
2992 match self {
2993 LoopSource::Loop => "loop",
2994 LoopSource::While => "while",
2995 LoopSource::ForLoop => "for",
2996 }
2997 }
2998}
2999
3000#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
3001pub enum LoopIdError {
3002 OutsideLoopScope,
3003 UnlabeledCfInWhileCondition,
3004 UnresolvedLabel,
3005}
3006
3007impl fmt::Display for LoopIdError {
3008 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3009 f.write_str(match self {
3010 LoopIdError::OutsideLoopScope => "not inside loop scope",
3011 LoopIdError::UnlabeledCfInWhileCondition => {
3012 "unlabeled control flow (break or continue) in while condition"
3013 }
3014 LoopIdError::UnresolvedLabel => "label not found",
3015 })
3016 }
3017}
3018
3019#[derive(Copy, Clone, Debug, HashStable_Generic)]
3020pub struct Destination {
3021 pub label: Option<Label>,
3023
3024 pub target_id: Result<HirId, LoopIdError>,
3027}
3028
3029#[derive(Copy, Clone, Debug, HashStable_Generic)]
3031pub enum YieldSource {
3032 Await { expr: Option<HirId> },
3034 Yield,
3036}
3037
3038impl fmt::Display for YieldSource {
3039 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3040 f.write_str(match self {
3041 YieldSource::Await { .. } => "`await`",
3042 YieldSource::Yield => "`yield`",
3043 })
3044 }
3045}
3046
3047#[derive(Debug, Clone, Copy, HashStable_Generic)]
3050pub struct MutTy<'hir> {
3051 pub ty: &'hir Ty<'hir>,
3052 pub mutbl: Mutability,
3053}
3054
3055#[derive(Debug, Clone, Copy, HashStable_Generic)]
3058pub struct FnSig<'hir> {
3059 pub header: FnHeader,
3060 pub decl: &'hir FnDecl<'hir>,
3061 pub span: Span,
3062}
3063
3064#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3068pub struct TraitItemId {
3069 pub owner_id: OwnerId,
3070}
3071
3072impl TraitItemId {
3073 #[inline]
3074 pub fn hir_id(&self) -> HirId {
3075 HirId::make_owner(self.owner_id.def_id)
3077 }
3078}
3079
3080#[derive(Debug, Clone, Copy, HashStable_Generic)]
3085pub struct TraitItem<'hir> {
3086 pub ident: Ident,
3087 pub owner_id: OwnerId,
3088 pub generics: &'hir Generics<'hir>,
3089 pub kind: TraitItemKind<'hir>,
3090 pub span: Span,
3091 pub defaultness: Defaultness,
3092 pub has_delayed_lints: bool,
3093}
3094
3095macro_rules! expect_methods_self_kind {
3096 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3097 $(
3098 #[track_caller]
3099 pub fn $name(&self) -> $ret_ty {
3100 let $pat = &self.kind else { expect_failed(stringify!($ident), self) };
3101 $ret_val
3102 }
3103 )*
3104 }
3105}
3106
3107macro_rules! expect_methods_self {
3108 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3109 $(
3110 #[track_caller]
3111 pub fn $name(&self) -> $ret_ty {
3112 let $pat = self else { expect_failed(stringify!($ident), self) };
3113 $ret_val
3114 }
3115 )*
3116 }
3117}
3118
3119#[track_caller]
3120fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3121 panic!("{ident}: found {found:?}")
3122}
3123
3124impl<'hir> TraitItem<'hir> {
3125 #[inline]
3126 pub fn hir_id(&self) -> HirId {
3127 HirId::make_owner(self.owner_id.def_id)
3129 }
3130
3131 pub fn trait_item_id(&self) -> TraitItemId {
3132 TraitItemId { owner_id: self.owner_id }
3133 }
3134
3135 expect_methods_self_kind! {
3136 expect_const, (&'hir Ty<'hir>, Option<BodyId>),
3137 TraitItemKind::Const(ty, body), (ty, *body);
3138
3139 expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3140 TraitItemKind::Fn(ty, trfn), (ty, trfn);
3141
3142 expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3143 TraitItemKind::Type(bounds, ty), (bounds, *ty);
3144 }
3145}
3146
3147#[derive(Debug, Clone, Copy, HashStable_Generic)]
3149pub enum TraitFn<'hir> {
3150 Required(&'hir [Option<Ident>]),
3152
3153 Provided(BodyId),
3155}
3156
3157#[derive(Debug, Clone, Copy, HashStable_Generic)]
3159pub enum TraitItemKind<'hir> {
3160 Const(&'hir Ty<'hir>, Option<BodyId>),
3162 Fn(FnSig<'hir>, TraitFn<'hir>),
3164 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3167}
3168
3169#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3173pub struct ImplItemId {
3174 pub owner_id: OwnerId,
3175}
3176
3177impl ImplItemId {
3178 #[inline]
3179 pub fn hir_id(&self) -> HirId {
3180 HirId::make_owner(self.owner_id.def_id)
3182 }
3183}
3184
3185#[derive(Debug, Clone, Copy, HashStable_Generic)]
3189pub struct ImplItem<'hir> {
3190 pub ident: Ident,
3191 pub owner_id: OwnerId,
3192 pub generics: &'hir Generics<'hir>,
3193 pub kind: ImplItemKind<'hir>,
3194 pub defaultness: Defaultness,
3195 pub span: Span,
3196 pub vis_span: Span,
3197 pub has_delayed_lints: bool,
3198 pub trait_item_def_id: Option<DefId>,
3200}
3201
3202impl<'hir> ImplItem<'hir> {
3203 #[inline]
3204 pub fn hir_id(&self) -> HirId {
3205 HirId::make_owner(self.owner_id.def_id)
3207 }
3208
3209 pub fn impl_item_id(&self) -> ImplItemId {
3210 ImplItemId { owner_id: self.owner_id }
3211 }
3212
3213 expect_methods_self_kind! {
3214 expect_const, (&'hir Ty<'hir>, BodyId), ImplItemKind::Const(ty, body), (ty, *body);
3215 expect_fn, (&FnSig<'hir>, BodyId), ImplItemKind::Fn(ty, body), (ty, *body);
3216 expect_type, &'hir Ty<'hir>, ImplItemKind::Type(ty), ty;
3217 }
3218}
3219
3220#[derive(Debug, Clone, Copy, HashStable_Generic)]
3222pub enum ImplItemKind<'hir> {
3223 Const(&'hir Ty<'hir>, BodyId),
3226 Fn(FnSig<'hir>, BodyId),
3228 Type(&'hir Ty<'hir>),
3230}
3231
3232#[derive(Debug, Clone, Copy, HashStable_Generic)]
3243pub struct AssocItemConstraint<'hir> {
3244 #[stable_hasher(ignore)]
3245 pub hir_id: HirId,
3246 pub ident: Ident,
3247 pub gen_args: &'hir GenericArgs<'hir>,
3248 pub kind: AssocItemConstraintKind<'hir>,
3249 pub span: Span,
3250}
3251
3252impl<'hir> AssocItemConstraint<'hir> {
3253 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3255 match self.kind {
3256 AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3257 _ => None,
3258 }
3259 }
3260
3261 pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3263 match self.kind {
3264 AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3265 _ => None,
3266 }
3267 }
3268}
3269
3270#[derive(Debug, Clone, Copy, HashStable_Generic)]
3271pub enum Term<'hir> {
3272 Ty(&'hir Ty<'hir>),
3273 Const(&'hir ConstArg<'hir>),
3274}
3275
3276impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3277 fn from(ty: &'hir Ty<'hir>) -> Self {
3278 Term::Ty(ty)
3279 }
3280}
3281
3282impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3283 fn from(c: &'hir ConstArg<'hir>) -> Self {
3284 Term::Const(c)
3285 }
3286}
3287
3288#[derive(Debug, Clone, Copy, HashStable_Generic)]
3290pub enum AssocItemConstraintKind<'hir> {
3291 Equality { term: Term<'hir> },
3298 Bound { bounds: &'hir [GenericBound<'hir>] },
3300}
3301
3302impl<'hir> AssocItemConstraintKind<'hir> {
3303 pub fn descr(&self) -> &'static str {
3304 match self {
3305 AssocItemConstraintKind::Equality { .. } => "binding",
3306 AssocItemConstraintKind::Bound { .. } => "constraint",
3307 }
3308 }
3309}
3310
3311#[derive(Debug, Clone, Copy, HashStable_Generic)]
3315pub enum AmbigArg {}
3316
3317#[derive(Debug, Clone, Copy, HashStable_Generic)]
3318#[repr(C)]
3319pub struct Ty<'hir, Unambig = ()> {
3326 #[stable_hasher(ignore)]
3327 pub hir_id: HirId,
3328 pub span: Span,
3329 pub kind: TyKind<'hir, Unambig>,
3330}
3331
3332impl<'hir> Ty<'hir, AmbigArg> {
3333 pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3344 let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3347 unsafe { &*ptr }
3348 }
3349}
3350
3351impl<'hir> Ty<'hir> {
3352 pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3358 if let TyKind::Infer(()) = self.kind {
3359 return None;
3360 }
3361
3362 let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3366 Some(unsafe { &*ptr })
3367 }
3368}
3369
3370impl<'hir> Ty<'hir, AmbigArg> {
3371 pub fn peel_refs(&self) -> &Ty<'hir> {
3372 let mut final_ty = self.as_unambig_ty();
3373 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3374 final_ty = ty;
3375 }
3376 final_ty
3377 }
3378}
3379
3380impl<'hir> Ty<'hir> {
3381 pub fn peel_refs(&self) -> &Self {
3382 let mut final_ty = self;
3383 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3384 final_ty = ty;
3385 }
3386 final_ty
3387 }
3388
3389 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3391 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3392 return None;
3393 };
3394 let [segment] = &path.segments else {
3395 return None;
3396 };
3397 match path.res {
3398 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3399 Some((def_id, segment.ident))
3400 }
3401 _ => None,
3402 }
3403 }
3404
3405 pub fn find_self_aliases(&self) -> Vec<Span> {
3406 use crate::intravisit::Visitor;
3407 struct MyVisitor(Vec<Span>);
3408 impl<'v> Visitor<'v> for MyVisitor {
3409 fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3410 if matches!(
3411 &t.kind,
3412 TyKind::Path(QPath::Resolved(
3413 _,
3414 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3415 ))
3416 ) {
3417 self.0.push(t.span);
3418 return;
3419 }
3420 crate::intravisit::walk_ty(self, t);
3421 }
3422 }
3423
3424 let mut my_visitor = MyVisitor(vec![]);
3425 my_visitor.visit_ty_unambig(self);
3426 my_visitor.0
3427 }
3428
3429 pub fn is_suggestable_infer_ty(&self) -> bool {
3432 fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3433 generic_args.iter().any(|arg| match arg {
3434 GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3435 GenericArg::Infer(_) => true,
3436 _ => false,
3437 })
3438 }
3439 debug!(?self);
3440 match &self.kind {
3441 TyKind::Infer(()) => true,
3442 TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3443 TyKind::Array(ty, length) => {
3444 ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3445 }
3446 TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3447 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3448 TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3449 ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3450 }
3451 TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3452 ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3453 || segments
3454 .iter()
3455 .any(|segment| are_suggestable_generic_args(segment.args().args))
3456 }
3457 _ => false,
3458 }
3459 }
3460}
3461
3462#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3464pub enum PrimTy {
3465 Int(IntTy),
3466 Uint(UintTy),
3467 Float(FloatTy),
3468 Str,
3469 Bool,
3470 Char,
3471}
3472
3473impl PrimTy {
3474 pub const ALL: [Self; 19] = [
3476 Self::Int(IntTy::I8),
3478 Self::Int(IntTy::I16),
3479 Self::Int(IntTy::I32),
3480 Self::Int(IntTy::I64),
3481 Self::Int(IntTy::I128),
3482 Self::Int(IntTy::Isize),
3483 Self::Uint(UintTy::U8),
3484 Self::Uint(UintTy::U16),
3485 Self::Uint(UintTy::U32),
3486 Self::Uint(UintTy::U64),
3487 Self::Uint(UintTy::U128),
3488 Self::Uint(UintTy::Usize),
3489 Self::Float(FloatTy::F16),
3490 Self::Float(FloatTy::F32),
3491 Self::Float(FloatTy::F64),
3492 Self::Float(FloatTy::F128),
3493 Self::Bool,
3494 Self::Char,
3495 Self::Str,
3496 ];
3497
3498 pub fn name_str(self) -> &'static str {
3502 match self {
3503 PrimTy::Int(i) => i.name_str(),
3504 PrimTy::Uint(u) => u.name_str(),
3505 PrimTy::Float(f) => f.name_str(),
3506 PrimTy::Str => "str",
3507 PrimTy::Bool => "bool",
3508 PrimTy::Char => "char",
3509 }
3510 }
3511
3512 pub fn name(self) -> Symbol {
3513 match self {
3514 PrimTy::Int(i) => i.name(),
3515 PrimTy::Uint(u) => u.name(),
3516 PrimTy::Float(f) => f.name(),
3517 PrimTy::Str => sym::str,
3518 PrimTy::Bool => sym::bool,
3519 PrimTy::Char => sym::char,
3520 }
3521 }
3522
3523 pub fn from_name(name: Symbol) -> Option<Self> {
3526 let ty = match name {
3527 sym::i8 => Self::Int(IntTy::I8),
3529 sym::i16 => Self::Int(IntTy::I16),
3530 sym::i32 => Self::Int(IntTy::I32),
3531 sym::i64 => Self::Int(IntTy::I64),
3532 sym::i128 => Self::Int(IntTy::I128),
3533 sym::isize => Self::Int(IntTy::Isize),
3534 sym::u8 => Self::Uint(UintTy::U8),
3535 sym::u16 => Self::Uint(UintTy::U16),
3536 sym::u32 => Self::Uint(UintTy::U32),
3537 sym::u64 => Self::Uint(UintTy::U64),
3538 sym::u128 => Self::Uint(UintTy::U128),
3539 sym::usize => Self::Uint(UintTy::Usize),
3540 sym::f16 => Self::Float(FloatTy::F16),
3541 sym::f32 => Self::Float(FloatTy::F32),
3542 sym::f64 => Self::Float(FloatTy::F64),
3543 sym::f128 => Self::Float(FloatTy::F128),
3544 sym::bool => Self::Bool,
3545 sym::char => Self::Char,
3546 sym::str => Self::Str,
3547 _ => return None,
3548 };
3549 Some(ty)
3550 }
3551}
3552
3553#[derive(Debug, Clone, Copy, HashStable_Generic)]
3554pub struct FnPtrTy<'hir> {
3555 pub safety: Safety,
3556 pub abi: ExternAbi,
3557 pub generic_params: &'hir [GenericParam<'hir>],
3558 pub decl: &'hir FnDecl<'hir>,
3559 pub param_idents: &'hir [Option<Ident>],
3562}
3563
3564#[derive(Debug, Clone, Copy, HashStable_Generic)]
3565pub struct UnsafeBinderTy<'hir> {
3566 pub generic_params: &'hir [GenericParam<'hir>],
3567 pub inner_ty: &'hir Ty<'hir>,
3568}
3569
3570#[derive(Debug, Clone, Copy, HashStable_Generic)]
3571pub struct OpaqueTy<'hir> {
3572 #[stable_hasher(ignore)]
3573 pub hir_id: HirId,
3574 pub def_id: LocalDefId,
3575 pub bounds: GenericBounds<'hir>,
3576 pub origin: OpaqueTyOrigin<LocalDefId>,
3577 pub span: Span,
3578}
3579
3580#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3581pub enum PreciseCapturingArgKind<T, U> {
3582 Lifetime(T),
3583 Param(U),
3585}
3586
3587pub type PreciseCapturingArg<'hir> =
3588 PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3589
3590impl PreciseCapturingArg<'_> {
3591 pub fn hir_id(self) -> HirId {
3592 match self {
3593 PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3594 PreciseCapturingArg::Param(param) => param.hir_id,
3595 }
3596 }
3597
3598 pub fn name(self) -> Symbol {
3599 match self {
3600 PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3601 PreciseCapturingArg::Param(param) => param.ident.name,
3602 }
3603 }
3604}
3605
3606#[derive(Debug, Clone, Copy, HashStable_Generic)]
3611pub struct PreciseCapturingNonLifetimeArg {
3612 #[stable_hasher(ignore)]
3613 pub hir_id: HirId,
3614 pub ident: Ident,
3615 pub res: Res,
3616}
3617
3618#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3619#[derive(HashStable_Generic, Encodable, Decodable)]
3620pub enum RpitContext {
3621 Trait,
3622 TraitImpl,
3623}
3624
3625#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3627#[derive(HashStable_Generic, Encodable, Decodable)]
3628pub enum OpaqueTyOrigin<D> {
3629 FnReturn {
3631 parent: D,
3633 in_trait_or_impl: Option<RpitContext>,
3635 },
3636 AsyncFn {
3638 parent: D,
3640 in_trait_or_impl: Option<RpitContext>,
3642 },
3643 TyAlias {
3645 parent: D,
3647 in_assoc_ty: bool,
3649 },
3650}
3651
3652#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3653pub enum InferDelegationKind {
3654 Input(usize),
3655 Output,
3656}
3657
3658#[derive(Debug, Clone, Copy, HashStable_Generic)]
3660#[repr(u8, C)]
3662pub enum TyKind<'hir, Unambig = ()> {
3663 InferDelegation(DefId, InferDelegationKind),
3665 Slice(&'hir Ty<'hir>),
3667 Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3669 Ptr(MutTy<'hir>),
3671 Ref(&'hir Lifetime, MutTy<'hir>),
3673 FnPtr(&'hir FnPtrTy<'hir>),
3675 UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3677 Never,
3679 Tup(&'hir [Ty<'hir>]),
3681 Path(QPath<'hir>),
3686 OpaqueDef(&'hir OpaqueTy<'hir>),
3688 TraitAscription(GenericBounds<'hir>),
3690 TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3696 Typeof(&'hir AnonConst),
3698 Err(rustc_span::ErrorGuaranteed),
3700 Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3702 Infer(Unambig),
3708}
3709
3710#[derive(Debug, Clone, Copy, HashStable_Generic)]
3711pub enum InlineAsmOperand<'hir> {
3712 In {
3713 reg: InlineAsmRegOrRegClass,
3714 expr: &'hir Expr<'hir>,
3715 },
3716 Out {
3717 reg: InlineAsmRegOrRegClass,
3718 late: bool,
3719 expr: Option<&'hir Expr<'hir>>,
3720 },
3721 InOut {
3722 reg: InlineAsmRegOrRegClass,
3723 late: bool,
3724 expr: &'hir Expr<'hir>,
3725 },
3726 SplitInOut {
3727 reg: InlineAsmRegOrRegClass,
3728 late: bool,
3729 in_expr: &'hir Expr<'hir>,
3730 out_expr: Option<&'hir Expr<'hir>>,
3731 },
3732 Const {
3733 anon_const: ConstBlock,
3734 },
3735 SymFn {
3736 expr: &'hir Expr<'hir>,
3737 },
3738 SymStatic {
3739 path: QPath<'hir>,
3740 def_id: DefId,
3741 },
3742 Label {
3743 block: &'hir Block<'hir>,
3744 },
3745}
3746
3747impl<'hir> InlineAsmOperand<'hir> {
3748 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3749 match *self {
3750 Self::In { reg, .. }
3751 | Self::Out { reg, .. }
3752 | Self::InOut { reg, .. }
3753 | Self::SplitInOut { reg, .. } => Some(reg),
3754 Self::Const { .. }
3755 | Self::SymFn { .. }
3756 | Self::SymStatic { .. }
3757 | Self::Label { .. } => None,
3758 }
3759 }
3760
3761 pub fn is_clobber(&self) -> bool {
3762 matches!(
3763 self,
3764 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3765 )
3766 }
3767}
3768
3769#[derive(Debug, Clone, Copy, HashStable_Generic)]
3770pub struct InlineAsm<'hir> {
3771 pub asm_macro: ast::AsmMacro,
3772 pub template: &'hir [InlineAsmTemplatePiece],
3773 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3774 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3775 pub options: InlineAsmOptions,
3776 pub line_spans: &'hir [Span],
3777}
3778
3779impl InlineAsm<'_> {
3780 pub fn contains_label(&self) -> bool {
3781 self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3782 }
3783}
3784
3785#[derive(Debug, Clone, Copy, HashStable_Generic)]
3787pub struct Param<'hir> {
3788 #[stable_hasher(ignore)]
3789 pub hir_id: HirId,
3790 pub pat: &'hir Pat<'hir>,
3791 pub ty_span: Span,
3792 pub span: Span,
3793}
3794
3795#[derive(Debug, Clone, Copy, HashStable_Generic)]
3797pub struct FnDecl<'hir> {
3798 pub inputs: &'hir [Ty<'hir>],
3802 pub output: FnRetTy<'hir>,
3803 pub c_variadic: bool,
3804 pub implicit_self: ImplicitSelfKind,
3806 pub lifetime_elision_allowed: bool,
3808}
3809
3810impl<'hir> FnDecl<'hir> {
3811 pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3812 if let FnRetTy::Return(ty) = self.output
3813 && let TyKind::InferDelegation(sig_id, _) = ty.kind
3814 {
3815 return Some(sig_id);
3816 }
3817 None
3818 }
3819}
3820
3821#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3823pub enum ImplicitSelfKind {
3824 Imm,
3826 Mut,
3828 RefImm,
3830 RefMut,
3832 None,
3835}
3836
3837impl ImplicitSelfKind {
3838 pub fn has_implicit_self(&self) -> bool {
3840 !matches!(*self, ImplicitSelfKind::None)
3841 }
3842}
3843
3844#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3845pub enum IsAsync {
3846 Async(Span),
3847 NotAsync,
3848}
3849
3850impl IsAsync {
3851 pub fn is_async(self) -> bool {
3852 matches!(self, IsAsync::Async(_))
3853 }
3854}
3855
3856#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3857pub enum Defaultness {
3858 Default { has_value: bool },
3859 Final,
3860}
3861
3862impl Defaultness {
3863 pub fn has_value(&self) -> bool {
3864 match *self {
3865 Defaultness::Default { has_value } => has_value,
3866 Defaultness::Final => true,
3867 }
3868 }
3869
3870 pub fn is_final(&self) -> bool {
3871 *self == Defaultness::Final
3872 }
3873
3874 pub fn is_default(&self) -> bool {
3875 matches!(*self, Defaultness::Default { .. })
3876 }
3877}
3878
3879#[derive(Debug, Clone, Copy, HashStable_Generic)]
3880pub enum FnRetTy<'hir> {
3881 DefaultReturn(Span),
3887 Return(&'hir Ty<'hir>),
3889}
3890
3891impl<'hir> FnRetTy<'hir> {
3892 #[inline]
3893 pub fn span(&self) -> Span {
3894 match *self {
3895 Self::DefaultReturn(span) => span,
3896 Self::Return(ref ty) => ty.span,
3897 }
3898 }
3899
3900 pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3901 if let Self::Return(ty) = self
3902 && ty.is_suggestable_infer_ty()
3903 {
3904 return Some(*ty);
3905 }
3906 None
3907 }
3908}
3909
3910#[derive(Copy, Clone, Debug, HashStable_Generic)]
3912pub enum ClosureBinder {
3913 Default,
3915 For { span: Span },
3919}
3920
3921#[derive(Debug, Clone, Copy, HashStable_Generic)]
3922pub struct Mod<'hir> {
3923 pub spans: ModSpans,
3924 pub item_ids: &'hir [ItemId],
3925}
3926
3927#[derive(Copy, Clone, Debug, HashStable_Generic)]
3928pub struct ModSpans {
3929 pub inner_span: Span,
3933 pub inject_use_span: Span,
3934}
3935
3936#[derive(Debug, Clone, Copy, HashStable_Generic)]
3937pub struct EnumDef<'hir> {
3938 pub variants: &'hir [Variant<'hir>],
3939}
3940
3941#[derive(Debug, Clone, Copy, HashStable_Generic)]
3942pub struct Variant<'hir> {
3943 pub ident: Ident,
3945 #[stable_hasher(ignore)]
3947 pub hir_id: HirId,
3948 pub def_id: LocalDefId,
3949 pub data: VariantData<'hir>,
3951 pub disr_expr: Option<&'hir AnonConst>,
3953 pub span: Span,
3955}
3956
3957#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3958pub enum UseKind {
3959 Single(Ident),
3966
3967 Glob,
3969
3970 ListStem,
3974}
3975
3976#[derive(Clone, Debug, Copy, HashStable_Generic)]
3983pub struct TraitRef<'hir> {
3984 pub path: &'hir Path<'hir>,
3985 #[stable_hasher(ignore)]
3987 pub hir_ref_id: HirId,
3988}
3989
3990impl TraitRef<'_> {
3991 pub fn trait_def_id(&self) -> Option<DefId> {
3993 match self.path.res {
3994 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3995 Res::Err => None,
3996 res => panic!("{res:?} did not resolve to a trait or trait alias"),
3997 }
3998 }
3999}
4000
4001#[derive(Clone, Debug, Copy, HashStable_Generic)]
4002pub struct PolyTraitRef<'hir> {
4003 pub bound_generic_params: &'hir [GenericParam<'hir>],
4005
4006 pub modifiers: TraitBoundModifiers,
4010
4011 pub trait_ref: TraitRef<'hir>,
4013
4014 pub span: Span,
4015}
4016
4017#[derive(Debug, Clone, Copy, HashStable_Generic)]
4018pub struct FieldDef<'hir> {
4019 pub span: Span,
4020 pub vis_span: Span,
4021 pub ident: Ident,
4022 #[stable_hasher(ignore)]
4023 pub hir_id: HirId,
4024 pub def_id: LocalDefId,
4025 pub ty: &'hir Ty<'hir>,
4026 pub safety: Safety,
4027 pub default: Option<&'hir AnonConst>,
4028}
4029
4030impl FieldDef<'_> {
4031 pub fn is_positional(&self) -> bool {
4033 self.ident.as_str().as_bytes()[0].is_ascii_digit()
4034 }
4035}
4036
4037#[derive(Debug, Clone, Copy, HashStable_Generic)]
4039pub enum VariantData<'hir> {
4040 Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4044 Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4048 Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4052}
4053
4054impl<'hir> VariantData<'hir> {
4055 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4057 match *self {
4058 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4059 _ => &[],
4060 }
4061 }
4062
4063 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4064 match *self {
4065 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4066 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4067 VariantData::Struct { .. } => None,
4068 }
4069 }
4070
4071 #[inline]
4072 pub fn ctor_kind(&self) -> Option<CtorKind> {
4073 self.ctor().map(|(kind, ..)| kind)
4074 }
4075
4076 #[inline]
4078 pub fn ctor_hir_id(&self) -> Option<HirId> {
4079 self.ctor().map(|(_, hir_id, _)| hir_id)
4080 }
4081
4082 #[inline]
4084 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4085 self.ctor().map(|(.., def_id)| def_id)
4086 }
4087}
4088
4089#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4093pub struct ItemId {
4094 pub owner_id: OwnerId,
4095}
4096
4097impl ItemId {
4098 #[inline]
4099 pub fn hir_id(&self) -> HirId {
4100 HirId::make_owner(self.owner_id.def_id)
4102 }
4103}
4104
4105#[derive(Debug, Clone, Copy, HashStable_Generic)]
4114pub struct Item<'hir> {
4115 pub owner_id: OwnerId,
4116 pub kind: ItemKind<'hir>,
4117 pub span: Span,
4118 pub vis_span: Span,
4119 pub has_delayed_lints: bool,
4120}
4121
4122impl<'hir> Item<'hir> {
4123 #[inline]
4124 pub fn hir_id(&self) -> HirId {
4125 HirId::make_owner(self.owner_id.def_id)
4127 }
4128
4129 pub fn item_id(&self) -> ItemId {
4130 ItemId { owner_id: self.owner_id }
4131 }
4132
4133 pub fn is_adt(&self) -> bool {
4136 matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4137 }
4138
4139 pub fn is_struct_or_union(&self) -> bool {
4141 matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4142 }
4143
4144 expect_methods_self_kind! {
4145 expect_extern_crate, (Option<Symbol>, Ident),
4146 ItemKind::ExternCrate(s, ident), (*s, *ident);
4147
4148 expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4149
4150 expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4151 ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4152
4153 expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, BodyId),
4154 ItemKind::Const(ident, generics, ty, body), (*ident, generics, ty, *body);
4155
4156 expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4157 ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4158
4159 expect_macro, (Ident, &ast::MacroDef, MacroKind),
4160 ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4161
4162 expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4163
4164 expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]),
4165 ItemKind::ForeignMod { abi, items }, (*abi, items);
4166
4167 expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4168
4169 expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4170 ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4171
4172 expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4173 ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4174
4175 expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4176 ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4177
4178 expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4179 ItemKind::Union(ident, generics, data), (*ident, generics, data);
4180
4181 expect_trait,
4182 (
4183 Constness,
4184 IsAuto,
4185 Safety,
4186 Ident,
4187 &'hir Generics<'hir>,
4188 GenericBounds<'hir>,
4189 &'hir [TraitItemId]
4190 ),
4191 ItemKind::Trait(constness, is_auto, safety, ident, generics, bounds, items),
4192 (*constness, *is_auto, *safety, *ident, generics, bounds, items);
4193
4194 expect_trait_alias, (Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4195 ItemKind::TraitAlias(ident, generics, bounds), (*ident, generics, bounds);
4196
4197 expect_impl, &'hir Impl<'hir>, ItemKind::Impl(imp), imp;
4198 }
4199}
4200
4201#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4202#[derive(Encodable, Decodable, HashStable_Generic)]
4203pub enum Safety {
4204 Unsafe,
4205 Safe,
4206}
4207
4208impl Safety {
4209 pub fn prefix_str(self) -> &'static str {
4210 match self {
4211 Self::Unsafe => "unsafe ",
4212 Self::Safe => "",
4213 }
4214 }
4215
4216 #[inline]
4217 pub fn is_unsafe(self) -> bool {
4218 !self.is_safe()
4219 }
4220
4221 #[inline]
4222 pub fn is_safe(self) -> bool {
4223 match self {
4224 Self::Unsafe => false,
4225 Self::Safe => true,
4226 }
4227 }
4228}
4229
4230impl fmt::Display for Safety {
4231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4232 f.write_str(match *self {
4233 Self::Unsafe => "unsafe",
4234 Self::Safe => "safe",
4235 })
4236 }
4237}
4238
4239#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4240pub enum Constness {
4241 Const,
4242 NotConst,
4243}
4244
4245impl fmt::Display for Constness {
4246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4247 f.write_str(match *self {
4248 Self::Const => "const",
4249 Self::NotConst => "non-const",
4250 })
4251 }
4252}
4253
4254#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4259pub enum HeaderSafety {
4260 SafeTargetFeatures,
4266 Normal(Safety),
4267}
4268
4269impl From<Safety> for HeaderSafety {
4270 fn from(v: Safety) -> Self {
4271 Self::Normal(v)
4272 }
4273}
4274
4275#[derive(Copy, Clone, Debug, HashStable_Generic)]
4276pub struct FnHeader {
4277 pub safety: HeaderSafety,
4278 pub constness: Constness,
4279 pub asyncness: IsAsync,
4280 pub abi: ExternAbi,
4281}
4282
4283impl FnHeader {
4284 pub fn is_async(&self) -> bool {
4285 matches!(self.asyncness, IsAsync::Async(_))
4286 }
4287
4288 pub fn is_const(&self) -> bool {
4289 matches!(self.constness, Constness::Const)
4290 }
4291
4292 pub fn is_unsafe(&self) -> bool {
4293 self.safety().is_unsafe()
4294 }
4295
4296 pub fn is_safe(&self) -> bool {
4297 self.safety().is_safe()
4298 }
4299
4300 pub fn safety(&self) -> Safety {
4301 match self.safety {
4302 HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4303 HeaderSafety::Normal(safety) => safety,
4304 }
4305 }
4306}
4307
4308#[derive(Debug, Clone, Copy, HashStable_Generic)]
4309pub enum ItemKind<'hir> {
4310 ExternCrate(Option<Symbol>, Ident),
4314
4315 Use(&'hir UsePath<'hir>, UseKind),
4321
4322 Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4324 Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, BodyId),
4326 Fn {
4328 sig: FnSig<'hir>,
4329 ident: Ident,
4330 generics: &'hir Generics<'hir>,
4331 body: BodyId,
4332 has_body: bool,
4336 },
4337 Macro(Ident, &'hir ast::MacroDef, MacroKind),
4339 Mod(Ident, &'hir Mod<'hir>),
4341 ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] },
4343 GlobalAsm {
4345 asm: &'hir InlineAsm<'hir>,
4346 fake_body: BodyId,
4352 },
4353 TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4355 Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4357 Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4359 Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4361 Trait(
4363 Constness,
4364 IsAuto,
4365 Safety,
4366 Ident,
4367 &'hir Generics<'hir>,
4368 GenericBounds<'hir>,
4369 &'hir [TraitItemId],
4370 ),
4371 TraitAlias(Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4373
4374 Impl(&'hir Impl<'hir>),
4376}
4377
4378#[derive(Debug, Clone, Copy, HashStable_Generic)]
4383pub struct Impl<'hir> {
4384 pub constness: Constness,
4385 pub safety: Safety,
4386 pub polarity: ImplPolarity,
4387 pub defaultness: Defaultness,
4388 pub defaultness_span: Option<Span>,
4391 pub generics: &'hir Generics<'hir>,
4392
4393 pub of_trait: Option<TraitRef<'hir>>,
4395
4396 pub self_ty: &'hir Ty<'hir>,
4397 pub items: &'hir [ImplItemId],
4398}
4399
4400impl ItemKind<'_> {
4401 pub fn ident(&self) -> Option<Ident> {
4402 match *self {
4403 ItemKind::ExternCrate(_, ident)
4404 | ItemKind::Use(_, UseKind::Single(ident))
4405 | ItemKind::Static(_, ident, ..)
4406 | ItemKind::Const(ident, ..)
4407 | ItemKind::Fn { ident, .. }
4408 | ItemKind::Macro(ident, ..)
4409 | ItemKind::Mod(ident, ..)
4410 | ItemKind::TyAlias(ident, ..)
4411 | ItemKind::Enum(ident, ..)
4412 | ItemKind::Struct(ident, ..)
4413 | ItemKind::Union(ident, ..)
4414 | ItemKind::Trait(_, _, _, ident, ..)
4415 | ItemKind::TraitAlias(ident, ..) => Some(ident),
4416
4417 ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4418 | ItemKind::ForeignMod { .. }
4419 | ItemKind::GlobalAsm { .. }
4420 | ItemKind::Impl(_) => None,
4421 }
4422 }
4423
4424 pub fn generics(&self) -> Option<&Generics<'_>> {
4425 Some(match self {
4426 ItemKind::Fn { generics, .. }
4427 | ItemKind::TyAlias(_, generics, _)
4428 | ItemKind::Const(_, generics, _, _)
4429 | ItemKind::Enum(_, generics, _)
4430 | ItemKind::Struct(_, generics, _)
4431 | ItemKind::Union(_, generics, _)
4432 | ItemKind::Trait(_, _, _, _, generics, _, _)
4433 | ItemKind::TraitAlias(_, generics, _)
4434 | ItemKind::Impl(Impl { generics, .. }) => generics,
4435 _ => return None,
4436 })
4437 }
4438}
4439
4440#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4444pub struct ForeignItemId {
4445 pub owner_id: OwnerId,
4446}
4447
4448impl ForeignItemId {
4449 #[inline]
4450 pub fn hir_id(&self) -> HirId {
4451 HirId::make_owner(self.owner_id.def_id)
4453 }
4454}
4455
4456#[derive(Debug, Clone, Copy, HashStable_Generic)]
4457pub struct ForeignItem<'hir> {
4458 pub ident: Ident,
4459 pub kind: ForeignItemKind<'hir>,
4460 pub owner_id: OwnerId,
4461 pub span: Span,
4462 pub vis_span: Span,
4463 pub has_delayed_lints: bool,
4464}
4465
4466impl ForeignItem<'_> {
4467 #[inline]
4468 pub fn hir_id(&self) -> HirId {
4469 HirId::make_owner(self.owner_id.def_id)
4471 }
4472
4473 pub fn foreign_item_id(&self) -> ForeignItemId {
4474 ForeignItemId { owner_id: self.owner_id }
4475 }
4476}
4477
4478#[derive(Debug, Clone, Copy, HashStable_Generic)]
4480pub enum ForeignItemKind<'hir> {
4481 Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4488 Static(&'hir Ty<'hir>, Mutability, Safety),
4490 Type,
4492}
4493
4494#[derive(Debug, Copy, Clone, HashStable_Generic)]
4496pub struct Upvar {
4497 pub span: Span,
4499}
4500
4501#[derive(Debug, Clone, HashStable_Generic)]
4505pub struct TraitCandidate {
4506 pub def_id: DefId,
4507 pub import_ids: SmallVec<[LocalDefId; 1]>,
4508}
4509
4510#[derive(Copy, Clone, Debug, HashStable_Generic)]
4511pub enum OwnerNode<'hir> {
4512 Item(&'hir Item<'hir>),
4513 ForeignItem(&'hir ForeignItem<'hir>),
4514 TraitItem(&'hir TraitItem<'hir>),
4515 ImplItem(&'hir ImplItem<'hir>),
4516 Crate(&'hir Mod<'hir>),
4517 Synthetic,
4518}
4519
4520impl<'hir> OwnerNode<'hir> {
4521 pub fn span(&self) -> Span {
4522 match self {
4523 OwnerNode::Item(Item { span, .. })
4524 | OwnerNode::ForeignItem(ForeignItem { span, .. })
4525 | OwnerNode::ImplItem(ImplItem { span, .. })
4526 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4527 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4528 OwnerNode::Synthetic => unreachable!(),
4529 }
4530 }
4531
4532 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4533 match self {
4534 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4535 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4536 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4537 | OwnerNode::ForeignItem(ForeignItem {
4538 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4539 }) => Some(fn_sig),
4540 _ => None,
4541 }
4542 }
4543
4544 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4545 match self {
4546 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4547 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4548 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4549 | OwnerNode::ForeignItem(ForeignItem {
4550 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4551 }) => Some(fn_sig.decl),
4552 _ => None,
4553 }
4554 }
4555
4556 pub fn body_id(&self) -> Option<BodyId> {
4557 match self {
4558 OwnerNode::Item(Item {
4559 kind:
4560 ItemKind::Static(_, _, _, body)
4561 | ItemKind::Const(_, _, _, body)
4562 | ItemKind::Fn { body, .. },
4563 ..
4564 })
4565 | OwnerNode::TraitItem(TraitItem {
4566 kind:
4567 TraitItemKind::Fn(_, TraitFn::Provided(body)) | TraitItemKind::Const(_, Some(body)),
4568 ..
4569 })
4570 | OwnerNode::ImplItem(ImplItem {
4571 kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, body),
4572 ..
4573 }) => Some(*body),
4574 _ => None,
4575 }
4576 }
4577
4578 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4579 Node::generics(self.into())
4580 }
4581
4582 pub fn def_id(self) -> OwnerId {
4583 match self {
4584 OwnerNode::Item(Item { owner_id, .. })
4585 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4586 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4587 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4588 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4589 OwnerNode::Synthetic => unreachable!(),
4590 }
4591 }
4592
4593 pub fn is_impl_block(&self) -> bool {
4595 matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4596 }
4597
4598 expect_methods_self! {
4599 expect_item, &'hir Item<'hir>, OwnerNode::Item(n), n;
4600 expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4601 expect_impl_item, &'hir ImplItem<'hir>, OwnerNode::ImplItem(n), n;
4602 expect_trait_item, &'hir TraitItem<'hir>, OwnerNode::TraitItem(n), n;
4603 }
4604}
4605
4606impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4607 fn from(val: &'hir Item<'hir>) -> Self {
4608 OwnerNode::Item(val)
4609 }
4610}
4611
4612impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4613 fn from(val: &'hir ForeignItem<'hir>) -> Self {
4614 OwnerNode::ForeignItem(val)
4615 }
4616}
4617
4618impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4619 fn from(val: &'hir ImplItem<'hir>) -> Self {
4620 OwnerNode::ImplItem(val)
4621 }
4622}
4623
4624impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4625 fn from(val: &'hir TraitItem<'hir>) -> Self {
4626 OwnerNode::TraitItem(val)
4627 }
4628}
4629
4630impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4631 fn from(val: OwnerNode<'hir>) -> Self {
4632 match val {
4633 OwnerNode::Item(n) => Node::Item(n),
4634 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4635 OwnerNode::ImplItem(n) => Node::ImplItem(n),
4636 OwnerNode::TraitItem(n) => Node::TraitItem(n),
4637 OwnerNode::Crate(n) => Node::Crate(n),
4638 OwnerNode::Synthetic => Node::Synthetic,
4639 }
4640 }
4641}
4642
4643#[derive(Copy, Clone, Debug, HashStable_Generic)]
4644pub enum Node<'hir> {
4645 Param(&'hir Param<'hir>),
4646 Item(&'hir Item<'hir>),
4647 ForeignItem(&'hir ForeignItem<'hir>),
4648 TraitItem(&'hir TraitItem<'hir>),
4649 ImplItem(&'hir ImplItem<'hir>),
4650 Variant(&'hir Variant<'hir>),
4651 Field(&'hir FieldDef<'hir>),
4652 AnonConst(&'hir AnonConst),
4653 ConstBlock(&'hir ConstBlock),
4654 ConstArg(&'hir ConstArg<'hir>),
4655 Expr(&'hir Expr<'hir>),
4656 ExprField(&'hir ExprField<'hir>),
4657 Stmt(&'hir Stmt<'hir>),
4658 PathSegment(&'hir PathSegment<'hir>),
4659 Ty(&'hir Ty<'hir>),
4660 AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4661 TraitRef(&'hir TraitRef<'hir>),
4662 OpaqueTy(&'hir OpaqueTy<'hir>),
4663 TyPat(&'hir TyPat<'hir>),
4664 Pat(&'hir Pat<'hir>),
4665 PatField(&'hir PatField<'hir>),
4666 PatExpr(&'hir PatExpr<'hir>),
4670 Arm(&'hir Arm<'hir>),
4671 Block(&'hir Block<'hir>),
4672 LetStmt(&'hir LetStmt<'hir>),
4673 Ctor(&'hir VariantData<'hir>),
4676 Lifetime(&'hir Lifetime),
4677 GenericParam(&'hir GenericParam<'hir>),
4678 Crate(&'hir Mod<'hir>),
4679 Infer(&'hir InferArg),
4680 WherePredicate(&'hir WherePredicate<'hir>),
4681 PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4682 Synthetic,
4684 Err(Span),
4685}
4686
4687impl<'hir> Node<'hir> {
4688 pub fn ident(&self) -> Option<Ident> {
4703 match self {
4704 Node::Item(item) => item.kind.ident(),
4705 Node::TraitItem(TraitItem { ident, .. })
4706 | Node::ImplItem(ImplItem { ident, .. })
4707 | Node::ForeignItem(ForeignItem { ident, .. })
4708 | Node::Field(FieldDef { ident, .. })
4709 | Node::Variant(Variant { ident, .. })
4710 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4711 Node::Lifetime(lt) => Some(lt.ident),
4712 Node::GenericParam(p) => Some(p.name.ident()),
4713 Node::AssocItemConstraint(c) => Some(c.ident),
4714 Node::PatField(f) => Some(f.ident),
4715 Node::ExprField(f) => Some(f.ident),
4716 Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4717 Node::Param(..)
4718 | Node::AnonConst(..)
4719 | Node::ConstBlock(..)
4720 | Node::ConstArg(..)
4721 | Node::Expr(..)
4722 | Node::Stmt(..)
4723 | Node::Block(..)
4724 | Node::Ctor(..)
4725 | Node::Pat(..)
4726 | Node::TyPat(..)
4727 | Node::PatExpr(..)
4728 | Node::Arm(..)
4729 | Node::LetStmt(..)
4730 | Node::Crate(..)
4731 | Node::Ty(..)
4732 | Node::TraitRef(..)
4733 | Node::OpaqueTy(..)
4734 | Node::Infer(..)
4735 | Node::WherePredicate(..)
4736 | Node::Synthetic
4737 | Node::Err(..) => None,
4738 }
4739 }
4740
4741 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4742 match self {
4743 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4744 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4745 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4746 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4747 Some(fn_sig.decl)
4748 }
4749 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4750 Some(fn_decl)
4751 }
4752 _ => None,
4753 }
4754 }
4755
4756 pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4758 if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4759 && let Some(trait_ref) = impl_block.of_trait
4760 && let Some(trait_id) = trait_ref.trait_def_id()
4761 && trait_id == trait_def_id
4762 {
4763 Some(impl_block)
4764 } else {
4765 None
4766 }
4767 }
4768
4769 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4770 match self {
4771 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4772 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4773 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4774 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4775 Some(fn_sig)
4776 }
4777 _ => None,
4778 }
4779 }
4780
4781 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4783 match self {
4784 Node::Item(it) => match it.kind {
4785 ItemKind::TyAlias(_, _, ty)
4786 | ItemKind::Static(_, _, ty, _)
4787 | ItemKind::Const(_, _, ty, _) => Some(ty),
4788 ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4789 _ => None,
4790 },
4791 Node::TraitItem(it) => match it.kind {
4792 TraitItemKind::Const(ty, _) => Some(ty),
4793 TraitItemKind::Type(_, ty) => ty,
4794 _ => None,
4795 },
4796 Node::ImplItem(it) => match it.kind {
4797 ImplItemKind::Const(ty, _) => Some(ty),
4798 ImplItemKind::Type(ty) => Some(ty),
4799 _ => None,
4800 },
4801 Node::ForeignItem(it) => match it.kind {
4802 ForeignItemKind::Static(ty, ..) => Some(ty),
4803 _ => None,
4804 },
4805 _ => None,
4806 }
4807 }
4808
4809 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4810 match self {
4811 Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
4812 _ => None,
4813 }
4814 }
4815
4816 #[inline]
4817 pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4818 match self {
4819 Node::Item(Item {
4820 owner_id,
4821 kind:
4822 ItemKind::Const(_, _, _, body)
4823 | ItemKind::Static(.., body)
4824 | ItemKind::Fn { body, .. },
4825 ..
4826 })
4827 | Node::TraitItem(TraitItem {
4828 owner_id,
4829 kind:
4830 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4831 ..
4832 })
4833 | Node::ImplItem(ImplItem {
4834 owner_id,
4835 kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
4836 ..
4837 }) => Some((owner_id.def_id, *body)),
4838
4839 Node::Item(Item {
4840 owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4841 }) => Some((owner_id.def_id, *fake_body)),
4842
4843 Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4844 Some((*def_id, *body))
4845 }
4846
4847 Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4848 Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4849
4850 _ => None,
4851 }
4852 }
4853
4854 pub fn body_id(&self) -> Option<BodyId> {
4855 Some(self.associated_body()?.1)
4856 }
4857
4858 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4859 match self {
4860 Node::ForeignItem(ForeignItem {
4861 kind: ForeignItemKind::Fn(_, _, generics), ..
4862 })
4863 | Node::TraitItem(TraitItem { generics, .. })
4864 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4865 Node::Item(item) => item.kind.generics(),
4866 _ => None,
4867 }
4868 }
4869
4870 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4871 match self {
4872 Node::Item(i) => Some(OwnerNode::Item(i)),
4873 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4874 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4875 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4876 Node::Crate(i) => Some(OwnerNode::Crate(i)),
4877 Node::Synthetic => Some(OwnerNode::Synthetic),
4878 _ => None,
4879 }
4880 }
4881
4882 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4883 match self {
4884 Node::Item(i) => match i.kind {
4885 ItemKind::Fn { ident, sig, generics, .. } => {
4886 Some(FnKind::ItemFn(ident, generics, sig.header))
4887 }
4888 _ => None,
4889 },
4890 Node::TraitItem(ti) => match ti.kind {
4891 TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4892 _ => None,
4893 },
4894 Node::ImplItem(ii) => match ii.kind {
4895 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4896 _ => None,
4897 },
4898 Node::Expr(e) => match e.kind {
4899 ExprKind::Closure { .. } => Some(FnKind::Closure),
4900 _ => None,
4901 },
4902 _ => None,
4903 }
4904 }
4905
4906 expect_methods_self! {
4907 expect_param, &'hir Param<'hir>, Node::Param(n), n;
4908 expect_item, &'hir Item<'hir>, Node::Item(n), n;
4909 expect_foreign_item, &'hir ForeignItem<'hir>, Node::ForeignItem(n), n;
4910 expect_trait_item, &'hir TraitItem<'hir>, Node::TraitItem(n), n;
4911 expect_impl_item, &'hir ImplItem<'hir>, Node::ImplItem(n), n;
4912 expect_variant, &'hir Variant<'hir>, Node::Variant(n), n;
4913 expect_field, &'hir FieldDef<'hir>, Node::Field(n), n;
4914 expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n;
4915 expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n;
4916 expect_expr, &'hir Expr<'hir>, Node::Expr(n), n;
4917 expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n;
4918 expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n;
4919 expect_path_segment, &'hir PathSegment<'hir>, Node::PathSegment(n), n;
4920 expect_ty, &'hir Ty<'hir>, Node::Ty(n), n;
4921 expect_assoc_item_constraint, &'hir AssocItemConstraint<'hir>, Node::AssocItemConstraint(n), n;
4922 expect_trait_ref, &'hir TraitRef<'hir>, Node::TraitRef(n), n;
4923 expect_opaque_ty, &'hir OpaqueTy<'hir>, Node::OpaqueTy(n), n;
4924 expect_pat, &'hir Pat<'hir>, Node::Pat(n), n;
4925 expect_pat_field, &'hir PatField<'hir>, Node::PatField(n), n;
4926 expect_arm, &'hir Arm<'hir>, Node::Arm(n), n;
4927 expect_block, &'hir Block<'hir>, Node::Block(n), n;
4928 expect_let_stmt, &'hir LetStmt<'hir>, Node::LetStmt(n), n;
4929 expect_ctor, &'hir VariantData<'hir>, Node::Ctor(n), n;
4930 expect_lifetime, &'hir Lifetime, Node::Lifetime(n), n;
4931 expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4932 expect_crate, &'hir Mod<'hir>, Node::Crate(n), n;
4933 expect_infer, &'hir InferArg, Node::Infer(n), n;
4934 expect_closure, &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4935 }
4936}
4937
4938#[cfg(target_pointer_width = "64")]
4940mod size_asserts {
4941 use rustc_data_structures::static_assert_size;
4942
4943 use super::*;
4944 static_assert_size!(Block<'_>, 48);
4946 static_assert_size!(Body<'_>, 24);
4947 static_assert_size!(Expr<'_>, 64);
4948 static_assert_size!(ExprKind<'_>, 48);
4949 static_assert_size!(FnDecl<'_>, 40);
4950 static_assert_size!(ForeignItem<'_>, 96);
4951 static_assert_size!(ForeignItemKind<'_>, 56);
4952 static_assert_size!(GenericArg<'_>, 16);
4953 static_assert_size!(GenericBound<'_>, 64);
4954 static_assert_size!(Generics<'_>, 56);
4955 static_assert_size!(Impl<'_>, 80);
4956 static_assert_size!(ImplItem<'_>, 96);
4957 static_assert_size!(ImplItemKind<'_>, 40);
4958 static_assert_size!(Item<'_>, 88);
4959 static_assert_size!(ItemKind<'_>, 64);
4960 static_assert_size!(LetStmt<'_>, 72);
4961 static_assert_size!(Param<'_>, 32);
4962 static_assert_size!(Pat<'_>, 72);
4963 static_assert_size!(PatKind<'_>, 48);
4964 static_assert_size!(Path<'_>, 40);
4965 static_assert_size!(PathSegment<'_>, 48);
4966 static_assert_size!(QPath<'_>, 24);
4967 static_assert_size!(Res, 12);
4968 static_assert_size!(Stmt<'_>, 32);
4969 static_assert_size!(StmtKind<'_>, 16);
4970 static_assert_size!(TraitItem<'_>, 88);
4971 static_assert_size!(TraitItemKind<'_>, 48);
4972 static_assert_size!(Ty<'_>, 48);
4973 static_assert_size!(TyKind<'_>, 32);
4974 }
4976
4977#[cfg(test)]
4978mod tests;