1use std::fmt;
3
4use rustc_abi::ExternAbi;
5use rustc_ast::attr::AttributeExt;
6use rustc_ast::token::CommentKind;
7use rustc_ast::util::parser::ExprPrecedence;
8use rustc_ast::{
9 self as ast, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitIntType,
10 LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind,
11};
12pub use rustc_ast::{
13 AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
14 BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
15 MetaItemInner, MetaItemLit, Movability, Mutability, UnOp,
16};
17use rustc_attr_data_structures::AttributeKind;
18use rustc_data_structures::fingerprint::Fingerprint;
19use rustc_data_structures::sorted_map::SortedMap;
20use rustc_data_structures::tagged_ptr::TaggedRef;
21use rustc_index::IndexVec;
22use rustc_macros::{Decodable, Encodable, HashStable_Generic};
23use rustc_span::def_id::LocalDefId;
24use rustc_span::hygiene::MacroKind;
25use rustc_span::source_map::Spanned;
26use rustc_span::{BytePos, DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
27use rustc_target::asm::InlineAsmRegOrRegClass;
28use smallvec::SmallVec;
29use thin_vec::ThinVec;
30use tracing::debug;
31
32use crate::LangItem;
33use crate::def::{CtorKind, DefKind, PerNS, Res};
34use crate::def_id::{DefId, LocalDefIdMap};
35pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId};
36use crate::intravisit::{FnKind, VisitorExt};
37
38#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
39pub enum AngleBrackets {
40 Missing,
42 Empty,
44 Full,
46}
47
48#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
49pub enum LifetimeSource {
50 Reference,
52
53 Path { angle_brackets: AngleBrackets },
56
57 OutlivesBound,
59
60 PreciseCapturing,
62
63 Other,
70}
71
72#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
73pub enum LifetimeSyntax {
74 Hidden,
76
77 Anonymous,
79
80 Named,
82}
83
84impl From<Ident> for LifetimeSyntax {
85 fn from(ident: Ident) -> Self {
86 let name = ident.name;
87
88 if name == sym::empty {
89 unreachable!("A lifetime name should never be empty");
90 } else if name == kw::UnderscoreLifetime {
91 LifetimeSyntax::Anonymous
92 } else {
93 debug_assert!(name.as_str().starts_with('\''));
94 LifetimeSyntax::Named
95 }
96 }
97}
98
99#[derive(Debug, Copy, Clone, HashStable_Generic)]
150pub struct Lifetime {
151 #[stable_hasher(ignore)]
152 pub hir_id: HirId,
153
154 pub ident: Ident,
158
159 pub kind: LifetimeKind,
161
162 pub source: LifetimeSource,
165
166 pub syntax: LifetimeSyntax,
169}
170
171#[derive(Debug, Copy, Clone, HashStable_Generic)]
172pub enum ParamName {
173 Plain(Ident),
175
176 Error(Ident),
182
183 Fresh,
198}
199
200impl ParamName {
201 pub fn ident(&self) -> Ident {
202 match *self {
203 ParamName::Plain(ident) | ParamName::Error(ident) => ident,
204 ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
205 }
206 }
207}
208
209#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
210pub enum LifetimeKind {
211 Param(LocalDefId),
213
214 ImplicitObjectLifetimeDefault,
226
227 Error,
230
231 Infer,
235
236 Static,
238}
239
240impl LifetimeKind {
241 fn is_elided(&self) -> bool {
242 match self {
243 LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true,
244
245 LifetimeKind::Error | LifetimeKind::Param(..) | LifetimeKind::Static => false,
250 }
251 }
252}
253
254impl fmt::Display for Lifetime {
255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256 self.ident.name.fmt(f)
257 }
258}
259
260impl Lifetime {
261 pub fn new(
262 hir_id: HirId,
263 ident: Ident,
264 kind: LifetimeKind,
265 source: LifetimeSource,
266 syntax: LifetimeSyntax,
267 ) -> Lifetime {
268 let lifetime = Lifetime { hir_id, ident, kind, source, syntax };
269
270 #[cfg(debug_assertions)]
272 match (lifetime.is_elided(), lifetime.is_anonymous()) {
273 (false, false) => {} (false, true) => {} (true, true) => {} (true, false) => panic!("bad Lifetime"),
277 }
278
279 lifetime
280 }
281
282 pub fn is_elided(&self) -> bool {
283 self.kind.is_elided()
284 }
285
286 pub fn is_anonymous(&self) -> bool {
287 self.ident.name == kw::UnderscoreLifetime
288 }
289
290 pub fn is_syntactically_hidden(&self) -> bool {
291 matches!(self.syntax, LifetimeSyntax::Hidden)
292 }
293
294 pub fn is_syntactically_anonymous(&self) -> bool {
295 matches!(self.syntax, LifetimeSyntax::Anonymous)
296 }
297
298 pub fn is_static(&self) -> bool {
299 self.kind == LifetimeKind::Static
300 }
301
302 pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
303 use LifetimeSource::*;
304 use LifetimeSyntax::*;
305
306 debug_assert!(new_lifetime.starts_with('\''));
307
308 match (self.syntax, self.source) {
309 (Named | Anonymous, _) => (self.ident.span, format!("{new_lifetime}")),
311
312 (Hidden, Path { angle_brackets: AngleBrackets::Full }) => {
314 (self.ident.span, format!("{new_lifetime}, "))
315 }
316
317 (Hidden, Path { angle_brackets: AngleBrackets::Empty }) => {
319 (self.ident.span, format!("{new_lifetime}"))
320 }
321
322 (Hidden, Path { angle_brackets: AngleBrackets::Missing }) => {
324 (self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
325 }
326
327 (Hidden, Reference) => (self.ident.span, format!("{new_lifetime} ")),
329
330 (Hidden, source) => {
331 unreachable!("can't suggest for a hidden lifetime of {source:?}")
332 }
333 }
334 }
335}
336
337#[derive(Debug, Clone, Copy, HashStable_Generic)]
341pub struct Path<'hir, R = Res> {
342 pub span: Span,
343 pub res: R,
345 pub segments: &'hir [PathSegment<'hir>],
347}
348
349pub type UsePath<'hir> = Path<'hir, PerNS<Option<Res>>>;
351
352impl Path<'_> {
353 pub fn is_global(&self) -> bool {
354 self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
355 }
356}
357
358#[derive(Debug, Clone, Copy, HashStable_Generic)]
361pub struct PathSegment<'hir> {
362 pub ident: Ident,
364 #[stable_hasher(ignore)]
365 pub hir_id: HirId,
366 pub res: Res,
367
368 pub args: Option<&'hir GenericArgs<'hir>>,
374
375 pub infer_args: bool,
380}
381
382impl<'hir> PathSegment<'hir> {
383 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
385 PathSegment { ident, hir_id, res, infer_args: true, args: None }
386 }
387
388 pub fn invalid() -> Self {
389 Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
390 }
391
392 pub fn args(&self) -> &GenericArgs<'hir> {
393 if let Some(ref args) = self.args {
394 args
395 } else {
396 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
397 DUMMY
398 }
399 }
400}
401
402#[derive(Clone, Copy, Debug, HashStable_Generic)]
418#[repr(C)]
419pub struct ConstArg<'hir, Unambig = ()> {
420 #[stable_hasher(ignore)]
421 pub hir_id: HirId,
422 pub kind: ConstArgKind<'hir, Unambig>,
423}
424
425impl<'hir> ConstArg<'hir, AmbigArg> {
426 pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
437 let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
440 unsafe { &*ptr }
441 }
442}
443
444impl<'hir> ConstArg<'hir> {
445 pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
451 if let ConstArgKind::Infer(_, ()) = self.kind {
452 return None;
453 }
454
455 let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
459 Some(unsafe { &*ptr })
460 }
461}
462
463impl<'hir, Unambig> ConstArg<'hir, Unambig> {
464 pub fn anon_const_hir_id(&self) -> Option<HirId> {
465 match self.kind {
466 ConstArgKind::Anon(ac) => Some(ac.hir_id),
467 _ => None,
468 }
469 }
470
471 pub fn span(&self) -> Span {
472 match self.kind {
473 ConstArgKind::Path(path) => path.span(),
474 ConstArgKind::Anon(anon) => anon.span,
475 ConstArgKind::Infer(span, _) => span,
476 }
477 }
478}
479
480#[derive(Clone, Copy, Debug, HashStable_Generic)]
482#[repr(u8, C)]
483pub enum ConstArgKind<'hir, Unambig = ()> {
484 Path(QPath<'hir>),
490 Anon(&'hir AnonConst),
491 Infer(Span, Unambig),
494}
495
496#[derive(Clone, Copy, Debug, HashStable_Generic)]
497pub struct InferArg {
498 #[stable_hasher(ignore)]
499 pub hir_id: HirId,
500 pub span: Span,
501}
502
503impl InferArg {
504 pub fn to_ty(&self) -> Ty<'static> {
505 Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
506 }
507}
508
509#[derive(Debug, Clone, Copy, HashStable_Generic)]
510pub enum GenericArg<'hir> {
511 Lifetime(&'hir Lifetime),
512 Type(&'hir Ty<'hir, AmbigArg>),
513 Const(&'hir ConstArg<'hir, AmbigArg>),
514 Infer(InferArg),
524}
525
526impl GenericArg<'_> {
527 pub fn span(&self) -> Span {
528 match self {
529 GenericArg::Lifetime(l) => l.ident.span,
530 GenericArg::Type(t) => t.span,
531 GenericArg::Const(c) => c.span(),
532 GenericArg::Infer(i) => i.span,
533 }
534 }
535
536 pub fn hir_id(&self) -> HirId {
537 match self {
538 GenericArg::Lifetime(l) => l.hir_id,
539 GenericArg::Type(t) => t.hir_id,
540 GenericArg::Const(c) => c.hir_id,
541 GenericArg::Infer(i) => i.hir_id,
542 }
543 }
544
545 pub fn descr(&self) -> &'static str {
546 match self {
547 GenericArg::Lifetime(_) => "lifetime",
548 GenericArg::Type(_) => "type",
549 GenericArg::Const(_) => "constant",
550 GenericArg::Infer(_) => "placeholder",
551 }
552 }
553
554 pub fn to_ord(&self) -> ast::ParamKindOrd {
555 match self {
556 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
557 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
558 ast::ParamKindOrd::TypeOrConst
559 }
560 }
561 }
562
563 pub fn is_ty_or_const(&self) -> bool {
564 match self {
565 GenericArg::Lifetime(_) => false,
566 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
567 }
568 }
569}
570
571#[derive(Debug, Clone, Copy, HashStable_Generic)]
573pub struct GenericArgs<'hir> {
574 pub args: &'hir [GenericArg<'hir>],
576 pub constraints: &'hir [AssocItemConstraint<'hir>],
578 pub parenthesized: GenericArgsParentheses,
583 pub span_ext: Span,
596}
597
598impl<'hir> GenericArgs<'hir> {
599 pub const fn none() -> Self {
600 Self {
601 args: &[],
602 constraints: &[],
603 parenthesized: GenericArgsParentheses::No,
604 span_ext: DUMMY_SP,
605 }
606 }
607
608 pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
613 if self.parenthesized != GenericArgsParentheses::ParenSugar {
614 return None;
615 }
616
617 let inputs = self
618 .args
619 .iter()
620 .find_map(|arg| {
621 let GenericArg::Type(ty) = arg else { return None };
622 let TyKind::Tup(tys) = &ty.kind else { return None };
623 Some(tys)
624 })
625 .unwrap();
626
627 Some((inputs, self.paren_sugar_output_inner()))
628 }
629
630 pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
635 (self.parenthesized == GenericArgsParentheses::ParenSugar)
636 .then(|| self.paren_sugar_output_inner())
637 }
638
639 fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
640 let [constraint] = self.constraints.try_into().unwrap();
641 debug_assert_eq!(constraint.ident.name, sym::Output);
642 constraint.ty().unwrap()
643 }
644
645 pub fn has_err(&self) -> Option<ErrorGuaranteed> {
646 self.args
647 .iter()
648 .find_map(|arg| {
649 let GenericArg::Type(ty) = arg else { return None };
650 let TyKind::Err(guar) = ty.kind else { return None };
651 Some(guar)
652 })
653 .or_else(|| {
654 self.constraints.iter().find_map(|constraint| {
655 let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
656 Some(guar)
657 })
658 })
659 }
660
661 #[inline]
662 pub fn num_lifetime_params(&self) -> usize {
663 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
664 }
665
666 #[inline]
667 pub fn has_lifetime_params(&self) -> bool {
668 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
669 }
670
671 #[inline]
672 pub fn num_generic_params(&self) -> usize {
675 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
676 }
677
678 pub fn span(&self) -> Option<Span> {
684 let span_ext = self.span_ext()?;
685 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
686 }
687
688 pub fn span_ext(&self) -> Option<Span> {
690 Some(self.span_ext).filter(|span| !span.is_empty())
691 }
692
693 pub fn is_empty(&self) -> bool {
694 self.args.is_empty()
695 }
696}
697
698#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)]
699pub enum GenericArgsParentheses {
700 No,
701 ReturnTypeNotation,
704 ParenSugar,
706}
707
708#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
710pub struct TraitBoundModifiers {
711 pub constness: BoundConstness,
712 pub polarity: BoundPolarity,
713}
714
715impl TraitBoundModifiers {
716 pub const NONE: Self =
717 TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
718}
719
720#[derive(Clone, Copy, Debug, HashStable_Generic)]
721pub enum GenericBound<'hir> {
722 Trait(PolyTraitRef<'hir>),
723 Outlives(&'hir Lifetime),
724 Use(&'hir [PreciseCapturingArg<'hir>], Span),
725}
726
727impl GenericBound<'_> {
728 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
729 match self {
730 GenericBound::Trait(data) => Some(&data.trait_ref),
731 _ => None,
732 }
733 }
734
735 pub fn span(&self) -> Span {
736 match self {
737 GenericBound::Trait(t, ..) => t.span,
738 GenericBound::Outlives(l) => l.ident.span,
739 GenericBound::Use(_, span) => *span,
740 }
741 }
742}
743
744pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
745
746#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, Debug)]
747pub enum MissingLifetimeKind {
748 Underscore,
750 Ampersand,
752 Comma,
754 Brackets,
756}
757
758#[derive(Copy, Clone, Debug, HashStable_Generic)]
759pub enum LifetimeParamKind {
760 Explicit,
763
764 Elided(MissingLifetimeKind),
767
768 Error,
770}
771
772#[derive(Debug, Clone, Copy, HashStable_Generic)]
773pub enum GenericParamKind<'hir> {
774 Lifetime {
776 kind: LifetimeParamKind,
777 },
778 Type {
779 default: Option<&'hir Ty<'hir>>,
780 synthetic: bool,
781 },
782 Const {
783 ty: &'hir Ty<'hir>,
784 default: Option<&'hir ConstArg<'hir>>,
786 synthetic: bool,
787 },
788}
789
790#[derive(Debug, Clone, Copy, HashStable_Generic)]
791pub struct GenericParam<'hir> {
792 #[stable_hasher(ignore)]
793 pub hir_id: HirId,
794 pub def_id: LocalDefId,
795 pub name: ParamName,
796 pub span: Span,
797 pub pure_wrt_drop: bool,
798 pub kind: GenericParamKind<'hir>,
799 pub colon_span: Option<Span>,
800 pub source: GenericParamSource,
801}
802
803impl<'hir> GenericParam<'hir> {
804 pub fn is_impl_trait(&self) -> bool {
808 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
809 }
810
811 pub fn is_elided_lifetime(&self) -> bool {
815 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
816 }
817}
818
819#[derive(Debug, Clone, Copy, HashStable_Generic)]
826pub enum GenericParamSource {
827 Generics,
829 Binder,
831}
832
833#[derive(Default)]
834pub struct GenericParamCount {
835 pub lifetimes: usize,
836 pub types: usize,
837 pub consts: usize,
838 pub infer: usize,
839}
840
841#[derive(Debug, Clone, Copy, HashStable_Generic)]
844pub struct Generics<'hir> {
845 pub params: &'hir [GenericParam<'hir>],
846 pub predicates: &'hir [WherePredicate<'hir>],
847 pub has_where_clause_predicates: bool,
848 pub where_clause_span: Span,
849 pub span: Span,
850}
851
852impl<'hir> Generics<'hir> {
853 pub const fn empty() -> &'hir Generics<'hir> {
854 const NOPE: Generics<'_> = Generics {
855 params: &[],
856 predicates: &[],
857 has_where_clause_predicates: false,
858 where_clause_span: DUMMY_SP,
859 span: DUMMY_SP,
860 };
861 &NOPE
862 }
863
864 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
865 self.params.iter().find(|¶m| name == param.name.ident().name)
866 }
867
868 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
870 if let Some(first) = self.params.first()
871 && self.span.contains(first.span)
872 {
873 Some(first.span.shrink_to_lo())
876 } else {
877 None
878 }
879 }
880
881 pub fn span_for_param_suggestion(&self) -> Option<Span> {
883 self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
884 self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
887 })
888 }
889
890 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
893 let end = self.where_clause_span.shrink_to_hi();
894 if self.has_where_clause_predicates {
895 self.predicates
896 .iter()
897 .rfind(|&p| p.kind.in_where_clause())
898 .map_or(end, |p| p.span)
899 .shrink_to_hi()
900 .to(end)
901 } else {
902 end
903 }
904 }
905
906 pub fn add_where_or_trailing_comma(&self) -> &'static str {
907 if self.has_where_clause_predicates {
908 ","
909 } else if self.where_clause_span.is_empty() {
910 " where"
911 } else {
912 ""
914 }
915 }
916
917 pub fn bounds_for_param(
918 &self,
919 param_def_id: LocalDefId,
920 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
921 self.predicates.iter().filter_map(move |pred| match pred.kind {
922 WherePredicateKind::BoundPredicate(bp)
923 if bp.is_param_bound(param_def_id.to_def_id()) =>
924 {
925 Some(bp)
926 }
927 _ => None,
928 })
929 }
930
931 pub fn outlives_for_param(
932 &self,
933 param_def_id: LocalDefId,
934 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
935 self.predicates.iter().filter_map(move |pred| match pred.kind {
936 WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
937 _ => None,
938 })
939 }
940
941 pub fn bounds_span_for_suggestions(
952 &self,
953 param_def_id: LocalDefId,
954 ) -> Option<(Span, Option<Span>)> {
955 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
956 |bound| {
957 let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
958 && let [.., segment] = trait_ref.path.segments
959 && let Some(ret_ty) = segment.args().paren_sugar_output()
960 && let ret_ty = ret_ty.peel_refs()
961 && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
962 && let TraitObjectSyntax::Dyn | TraitObjectSyntax::DynStar = tagged_ptr.tag()
963 && ret_ty.span.can_be_used_for_suggestions()
964 {
965 Some(ret_ty.span)
966 } else {
967 None
968 };
969
970 span_for_parentheses.map_or_else(
971 || {
972 let bs = bound.span();
975 bs.can_be_used_for_suggestions().then(|| (bs.shrink_to_hi(), None))
976 },
977 |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
978 )
979 },
980 )
981 }
982
983 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
984 let predicate = &self.predicates[pos];
985 let span = predicate.span;
986
987 if !predicate.kind.in_where_clause() {
988 return span;
991 }
992
993 if pos < self.predicates.len() - 1 {
995 let next_pred = &self.predicates[pos + 1];
996 if next_pred.kind.in_where_clause() {
997 return span.until(next_pred.span);
1000 }
1001 }
1002
1003 if pos > 0 {
1004 let prev_pred = &self.predicates[pos - 1];
1005 if prev_pred.kind.in_where_clause() {
1006 return prev_pred.span.shrink_to_hi().to(span);
1009 }
1010 }
1011
1012 self.where_clause_span
1016 }
1017
1018 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
1019 let predicate = &self.predicates[predicate_pos];
1020 let bounds = predicate.kind.bounds();
1021
1022 if bounds.len() == 1 {
1023 return self.span_for_predicate_removal(predicate_pos);
1024 }
1025
1026 let bound_span = bounds[bound_pos].span();
1027 if bound_pos < bounds.len() - 1 {
1028 bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
1034 } else {
1035 bound_span.with_lo(bounds[bound_pos - 1].span().hi())
1041 }
1042 }
1043}
1044
1045#[derive(Debug, Clone, Copy, HashStable_Generic)]
1047pub struct WherePredicate<'hir> {
1048 #[stable_hasher(ignore)]
1049 pub hir_id: HirId,
1050 pub span: Span,
1051 pub kind: &'hir WherePredicateKind<'hir>,
1052}
1053
1054#[derive(Debug, Clone, Copy, HashStable_Generic)]
1056pub enum WherePredicateKind<'hir> {
1057 BoundPredicate(WhereBoundPredicate<'hir>),
1059 RegionPredicate(WhereRegionPredicate<'hir>),
1061 EqPredicate(WhereEqPredicate<'hir>),
1063}
1064
1065impl<'hir> WherePredicateKind<'hir> {
1066 pub fn in_where_clause(&self) -> bool {
1067 match self {
1068 WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
1069 WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
1070 WherePredicateKind::EqPredicate(_) => false,
1071 }
1072 }
1073
1074 pub fn bounds(&self) -> GenericBounds<'hir> {
1075 match self {
1076 WherePredicateKind::BoundPredicate(p) => p.bounds,
1077 WherePredicateKind::RegionPredicate(p) => p.bounds,
1078 WherePredicateKind::EqPredicate(_) => &[],
1079 }
1080 }
1081}
1082
1083#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
1084pub enum PredicateOrigin {
1085 WhereClause,
1086 GenericParam,
1087 ImplTrait,
1088}
1089
1090#[derive(Debug, Clone, Copy, HashStable_Generic)]
1092pub struct WhereBoundPredicate<'hir> {
1093 pub origin: PredicateOrigin,
1095 pub bound_generic_params: &'hir [GenericParam<'hir>],
1097 pub bounded_ty: &'hir Ty<'hir>,
1099 pub bounds: GenericBounds<'hir>,
1101}
1102
1103impl<'hir> WhereBoundPredicate<'hir> {
1104 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
1106 self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
1107 }
1108}
1109
1110#[derive(Debug, Clone, Copy, HashStable_Generic)]
1112pub struct WhereRegionPredicate<'hir> {
1113 pub in_where_clause: bool,
1114 pub lifetime: &'hir Lifetime,
1115 pub bounds: GenericBounds<'hir>,
1116}
1117
1118impl<'hir> WhereRegionPredicate<'hir> {
1119 fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
1121 self.lifetime.kind == LifetimeKind::Param(param_def_id)
1122 }
1123}
1124
1125#[derive(Debug, Clone, Copy, HashStable_Generic)]
1127pub struct WhereEqPredicate<'hir> {
1128 pub lhs_ty: &'hir Ty<'hir>,
1129 pub rhs_ty: &'hir Ty<'hir>,
1130}
1131
1132#[derive(Clone, Copy, Debug)]
1136pub struct ParentedNode<'tcx> {
1137 pub parent: ItemLocalId,
1138 pub node: Node<'tcx>,
1139}
1140
1141#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1143pub enum AttrArgs {
1144 Empty,
1146 Delimited(DelimArgs),
1148 Eq {
1150 eq_span: Span,
1152 expr: MetaItemLit,
1154 },
1155}
1156
1157#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1158pub struct AttrPath {
1159 pub segments: Box<[Ident]>,
1160 pub span: Span,
1161}
1162
1163impl AttrPath {
1164 pub fn from_ast(path: &ast::Path) -> Self {
1165 AttrPath {
1166 segments: path.segments.iter().map(|i| i.ident).collect::<Vec<_>>().into_boxed_slice(),
1167 span: path.span,
1168 }
1169 }
1170}
1171
1172impl fmt::Display for AttrPath {
1173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1174 write!(f, "{}", self.segments.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("::"))
1175 }
1176}
1177
1178#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1179pub struct AttrItem {
1180 pub path: AttrPath,
1182 pub args: AttrArgs,
1183 pub id: HashIgnoredAttrId,
1184 pub style: AttrStyle,
1187 pub span: Span,
1189}
1190
1191#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1194pub struct HashIgnoredAttrId {
1195 pub attr_id: AttrId,
1196}
1197
1198#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1199pub enum Attribute {
1200 Parsed(AttributeKind),
1206
1207 Unparsed(Box<AttrItem>),
1210}
1211
1212impl Attribute {
1213 pub fn get_normal_item(&self) -> &AttrItem {
1214 match &self {
1215 Attribute::Unparsed(normal) => &normal,
1216 _ => panic!("unexpected parsed attribute"),
1217 }
1218 }
1219
1220 pub fn unwrap_normal_item(self) -> AttrItem {
1221 match self {
1222 Attribute::Unparsed(normal) => *normal,
1223 _ => panic!("unexpected parsed attribute"),
1224 }
1225 }
1226
1227 pub fn value_lit(&self) -> Option<&MetaItemLit> {
1228 match &self {
1229 Attribute::Unparsed(n) => match n.as_ref() {
1230 AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1231 _ => None,
1232 },
1233 _ => None,
1234 }
1235 }
1236}
1237
1238impl AttributeExt for Attribute {
1239 #[inline]
1240 fn id(&self) -> AttrId {
1241 match &self {
1242 Attribute::Unparsed(u) => u.id.attr_id,
1243 _ => panic!(),
1244 }
1245 }
1246
1247 #[inline]
1248 fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1249 match &self {
1250 Attribute::Unparsed(n) => match n.as_ref() {
1251 AttrItem { args: AttrArgs::Delimited(d), .. } => {
1252 ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1253 }
1254 _ => None,
1255 },
1256 _ => None,
1257 }
1258 }
1259
1260 #[inline]
1261 fn value_str(&self) -> Option<Symbol> {
1262 self.value_lit().and_then(|x| x.value_str())
1263 }
1264
1265 #[inline]
1266 fn value_span(&self) -> Option<Span> {
1267 self.value_lit().map(|i| i.span)
1268 }
1269
1270 #[inline]
1272 fn ident(&self) -> Option<Ident> {
1273 match &self {
1274 Attribute::Unparsed(n) => {
1275 if let [ident] = n.path.segments.as_ref() {
1276 Some(*ident)
1277 } else {
1278 None
1279 }
1280 }
1281 _ => None,
1282 }
1283 }
1284
1285 #[inline]
1286 fn path_matches(&self, name: &[Symbol]) -> bool {
1287 match &self {
1288 Attribute::Unparsed(n) => {
1289 n.path.segments.len() == name.len()
1290 && n.path.segments.iter().zip(name).all(|(s, n)| s.name == *n)
1291 }
1292 _ => false,
1293 }
1294 }
1295
1296 #[inline]
1297 fn is_doc_comment(&self) -> bool {
1298 matches!(self, Attribute::Parsed(AttributeKind::DocComment { .. }))
1299 }
1300
1301 #[inline]
1302 fn span(&self) -> Span {
1303 match &self {
1304 Attribute::Unparsed(u) => u.span,
1305 Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1307 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1308 a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1309 }
1310 }
1311
1312 #[inline]
1313 fn is_word(&self) -> bool {
1314 match &self {
1315 Attribute::Unparsed(n) => {
1316 matches!(n.args, AttrArgs::Empty)
1317 }
1318 _ => false,
1319 }
1320 }
1321
1322 #[inline]
1323 fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1324 match &self {
1325 Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1326 _ => None,
1327 }
1328 }
1329
1330 #[inline]
1331 fn doc_str(&self) -> Option<Symbol> {
1332 match &self {
1333 Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1334 Attribute::Unparsed(_) if self.has_name(sym::doc) => self.value_str(),
1335 _ => None,
1336 }
1337 }
1338 #[inline]
1339 fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1340 match &self {
1341 Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1342 Some((*comment, *kind))
1343 }
1344 Attribute::Unparsed(_) if self.has_name(sym::doc) => {
1345 self.value_str().map(|s| (s, CommentKind::Line))
1346 }
1347 _ => None,
1348 }
1349 }
1350
1351 #[inline]
1352 fn style(&self) -> AttrStyle {
1353 match &self {
1354 Attribute::Unparsed(u) => u.style,
1355 Attribute::Parsed(AttributeKind::DocComment { style, .. }) => *style,
1356 _ => panic!(),
1357 }
1358 }
1359}
1360
1361impl Attribute {
1363 #[inline]
1364 pub fn id(&self) -> AttrId {
1365 AttributeExt::id(self)
1366 }
1367
1368 #[inline]
1369 pub fn name(&self) -> Option<Symbol> {
1370 AttributeExt::name(self)
1371 }
1372
1373 #[inline]
1374 pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1375 AttributeExt::meta_item_list(self)
1376 }
1377
1378 #[inline]
1379 pub fn value_str(&self) -> Option<Symbol> {
1380 AttributeExt::value_str(self)
1381 }
1382
1383 #[inline]
1384 pub fn value_span(&self) -> Option<Span> {
1385 AttributeExt::value_span(self)
1386 }
1387
1388 #[inline]
1389 pub fn ident(&self) -> Option<Ident> {
1390 AttributeExt::ident(self)
1391 }
1392
1393 #[inline]
1394 pub fn path_matches(&self, name: &[Symbol]) -> bool {
1395 AttributeExt::path_matches(self, name)
1396 }
1397
1398 #[inline]
1399 pub fn is_doc_comment(&self) -> bool {
1400 AttributeExt::is_doc_comment(self)
1401 }
1402
1403 #[inline]
1404 pub fn has_name(&self, name: Symbol) -> bool {
1405 AttributeExt::has_name(self, name)
1406 }
1407
1408 #[inline]
1409 pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1410 AttributeExt::has_any_name(self, names)
1411 }
1412
1413 #[inline]
1414 pub fn span(&self) -> Span {
1415 AttributeExt::span(self)
1416 }
1417
1418 #[inline]
1419 pub fn is_word(&self) -> bool {
1420 AttributeExt::is_word(self)
1421 }
1422
1423 #[inline]
1424 pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1425 AttributeExt::path(self)
1426 }
1427
1428 #[inline]
1429 pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1430 AttributeExt::ident_path(self)
1431 }
1432
1433 #[inline]
1434 pub fn doc_str(&self) -> Option<Symbol> {
1435 AttributeExt::doc_str(self)
1436 }
1437
1438 #[inline]
1439 pub fn is_proc_macro_attr(&self) -> bool {
1440 AttributeExt::is_proc_macro_attr(self)
1441 }
1442
1443 #[inline]
1444 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1445 AttributeExt::doc_str_and_comment_kind(self)
1446 }
1447
1448 #[inline]
1449 pub fn style(&self) -> AttrStyle {
1450 AttributeExt::style(self)
1451 }
1452}
1453
1454#[derive(Debug)]
1456pub struct AttributeMap<'tcx> {
1457 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1458 pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1460 pub opt_hash: Option<Fingerprint>,
1462}
1463
1464impl<'tcx> AttributeMap<'tcx> {
1465 pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1466 map: SortedMap::new(),
1467 opt_hash: Some(Fingerprint::ZERO),
1468 define_opaque: None,
1469 };
1470
1471 #[inline]
1472 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1473 self.map.get(&id).copied().unwrap_or(&[])
1474 }
1475}
1476
1477pub struct OwnerNodes<'tcx> {
1481 pub opt_hash_including_bodies: Option<Fingerprint>,
1484 pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1489 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1491}
1492
1493impl<'tcx> OwnerNodes<'tcx> {
1494 pub fn node(&self) -> OwnerNode<'tcx> {
1495 self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1497 }
1498}
1499
1500impl fmt::Debug for OwnerNodes<'_> {
1501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1502 f.debug_struct("OwnerNodes")
1503 .field("node", &self.nodes[ItemLocalId::ZERO])
1505 .field(
1506 "parents",
1507 &fmt::from_fn(|f| {
1508 f.debug_list()
1509 .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1510 fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1511 }))
1512 .finish()
1513 }),
1514 )
1515 .field("bodies", &self.bodies)
1516 .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1517 .finish()
1518 }
1519}
1520
1521#[derive(Debug, HashStable_Generic)]
1523pub struct OwnerInfo<'hir> {
1524 pub nodes: OwnerNodes<'hir>,
1526 pub parenting: LocalDefIdMap<ItemLocalId>,
1528 pub attrs: AttributeMap<'hir>,
1530 pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1533}
1534
1535impl<'tcx> OwnerInfo<'tcx> {
1536 #[inline]
1537 pub fn node(&self) -> OwnerNode<'tcx> {
1538 self.nodes.node()
1539 }
1540}
1541
1542#[derive(Copy, Clone, Debug, HashStable_Generic)]
1543pub enum MaybeOwner<'tcx> {
1544 Owner(&'tcx OwnerInfo<'tcx>),
1545 NonOwner(HirId),
1546 Phantom,
1548}
1549
1550impl<'tcx> MaybeOwner<'tcx> {
1551 pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1552 match self {
1553 MaybeOwner::Owner(i) => Some(i),
1554 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1555 }
1556 }
1557
1558 pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1559 self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1560 }
1561}
1562
1563#[derive(Debug)]
1570pub struct Crate<'hir> {
1571 pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1572 pub opt_hir_hash: Option<Fingerprint>,
1574}
1575
1576#[derive(Debug, Clone, Copy, HashStable_Generic)]
1577pub struct Closure<'hir> {
1578 pub def_id: LocalDefId,
1579 pub binder: ClosureBinder,
1580 pub constness: Constness,
1581 pub capture_clause: CaptureBy,
1582 pub bound_generic_params: &'hir [GenericParam<'hir>],
1583 pub fn_decl: &'hir FnDecl<'hir>,
1584 pub body: BodyId,
1585 pub fn_decl_span: Span,
1587 pub fn_arg_span: Option<Span>,
1589 pub kind: ClosureKind,
1590}
1591
1592#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1593pub enum ClosureKind {
1594 Closure,
1596 Coroutine(CoroutineKind),
1601 CoroutineClosure(CoroutineDesugaring),
1606}
1607
1608#[derive(Debug, Clone, Copy, HashStable_Generic)]
1612pub struct Block<'hir> {
1613 pub stmts: &'hir [Stmt<'hir>],
1615 pub expr: Option<&'hir Expr<'hir>>,
1618 #[stable_hasher(ignore)]
1619 pub hir_id: HirId,
1620 pub rules: BlockCheckMode,
1622 pub span: Span,
1624 pub targeted_by_break: bool,
1628}
1629
1630impl<'hir> Block<'hir> {
1631 pub fn innermost_block(&self) -> &Block<'hir> {
1632 let mut block = self;
1633 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1634 block = inner_block;
1635 }
1636 block
1637 }
1638}
1639
1640#[derive(Debug, Clone, Copy, HashStable_Generic)]
1641pub struct TyPat<'hir> {
1642 #[stable_hasher(ignore)]
1643 pub hir_id: HirId,
1644 pub kind: TyPatKind<'hir>,
1645 pub span: Span,
1646}
1647
1648#[derive(Debug, Clone, Copy, HashStable_Generic)]
1649pub struct Pat<'hir> {
1650 #[stable_hasher(ignore)]
1651 pub hir_id: HirId,
1652 pub kind: PatKind<'hir>,
1653 pub span: Span,
1654 pub default_binding_modes: bool,
1657}
1658
1659impl<'hir> Pat<'hir> {
1660 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1661 if !it(self) {
1662 return false;
1663 }
1664
1665 use PatKind::*;
1666 match self.kind {
1667 Missing => unreachable!(),
1668 Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1669 Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_short_(it),
1670 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1671 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1672 Slice(before, slice, after) => {
1673 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1674 }
1675 }
1676 }
1677
1678 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1685 self.walk_short_(&mut it)
1686 }
1687
1688 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1689 if !it(self) {
1690 return;
1691 }
1692
1693 use PatKind::*;
1694 match self.kind {
1695 Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1696 Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1697 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1698 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1699 Slice(before, slice, after) => {
1700 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1701 }
1702 }
1703 }
1704
1705 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1709 self.walk_(&mut it)
1710 }
1711
1712 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1716 self.walk(|p| {
1717 it(p);
1718 true
1719 })
1720 }
1721
1722 pub fn is_never_pattern(&self) -> bool {
1724 let mut is_never_pattern = false;
1725 self.walk(|pat| match &pat.kind {
1726 PatKind::Never => {
1727 is_never_pattern = true;
1728 false
1729 }
1730 PatKind::Or(s) => {
1731 is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1732 false
1733 }
1734 _ => true,
1735 });
1736 is_never_pattern
1737 }
1738}
1739
1740#[derive(Debug, Clone, Copy, HashStable_Generic)]
1746pub struct PatField<'hir> {
1747 #[stable_hasher(ignore)]
1748 pub hir_id: HirId,
1749 pub ident: Ident,
1751 pub pat: &'hir Pat<'hir>,
1753 pub is_shorthand: bool,
1754 pub span: Span,
1755}
1756
1757#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1758pub enum RangeEnd {
1759 Included,
1760 Excluded,
1761}
1762
1763impl fmt::Display for RangeEnd {
1764 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1765 f.write_str(match self {
1766 RangeEnd::Included => "..=",
1767 RangeEnd::Excluded => "..",
1768 })
1769 }
1770}
1771
1772#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1776pub struct DotDotPos(u32);
1777
1778impl DotDotPos {
1779 pub fn new(n: Option<usize>) -> Self {
1781 match n {
1782 Some(n) => {
1783 assert!(n < u32::MAX as usize);
1784 Self(n as u32)
1785 }
1786 None => Self(u32::MAX),
1787 }
1788 }
1789
1790 pub fn as_opt_usize(&self) -> Option<usize> {
1791 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1792 }
1793}
1794
1795impl fmt::Debug for DotDotPos {
1796 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1797 self.as_opt_usize().fmt(f)
1798 }
1799}
1800
1801#[derive(Debug, Clone, Copy, HashStable_Generic)]
1802pub struct PatExpr<'hir> {
1803 #[stable_hasher(ignore)]
1804 pub hir_id: HirId,
1805 pub span: Span,
1806 pub kind: PatExprKind<'hir>,
1807}
1808
1809#[derive(Debug, Clone, Copy, HashStable_Generic)]
1810pub enum PatExprKind<'hir> {
1811 Lit {
1812 lit: &'hir Lit,
1813 negated: bool,
1816 },
1817 ConstBlock(ConstBlock),
1818 Path(QPath<'hir>),
1820}
1821
1822#[derive(Debug, Clone, Copy, HashStable_Generic)]
1823pub enum TyPatKind<'hir> {
1824 Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1826
1827 Or(&'hir [TyPat<'hir>]),
1829
1830 Err(ErrorGuaranteed),
1832}
1833
1834#[derive(Debug, Clone, Copy, HashStable_Generic)]
1835pub enum PatKind<'hir> {
1836 Missing,
1838
1839 Wild,
1841
1842 Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1853
1854 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1857
1858 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1862
1863 Or(&'hir [Pat<'hir>]),
1866
1867 Never,
1869
1870 Tuple(&'hir [Pat<'hir>], DotDotPos),
1874
1875 Box(&'hir Pat<'hir>),
1877
1878 Deref(&'hir Pat<'hir>),
1880
1881 Ref(&'hir Pat<'hir>, Mutability),
1883
1884 Expr(&'hir PatExpr<'hir>),
1886
1887 Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
1889
1890 Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
1892
1893 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1903
1904 Err(ErrorGuaranteed),
1906}
1907
1908#[derive(Debug, Clone, Copy, HashStable_Generic)]
1910pub struct Stmt<'hir> {
1911 #[stable_hasher(ignore)]
1912 pub hir_id: HirId,
1913 pub kind: StmtKind<'hir>,
1914 pub span: Span,
1915}
1916
1917#[derive(Debug, Clone, Copy, HashStable_Generic)]
1919pub enum StmtKind<'hir> {
1920 Let(&'hir LetStmt<'hir>),
1922
1923 Item(ItemId),
1925
1926 Expr(&'hir Expr<'hir>),
1928
1929 Semi(&'hir Expr<'hir>),
1931}
1932
1933#[derive(Debug, Clone, Copy, HashStable_Generic)]
1935pub struct LetStmt<'hir> {
1936 pub super_: Option<Span>,
1938 pub pat: &'hir Pat<'hir>,
1939 pub ty: Option<&'hir Ty<'hir>>,
1941 pub init: Option<&'hir Expr<'hir>>,
1943 pub els: Option<&'hir Block<'hir>>,
1945 #[stable_hasher(ignore)]
1946 pub hir_id: HirId,
1947 pub span: Span,
1948 pub source: LocalSource,
1952}
1953
1954#[derive(Debug, Clone, Copy, HashStable_Generic)]
1957pub struct Arm<'hir> {
1958 #[stable_hasher(ignore)]
1959 pub hir_id: HirId,
1960 pub span: Span,
1961 pub pat: &'hir Pat<'hir>,
1963 pub guard: Option<&'hir Expr<'hir>>,
1965 pub body: &'hir Expr<'hir>,
1967}
1968
1969#[derive(Debug, Clone, Copy, HashStable_Generic)]
1975pub struct LetExpr<'hir> {
1976 pub span: Span,
1977 pub pat: &'hir Pat<'hir>,
1978 pub ty: Option<&'hir Ty<'hir>>,
1979 pub init: &'hir Expr<'hir>,
1980 pub recovered: ast::Recovered,
1983}
1984
1985#[derive(Debug, Clone, Copy, HashStable_Generic)]
1986pub struct ExprField<'hir> {
1987 #[stable_hasher(ignore)]
1988 pub hir_id: HirId,
1989 pub ident: Ident,
1990 pub expr: &'hir Expr<'hir>,
1991 pub span: Span,
1992 pub is_shorthand: bool,
1993}
1994
1995#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
1996pub enum BlockCheckMode {
1997 DefaultBlock,
1998 UnsafeBlock(UnsafeSource),
1999}
2000
2001#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2002pub enum UnsafeSource {
2003 CompilerGenerated,
2004 UserProvided,
2005}
2006
2007#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
2008pub struct BodyId {
2009 pub hir_id: HirId,
2010}
2011
2012#[derive(Debug, Clone, Copy, HashStable_Generic)]
2034pub struct Body<'hir> {
2035 pub params: &'hir [Param<'hir>],
2036 pub value: &'hir Expr<'hir>,
2037}
2038
2039impl<'hir> Body<'hir> {
2040 pub fn id(&self) -> BodyId {
2041 BodyId { hir_id: self.value.hir_id }
2042 }
2043}
2044
2045#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2047pub enum CoroutineKind {
2048 Desugared(CoroutineDesugaring, CoroutineSource),
2050
2051 Coroutine(Movability),
2053}
2054
2055impl CoroutineKind {
2056 pub fn movability(self) -> Movability {
2057 match self {
2058 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2059 | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2060 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2061 CoroutineKind::Coroutine(mov) => mov,
2062 }
2063 }
2064}
2065
2066impl CoroutineKind {
2067 pub fn is_fn_like(self) -> bool {
2068 matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2069 }
2070}
2071
2072impl fmt::Display for CoroutineKind {
2073 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2074 match self {
2075 CoroutineKind::Desugared(d, k) => {
2076 d.fmt(f)?;
2077 k.fmt(f)
2078 }
2079 CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2080 }
2081 }
2082}
2083
2084#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
2090pub enum CoroutineSource {
2091 Block,
2093
2094 Closure,
2096
2097 Fn,
2099}
2100
2101impl fmt::Display for CoroutineSource {
2102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2103 match self {
2104 CoroutineSource::Block => "block",
2105 CoroutineSource::Closure => "closure body",
2106 CoroutineSource::Fn => "fn body",
2107 }
2108 .fmt(f)
2109 }
2110}
2111
2112#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
2113pub enum CoroutineDesugaring {
2114 Async,
2116
2117 Gen,
2119
2120 AsyncGen,
2123}
2124
2125impl fmt::Display for CoroutineDesugaring {
2126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2127 match self {
2128 CoroutineDesugaring::Async => {
2129 if f.alternate() {
2130 f.write_str("`async` ")?;
2131 } else {
2132 f.write_str("async ")?
2133 }
2134 }
2135 CoroutineDesugaring::Gen => {
2136 if f.alternate() {
2137 f.write_str("`gen` ")?;
2138 } else {
2139 f.write_str("gen ")?
2140 }
2141 }
2142 CoroutineDesugaring::AsyncGen => {
2143 if f.alternate() {
2144 f.write_str("`async gen` ")?;
2145 } else {
2146 f.write_str("async gen ")?
2147 }
2148 }
2149 }
2150
2151 Ok(())
2152 }
2153}
2154
2155#[derive(Copy, Clone, Debug)]
2156pub enum BodyOwnerKind {
2157 Fn,
2159
2160 Closure,
2162
2163 Const { inline: bool },
2165
2166 Static(Mutability),
2168
2169 GlobalAsm,
2171}
2172
2173impl BodyOwnerKind {
2174 pub fn is_fn_or_closure(self) -> bool {
2175 match self {
2176 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2177 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2178 false
2179 }
2180 }
2181 }
2182}
2183
2184#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2186pub enum ConstContext {
2187 ConstFn,
2189
2190 Static(Mutability),
2192
2193 Const { inline: bool },
2203}
2204
2205impl ConstContext {
2206 pub fn keyword_name(self) -> &'static str {
2210 match self {
2211 Self::Const { .. } => "const",
2212 Self::Static(Mutability::Not) => "static",
2213 Self::Static(Mutability::Mut) => "static mut",
2214 Self::ConstFn => "const fn",
2215 }
2216 }
2217}
2218
2219impl fmt::Display for ConstContext {
2222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2223 match *self {
2224 Self::Const { .. } => write!(f, "constant"),
2225 Self::Static(_) => write!(f, "static"),
2226 Self::ConstFn => write!(f, "constant function"),
2227 }
2228 }
2229}
2230
2231pub type Lit = Spanned<LitKind>;
2236
2237#[derive(Copy, Clone, Debug, HashStable_Generic)]
2246pub struct AnonConst {
2247 #[stable_hasher(ignore)]
2248 pub hir_id: HirId,
2249 pub def_id: LocalDefId,
2250 pub body: BodyId,
2251 pub span: Span,
2252}
2253
2254#[derive(Copy, Clone, Debug, HashStable_Generic)]
2256pub struct ConstBlock {
2257 #[stable_hasher(ignore)]
2258 pub hir_id: HirId,
2259 pub def_id: LocalDefId,
2260 pub body: BodyId,
2261}
2262
2263#[derive(Debug, Clone, Copy, HashStable_Generic)]
2272pub struct Expr<'hir> {
2273 #[stable_hasher(ignore)]
2274 pub hir_id: HirId,
2275 pub kind: ExprKind<'hir>,
2276 pub span: Span,
2277}
2278
2279impl Expr<'_> {
2280 pub fn precedence(&self) -> ExprPrecedence {
2281 match &self.kind {
2282 ExprKind::Closure(closure) => {
2283 match closure.fn_decl.output {
2284 FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2285 FnRetTy::Return(_) => ExprPrecedence::Unambiguous,
2286 }
2287 }
2288
2289 ExprKind::Break(..)
2290 | ExprKind::Ret(..)
2291 | ExprKind::Yield(..)
2292 | ExprKind::Become(..) => ExprPrecedence::Jump,
2293
2294 ExprKind::Binary(op, ..) => op.node.precedence(),
2296 ExprKind::Cast(..) => ExprPrecedence::Cast,
2297
2298 ExprKind::Assign(..) |
2299 ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2300
2301 ExprKind::AddrOf(..)
2303 | ExprKind::Let(..)
2308 | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2309
2310 ExprKind::Array(_)
2312 | ExprKind::Block(..)
2313 | ExprKind::Call(..)
2314 | ExprKind::ConstBlock(_)
2315 | ExprKind::Continue(..)
2316 | ExprKind::Field(..)
2317 | ExprKind::If(..)
2318 | ExprKind::Index(..)
2319 | ExprKind::InlineAsm(..)
2320 | ExprKind::Lit(_)
2321 | ExprKind::Loop(..)
2322 | ExprKind::Match(..)
2323 | ExprKind::MethodCall(..)
2324 | ExprKind::OffsetOf(..)
2325 | ExprKind::Path(..)
2326 | ExprKind::Repeat(..)
2327 | ExprKind::Struct(..)
2328 | ExprKind::Tup(_)
2329 | ExprKind::Type(..)
2330 | ExprKind::UnsafeBinderCast(..)
2331 | ExprKind::Use(..)
2332 | ExprKind::Err(_) => ExprPrecedence::Unambiguous,
2333
2334 ExprKind::DropTemps(expr, ..) => expr.precedence(),
2335 }
2336 }
2337
2338 pub fn is_syntactic_place_expr(&self) -> bool {
2343 self.is_place_expr(|_| true)
2344 }
2345
2346 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2351 match self.kind {
2352 ExprKind::Path(QPath::Resolved(_, ref path)) => {
2353 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2354 }
2355
2356 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2360
2361 ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2363
2364 ExprKind::Unary(UnOp::Deref, _) => true,
2365
2366 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2367 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2368 }
2369
2370 ExprKind::Path(QPath::LangItem(..)) => false,
2372
2373 ExprKind::Err(_guar)
2375 | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2376
2377 ExprKind::Path(QPath::TypeRelative(..))
2380 | ExprKind::Call(..)
2381 | ExprKind::MethodCall(..)
2382 | ExprKind::Use(..)
2383 | ExprKind::Struct(..)
2384 | ExprKind::Tup(..)
2385 | ExprKind::If(..)
2386 | ExprKind::Match(..)
2387 | ExprKind::Closure { .. }
2388 | ExprKind::Block(..)
2389 | ExprKind::Repeat(..)
2390 | ExprKind::Array(..)
2391 | ExprKind::Break(..)
2392 | ExprKind::Continue(..)
2393 | ExprKind::Ret(..)
2394 | ExprKind::Become(..)
2395 | ExprKind::Let(..)
2396 | ExprKind::Loop(..)
2397 | ExprKind::Assign(..)
2398 | ExprKind::InlineAsm(..)
2399 | ExprKind::OffsetOf(..)
2400 | ExprKind::AssignOp(..)
2401 | ExprKind::Lit(_)
2402 | ExprKind::ConstBlock(..)
2403 | ExprKind::Unary(..)
2404 | ExprKind::AddrOf(..)
2405 | ExprKind::Binary(..)
2406 | ExprKind::Yield(..)
2407 | ExprKind::Cast(..)
2408 | ExprKind::DropTemps(..) => false,
2409 }
2410 }
2411
2412 pub fn is_size_lit(&self) -> bool {
2415 matches!(
2416 self.kind,
2417 ExprKind::Lit(Lit {
2418 node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2419 ..
2420 })
2421 )
2422 }
2423
2424 pub fn peel_drop_temps(&self) -> &Self {
2430 let mut expr = self;
2431 while let ExprKind::DropTemps(inner) = &expr.kind {
2432 expr = inner;
2433 }
2434 expr
2435 }
2436
2437 pub fn peel_blocks(&self) -> &Self {
2438 let mut expr = self;
2439 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2440 expr = inner;
2441 }
2442 expr
2443 }
2444
2445 pub fn peel_borrows(&self) -> &Self {
2446 let mut expr = self;
2447 while let ExprKind::AddrOf(.., inner) = &expr.kind {
2448 expr = inner;
2449 }
2450 expr
2451 }
2452
2453 pub fn can_have_side_effects(&self) -> bool {
2454 match self.peel_drop_temps().kind {
2455 ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2456 false
2457 }
2458 ExprKind::Type(base, _)
2459 | ExprKind::Unary(_, base)
2460 | ExprKind::Field(base, _)
2461 | ExprKind::Index(base, _, _)
2462 | ExprKind::AddrOf(.., base)
2463 | ExprKind::Cast(base, _)
2464 | ExprKind::UnsafeBinderCast(_, base, _) => {
2465 base.can_have_side_effects()
2469 }
2470 ExprKind::Struct(_, fields, init) => {
2471 let init_side_effects = match init {
2472 StructTailExpr::Base(init) => init.can_have_side_effects(),
2473 StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2474 };
2475 fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2476 || init_side_effects
2477 }
2478
2479 ExprKind::Array(args)
2480 | ExprKind::Tup(args)
2481 | ExprKind::Call(
2482 Expr {
2483 kind:
2484 ExprKind::Path(QPath::Resolved(
2485 None,
2486 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2487 )),
2488 ..
2489 },
2490 args,
2491 ) => args.iter().any(|arg| arg.can_have_side_effects()),
2492 ExprKind::If(..)
2493 | ExprKind::Match(..)
2494 | ExprKind::MethodCall(..)
2495 | ExprKind::Call(..)
2496 | ExprKind::Closure { .. }
2497 | ExprKind::Block(..)
2498 | ExprKind::Repeat(..)
2499 | ExprKind::Break(..)
2500 | ExprKind::Continue(..)
2501 | ExprKind::Ret(..)
2502 | ExprKind::Become(..)
2503 | ExprKind::Let(..)
2504 | ExprKind::Loop(..)
2505 | ExprKind::Assign(..)
2506 | ExprKind::InlineAsm(..)
2507 | ExprKind::AssignOp(..)
2508 | ExprKind::ConstBlock(..)
2509 | ExprKind::Binary(..)
2510 | ExprKind::Yield(..)
2511 | ExprKind::DropTemps(..)
2512 | ExprKind::Err(_) => true,
2513 }
2514 }
2515
2516 pub fn is_approximately_pattern(&self) -> bool {
2518 match &self.kind {
2519 ExprKind::Array(_)
2520 | ExprKind::Call(..)
2521 | ExprKind::Tup(_)
2522 | ExprKind::Lit(_)
2523 | ExprKind::Path(_)
2524 | ExprKind::Struct(..) => true,
2525 _ => false,
2526 }
2527 }
2528
2529 pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2534 match (self.kind, other.kind) {
2535 (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2536 (
2537 ExprKind::Path(QPath::LangItem(item1, _)),
2538 ExprKind::Path(QPath::LangItem(item2, _)),
2539 ) => item1 == item2,
2540 (
2541 ExprKind::Path(QPath::Resolved(None, path1)),
2542 ExprKind::Path(QPath::Resolved(None, path2)),
2543 ) => path1.res == path2.res,
2544 (
2545 ExprKind::Struct(
2546 QPath::LangItem(LangItem::RangeTo, _),
2547 [val1],
2548 StructTailExpr::None,
2549 ),
2550 ExprKind::Struct(
2551 QPath::LangItem(LangItem::RangeTo, _),
2552 [val2],
2553 StructTailExpr::None,
2554 ),
2555 )
2556 | (
2557 ExprKind::Struct(
2558 QPath::LangItem(LangItem::RangeToInclusive, _),
2559 [val1],
2560 StructTailExpr::None,
2561 ),
2562 ExprKind::Struct(
2563 QPath::LangItem(LangItem::RangeToInclusive, _),
2564 [val2],
2565 StructTailExpr::None,
2566 ),
2567 )
2568 | (
2569 ExprKind::Struct(
2570 QPath::LangItem(LangItem::RangeFrom, _),
2571 [val1],
2572 StructTailExpr::None,
2573 ),
2574 ExprKind::Struct(
2575 QPath::LangItem(LangItem::RangeFrom, _),
2576 [val2],
2577 StructTailExpr::None,
2578 ),
2579 )
2580 | (
2581 ExprKind::Struct(
2582 QPath::LangItem(LangItem::RangeFromCopy, _),
2583 [val1],
2584 StructTailExpr::None,
2585 ),
2586 ExprKind::Struct(
2587 QPath::LangItem(LangItem::RangeFromCopy, _),
2588 [val2],
2589 StructTailExpr::None,
2590 ),
2591 ) => val1.expr.equivalent_for_indexing(val2.expr),
2592 (
2593 ExprKind::Struct(
2594 QPath::LangItem(LangItem::Range, _),
2595 [val1, val3],
2596 StructTailExpr::None,
2597 ),
2598 ExprKind::Struct(
2599 QPath::LangItem(LangItem::Range, _),
2600 [val2, val4],
2601 StructTailExpr::None,
2602 ),
2603 )
2604 | (
2605 ExprKind::Struct(
2606 QPath::LangItem(LangItem::RangeCopy, _),
2607 [val1, val3],
2608 StructTailExpr::None,
2609 ),
2610 ExprKind::Struct(
2611 QPath::LangItem(LangItem::RangeCopy, _),
2612 [val2, val4],
2613 StructTailExpr::None,
2614 ),
2615 )
2616 | (
2617 ExprKind::Struct(
2618 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2619 [val1, val3],
2620 StructTailExpr::None,
2621 ),
2622 ExprKind::Struct(
2623 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2624 [val2, val4],
2625 StructTailExpr::None,
2626 ),
2627 ) => {
2628 val1.expr.equivalent_for_indexing(val2.expr)
2629 && val3.expr.equivalent_for_indexing(val4.expr)
2630 }
2631 _ => false,
2632 }
2633 }
2634
2635 pub fn method_ident(&self) -> Option<Ident> {
2636 match self.kind {
2637 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2638 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2639 _ => None,
2640 }
2641 }
2642}
2643
2644pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2647 match expr.kind {
2648 ExprKind::Struct(ref qpath, _, _) => matches!(
2650 **qpath,
2651 QPath::LangItem(
2652 LangItem::Range
2653 | LangItem::RangeTo
2654 | LangItem::RangeFrom
2655 | LangItem::RangeFull
2656 | LangItem::RangeToInclusive
2657 | LangItem::RangeCopy
2658 | LangItem::RangeFromCopy
2659 | LangItem::RangeInclusiveCopy,
2660 ..
2661 )
2662 ),
2663
2664 ExprKind::Call(ref func, _) => {
2666 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
2667 }
2668
2669 _ => false,
2670 }
2671}
2672
2673pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2680 match expr.kind {
2681 ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2683 _ if is_range_literal(expr) => true,
2685 _ => false,
2686 }
2687}
2688
2689#[derive(Debug, Clone, Copy, HashStable_Generic)]
2690pub enum ExprKind<'hir> {
2691 ConstBlock(ConstBlock),
2693 Array(&'hir [Expr<'hir>]),
2695 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2702 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2719 Use(&'hir Expr<'hir>, Span),
2721 Tup(&'hir [Expr<'hir>]),
2723 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2725 Unary(UnOp, &'hir Expr<'hir>),
2727 Lit(&'hir Lit),
2729 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2731 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2733 DropTemps(&'hir Expr<'hir>),
2739 Let(&'hir LetExpr<'hir>),
2744 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2753 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2759 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2762 Closure(&'hir Closure<'hir>),
2769 Block(&'hir Block<'hir>, Option<Label>),
2771
2772 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2774 AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2778 Field(&'hir Expr<'hir>, Ident),
2780 Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2784
2785 Path(QPath<'hir>),
2787
2788 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2790 Break(Destination, Option<&'hir Expr<'hir>>),
2792 Continue(Destination),
2794 Ret(Option<&'hir Expr<'hir>>),
2796 Become(&'hir Expr<'hir>),
2798
2799 InlineAsm(&'hir InlineAsm<'hir>),
2801
2802 OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2804
2805 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2810
2811 Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2816
2817 Yield(&'hir Expr<'hir>, YieldSource),
2819
2820 UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2823
2824 Err(rustc_span::ErrorGuaranteed),
2826}
2827
2828#[derive(Debug, Clone, Copy, HashStable_Generic)]
2829pub enum StructTailExpr<'hir> {
2830 None,
2832 Base(&'hir Expr<'hir>),
2835 DefaultFields(Span),
2839}
2840
2841#[derive(Debug, Clone, Copy, HashStable_Generic)]
2847pub enum QPath<'hir> {
2848 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2855
2856 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2863
2864 LangItem(LangItem, Span),
2866}
2867
2868impl<'hir> QPath<'hir> {
2869 pub fn span(&self) -> Span {
2871 match *self {
2872 QPath::Resolved(_, path) => path.span,
2873 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2874 QPath::LangItem(_, span) => span,
2875 }
2876 }
2877
2878 pub fn qself_span(&self) -> Span {
2881 match *self {
2882 QPath::Resolved(_, path) => path.span,
2883 QPath::TypeRelative(qself, _) => qself.span,
2884 QPath::LangItem(_, span) => span,
2885 }
2886 }
2887}
2888
2889#[derive(Copy, Clone, Debug, HashStable_Generic)]
2891pub enum LocalSource {
2892 Normal,
2894 AsyncFn,
2905 AwaitDesugar,
2907 AssignDesugar(Span),
2910 Contract,
2912}
2913
2914#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2916pub enum MatchSource {
2917 Normal,
2919 Postfix,
2921 ForLoopDesugar,
2923 TryDesugar(HirId),
2925 AwaitDesugar,
2927 FormatArgs,
2929}
2930
2931impl MatchSource {
2932 #[inline]
2933 pub const fn name(self) -> &'static str {
2934 use MatchSource::*;
2935 match self {
2936 Normal => "match",
2937 Postfix => ".match",
2938 ForLoopDesugar => "for",
2939 TryDesugar(_) => "?",
2940 AwaitDesugar => ".await",
2941 FormatArgs => "format_args!()",
2942 }
2943 }
2944}
2945
2946#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2948pub enum LoopSource {
2949 Loop,
2951 While,
2953 ForLoop,
2955}
2956
2957impl LoopSource {
2958 pub fn name(self) -> &'static str {
2959 match self {
2960 LoopSource::Loop => "loop",
2961 LoopSource::While => "while",
2962 LoopSource::ForLoop => "for",
2963 }
2964 }
2965}
2966
2967#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2968pub enum LoopIdError {
2969 OutsideLoopScope,
2970 UnlabeledCfInWhileCondition,
2971 UnresolvedLabel,
2972}
2973
2974impl fmt::Display for LoopIdError {
2975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2976 f.write_str(match self {
2977 LoopIdError::OutsideLoopScope => "not inside loop scope",
2978 LoopIdError::UnlabeledCfInWhileCondition => {
2979 "unlabeled control flow (break or continue) in while condition"
2980 }
2981 LoopIdError::UnresolvedLabel => "label not found",
2982 })
2983 }
2984}
2985
2986#[derive(Copy, Clone, Debug, HashStable_Generic)]
2987pub struct Destination {
2988 pub label: Option<Label>,
2990
2991 pub target_id: Result<HirId, LoopIdError>,
2994}
2995
2996#[derive(Copy, Clone, Debug, HashStable_Generic)]
2998pub enum YieldSource {
2999 Await { expr: Option<HirId> },
3001 Yield,
3003}
3004
3005impl fmt::Display for YieldSource {
3006 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3007 f.write_str(match self {
3008 YieldSource::Await { .. } => "`await`",
3009 YieldSource::Yield => "`yield`",
3010 })
3011 }
3012}
3013
3014#[derive(Debug, Clone, Copy, HashStable_Generic)]
3017pub struct MutTy<'hir> {
3018 pub ty: &'hir Ty<'hir>,
3019 pub mutbl: Mutability,
3020}
3021
3022#[derive(Debug, Clone, Copy, HashStable_Generic)]
3025pub struct FnSig<'hir> {
3026 pub header: FnHeader,
3027 pub decl: &'hir FnDecl<'hir>,
3028 pub span: Span,
3029}
3030
3031#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3035pub struct TraitItemId {
3036 pub owner_id: OwnerId,
3037}
3038
3039impl TraitItemId {
3040 #[inline]
3041 pub fn hir_id(&self) -> HirId {
3042 HirId::make_owner(self.owner_id.def_id)
3044 }
3045}
3046
3047#[derive(Debug, Clone, Copy, HashStable_Generic)]
3052pub struct TraitItem<'hir> {
3053 pub ident: Ident,
3054 pub owner_id: OwnerId,
3055 pub generics: &'hir Generics<'hir>,
3056 pub kind: TraitItemKind<'hir>,
3057 pub span: Span,
3058 pub defaultness: Defaultness,
3059}
3060
3061macro_rules! expect_methods_self_kind {
3062 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3063 $(
3064 #[track_caller]
3065 pub fn $name(&self) -> $ret_ty {
3066 let $pat = &self.kind else { expect_failed(stringify!($ident), self) };
3067 $ret_val
3068 }
3069 )*
3070 }
3071}
3072
3073macro_rules! expect_methods_self {
3074 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3075 $(
3076 #[track_caller]
3077 pub fn $name(&self) -> $ret_ty {
3078 let $pat = self else { expect_failed(stringify!($ident), self) };
3079 $ret_val
3080 }
3081 )*
3082 }
3083}
3084
3085#[track_caller]
3086fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3087 panic!("{ident}: found {found:?}")
3088}
3089
3090impl<'hir> TraitItem<'hir> {
3091 #[inline]
3092 pub fn hir_id(&self) -> HirId {
3093 HirId::make_owner(self.owner_id.def_id)
3095 }
3096
3097 pub fn trait_item_id(&self) -> TraitItemId {
3098 TraitItemId { owner_id: self.owner_id }
3099 }
3100
3101 expect_methods_self_kind! {
3102 expect_const, (&'hir Ty<'hir>, Option<BodyId>),
3103 TraitItemKind::Const(ty, body), (ty, *body);
3104
3105 expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3106 TraitItemKind::Fn(ty, trfn), (ty, trfn);
3107
3108 expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3109 TraitItemKind::Type(bounds, ty), (bounds, *ty);
3110 }
3111}
3112
3113#[derive(Debug, Clone, Copy, HashStable_Generic)]
3115pub enum TraitFn<'hir> {
3116 Required(&'hir [Option<Ident>]),
3118
3119 Provided(BodyId),
3121}
3122
3123#[derive(Debug, Clone, Copy, HashStable_Generic)]
3125pub enum TraitItemKind<'hir> {
3126 Const(&'hir Ty<'hir>, Option<BodyId>),
3128 Fn(FnSig<'hir>, TraitFn<'hir>),
3130 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3133}
3134
3135#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3139pub struct ImplItemId {
3140 pub owner_id: OwnerId,
3141}
3142
3143impl ImplItemId {
3144 #[inline]
3145 pub fn hir_id(&self) -> HirId {
3146 HirId::make_owner(self.owner_id.def_id)
3148 }
3149}
3150
3151#[derive(Debug, Clone, Copy, HashStable_Generic)]
3155pub struct ImplItem<'hir> {
3156 pub ident: Ident,
3157 pub owner_id: OwnerId,
3158 pub generics: &'hir Generics<'hir>,
3159 pub kind: ImplItemKind<'hir>,
3160 pub defaultness: Defaultness,
3161 pub span: Span,
3162 pub vis_span: Span,
3163}
3164
3165impl<'hir> ImplItem<'hir> {
3166 #[inline]
3167 pub fn hir_id(&self) -> HirId {
3168 HirId::make_owner(self.owner_id.def_id)
3170 }
3171
3172 pub fn impl_item_id(&self) -> ImplItemId {
3173 ImplItemId { owner_id: self.owner_id }
3174 }
3175
3176 expect_methods_self_kind! {
3177 expect_const, (&'hir Ty<'hir>, BodyId), ImplItemKind::Const(ty, body), (ty, *body);
3178 expect_fn, (&FnSig<'hir>, BodyId), ImplItemKind::Fn(ty, body), (ty, *body);
3179 expect_type, &'hir Ty<'hir>, ImplItemKind::Type(ty), ty;
3180 }
3181}
3182
3183#[derive(Debug, Clone, Copy, HashStable_Generic)]
3185pub enum ImplItemKind<'hir> {
3186 Const(&'hir Ty<'hir>, BodyId),
3189 Fn(FnSig<'hir>, BodyId),
3191 Type(&'hir Ty<'hir>),
3193}
3194
3195#[derive(Debug, Clone, Copy, HashStable_Generic)]
3206pub struct AssocItemConstraint<'hir> {
3207 #[stable_hasher(ignore)]
3208 pub hir_id: HirId,
3209 pub ident: Ident,
3210 pub gen_args: &'hir GenericArgs<'hir>,
3211 pub kind: AssocItemConstraintKind<'hir>,
3212 pub span: Span,
3213}
3214
3215impl<'hir> AssocItemConstraint<'hir> {
3216 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3218 match self.kind {
3219 AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3220 _ => None,
3221 }
3222 }
3223
3224 pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3226 match self.kind {
3227 AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3228 _ => None,
3229 }
3230 }
3231}
3232
3233#[derive(Debug, Clone, Copy, HashStable_Generic)]
3234pub enum Term<'hir> {
3235 Ty(&'hir Ty<'hir>),
3236 Const(&'hir ConstArg<'hir>),
3237}
3238
3239impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3240 fn from(ty: &'hir Ty<'hir>) -> Self {
3241 Term::Ty(ty)
3242 }
3243}
3244
3245impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3246 fn from(c: &'hir ConstArg<'hir>) -> Self {
3247 Term::Const(c)
3248 }
3249}
3250
3251#[derive(Debug, Clone, Copy, HashStable_Generic)]
3253pub enum AssocItemConstraintKind<'hir> {
3254 Equality { term: Term<'hir> },
3261 Bound { bounds: &'hir [GenericBound<'hir>] },
3263}
3264
3265impl<'hir> AssocItemConstraintKind<'hir> {
3266 pub fn descr(&self) -> &'static str {
3267 match self {
3268 AssocItemConstraintKind::Equality { .. } => "binding",
3269 AssocItemConstraintKind::Bound { .. } => "constraint",
3270 }
3271 }
3272}
3273
3274#[derive(Debug, Clone, Copy, HashStable_Generic)]
3278pub enum AmbigArg {}
3279
3280#[derive(Debug, Clone, Copy, HashStable_Generic)]
3281#[repr(C)]
3282pub struct Ty<'hir, Unambig = ()> {
3289 #[stable_hasher(ignore)]
3290 pub hir_id: HirId,
3291 pub span: Span,
3292 pub kind: TyKind<'hir, Unambig>,
3293}
3294
3295impl<'hir> Ty<'hir, AmbigArg> {
3296 pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3307 let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3310 unsafe { &*ptr }
3311 }
3312}
3313
3314impl<'hir> Ty<'hir> {
3315 pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3321 if let TyKind::Infer(()) = self.kind {
3322 return None;
3323 }
3324
3325 let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3329 Some(unsafe { &*ptr })
3330 }
3331}
3332
3333impl<'hir> Ty<'hir, AmbigArg> {
3334 pub fn peel_refs(&self) -> &Ty<'hir> {
3335 let mut final_ty = self.as_unambig_ty();
3336 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3337 final_ty = ty;
3338 }
3339 final_ty
3340 }
3341}
3342
3343impl<'hir> Ty<'hir> {
3344 pub fn peel_refs(&self) -> &Self {
3345 let mut final_ty = self;
3346 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3347 final_ty = ty;
3348 }
3349 final_ty
3350 }
3351
3352 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3354 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3355 return None;
3356 };
3357 let [segment] = &path.segments else {
3358 return None;
3359 };
3360 match path.res {
3361 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3362 Some((def_id, segment.ident))
3363 }
3364 _ => None,
3365 }
3366 }
3367
3368 pub fn find_self_aliases(&self) -> Vec<Span> {
3369 use crate::intravisit::Visitor;
3370 struct MyVisitor(Vec<Span>);
3371 impl<'v> Visitor<'v> for MyVisitor {
3372 fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3373 if matches!(
3374 &t.kind,
3375 TyKind::Path(QPath::Resolved(
3376 _,
3377 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3378 ))
3379 ) {
3380 self.0.push(t.span);
3381 return;
3382 }
3383 crate::intravisit::walk_ty(self, t);
3384 }
3385 }
3386
3387 let mut my_visitor = MyVisitor(vec![]);
3388 my_visitor.visit_ty_unambig(self);
3389 my_visitor.0
3390 }
3391
3392 pub fn is_suggestable_infer_ty(&self) -> bool {
3395 fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3396 generic_args.iter().any(|arg| match arg {
3397 GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3398 GenericArg::Infer(_) => true,
3399 _ => false,
3400 })
3401 }
3402 debug!(?self);
3403 match &self.kind {
3404 TyKind::Infer(()) => true,
3405 TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3406 TyKind::Array(ty, length) => {
3407 ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3408 }
3409 TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3410 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3411 TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3412 ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3413 }
3414 TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3415 ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3416 || segments
3417 .iter()
3418 .any(|segment| are_suggestable_generic_args(segment.args().args))
3419 }
3420 _ => false,
3421 }
3422 }
3423}
3424
3425#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3427pub enum PrimTy {
3428 Int(IntTy),
3429 Uint(UintTy),
3430 Float(FloatTy),
3431 Str,
3432 Bool,
3433 Char,
3434}
3435
3436impl PrimTy {
3437 pub const ALL: [Self; 19] = [
3439 Self::Int(IntTy::I8),
3441 Self::Int(IntTy::I16),
3442 Self::Int(IntTy::I32),
3443 Self::Int(IntTy::I64),
3444 Self::Int(IntTy::I128),
3445 Self::Int(IntTy::Isize),
3446 Self::Uint(UintTy::U8),
3447 Self::Uint(UintTy::U16),
3448 Self::Uint(UintTy::U32),
3449 Self::Uint(UintTy::U64),
3450 Self::Uint(UintTy::U128),
3451 Self::Uint(UintTy::Usize),
3452 Self::Float(FloatTy::F16),
3453 Self::Float(FloatTy::F32),
3454 Self::Float(FloatTy::F64),
3455 Self::Float(FloatTy::F128),
3456 Self::Bool,
3457 Self::Char,
3458 Self::Str,
3459 ];
3460
3461 pub fn name_str(self) -> &'static str {
3465 match self {
3466 PrimTy::Int(i) => i.name_str(),
3467 PrimTy::Uint(u) => u.name_str(),
3468 PrimTy::Float(f) => f.name_str(),
3469 PrimTy::Str => "str",
3470 PrimTy::Bool => "bool",
3471 PrimTy::Char => "char",
3472 }
3473 }
3474
3475 pub fn name(self) -> Symbol {
3476 match self {
3477 PrimTy::Int(i) => i.name(),
3478 PrimTy::Uint(u) => u.name(),
3479 PrimTy::Float(f) => f.name(),
3480 PrimTy::Str => sym::str,
3481 PrimTy::Bool => sym::bool,
3482 PrimTy::Char => sym::char,
3483 }
3484 }
3485
3486 pub fn from_name(name: Symbol) -> Option<Self> {
3489 let ty = match name {
3490 sym::i8 => Self::Int(IntTy::I8),
3492 sym::i16 => Self::Int(IntTy::I16),
3493 sym::i32 => Self::Int(IntTy::I32),
3494 sym::i64 => Self::Int(IntTy::I64),
3495 sym::i128 => Self::Int(IntTy::I128),
3496 sym::isize => Self::Int(IntTy::Isize),
3497 sym::u8 => Self::Uint(UintTy::U8),
3498 sym::u16 => Self::Uint(UintTy::U16),
3499 sym::u32 => Self::Uint(UintTy::U32),
3500 sym::u64 => Self::Uint(UintTy::U64),
3501 sym::u128 => Self::Uint(UintTy::U128),
3502 sym::usize => Self::Uint(UintTy::Usize),
3503 sym::f16 => Self::Float(FloatTy::F16),
3504 sym::f32 => Self::Float(FloatTy::F32),
3505 sym::f64 => Self::Float(FloatTy::F64),
3506 sym::f128 => Self::Float(FloatTy::F128),
3507 sym::bool => Self::Bool,
3508 sym::char => Self::Char,
3509 sym::str => Self::Str,
3510 _ => return None,
3511 };
3512 Some(ty)
3513 }
3514}
3515
3516#[derive(Debug, Clone, Copy, HashStable_Generic)]
3517pub struct BareFnTy<'hir> {
3518 pub safety: Safety,
3519 pub abi: ExternAbi,
3520 pub generic_params: &'hir [GenericParam<'hir>],
3521 pub decl: &'hir FnDecl<'hir>,
3522 pub param_idents: &'hir [Option<Ident>],
3525}
3526
3527#[derive(Debug, Clone, Copy, HashStable_Generic)]
3528pub struct UnsafeBinderTy<'hir> {
3529 pub generic_params: &'hir [GenericParam<'hir>],
3530 pub inner_ty: &'hir Ty<'hir>,
3531}
3532
3533#[derive(Debug, Clone, Copy, HashStable_Generic)]
3534pub struct OpaqueTy<'hir> {
3535 #[stable_hasher(ignore)]
3536 pub hir_id: HirId,
3537 pub def_id: LocalDefId,
3538 pub bounds: GenericBounds<'hir>,
3539 pub origin: OpaqueTyOrigin<LocalDefId>,
3540 pub span: Span,
3541}
3542
3543#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3544pub enum PreciseCapturingArgKind<T, U> {
3545 Lifetime(T),
3546 Param(U),
3548}
3549
3550pub type PreciseCapturingArg<'hir> =
3551 PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3552
3553impl PreciseCapturingArg<'_> {
3554 pub fn hir_id(self) -> HirId {
3555 match self {
3556 PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3557 PreciseCapturingArg::Param(param) => param.hir_id,
3558 }
3559 }
3560
3561 pub fn name(self) -> Symbol {
3562 match self {
3563 PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3564 PreciseCapturingArg::Param(param) => param.ident.name,
3565 }
3566 }
3567}
3568
3569#[derive(Debug, Clone, Copy, HashStable_Generic)]
3574pub struct PreciseCapturingNonLifetimeArg {
3575 #[stable_hasher(ignore)]
3576 pub hir_id: HirId,
3577 pub ident: Ident,
3578 pub res: Res,
3579}
3580
3581#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3582#[derive(HashStable_Generic, Encodable, Decodable)]
3583pub enum RpitContext {
3584 Trait,
3585 TraitImpl,
3586}
3587
3588#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3590#[derive(HashStable_Generic, Encodable, Decodable)]
3591pub enum OpaqueTyOrigin<D> {
3592 FnReturn {
3594 parent: D,
3596 in_trait_or_impl: Option<RpitContext>,
3598 },
3599 AsyncFn {
3601 parent: D,
3603 in_trait_or_impl: Option<RpitContext>,
3605 },
3606 TyAlias {
3608 parent: D,
3610 in_assoc_ty: bool,
3612 },
3613}
3614
3615#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3616pub enum InferDelegationKind {
3617 Input(usize),
3618 Output,
3619}
3620
3621#[derive(Debug, Clone, Copy, HashStable_Generic)]
3623#[repr(u8, C)]
3625pub enum TyKind<'hir, Unambig = ()> {
3626 InferDelegation(DefId, InferDelegationKind),
3628 Slice(&'hir Ty<'hir>),
3630 Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3632 Ptr(MutTy<'hir>),
3634 Ref(&'hir Lifetime, MutTy<'hir>),
3636 BareFn(&'hir BareFnTy<'hir>),
3638 UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3640 Never,
3642 Tup(&'hir [Ty<'hir>]),
3644 Path(QPath<'hir>),
3649 OpaqueDef(&'hir OpaqueTy<'hir>),
3651 TraitAscription(GenericBounds<'hir>),
3653 TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3659 Typeof(&'hir AnonConst),
3661 Err(rustc_span::ErrorGuaranteed),
3663 Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3665 Infer(Unambig),
3671}
3672
3673#[derive(Debug, Clone, Copy, HashStable_Generic)]
3674pub enum InlineAsmOperand<'hir> {
3675 In {
3676 reg: InlineAsmRegOrRegClass,
3677 expr: &'hir Expr<'hir>,
3678 },
3679 Out {
3680 reg: InlineAsmRegOrRegClass,
3681 late: bool,
3682 expr: Option<&'hir Expr<'hir>>,
3683 },
3684 InOut {
3685 reg: InlineAsmRegOrRegClass,
3686 late: bool,
3687 expr: &'hir Expr<'hir>,
3688 },
3689 SplitInOut {
3690 reg: InlineAsmRegOrRegClass,
3691 late: bool,
3692 in_expr: &'hir Expr<'hir>,
3693 out_expr: Option<&'hir Expr<'hir>>,
3694 },
3695 Const {
3696 anon_const: ConstBlock,
3697 },
3698 SymFn {
3699 expr: &'hir Expr<'hir>,
3700 },
3701 SymStatic {
3702 path: QPath<'hir>,
3703 def_id: DefId,
3704 },
3705 Label {
3706 block: &'hir Block<'hir>,
3707 },
3708}
3709
3710impl<'hir> InlineAsmOperand<'hir> {
3711 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3712 match *self {
3713 Self::In { reg, .. }
3714 | Self::Out { reg, .. }
3715 | Self::InOut { reg, .. }
3716 | Self::SplitInOut { reg, .. } => Some(reg),
3717 Self::Const { .. }
3718 | Self::SymFn { .. }
3719 | Self::SymStatic { .. }
3720 | Self::Label { .. } => None,
3721 }
3722 }
3723
3724 pub fn is_clobber(&self) -> bool {
3725 matches!(
3726 self,
3727 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3728 )
3729 }
3730}
3731
3732#[derive(Debug, Clone, Copy, HashStable_Generic)]
3733pub struct InlineAsm<'hir> {
3734 pub asm_macro: ast::AsmMacro,
3735 pub template: &'hir [InlineAsmTemplatePiece],
3736 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3737 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3738 pub options: InlineAsmOptions,
3739 pub line_spans: &'hir [Span],
3740}
3741
3742impl InlineAsm<'_> {
3743 pub fn contains_label(&self) -> bool {
3744 self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3745 }
3746}
3747
3748#[derive(Debug, Clone, Copy, HashStable_Generic)]
3750pub struct Param<'hir> {
3751 #[stable_hasher(ignore)]
3752 pub hir_id: HirId,
3753 pub pat: &'hir Pat<'hir>,
3754 pub ty_span: Span,
3755 pub span: Span,
3756}
3757
3758#[derive(Debug, Clone, Copy, HashStable_Generic)]
3760pub struct FnDecl<'hir> {
3761 pub inputs: &'hir [Ty<'hir>],
3765 pub output: FnRetTy<'hir>,
3766 pub c_variadic: bool,
3767 pub implicit_self: ImplicitSelfKind,
3769 pub lifetime_elision_allowed: bool,
3771}
3772
3773impl<'hir> FnDecl<'hir> {
3774 pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3775 if let FnRetTy::Return(ty) = self.output
3776 && let TyKind::InferDelegation(sig_id, _) = ty.kind
3777 {
3778 return Some(sig_id);
3779 }
3780 None
3781 }
3782}
3783
3784#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3786pub enum ImplicitSelfKind {
3787 Imm,
3789 Mut,
3791 RefImm,
3793 RefMut,
3795 None,
3798}
3799
3800impl ImplicitSelfKind {
3801 pub fn has_implicit_self(&self) -> bool {
3803 !matches!(*self, ImplicitSelfKind::None)
3804 }
3805}
3806
3807#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3808pub enum IsAsync {
3809 Async(Span),
3810 NotAsync,
3811}
3812
3813impl IsAsync {
3814 pub fn is_async(self) -> bool {
3815 matches!(self, IsAsync::Async(_))
3816 }
3817}
3818
3819#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3820pub enum Defaultness {
3821 Default { has_value: bool },
3822 Final,
3823}
3824
3825impl Defaultness {
3826 pub fn has_value(&self) -> bool {
3827 match *self {
3828 Defaultness::Default { has_value } => has_value,
3829 Defaultness::Final => true,
3830 }
3831 }
3832
3833 pub fn is_final(&self) -> bool {
3834 *self == Defaultness::Final
3835 }
3836
3837 pub fn is_default(&self) -> bool {
3838 matches!(*self, Defaultness::Default { .. })
3839 }
3840}
3841
3842#[derive(Debug, Clone, Copy, HashStable_Generic)]
3843pub enum FnRetTy<'hir> {
3844 DefaultReturn(Span),
3850 Return(&'hir Ty<'hir>),
3852}
3853
3854impl<'hir> FnRetTy<'hir> {
3855 #[inline]
3856 pub fn span(&self) -> Span {
3857 match *self {
3858 Self::DefaultReturn(span) => span,
3859 Self::Return(ref ty) => ty.span,
3860 }
3861 }
3862
3863 pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3864 if let Self::Return(ty) = self
3865 && ty.is_suggestable_infer_ty()
3866 {
3867 return Some(*ty);
3868 }
3869 None
3870 }
3871}
3872
3873#[derive(Copy, Clone, Debug, HashStable_Generic)]
3875pub enum ClosureBinder {
3876 Default,
3878 For { span: Span },
3882}
3883
3884#[derive(Debug, Clone, Copy, HashStable_Generic)]
3885pub struct Mod<'hir> {
3886 pub spans: ModSpans,
3887 pub item_ids: &'hir [ItemId],
3888}
3889
3890#[derive(Copy, Clone, Debug, HashStable_Generic)]
3891pub struct ModSpans {
3892 pub inner_span: Span,
3896 pub inject_use_span: Span,
3897}
3898
3899#[derive(Debug, Clone, Copy, HashStable_Generic)]
3900pub struct EnumDef<'hir> {
3901 pub variants: &'hir [Variant<'hir>],
3902}
3903
3904#[derive(Debug, Clone, Copy, HashStable_Generic)]
3905pub struct Variant<'hir> {
3906 pub ident: Ident,
3908 #[stable_hasher(ignore)]
3910 pub hir_id: HirId,
3911 pub def_id: LocalDefId,
3912 pub data: VariantData<'hir>,
3914 pub disr_expr: Option<&'hir AnonConst>,
3916 pub span: Span,
3918}
3919
3920#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3921pub enum UseKind {
3922 Single(Ident),
3929
3930 Glob,
3932
3933 ListStem,
3937}
3938
3939#[derive(Clone, Debug, Copy, HashStable_Generic)]
3946pub struct TraitRef<'hir> {
3947 pub path: &'hir Path<'hir>,
3948 #[stable_hasher(ignore)]
3950 pub hir_ref_id: HirId,
3951}
3952
3953impl TraitRef<'_> {
3954 pub fn trait_def_id(&self) -> Option<DefId> {
3956 match self.path.res {
3957 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3958 Res::Err => None,
3959 res => panic!("{res:?} did not resolve to a trait or trait alias"),
3960 }
3961 }
3962}
3963
3964#[derive(Clone, Debug, Copy, HashStable_Generic)]
3965pub struct PolyTraitRef<'hir> {
3966 pub bound_generic_params: &'hir [GenericParam<'hir>],
3968
3969 pub modifiers: TraitBoundModifiers,
3973
3974 pub trait_ref: TraitRef<'hir>,
3976
3977 pub span: Span,
3978}
3979
3980#[derive(Debug, Clone, Copy, HashStable_Generic)]
3981pub struct FieldDef<'hir> {
3982 pub span: Span,
3983 pub vis_span: Span,
3984 pub ident: Ident,
3985 #[stable_hasher(ignore)]
3986 pub hir_id: HirId,
3987 pub def_id: LocalDefId,
3988 pub ty: &'hir Ty<'hir>,
3989 pub safety: Safety,
3990 pub default: Option<&'hir AnonConst>,
3991}
3992
3993impl FieldDef<'_> {
3994 pub fn is_positional(&self) -> bool {
3996 self.ident.as_str().as_bytes()[0].is_ascii_digit()
3997 }
3998}
3999
4000#[derive(Debug, Clone, Copy, HashStable_Generic)]
4002pub enum VariantData<'hir> {
4003 Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4007 Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4011 Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4015}
4016
4017impl<'hir> VariantData<'hir> {
4018 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4020 match *self {
4021 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4022 _ => &[],
4023 }
4024 }
4025
4026 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4027 match *self {
4028 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4029 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4030 VariantData::Struct { .. } => None,
4031 }
4032 }
4033
4034 #[inline]
4035 pub fn ctor_kind(&self) -> Option<CtorKind> {
4036 self.ctor().map(|(kind, ..)| kind)
4037 }
4038
4039 #[inline]
4041 pub fn ctor_hir_id(&self) -> Option<HirId> {
4042 self.ctor().map(|(_, hir_id, _)| hir_id)
4043 }
4044
4045 #[inline]
4047 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4048 self.ctor().map(|(.., def_id)| def_id)
4049 }
4050}
4051
4052#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4056pub struct ItemId {
4057 pub owner_id: OwnerId,
4058}
4059
4060impl ItemId {
4061 #[inline]
4062 pub fn hir_id(&self) -> HirId {
4063 HirId::make_owner(self.owner_id.def_id)
4065 }
4066}
4067
4068#[derive(Debug, Clone, Copy, HashStable_Generic)]
4077pub struct Item<'hir> {
4078 pub owner_id: OwnerId,
4079 pub kind: ItemKind<'hir>,
4080 pub span: Span,
4081 pub vis_span: Span,
4082}
4083
4084impl<'hir> Item<'hir> {
4085 #[inline]
4086 pub fn hir_id(&self) -> HirId {
4087 HirId::make_owner(self.owner_id.def_id)
4089 }
4090
4091 pub fn item_id(&self) -> ItemId {
4092 ItemId { owner_id: self.owner_id }
4093 }
4094
4095 pub fn is_adt(&self) -> bool {
4098 matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4099 }
4100
4101 pub fn is_struct_or_union(&self) -> bool {
4103 matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4104 }
4105
4106 expect_methods_self_kind! {
4107 expect_extern_crate, (Option<Symbol>, Ident),
4108 ItemKind::ExternCrate(s, ident), (*s, *ident);
4109
4110 expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4111
4112 expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4113 ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4114
4115 expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, BodyId),
4116 ItemKind::Const(ident, generics, ty, body), (*ident, generics, ty, *body);
4117
4118 expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4119 ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4120
4121 expect_macro, (Ident, &ast::MacroDef, MacroKind),
4122 ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4123
4124 expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4125
4126 expect_foreign_mod, (ExternAbi, &'hir [ForeignItemRef]),
4127 ItemKind::ForeignMod { abi, items }, (*abi, items);
4128
4129 expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4130
4131 expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4132 ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4133
4134 expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4135 ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4136
4137 expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4138 ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4139
4140 expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4141 ItemKind::Union(ident, generics, data), (*ident, generics, data);
4142
4143 expect_trait,
4144 (
4145 IsAuto,
4146 Safety,
4147 Ident,
4148 &'hir Generics<'hir>,
4149 GenericBounds<'hir>,
4150 &'hir [TraitItemRef]
4151 ),
4152 ItemKind::Trait(is_auto, safety, ident, generics, bounds, items),
4153 (*is_auto, *safety, *ident, generics, bounds, items);
4154
4155 expect_trait_alias, (Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4156 ItemKind::TraitAlias(ident, generics, bounds), (*ident, generics, bounds);
4157
4158 expect_impl, &'hir Impl<'hir>, ItemKind::Impl(imp), imp;
4159 }
4160}
4161
4162#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4163#[derive(Encodable, Decodable, HashStable_Generic)]
4164pub enum Safety {
4165 Unsafe,
4166 Safe,
4167}
4168
4169impl Safety {
4170 pub fn prefix_str(self) -> &'static str {
4171 match self {
4172 Self::Unsafe => "unsafe ",
4173 Self::Safe => "",
4174 }
4175 }
4176
4177 #[inline]
4178 pub fn is_unsafe(self) -> bool {
4179 !self.is_safe()
4180 }
4181
4182 #[inline]
4183 pub fn is_safe(self) -> bool {
4184 match self {
4185 Self::Unsafe => false,
4186 Self::Safe => true,
4187 }
4188 }
4189}
4190
4191impl fmt::Display for Safety {
4192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4193 f.write_str(match *self {
4194 Self::Unsafe => "unsafe",
4195 Self::Safe => "safe",
4196 })
4197 }
4198}
4199
4200#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4201pub enum Constness {
4202 Const,
4203 NotConst,
4204}
4205
4206impl fmt::Display for Constness {
4207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4208 f.write_str(match *self {
4209 Self::Const => "const",
4210 Self::NotConst => "non-const",
4211 })
4212 }
4213}
4214
4215#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4220pub enum HeaderSafety {
4221 SafeTargetFeatures,
4227 Normal(Safety),
4228}
4229
4230impl From<Safety> for HeaderSafety {
4231 fn from(v: Safety) -> Self {
4232 Self::Normal(v)
4233 }
4234}
4235
4236#[derive(Copy, Clone, Debug, HashStable_Generic)]
4237pub struct FnHeader {
4238 pub safety: HeaderSafety,
4239 pub constness: Constness,
4240 pub asyncness: IsAsync,
4241 pub abi: ExternAbi,
4242}
4243
4244impl FnHeader {
4245 pub fn is_async(&self) -> bool {
4246 matches!(self.asyncness, IsAsync::Async(_))
4247 }
4248
4249 pub fn is_const(&self) -> bool {
4250 matches!(self.constness, Constness::Const)
4251 }
4252
4253 pub fn is_unsafe(&self) -> bool {
4254 self.safety().is_unsafe()
4255 }
4256
4257 pub fn is_safe(&self) -> bool {
4258 self.safety().is_safe()
4259 }
4260
4261 pub fn safety(&self) -> Safety {
4262 match self.safety {
4263 HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4264 HeaderSafety::Normal(safety) => safety,
4265 }
4266 }
4267}
4268
4269#[derive(Debug, Clone, Copy, HashStable_Generic)]
4270pub enum ItemKind<'hir> {
4271 ExternCrate(Option<Symbol>, Ident),
4275
4276 Use(&'hir UsePath<'hir>, UseKind),
4282
4283 Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4285 Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, BodyId),
4287 Fn {
4289 sig: FnSig<'hir>,
4290 ident: Ident,
4291 generics: &'hir Generics<'hir>,
4292 body: BodyId,
4293 has_body: bool,
4297 },
4298 Macro(Ident, &'hir ast::MacroDef, MacroKind),
4300 Mod(Ident, &'hir Mod<'hir>),
4302 ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemRef] },
4304 GlobalAsm {
4306 asm: &'hir InlineAsm<'hir>,
4307 fake_body: BodyId,
4313 },
4314 TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4316 Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4318 Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4320 Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4322 Trait(IsAuto, Safety, Ident, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
4324 TraitAlias(Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4326
4327 Impl(&'hir Impl<'hir>),
4329}
4330
4331#[derive(Debug, Clone, Copy, HashStable_Generic)]
4336pub struct Impl<'hir> {
4337 pub constness: Constness,
4338 pub safety: Safety,
4339 pub polarity: ImplPolarity,
4340 pub defaultness: Defaultness,
4341 pub defaultness_span: Option<Span>,
4344 pub generics: &'hir Generics<'hir>,
4345
4346 pub of_trait: Option<TraitRef<'hir>>,
4348
4349 pub self_ty: &'hir Ty<'hir>,
4350 pub items: &'hir [ImplItemRef],
4351}
4352
4353impl ItemKind<'_> {
4354 pub fn ident(&self) -> Option<Ident> {
4355 match *self {
4356 ItemKind::ExternCrate(_, ident)
4357 | ItemKind::Use(_, UseKind::Single(ident))
4358 | ItemKind::Static(_, ident, ..)
4359 | ItemKind::Const(ident, ..)
4360 | ItemKind::Fn { ident, .. }
4361 | ItemKind::Macro(ident, ..)
4362 | ItemKind::Mod(ident, ..)
4363 | ItemKind::TyAlias(ident, ..)
4364 | ItemKind::Enum(ident, ..)
4365 | ItemKind::Struct(ident, ..)
4366 | ItemKind::Union(ident, ..)
4367 | ItemKind::Trait(_, _, ident, ..)
4368 | ItemKind::TraitAlias(ident, ..) => Some(ident),
4369
4370 ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4371 | ItemKind::ForeignMod { .. }
4372 | ItemKind::GlobalAsm { .. }
4373 | ItemKind::Impl(_) => None,
4374 }
4375 }
4376
4377 pub fn generics(&self) -> Option<&Generics<'_>> {
4378 Some(match self {
4379 ItemKind::Fn { generics, .. }
4380 | ItemKind::TyAlias(_, generics, _)
4381 | ItemKind::Const(_, generics, _, _)
4382 | ItemKind::Enum(_, generics, _)
4383 | ItemKind::Struct(_, generics, _)
4384 | ItemKind::Union(_, generics, _)
4385 | ItemKind::Trait(_, _, _, generics, _, _)
4386 | ItemKind::TraitAlias(_, generics, _)
4387 | ItemKind::Impl(Impl { generics, .. }) => generics,
4388 _ => return None,
4389 })
4390 }
4391
4392 pub fn descr(&self) -> &'static str {
4393 match self {
4394 ItemKind::ExternCrate(..) => "extern crate",
4395 ItemKind::Use(..) => "`use` import",
4396 ItemKind::Static(..) => "static item",
4397 ItemKind::Const(..) => "constant item",
4398 ItemKind::Fn { .. } => "function",
4399 ItemKind::Macro(..) => "macro",
4400 ItemKind::Mod(..) => "module",
4401 ItemKind::ForeignMod { .. } => "extern block",
4402 ItemKind::GlobalAsm { .. } => "global asm item",
4403 ItemKind::TyAlias(..) => "type alias",
4404 ItemKind::Enum(..) => "enum",
4405 ItemKind::Struct(..) => "struct",
4406 ItemKind::Union(..) => "union",
4407 ItemKind::Trait(..) => "trait",
4408 ItemKind::TraitAlias(..) => "trait alias",
4409 ItemKind::Impl(..) => "implementation",
4410 }
4411 }
4412}
4413
4414#[derive(Debug, Clone, Copy, HashStable_Generic)]
4421pub struct TraitItemRef {
4422 pub id: TraitItemId,
4423 pub ident: Ident,
4424 pub kind: AssocItemKind,
4425 pub span: Span,
4426}
4427
4428#[derive(Debug, Clone, Copy, HashStable_Generic)]
4435pub struct ImplItemRef {
4436 pub id: ImplItemId,
4437 pub ident: Ident,
4438 pub kind: AssocItemKind,
4439 pub span: Span,
4440 pub trait_item_def_id: Option<DefId>,
4442}
4443
4444#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
4445pub enum AssocItemKind {
4446 Const,
4447 Fn { has_self: bool },
4448 Type,
4449}
4450
4451#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4455pub struct ForeignItemId {
4456 pub owner_id: OwnerId,
4457}
4458
4459impl ForeignItemId {
4460 #[inline]
4461 pub fn hir_id(&self) -> HirId {
4462 HirId::make_owner(self.owner_id.def_id)
4464 }
4465}
4466
4467#[derive(Debug, Clone, Copy, HashStable_Generic)]
4474pub struct ForeignItemRef {
4475 pub id: ForeignItemId,
4476 pub ident: Ident,
4477 pub span: Span,
4478}
4479
4480#[derive(Debug, Clone, Copy, HashStable_Generic)]
4481pub struct ForeignItem<'hir> {
4482 pub ident: Ident,
4483 pub kind: ForeignItemKind<'hir>,
4484 pub owner_id: OwnerId,
4485 pub span: Span,
4486 pub vis_span: Span,
4487}
4488
4489impl ForeignItem<'_> {
4490 #[inline]
4491 pub fn hir_id(&self) -> HirId {
4492 HirId::make_owner(self.owner_id.def_id)
4494 }
4495
4496 pub fn foreign_item_id(&self) -> ForeignItemId {
4497 ForeignItemId { owner_id: self.owner_id }
4498 }
4499}
4500
4501#[derive(Debug, Clone, Copy, HashStable_Generic)]
4503pub enum ForeignItemKind<'hir> {
4504 Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4511 Static(&'hir Ty<'hir>, Mutability, Safety),
4513 Type,
4515}
4516
4517#[derive(Debug, Copy, Clone, HashStable_Generic)]
4519pub struct Upvar {
4520 pub span: Span,
4522}
4523
4524#[derive(Debug, Clone, HashStable_Generic)]
4528pub struct TraitCandidate {
4529 pub def_id: DefId,
4530 pub import_ids: SmallVec<[LocalDefId; 1]>,
4531}
4532
4533#[derive(Copy, Clone, Debug, HashStable_Generic)]
4534pub enum OwnerNode<'hir> {
4535 Item(&'hir Item<'hir>),
4536 ForeignItem(&'hir ForeignItem<'hir>),
4537 TraitItem(&'hir TraitItem<'hir>),
4538 ImplItem(&'hir ImplItem<'hir>),
4539 Crate(&'hir Mod<'hir>),
4540 Synthetic,
4541}
4542
4543impl<'hir> OwnerNode<'hir> {
4544 pub fn span(&self) -> Span {
4545 match self {
4546 OwnerNode::Item(Item { span, .. })
4547 | OwnerNode::ForeignItem(ForeignItem { span, .. })
4548 | OwnerNode::ImplItem(ImplItem { span, .. })
4549 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4550 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4551 OwnerNode::Synthetic => unreachable!(),
4552 }
4553 }
4554
4555 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4556 match self {
4557 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4558 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4559 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4560 | OwnerNode::ForeignItem(ForeignItem {
4561 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4562 }) => Some(fn_sig),
4563 _ => None,
4564 }
4565 }
4566
4567 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4568 match self {
4569 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4570 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4571 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4572 | OwnerNode::ForeignItem(ForeignItem {
4573 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4574 }) => Some(fn_sig.decl),
4575 _ => None,
4576 }
4577 }
4578
4579 pub fn body_id(&self) -> Option<BodyId> {
4580 match self {
4581 OwnerNode::Item(Item {
4582 kind:
4583 ItemKind::Static(_, _, _, body)
4584 | ItemKind::Const(_, _, _, body)
4585 | ItemKind::Fn { body, .. },
4586 ..
4587 })
4588 | OwnerNode::TraitItem(TraitItem {
4589 kind:
4590 TraitItemKind::Fn(_, TraitFn::Provided(body)) | TraitItemKind::Const(_, Some(body)),
4591 ..
4592 })
4593 | OwnerNode::ImplItem(ImplItem {
4594 kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, body),
4595 ..
4596 }) => Some(*body),
4597 _ => None,
4598 }
4599 }
4600
4601 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4602 Node::generics(self.into())
4603 }
4604
4605 pub fn def_id(self) -> OwnerId {
4606 match self {
4607 OwnerNode::Item(Item { owner_id, .. })
4608 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4609 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4610 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4611 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4612 OwnerNode::Synthetic => unreachable!(),
4613 }
4614 }
4615
4616 pub fn is_impl_block(&self) -> bool {
4618 matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4619 }
4620
4621 expect_methods_self! {
4622 expect_item, &'hir Item<'hir>, OwnerNode::Item(n), n;
4623 expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4624 expect_impl_item, &'hir ImplItem<'hir>, OwnerNode::ImplItem(n), n;
4625 expect_trait_item, &'hir TraitItem<'hir>, OwnerNode::TraitItem(n), n;
4626 }
4627}
4628
4629impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4630 fn from(val: &'hir Item<'hir>) -> Self {
4631 OwnerNode::Item(val)
4632 }
4633}
4634
4635impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4636 fn from(val: &'hir ForeignItem<'hir>) -> Self {
4637 OwnerNode::ForeignItem(val)
4638 }
4639}
4640
4641impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4642 fn from(val: &'hir ImplItem<'hir>) -> Self {
4643 OwnerNode::ImplItem(val)
4644 }
4645}
4646
4647impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4648 fn from(val: &'hir TraitItem<'hir>) -> Self {
4649 OwnerNode::TraitItem(val)
4650 }
4651}
4652
4653impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4654 fn from(val: OwnerNode<'hir>) -> Self {
4655 match val {
4656 OwnerNode::Item(n) => Node::Item(n),
4657 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4658 OwnerNode::ImplItem(n) => Node::ImplItem(n),
4659 OwnerNode::TraitItem(n) => Node::TraitItem(n),
4660 OwnerNode::Crate(n) => Node::Crate(n),
4661 OwnerNode::Synthetic => Node::Synthetic,
4662 }
4663 }
4664}
4665
4666#[derive(Copy, Clone, Debug, HashStable_Generic)]
4667pub enum Node<'hir> {
4668 Param(&'hir Param<'hir>),
4669 Item(&'hir Item<'hir>),
4670 ForeignItem(&'hir ForeignItem<'hir>),
4671 TraitItem(&'hir TraitItem<'hir>),
4672 ImplItem(&'hir ImplItem<'hir>),
4673 Variant(&'hir Variant<'hir>),
4674 Field(&'hir FieldDef<'hir>),
4675 AnonConst(&'hir AnonConst),
4676 ConstBlock(&'hir ConstBlock),
4677 ConstArg(&'hir ConstArg<'hir>),
4678 Expr(&'hir Expr<'hir>),
4679 ExprField(&'hir ExprField<'hir>),
4680 Stmt(&'hir Stmt<'hir>),
4681 PathSegment(&'hir PathSegment<'hir>),
4682 Ty(&'hir Ty<'hir>),
4683 AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4684 TraitRef(&'hir TraitRef<'hir>),
4685 OpaqueTy(&'hir OpaqueTy<'hir>),
4686 TyPat(&'hir TyPat<'hir>),
4687 Pat(&'hir Pat<'hir>),
4688 PatField(&'hir PatField<'hir>),
4689 PatExpr(&'hir PatExpr<'hir>),
4693 Arm(&'hir Arm<'hir>),
4694 Block(&'hir Block<'hir>),
4695 LetStmt(&'hir LetStmt<'hir>),
4696 Ctor(&'hir VariantData<'hir>),
4699 Lifetime(&'hir Lifetime),
4700 GenericParam(&'hir GenericParam<'hir>),
4701 Crate(&'hir Mod<'hir>),
4702 Infer(&'hir InferArg),
4703 WherePredicate(&'hir WherePredicate<'hir>),
4704 PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4705 Synthetic,
4707 Err(Span),
4708}
4709
4710impl<'hir> Node<'hir> {
4711 pub fn ident(&self) -> Option<Ident> {
4726 match self {
4727 Node::Item(item) => item.kind.ident(),
4728 Node::TraitItem(TraitItem { ident, .. })
4729 | Node::ImplItem(ImplItem { ident, .. })
4730 | Node::ForeignItem(ForeignItem { ident, .. })
4731 | Node::Field(FieldDef { ident, .. })
4732 | Node::Variant(Variant { ident, .. })
4733 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4734 Node::Lifetime(lt) => Some(lt.ident),
4735 Node::GenericParam(p) => Some(p.name.ident()),
4736 Node::AssocItemConstraint(c) => Some(c.ident),
4737 Node::PatField(f) => Some(f.ident),
4738 Node::ExprField(f) => Some(f.ident),
4739 Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4740 Node::Param(..)
4741 | Node::AnonConst(..)
4742 | Node::ConstBlock(..)
4743 | Node::ConstArg(..)
4744 | Node::Expr(..)
4745 | Node::Stmt(..)
4746 | Node::Block(..)
4747 | Node::Ctor(..)
4748 | Node::Pat(..)
4749 | Node::TyPat(..)
4750 | Node::PatExpr(..)
4751 | Node::Arm(..)
4752 | Node::LetStmt(..)
4753 | Node::Crate(..)
4754 | Node::Ty(..)
4755 | Node::TraitRef(..)
4756 | Node::OpaqueTy(..)
4757 | Node::Infer(..)
4758 | Node::WherePredicate(..)
4759 | Node::Synthetic
4760 | Node::Err(..) => None,
4761 }
4762 }
4763
4764 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4765 match self {
4766 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4767 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4768 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4769 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4770 Some(fn_sig.decl)
4771 }
4772 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4773 Some(fn_decl)
4774 }
4775 _ => None,
4776 }
4777 }
4778
4779 pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4781 if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4782 && let Some(trait_ref) = impl_block.of_trait
4783 && let Some(trait_id) = trait_ref.trait_def_id()
4784 && trait_id == trait_def_id
4785 {
4786 Some(impl_block)
4787 } else {
4788 None
4789 }
4790 }
4791
4792 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4793 match self {
4794 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4795 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4796 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4797 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4798 Some(fn_sig)
4799 }
4800 _ => None,
4801 }
4802 }
4803
4804 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4806 match self {
4807 Node::Item(it) => match it.kind {
4808 ItemKind::TyAlias(_, _, ty)
4809 | ItemKind::Static(_, _, ty, _)
4810 | ItemKind::Const(_, _, ty, _) => Some(ty),
4811 ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4812 _ => None,
4813 },
4814 Node::TraitItem(it) => match it.kind {
4815 TraitItemKind::Const(ty, _) => Some(ty),
4816 TraitItemKind::Type(_, ty) => ty,
4817 _ => None,
4818 },
4819 Node::ImplItem(it) => match it.kind {
4820 ImplItemKind::Const(ty, _) => Some(ty),
4821 ImplItemKind::Type(ty) => Some(ty),
4822 _ => None,
4823 },
4824 _ => None,
4825 }
4826 }
4827
4828 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4829 match self {
4830 Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
4831 _ => None,
4832 }
4833 }
4834
4835 #[inline]
4836 pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4837 match self {
4838 Node::Item(Item {
4839 owner_id,
4840 kind:
4841 ItemKind::Const(_, _, _, body)
4842 | ItemKind::Static(.., body)
4843 | ItemKind::Fn { body, .. },
4844 ..
4845 })
4846 | Node::TraitItem(TraitItem {
4847 owner_id,
4848 kind:
4849 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4850 ..
4851 })
4852 | Node::ImplItem(ImplItem {
4853 owner_id,
4854 kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
4855 ..
4856 }) => Some((owner_id.def_id, *body)),
4857
4858 Node::Item(Item {
4859 owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4860 }) => Some((owner_id.def_id, *fake_body)),
4861
4862 Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4863 Some((*def_id, *body))
4864 }
4865
4866 Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4867 Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4868
4869 _ => None,
4870 }
4871 }
4872
4873 pub fn body_id(&self) -> Option<BodyId> {
4874 Some(self.associated_body()?.1)
4875 }
4876
4877 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4878 match self {
4879 Node::ForeignItem(ForeignItem {
4880 kind: ForeignItemKind::Fn(_, _, generics), ..
4881 })
4882 | Node::TraitItem(TraitItem { generics, .. })
4883 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4884 Node::Item(item) => item.kind.generics(),
4885 _ => None,
4886 }
4887 }
4888
4889 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4890 match self {
4891 Node::Item(i) => Some(OwnerNode::Item(i)),
4892 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4893 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4894 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4895 Node::Crate(i) => Some(OwnerNode::Crate(i)),
4896 Node::Synthetic => Some(OwnerNode::Synthetic),
4897 _ => None,
4898 }
4899 }
4900
4901 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4902 match self {
4903 Node::Item(i) => match i.kind {
4904 ItemKind::Fn { ident, sig, generics, .. } => {
4905 Some(FnKind::ItemFn(ident, generics, sig.header))
4906 }
4907 _ => None,
4908 },
4909 Node::TraitItem(ti) => match ti.kind {
4910 TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4911 _ => None,
4912 },
4913 Node::ImplItem(ii) => match ii.kind {
4914 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4915 _ => None,
4916 },
4917 Node::Expr(e) => match e.kind {
4918 ExprKind::Closure { .. } => Some(FnKind::Closure),
4919 _ => None,
4920 },
4921 _ => None,
4922 }
4923 }
4924
4925 expect_methods_self! {
4926 expect_param, &'hir Param<'hir>, Node::Param(n), n;
4927 expect_item, &'hir Item<'hir>, Node::Item(n), n;
4928 expect_foreign_item, &'hir ForeignItem<'hir>, Node::ForeignItem(n), n;
4929 expect_trait_item, &'hir TraitItem<'hir>, Node::TraitItem(n), n;
4930 expect_impl_item, &'hir ImplItem<'hir>, Node::ImplItem(n), n;
4931 expect_variant, &'hir Variant<'hir>, Node::Variant(n), n;
4932 expect_field, &'hir FieldDef<'hir>, Node::Field(n), n;
4933 expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n;
4934 expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n;
4935 expect_expr, &'hir Expr<'hir>, Node::Expr(n), n;
4936 expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n;
4937 expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n;
4938 expect_path_segment, &'hir PathSegment<'hir>, Node::PathSegment(n), n;
4939 expect_ty, &'hir Ty<'hir>, Node::Ty(n), n;
4940 expect_assoc_item_constraint, &'hir AssocItemConstraint<'hir>, Node::AssocItemConstraint(n), n;
4941 expect_trait_ref, &'hir TraitRef<'hir>, Node::TraitRef(n), n;
4942 expect_opaque_ty, &'hir OpaqueTy<'hir>, Node::OpaqueTy(n), n;
4943 expect_pat, &'hir Pat<'hir>, Node::Pat(n), n;
4944 expect_pat_field, &'hir PatField<'hir>, Node::PatField(n), n;
4945 expect_arm, &'hir Arm<'hir>, Node::Arm(n), n;
4946 expect_block, &'hir Block<'hir>, Node::Block(n), n;
4947 expect_let_stmt, &'hir LetStmt<'hir>, Node::LetStmt(n), n;
4948 expect_ctor, &'hir VariantData<'hir>, Node::Ctor(n), n;
4949 expect_lifetime, &'hir Lifetime, Node::Lifetime(n), n;
4950 expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4951 expect_crate, &'hir Mod<'hir>, Node::Crate(n), n;
4952 expect_infer, &'hir InferArg, Node::Infer(n), n;
4953 expect_closure, &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4954 }
4955}
4956
4957#[cfg(target_pointer_width = "64")]
4959mod size_asserts {
4960 use rustc_data_structures::static_assert_size;
4961
4962 use super::*;
4963 static_assert_size!(Block<'_>, 48);
4965 static_assert_size!(Body<'_>, 24);
4966 static_assert_size!(Expr<'_>, 64);
4967 static_assert_size!(ExprKind<'_>, 48);
4968 static_assert_size!(FnDecl<'_>, 40);
4969 static_assert_size!(ForeignItem<'_>, 88);
4970 static_assert_size!(ForeignItemKind<'_>, 56);
4971 static_assert_size!(GenericArg<'_>, 16);
4972 static_assert_size!(GenericBound<'_>, 64);
4973 static_assert_size!(Generics<'_>, 56);
4974 static_assert_size!(Impl<'_>, 80);
4975 static_assert_size!(ImplItem<'_>, 88);
4976 static_assert_size!(ImplItemKind<'_>, 40);
4977 static_assert_size!(Item<'_>, 88);
4978 static_assert_size!(ItemKind<'_>, 64);
4979 static_assert_size!(LetStmt<'_>, 72);
4980 static_assert_size!(Param<'_>, 32);
4981 static_assert_size!(Pat<'_>, 72);
4982 static_assert_size!(Path<'_>, 40);
4983 static_assert_size!(PathSegment<'_>, 48);
4984 static_assert_size!(PatKind<'_>, 48);
4985 static_assert_size!(QPath<'_>, 24);
4986 static_assert_size!(Res, 12);
4987 static_assert_size!(Stmt<'_>, 32);
4988 static_assert_size!(StmtKind<'_>, 16);
4989 static_assert_size!(TraitItem<'_>, 88);
4990 static_assert_size!(TraitItemKind<'_>, 48);
4991 static_assert_size!(Ty<'_>, 48);
4992 static_assert_size!(TyKind<'_>, 32);
4993 }
4995
4996#[cfg(test)]
4997mod tests;