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, 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 == kw::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, SmallVec<[Res; 3]>>;
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::Path(QPath::TypeRelative(..))
2376 | ExprKind::Call(..)
2377 | ExprKind::MethodCall(..)
2378 | ExprKind::Use(..)
2379 | ExprKind::Struct(..)
2380 | ExprKind::Tup(..)
2381 | ExprKind::If(..)
2382 | ExprKind::Match(..)
2383 | ExprKind::Closure { .. }
2384 | ExprKind::Block(..)
2385 | ExprKind::Repeat(..)
2386 | ExprKind::Array(..)
2387 | ExprKind::Break(..)
2388 | ExprKind::Continue(..)
2389 | ExprKind::Ret(..)
2390 | ExprKind::Become(..)
2391 | ExprKind::Let(..)
2392 | ExprKind::Loop(..)
2393 | ExprKind::Assign(..)
2394 | ExprKind::InlineAsm(..)
2395 | ExprKind::OffsetOf(..)
2396 | ExprKind::AssignOp(..)
2397 | ExprKind::Lit(_)
2398 | ExprKind::ConstBlock(..)
2399 | ExprKind::Unary(..)
2400 | ExprKind::AddrOf(..)
2401 | ExprKind::Binary(..)
2402 | ExprKind::Yield(..)
2403 | ExprKind::Cast(..)
2404 | ExprKind::DropTemps(..)
2405 | ExprKind::Err(_) => false,
2406 }
2407 }
2408
2409 pub fn is_size_lit(&self) -> bool {
2412 matches!(
2413 self.kind,
2414 ExprKind::Lit(Lit {
2415 node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2416 ..
2417 })
2418 )
2419 }
2420
2421 pub fn peel_drop_temps(&self) -> &Self {
2427 let mut expr = self;
2428 while let ExprKind::DropTemps(inner) = &expr.kind {
2429 expr = inner;
2430 }
2431 expr
2432 }
2433
2434 pub fn peel_blocks(&self) -> &Self {
2435 let mut expr = self;
2436 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2437 expr = inner;
2438 }
2439 expr
2440 }
2441
2442 pub fn peel_borrows(&self) -> &Self {
2443 let mut expr = self;
2444 while let ExprKind::AddrOf(.., inner) = &expr.kind {
2445 expr = inner;
2446 }
2447 expr
2448 }
2449
2450 pub fn can_have_side_effects(&self) -> bool {
2451 match self.peel_drop_temps().kind {
2452 ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2453 false
2454 }
2455 ExprKind::Type(base, _)
2456 | ExprKind::Unary(_, base)
2457 | ExprKind::Field(base, _)
2458 | ExprKind::Index(base, _, _)
2459 | ExprKind::AddrOf(.., base)
2460 | ExprKind::Cast(base, _)
2461 | ExprKind::UnsafeBinderCast(_, base, _) => {
2462 base.can_have_side_effects()
2466 }
2467 ExprKind::Struct(_, fields, init) => {
2468 let init_side_effects = match init {
2469 StructTailExpr::Base(init) => init.can_have_side_effects(),
2470 StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2471 };
2472 fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2473 || init_side_effects
2474 }
2475
2476 ExprKind::Array(args)
2477 | ExprKind::Tup(args)
2478 | ExprKind::Call(
2479 Expr {
2480 kind:
2481 ExprKind::Path(QPath::Resolved(
2482 None,
2483 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2484 )),
2485 ..
2486 },
2487 args,
2488 ) => args.iter().any(|arg| arg.can_have_side_effects()),
2489 ExprKind::If(..)
2490 | ExprKind::Match(..)
2491 | ExprKind::MethodCall(..)
2492 | ExprKind::Call(..)
2493 | ExprKind::Closure { .. }
2494 | ExprKind::Block(..)
2495 | ExprKind::Repeat(..)
2496 | ExprKind::Break(..)
2497 | ExprKind::Continue(..)
2498 | ExprKind::Ret(..)
2499 | ExprKind::Become(..)
2500 | ExprKind::Let(..)
2501 | ExprKind::Loop(..)
2502 | ExprKind::Assign(..)
2503 | ExprKind::InlineAsm(..)
2504 | ExprKind::AssignOp(..)
2505 | ExprKind::ConstBlock(..)
2506 | ExprKind::Binary(..)
2507 | ExprKind::Yield(..)
2508 | ExprKind::DropTemps(..)
2509 | ExprKind::Err(_) => true,
2510 }
2511 }
2512
2513 pub fn is_approximately_pattern(&self) -> bool {
2515 match &self.kind {
2516 ExprKind::Array(_)
2517 | ExprKind::Call(..)
2518 | ExprKind::Tup(_)
2519 | ExprKind::Lit(_)
2520 | ExprKind::Path(_)
2521 | ExprKind::Struct(..) => true,
2522 _ => false,
2523 }
2524 }
2525
2526 pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2531 match (self.kind, other.kind) {
2532 (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2533 (
2534 ExprKind::Path(QPath::LangItem(item1, _)),
2535 ExprKind::Path(QPath::LangItem(item2, _)),
2536 ) => item1 == item2,
2537 (
2538 ExprKind::Path(QPath::Resolved(None, path1)),
2539 ExprKind::Path(QPath::Resolved(None, path2)),
2540 ) => path1.res == path2.res,
2541 (
2542 ExprKind::Struct(
2543 QPath::LangItem(LangItem::RangeTo, _),
2544 [val1],
2545 StructTailExpr::None,
2546 ),
2547 ExprKind::Struct(
2548 QPath::LangItem(LangItem::RangeTo, _),
2549 [val2],
2550 StructTailExpr::None,
2551 ),
2552 )
2553 | (
2554 ExprKind::Struct(
2555 QPath::LangItem(LangItem::RangeToInclusive, _),
2556 [val1],
2557 StructTailExpr::None,
2558 ),
2559 ExprKind::Struct(
2560 QPath::LangItem(LangItem::RangeToInclusive, _),
2561 [val2],
2562 StructTailExpr::None,
2563 ),
2564 )
2565 | (
2566 ExprKind::Struct(
2567 QPath::LangItem(LangItem::RangeFrom, _),
2568 [val1],
2569 StructTailExpr::None,
2570 ),
2571 ExprKind::Struct(
2572 QPath::LangItem(LangItem::RangeFrom, _),
2573 [val2],
2574 StructTailExpr::None,
2575 ),
2576 )
2577 | (
2578 ExprKind::Struct(
2579 QPath::LangItem(LangItem::RangeFromCopy, _),
2580 [val1],
2581 StructTailExpr::None,
2582 ),
2583 ExprKind::Struct(
2584 QPath::LangItem(LangItem::RangeFromCopy, _),
2585 [val2],
2586 StructTailExpr::None,
2587 ),
2588 ) => val1.expr.equivalent_for_indexing(val2.expr),
2589 (
2590 ExprKind::Struct(
2591 QPath::LangItem(LangItem::Range, _),
2592 [val1, val3],
2593 StructTailExpr::None,
2594 ),
2595 ExprKind::Struct(
2596 QPath::LangItem(LangItem::Range, _),
2597 [val2, val4],
2598 StructTailExpr::None,
2599 ),
2600 )
2601 | (
2602 ExprKind::Struct(
2603 QPath::LangItem(LangItem::RangeCopy, _),
2604 [val1, val3],
2605 StructTailExpr::None,
2606 ),
2607 ExprKind::Struct(
2608 QPath::LangItem(LangItem::RangeCopy, _),
2609 [val2, val4],
2610 StructTailExpr::None,
2611 ),
2612 )
2613 | (
2614 ExprKind::Struct(
2615 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2616 [val1, val3],
2617 StructTailExpr::None,
2618 ),
2619 ExprKind::Struct(
2620 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2621 [val2, val4],
2622 StructTailExpr::None,
2623 ),
2624 ) => {
2625 val1.expr.equivalent_for_indexing(val2.expr)
2626 && val3.expr.equivalent_for_indexing(val4.expr)
2627 }
2628 _ => false,
2629 }
2630 }
2631
2632 pub fn method_ident(&self) -> Option<Ident> {
2633 match self.kind {
2634 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2635 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2636 _ => None,
2637 }
2638 }
2639}
2640
2641pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2644 match expr.kind {
2645 ExprKind::Struct(ref qpath, _, _) => matches!(
2647 **qpath,
2648 QPath::LangItem(
2649 LangItem::Range
2650 | LangItem::RangeTo
2651 | LangItem::RangeFrom
2652 | LangItem::RangeFull
2653 | LangItem::RangeToInclusive
2654 | LangItem::RangeCopy
2655 | LangItem::RangeFromCopy
2656 | LangItem::RangeInclusiveCopy,
2657 ..
2658 )
2659 ),
2660
2661 ExprKind::Call(ref func, _) => {
2663 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
2664 }
2665
2666 _ => false,
2667 }
2668}
2669
2670pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2677 match expr.kind {
2678 ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2680 _ if is_range_literal(expr) => true,
2682 _ => false,
2683 }
2684}
2685
2686#[derive(Debug, Clone, Copy, HashStable_Generic)]
2687pub enum ExprKind<'hir> {
2688 ConstBlock(ConstBlock),
2690 Array(&'hir [Expr<'hir>]),
2692 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2699 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2716 Use(&'hir Expr<'hir>, Span),
2718 Tup(&'hir [Expr<'hir>]),
2720 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2722 Unary(UnOp, &'hir Expr<'hir>),
2724 Lit(&'hir Lit),
2726 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2728 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2730 DropTemps(&'hir Expr<'hir>),
2736 Let(&'hir LetExpr<'hir>),
2741 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2748 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2754 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2757 Closure(&'hir Closure<'hir>),
2764 Block(&'hir Block<'hir>, Option<Label>),
2766
2767 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2769 AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2773 Field(&'hir Expr<'hir>, Ident),
2775 Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2779
2780 Path(QPath<'hir>),
2782
2783 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2785 Break(Destination, Option<&'hir Expr<'hir>>),
2787 Continue(Destination),
2789 Ret(Option<&'hir Expr<'hir>>),
2791 Become(&'hir Expr<'hir>),
2793
2794 InlineAsm(&'hir InlineAsm<'hir>),
2796
2797 OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2799
2800 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2805
2806 Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2811
2812 Yield(&'hir Expr<'hir>, YieldSource),
2814
2815 UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2818
2819 Err(rustc_span::ErrorGuaranteed),
2821}
2822
2823#[derive(Debug, Clone, Copy, HashStable_Generic)]
2824pub enum StructTailExpr<'hir> {
2825 None,
2827 Base(&'hir Expr<'hir>),
2830 DefaultFields(Span),
2834}
2835
2836#[derive(Debug, Clone, Copy, HashStable_Generic)]
2842pub enum QPath<'hir> {
2843 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2850
2851 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2858
2859 LangItem(LangItem, Span),
2861}
2862
2863impl<'hir> QPath<'hir> {
2864 pub fn span(&self) -> Span {
2866 match *self {
2867 QPath::Resolved(_, path) => path.span,
2868 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2869 QPath::LangItem(_, span) => span,
2870 }
2871 }
2872
2873 pub fn qself_span(&self) -> Span {
2876 match *self {
2877 QPath::Resolved(_, path) => path.span,
2878 QPath::TypeRelative(qself, _) => qself.span,
2879 QPath::LangItem(_, span) => span,
2880 }
2881 }
2882}
2883
2884#[derive(Copy, Clone, Debug, HashStable_Generic)]
2886pub enum LocalSource {
2887 Normal,
2889 AsyncFn,
2900 AwaitDesugar,
2902 AssignDesugar(Span),
2905 Contract,
2907}
2908
2909#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2911pub enum MatchSource {
2912 Normal,
2914 Postfix,
2916 ForLoopDesugar,
2918 TryDesugar(HirId),
2920 AwaitDesugar,
2922 FormatArgs,
2924}
2925
2926impl MatchSource {
2927 #[inline]
2928 pub const fn name(self) -> &'static str {
2929 use MatchSource::*;
2930 match self {
2931 Normal => "match",
2932 Postfix => ".match",
2933 ForLoopDesugar => "for",
2934 TryDesugar(_) => "?",
2935 AwaitDesugar => ".await",
2936 FormatArgs => "format_args!()",
2937 }
2938 }
2939}
2940
2941#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2943pub enum LoopSource {
2944 Loop,
2946 While,
2948 ForLoop,
2950}
2951
2952impl LoopSource {
2953 pub fn name(self) -> &'static str {
2954 match self {
2955 LoopSource::Loop => "loop",
2956 LoopSource::While => "while",
2957 LoopSource::ForLoop => "for",
2958 }
2959 }
2960}
2961
2962#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2963pub enum LoopIdError {
2964 OutsideLoopScope,
2965 UnlabeledCfInWhileCondition,
2966 UnresolvedLabel,
2967}
2968
2969impl fmt::Display for LoopIdError {
2970 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2971 f.write_str(match self {
2972 LoopIdError::OutsideLoopScope => "not inside loop scope",
2973 LoopIdError::UnlabeledCfInWhileCondition => {
2974 "unlabeled control flow (break or continue) in while condition"
2975 }
2976 LoopIdError::UnresolvedLabel => "label not found",
2977 })
2978 }
2979}
2980
2981#[derive(Copy, Clone, Debug, HashStable_Generic)]
2982pub struct Destination {
2983 pub label: Option<Label>,
2985
2986 pub target_id: Result<HirId, LoopIdError>,
2989}
2990
2991#[derive(Copy, Clone, Debug, HashStable_Generic)]
2993pub enum YieldSource {
2994 Await { expr: Option<HirId> },
2996 Yield,
2998}
2999
3000impl fmt::Display for YieldSource {
3001 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3002 f.write_str(match self {
3003 YieldSource::Await { .. } => "`await`",
3004 YieldSource::Yield => "`yield`",
3005 })
3006 }
3007}
3008
3009#[derive(Debug, Clone, Copy, HashStable_Generic)]
3012pub struct MutTy<'hir> {
3013 pub ty: &'hir Ty<'hir>,
3014 pub mutbl: Mutability,
3015}
3016
3017#[derive(Debug, Clone, Copy, HashStable_Generic)]
3020pub struct FnSig<'hir> {
3021 pub header: FnHeader,
3022 pub decl: &'hir FnDecl<'hir>,
3023 pub span: Span,
3024}
3025
3026#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3030pub struct TraitItemId {
3031 pub owner_id: OwnerId,
3032}
3033
3034impl TraitItemId {
3035 #[inline]
3036 pub fn hir_id(&self) -> HirId {
3037 HirId::make_owner(self.owner_id.def_id)
3039 }
3040}
3041
3042#[derive(Debug, Clone, Copy, HashStable_Generic)]
3047pub struct TraitItem<'hir> {
3048 pub ident: Ident,
3049 pub owner_id: OwnerId,
3050 pub generics: &'hir Generics<'hir>,
3051 pub kind: TraitItemKind<'hir>,
3052 pub span: Span,
3053 pub defaultness: Defaultness,
3054}
3055
3056macro_rules! expect_methods_self_kind {
3057 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3058 $(
3059 #[track_caller]
3060 pub fn $name(&self) -> $ret_ty {
3061 let $pat = &self.kind else { expect_failed(stringify!($ident), self) };
3062 $ret_val
3063 }
3064 )*
3065 }
3066}
3067
3068macro_rules! expect_methods_self {
3069 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3070 $(
3071 #[track_caller]
3072 pub fn $name(&self) -> $ret_ty {
3073 let $pat = self else { expect_failed(stringify!($ident), self) };
3074 $ret_val
3075 }
3076 )*
3077 }
3078}
3079
3080#[track_caller]
3081fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3082 panic!("{ident}: found {found:?}")
3083}
3084
3085impl<'hir> TraitItem<'hir> {
3086 #[inline]
3087 pub fn hir_id(&self) -> HirId {
3088 HirId::make_owner(self.owner_id.def_id)
3090 }
3091
3092 pub fn trait_item_id(&self) -> TraitItemId {
3093 TraitItemId { owner_id: self.owner_id }
3094 }
3095
3096 expect_methods_self_kind! {
3097 expect_const, (&'hir Ty<'hir>, Option<BodyId>),
3098 TraitItemKind::Const(ty, body), (ty, *body);
3099
3100 expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3101 TraitItemKind::Fn(ty, trfn), (ty, trfn);
3102
3103 expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3104 TraitItemKind::Type(bounds, ty), (bounds, *ty);
3105 }
3106}
3107
3108#[derive(Debug, Clone, Copy, HashStable_Generic)]
3110pub enum TraitFn<'hir> {
3111 Required(&'hir [Option<Ident>]),
3113
3114 Provided(BodyId),
3116}
3117
3118#[derive(Debug, Clone, Copy, HashStable_Generic)]
3120pub enum TraitItemKind<'hir> {
3121 Const(&'hir Ty<'hir>, Option<BodyId>),
3123 Fn(FnSig<'hir>, TraitFn<'hir>),
3125 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3128}
3129
3130#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3134pub struct ImplItemId {
3135 pub owner_id: OwnerId,
3136}
3137
3138impl ImplItemId {
3139 #[inline]
3140 pub fn hir_id(&self) -> HirId {
3141 HirId::make_owner(self.owner_id.def_id)
3143 }
3144}
3145
3146#[derive(Debug, Clone, Copy, HashStable_Generic)]
3150pub struct ImplItem<'hir> {
3151 pub ident: Ident,
3152 pub owner_id: OwnerId,
3153 pub generics: &'hir Generics<'hir>,
3154 pub kind: ImplItemKind<'hir>,
3155 pub defaultness: Defaultness,
3156 pub span: Span,
3157 pub vis_span: Span,
3158}
3159
3160impl<'hir> ImplItem<'hir> {
3161 #[inline]
3162 pub fn hir_id(&self) -> HirId {
3163 HirId::make_owner(self.owner_id.def_id)
3165 }
3166
3167 pub fn impl_item_id(&self) -> ImplItemId {
3168 ImplItemId { owner_id: self.owner_id }
3169 }
3170
3171 expect_methods_self_kind! {
3172 expect_const, (&'hir Ty<'hir>, BodyId), ImplItemKind::Const(ty, body), (ty, *body);
3173 expect_fn, (&FnSig<'hir>, BodyId), ImplItemKind::Fn(ty, body), (ty, *body);
3174 expect_type, &'hir Ty<'hir>, ImplItemKind::Type(ty), ty;
3175 }
3176}
3177
3178#[derive(Debug, Clone, Copy, HashStable_Generic)]
3180pub enum ImplItemKind<'hir> {
3181 Const(&'hir Ty<'hir>, BodyId),
3184 Fn(FnSig<'hir>, BodyId),
3186 Type(&'hir Ty<'hir>),
3188}
3189
3190#[derive(Debug, Clone, Copy, HashStable_Generic)]
3201pub struct AssocItemConstraint<'hir> {
3202 #[stable_hasher(ignore)]
3203 pub hir_id: HirId,
3204 pub ident: Ident,
3205 pub gen_args: &'hir GenericArgs<'hir>,
3206 pub kind: AssocItemConstraintKind<'hir>,
3207 pub span: Span,
3208}
3209
3210impl<'hir> AssocItemConstraint<'hir> {
3211 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3213 match self.kind {
3214 AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3215 _ => None,
3216 }
3217 }
3218
3219 pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3221 match self.kind {
3222 AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3223 _ => None,
3224 }
3225 }
3226}
3227
3228#[derive(Debug, Clone, Copy, HashStable_Generic)]
3229pub enum Term<'hir> {
3230 Ty(&'hir Ty<'hir>),
3231 Const(&'hir ConstArg<'hir>),
3232}
3233
3234impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3235 fn from(ty: &'hir Ty<'hir>) -> Self {
3236 Term::Ty(ty)
3237 }
3238}
3239
3240impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3241 fn from(c: &'hir ConstArg<'hir>) -> Self {
3242 Term::Const(c)
3243 }
3244}
3245
3246#[derive(Debug, Clone, Copy, HashStable_Generic)]
3248pub enum AssocItemConstraintKind<'hir> {
3249 Equality { term: Term<'hir> },
3256 Bound { bounds: &'hir [GenericBound<'hir>] },
3258}
3259
3260impl<'hir> AssocItemConstraintKind<'hir> {
3261 pub fn descr(&self) -> &'static str {
3262 match self {
3263 AssocItemConstraintKind::Equality { .. } => "binding",
3264 AssocItemConstraintKind::Bound { .. } => "constraint",
3265 }
3266 }
3267}
3268
3269#[derive(Debug, Clone, Copy, HashStable_Generic)]
3273pub enum AmbigArg {}
3274
3275#[derive(Debug, Clone, Copy, HashStable_Generic)]
3276#[repr(C)]
3277pub struct Ty<'hir, Unambig = ()> {
3284 #[stable_hasher(ignore)]
3285 pub hir_id: HirId,
3286 pub span: Span,
3287 pub kind: TyKind<'hir, Unambig>,
3288}
3289
3290impl<'hir> Ty<'hir, AmbigArg> {
3291 pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3302 let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3305 unsafe { &*ptr }
3306 }
3307}
3308
3309impl<'hir> Ty<'hir> {
3310 pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3316 if let TyKind::Infer(()) = self.kind {
3317 return None;
3318 }
3319
3320 let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3324 Some(unsafe { &*ptr })
3325 }
3326}
3327
3328impl<'hir> Ty<'hir, AmbigArg> {
3329 pub fn peel_refs(&self) -> &Ty<'hir> {
3330 let mut final_ty = self.as_unambig_ty();
3331 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3332 final_ty = ty;
3333 }
3334 final_ty
3335 }
3336}
3337
3338impl<'hir> Ty<'hir> {
3339 pub fn peel_refs(&self) -> &Self {
3340 let mut final_ty = self;
3341 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3342 final_ty = ty;
3343 }
3344 final_ty
3345 }
3346
3347 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3349 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3350 return None;
3351 };
3352 let [segment] = &path.segments else {
3353 return None;
3354 };
3355 match path.res {
3356 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3357 Some((def_id, segment.ident))
3358 }
3359 _ => None,
3360 }
3361 }
3362
3363 pub fn find_self_aliases(&self) -> Vec<Span> {
3364 use crate::intravisit::Visitor;
3365 struct MyVisitor(Vec<Span>);
3366 impl<'v> Visitor<'v> for MyVisitor {
3367 fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3368 if matches!(
3369 &t.kind,
3370 TyKind::Path(QPath::Resolved(
3371 _,
3372 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3373 ))
3374 ) {
3375 self.0.push(t.span);
3376 return;
3377 }
3378 crate::intravisit::walk_ty(self, t);
3379 }
3380 }
3381
3382 let mut my_visitor = MyVisitor(vec![]);
3383 my_visitor.visit_ty_unambig(self);
3384 my_visitor.0
3385 }
3386
3387 pub fn is_suggestable_infer_ty(&self) -> bool {
3390 fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3391 generic_args.iter().any(|arg| match arg {
3392 GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3393 GenericArg::Infer(_) => true,
3394 _ => false,
3395 })
3396 }
3397 debug!(?self);
3398 match &self.kind {
3399 TyKind::Infer(()) => true,
3400 TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3401 TyKind::Array(ty, length) => {
3402 ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3403 }
3404 TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3405 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3406 TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3407 ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3408 }
3409 TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3410 ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3411 || segments
3412 .iter()
3413 .any(|segment| are_suggestable_generic_args(segment.args().args))
3414 }
3415 _ => false,
3416 }
3417 }
3418}
3419
3420#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3422pub enum PrimTy {
3423 Int(IntTy),
3424 Uint(UintTy),
3425 Float(FloatTy),
3426 Str,
3427 Bool,
3428 Char,
3429}
3430
3431impl PrimTy {
3432 pub const ALL: [Self; 19] = [
3434 Self::Int(IntTy::I8),
3436 Self::Int(IntTy::I16),
3437 Self::Int(IntTy::I32),
3438 Self::Int(IntTy::I64),
3439 Self::Int(IntTy::I128),
3440 Self::Int(IntTy::Isize),
3441 Self::Uint(UintTy::U8),
3442 Self::Uint(UintTy::U16),
3443 Self::Uint(UintTy::U32),
3444 Self::Uint(UintTy::U64),
3445 Self::Uint(UintTy::U128),
3446 Self::Uint(UintTy::Usize),
3447 Self::Float(FloatTy::F16),
3448 Self::Float(FloatTy::F32),
3449 Self::Float(FloatTy::F64),
3450 Self::Float(FloatTy::F128),
3451 Self::Bool,
3452 Self::Char,
3453 Self::Str,
3454 ];
3455
3456 pub fn name_str(self) -> &'static str {
3460 match self {
3461 PrimTy::Int(i) => i.name_str(),
3462 PrimTy::Uint(u) => u.name_str(),
3463 PrimTy::Float(f) => f.name_str(),
3464 PrimTy::Str => "str",
3465 PrimTy::Bool => "bool",
3466 PrimTy::Char => "char",
3467 }
3468 }
3469
3470 pub fn name(self) -> Symbol {
3471 match self {
3472 PrimTy::Int(i) => i.name(),
3473 PrimTy::Uint(u) => u.name(),
3474 PrimTy::Float(f) => f.name(),
3475 PrimTy::Str => sym::str,
3476 PrimTy::Bool => sym::bool,
3477 PrimTy::Char => sym::char,
3478 }
3479 }
3480
3481 pub fn from_name(name: Symbol) -> Option<Self> {
3484 let ty = match name {
3485 sym::i8 => Self::Int(IntTy::I8),
3487 sym::i16 => Self::Int(IntTy::I16),
3488 sym::i32 => Self::Int(IntTy::I32),
3489 sym::i64 => Self::Int(IntTy::I64),
3490 sym::i128 => Self::Int(IntTy::I128),
3491 sym::isize => Self::Int(IntTy::Isize),
3492 sym::u8 => Self::Uint(UintTy::U8),
3493 sym::u16 => Self::Uint(UintTy::U16),
3494 sym::u32 => Self::Uint(UintTy::U32),
3495 sym::u64 => Self::Uint(UintTy::U64),
3496 sym::u128 => Self::Uint(UintTy::U128),
3497 sym::usize => Self::Uint(UintTy::Usize),
3498 sym::f16 => Self::Float(FloatTy::F16),
3499 sym::f32 => Self::Float(FloatTy::F32),
3500 sym::f64 => Self::Float(FloatTy::F64),
3501 sym::f128 => Self::Float(FloatTy::F128),
3502 sym::bool => Self::Bool,
3503 sym::char => Self::Char,
3504 sym::str => Self::Str,
3505 _ => return None,
3506 };
3507 Some(ty)
3508 }
3509}
3510
3511#[derive(Debug, Clone, Copy, HashStable_Generic)]
3512pub struct BareFnTy<'hir> {
3513 pub safety: Safety,
3514 pub abi: ExternAbi,
3515 pub generic_params: &'hir [GenericParam<'hir>],
3516 pub decl: &'hir FnDecl<'hir>,
3517 pub param_idents: &'hir [Option<Ident>],
3520}
3521
3522#[derive(Debug, Clone, Copy, HashStable_Generic)]
3523pub struct UnsafeBinderTy<'hir> {
3524 pub generic_params: &'hir [GenericParam<'hir>],
3525 pub inner_ty: &'hir Ty<'hir>,
3526}
3527
3528#[derive(Debug, Clone, Copy, HashStable_Generic)]
3529pub struct OpaqueTy<'hir> {
3530 #[stable_hasher(ignore)]
3531 pub hir_id: HirId,
3532 pub def_id: LocalDefId,
3533 pub bounds: GenericBounds<'hir>,
3534 pub origin: OpaqueTyOrigin<LocalDefId>,
3535 pub span: Span,
3536}
3537
3538#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3539pub enum PreciseCapturingArgKind<T, U> {
3540 Lifetime(T),
3541 Param(U),
3543}
3544
3545pub type PreciseCapturingArg<'hir> =
3546 PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3547
3548impl PreciseCapturingArg<'_> {
3549 pub fn hir_id(self) -> HirId {
3550 match self {
3551 PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3552 PreciseCapturingArg::Param(param) => param.hir_id,
3553 }
3554 }
3555
3556 pub fn name(self) -> Symbol {
3557 match self {
3558 PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3559 PreciseCapturingArg::Param(param) => param.ident.name,
3560 }
3561 }
3562}
3563
3564#[derive(Debug, Clone, Copy, HashStable_Generic)]
3569pub struct PreciseCapturingNonLifetimeArg {
3570 #[stable_hasher(ignore)]
3571 pub hir_id: HirId,
3572 pub ident: Ident,
3573 pub res: Res,
3574}
3575
3576#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3577#[derive(HashStable_Generic, Encodable, Decodable)]
3578pub enum RpitContext {
3579 Trait,
3580 TraitImpl,
3581}
3582
3583#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3585#[derive(HashStable_Generic, Encodable, Decodable)]
3586pub enum OpaqueTyOrigin<D> {
3587 FnReturn {
3589 parent: D,
3591 in_trait_or_impl: Option<RpitContext>,
3593 },
3594 AsyncFn {
3596 parent: D,
3598 in_trait_or_impl: Option<RpitContext>,
3600 },
3601 TyAlias {
3603 parent: D,
3605 in_assoc_ty: bool,
3607 },
3608}
3609
3610#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3611pub enum InferDelegationKind {
3612 Input(usize),
3613 Output,
3614}
3615
3616#[derive(Debug, Clone, Copy, HashStable_Generic)]
3618#[repr(u8, C)]
3620pub enum TyKind<'hir, Unambig = ()> {
3621 InferDelegation(DefId, InferDelegationKind),
3623 Slice(&'hir Ty<'hir>),
3625 Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3627 Ptr(MutTy<'hir>),
3629 Ref(&'hir Lifetime, MutTy<'hir>),
3631 BareFn(&'hir BareFnTy<'hir>),
3633 UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3635 Never,
3637 Tup(&'hir [Ty<'hir>]),
3639 Path(QPath<'hir>),
3644 OpaqueDef(&'hir OpaqueTy<'hir>),
3646 TraitAscription(GenericBounds<'hir>),
3648 TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3654 Typeof(&'hir AnonConst),
3656 Err(rustc_span::ErrorGuaranteed),
3658 Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3660 Infer(Unambig),
3666}
3667
3668#[derive(Debug, Clone, Copy, HashStable_Generic)]
3669pub enum InlineAsmOperand<'hir> {
3670 In {
3671 reg: InlineAsmRegOrRegClass,
3672 expr: &'hir Expr<'hir>,
3673 },
3674 Out {
3675 reg: InlineAsmRegOrRegClass,
3676 late: bool,
3677 expr: Option<&'hir Expr<'hir>>,
3678 },
3679 InOut {
3680 reg: InlineAsmRegOrRegClass,
3681 late: bool,
3682 expr: &'hir Expr<'hir>,
3683 },
3684 SplitInOut {
3685 reg: InlineAsmRegOrRegClass,
3686 late: bool,
3687 in_expr: &'hir Expr<'hir>,
3688 out_expr: Option<&'hir Expr<'hir>>,
3689 },
3690 Const {
3691 anon_const: ConstBlock,
3692 },
3693 SymFn {
3694 expr: &'hir Expr<'hir>,
3695 },
3696 SymStatic {
3697 path: QPath<'hir>,
3698 def_id: DefId,
3699 },
3700 Label {
3701 block: &'hir Block<'hir>,
3702 },
3703}
3704
3705impl<'hir> InlineAsmOperand<'hir> {
3706 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3707 match *self {
3708 Self::In { reg, .. }
3709 | Self::Out { reg, .. }
3710 | Self::InOut { reg, .. }
3711 | Self::SplitInOut { reg, .. } => Some(reg),
3712 Self::Const { .. }
3713 | Self::SymFn { .. }
3714 | Self::SymStatic { .. }
3715 | Self::Label { .. } => None,
3716 }
3717 }
3718
3719 pub fn is_clobber(&self) -> bool {
3720 matches!(
3721 self,
3722 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3723 )
3724 }
3725}
3726
3727#[derive(Debug, Clone, Copy, HashStable_Generic)]
3728pub struct InlineAsm<'hir> {
3729 pub asm_macro: ast::AsmMacro,
3730 pub template: &'hir [InlineAsmTemplatePiece],
3731 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3732 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3733 pub options: InlineAsmOptions,
3734 pub line_spans: &'hir [Span],
3735}
3736
3737impl InlineAsm<'_> {
3738 pub fn contains_label(&self) -> bool {
3739 self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3740 }
3741}
3742
3743#[derive(Debug, Clone, Copy, HashStable_Generic)]
3745pub struct Param<'hir> {
3746 #[stable_hasher(ignore)]
3747 pub hir_id: HirId,
3748 pub pat: &'hir Pat<'hir>,
3749 pub ty_span: Span,
3750 pub span: Span,
3751}
3752
3753#[derive(Debug, Clone, Copy, HashStable_Generic)]
3755pub struct FnDecl<'hir> {
3756 pub inputs: &'hir [Ty<'hir>],
3760 pub output: FnRetTy<'hir>,
3761 pub c_variadic: bool,
3762 pub implicit_self: ImplicitSelfKind,
3764 pub lifetime_elision_allowed: bool,
3766}
3767
3768impl<'hir> FnDecl<'hir> {
3769 pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3770 if let FnRetTy::Return(ty) = self.output
3771 && let TyKind::InferDelegation(sig_id, _) = ty.kind
3772 {
3773 return Some(sig_id);
3774 }
3775 None
3776 }
3777}
3778
3779#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3781pub enum ImplicitSelfKind {
3782 Imm,
3784 Mut,
3786 RefImm,
3788 RefMut,
3790 None,
3793}
3794
3795impl ImplicitSelfKind {
3796 pub fn has_implicit_self(&self) -> bool {
3798 !matches!(*self, ImplicitSelfKind::None)
3799 }
3800}
3801
3802#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3803pub enum IsAsync {
3804 Async(Span),
3805 NotAsync,
3806}
3807
3808impl IsAsync {
3809 pub fn is_async(self) -> bool {
3810 matches!(self, IsAsync::Async(_))
3811 }
3812}
3813
3814#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3815pub enum Defaultness {
3816 Default { has_value: bool },
3817 Final,
3818}
3819
3820impl Defaultness {
3821 pub fn has_value(&self) -> bool {
3822 match *self {
3823 Defaultness::Default { has_value } => has_value,
3824 Defaultness::Final => true,
3825 }
3826 }
3827
3828 pub fn is_final(&self) -> bool {
3829 *self == Defaultness::Final
3830 }
3831
3832 pub fn is_default(&self) -> bool {
3833 matches!(*self, Defaultness::Default { .. })
3834 }
3835}
3836
3837#[derive(Debug, Clone, Copy, HashStable_Generic)]
3838pub enum FnRetTy<'hir> {
3839 DefaultReturn(Span),
3845 Return(&'hir Ty<'hir>),
3847}
3848
3849impl<'hir> FnRetTy<'hir> {
3850 #[inline]
3851 pub fn span(&self) -> Span {
3852 match *self {
3853 Self::DefaultReturn(span) => span,
3854 Self::Return(ref ty) => ty.span,
3855 }
3856 }
3857
3858 pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3859 if let Self::Return(ty) = self
3860 && ty.is_suggestable_infer_ty()
3861 {
3862 return Some(*ty);
3863 }
3864 None
3865 }
3866}
3867
3868#[derive(Copy, Clone, Debug, HashStable_Generic)]
3870pub enum ClosureBinder {
3871 Default,
3873 For { span: Span },
3877}
3878
3879#[derive(Debug, Clone, Copy, HashStable_Generic)]
3880pub struct Mod<'hir> {
3881 pub spans: ModSpans,
3882 pub item_ids: &'hir [ItemId],
3883}
3884
3885#[derive(Copy, Clone, Debug, HashStable_Generic)]
3886pub struct ModSpans {
3887 pub inner_span: Span,
3891 pub inject_use_span: Span,
3892}
3893
3894#[derive(Debug, Clone, Copy, HashStable_Generic)]
3895pub struct EnumDef<'hir> {
3896 pub variants: &'hir [Variant<'hir>],
3897}
3898
3899#[derive(Debug, Clone, Copy, HashStable_Generic)]
3900pub struct Variant<'hir> {
3901 pub ident: Ident,
3903 #[stable_hasher(ignore)]
3905 pub hir_id: HirId,
3906 pub def_id: LocalDefId,
3907 pub data: VariantData<'hir>,
3909 pub disr_expr: Option<&'hir AnonConst>,
3911 pub span: Span,
3913}
3914
3915#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3916pub enum UseKind {
3917 Single(Ident),
3924
3925 Glob,
3927
3928 ListStem,
3932}
3933
3934#[derive(Clone, Debug, Copy, HashStable_Generic)]
3941pub struct TraitRef<'hir> {
3942 pub path: &'hir Path<'hir>,
3943 #[stable_hasher(ignore)]
3945 pub hir_ref_id: HirId,
3946}
3947
3948impl TraitRef<'_> {
3949 pub fn trait_def_id(&self) -> Option<DefId> {
3951 match self.path.res {
3952 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3953 Res::Err => None,
3954 res => panic!("{res:?} did not resolve to a trait or trait alias"),
3955 }
3956 }
3957}
3958
3959#[derive(Clone, Debug, Copy, HashStable_Generic)]
3960pub struct PolyTraitRef<'hir> {
3961 pub bound_generic_params: &'hir [GenericParam<'hir>],
3963
3964 pub modifiers: TraitBoundModifiers,
3968
3969 pub trait_ref: TraitRef<'hir>,
3971
3972 pub span: Span,
3973}
3974
3975#[derive(Debug, Clone, Copy, HashStable_Generic)]
3976pub struct FieldDef<'hir> {
3977 pub span: Span,
3978 pub vis_span: Span,
3979 pub ident: Ident,
3980 #[stable_hasher(ignore)]
3981 pub hir_id: HirId,
3982 pub def_id: LocalDefId,
3983 pub ty: &'hir Ty<'hir>,
3984 pub safety: Safety,
3985 pub default: Option<&'hir AnonConst>,
3986}
3987
3988impl FieldDef<'_> {
3989 pub fn is_positional(&self) -> bool {
3991 self.ident.as_str().as_bytes()[0].is_ascii_digit()
3992 }
3993}
3994
3995#[derive(Debug, Clone, Copy, HashStable_Generic)]
3997pub enum VariantData<'hir> {
3998 Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4002 Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
4006 Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
4010}
4011
4012impl<'hir> VariantData<'hir> {
4013 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4015 match *self {
4016 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4017 _ => &[],
4018 }
4019 }
4020
4021 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4022 match *self {
4023 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4024 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4025 VariantData::Struct { .. } => None,
4026 }
4027 }
4028
4029 #[inline]
4030 pub fn ctor_kind(&self) -> Option<CtorKind> {
4031 self.ctor().map(|(kind, ..)| kind)
4032 }
4033
4034 #[inline]
4036 pub fn ctor_hir_id(&self) -> Option<HirId> {
4037 self.ctor().map(|(_, hir_id, _)| hir_id)
4038 }
4039
4040 #[inline]
4042 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4043 self.ctor().map(|(.., def_id)| def_id)
4044 }
4045}
4046
4047#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
4051pub struct ItemId {
4052 pub owner_id: OwnerId,
4053}
4054
4055impl ItemId {
4056 #[inline]
4057 pub fn hir_id(&self) -> HirId {
4058 HirId::make_owner(self.owner_id.def_id)
4060 }
4061}
4062
4063#[derive(Debug, Clone, Copy, HashStable_Generic)]
4072pub struct Item<'hir> {
4073 pub owner_id: OwnerId,
4074 pub kind: ItemKind<'hir>,
4075 pub span: Span,
4076 pub vis_span: Span,
4077}
4078
4079impl<'hir> Item<'hir> {
4080 #[inline]
4081 pub fn hir_id(&self) -> HirId {
4082 HirId::make_owner(self.owner_id.def_id)
4084 }
4085
4086 pub fn item_id(&self) -> ItemId {
4087 ItemId { owner_id: self.owner_id }
4088 }
4089
4090 pub fn is_adt(&self) -> bool {
4093 matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4094 }
4095
4096 pub fn is_struct_or_union(&self) -> bool {
4098 matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4099 }
4100
4101 expect_methods_self_kind! {
4102 expect_extern_crate, (Option<Symbol>, Ident),
4103 ItemKind::ExternCrate(s, ident), (*s, *ident);
4104
4105 expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4106
4107 expect_static, (Ident, &'hir Ty<'hir>, Mutability, BodyId),
4108 ItemKind::Static(ident, ty, mutbl, body), (*ident, ty, *mutbl, *body);
4109
4110 expect_const, (Ident, &'hir Ty<'hir>, &'hir Generics<'hir>, BodyId),
4111 ItemKind::Const(ident, ty, generics, body), (*ident, ty, generics, *body);
4112
4113 expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4114 ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4115
4116 expect_macro, (Ident, &ast::MacroDef, MacroKind),
4117 ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4118
4119 expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4120
4121 expect_foreign_mod, (ExternAbi, &'hir [ForeignItemRef]),
4122 ItemKind::ForeignMod { abi, items }, (*abi, items);
4123
4124 expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4125
4126 expect_ty_alias, (Ident, &'hir Ty<'hir>, &'hir Generics<'hir>),
4127 ItemKind::TyAlias(ident, ty, generics), (*ident, ty, generics);
4128
4129 expect_enum, (Ident, &EnumDef<'hir>, &'hir Generics<'hir>),
4130 ItemKind::Enum(ident, def, generics), (*ident, def, generics);
4131
4132 expect_struct, (Ident, &VariantData<'hir>, &'hir Generics<'hir>),
4133 ItemKind::Struct(ident, data, generics), (*ident, data, generics);
4134
4135 expect_union, (Ident, &VariantData<'hir>, &'hir Generics<'hir>),
4136 ItemKind::Union(ident, data, generics), (*ident, data, generics);
4137
4138 expect_trait,
4139 (
4140 IsAuto,
4141 Safety,
4142 Ident,
4143 &'hir Generics<'hir>,
4144 GenericBounds<'hir>,
4145 &'hir [TraitItemRef]
4146 ),
4147 ItemKind::Trait(is_auto, safety, ident, generics, bounds, items),
4148 (*is_auto, *safety, *ident, generics, bounds, items);
4149
4150 expect_trait_alias, (Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4151 ItemKind::TraitAlias(ident, generics, bounds), (*ident, generics, bounds);
4152
4153 expect_impl, &'hir Impl<'hir>, ItemKind::Impl(imp), imp;
4154 }
4155}
4156
4157#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4158#[derive(Encodable, Decodable, HashStable_Generic)]
4159pub enum Safety {
4160 Unsafe,
4161 Safe,
4162}
4163
4164impl Safety {
4165 pub fn prefix_str(self) -> &'static str {
4166 match self {
4167 Self::Unsafe => "unsafe ",
4168 Self::Safe => "",
4169 }
4170 }
4171
4172 #[inline]
4173 pub fn is_unsafe(self) -> bool {
4174 !self.is_safe()
4175 }
4176
4177 #[inline]
4178 pub fn is_safe(self) -> bool {
4179 match self {
4180 Self::Unsafe => false,
4181 Self::Safe => true,
4182 }
4183 }
4184}
4185
4186impl fmt::Display for Safety {
4187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4188 f.write_str(match *self {
4189 Self::Unsafe => "unsafe",
4190 Self::Safe => "safe",
4191 })
4192 }
4193}
4194
4195#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4196pub enum Constness {
4197 Const,
4198 NotConst,
4199}
4200
4201impl fmt::Display for Constness {
4202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4203 f.write_str(match *self {
4204 Self::Const => "const",
4205 Self::NotConst => "non-const",
4206 })
4207 }
4208}
4209
4210#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4215pub enum HeaderSafety {
4216 SafeTargetFeatures,
4222 Normal(Safety),
4223}
4224
4225impl From<Safety> for HeaderSafety {
4226 fn from(v: Safety) -> Self {
4227 Self::Normal(v)
4228 }
4229}
4230
4231#[derive(Copy, Clone, Debug, HashStable_Generic)]
4232pub struct FnHeader {
4233 pub safety: HeaderSafety,
4234 pub constness: Constness,
4235 pub asyncness: IsAsync,
4236 pub abi: ExternAbi,
4237}
4238
4239impl FnHeader {
4240 pub fn is_async(&self) -> bool {
4241 matches!(self.asyncness, IsAsync::Async(_))
4242 }
4243
4244 pub fn is_const(&self) -> bool {
4245 matches!(self.constness, Constness::Const)
4246 }
4247
4248 pub fn is_unsafe(&self) -> bool {
4249 self.safety().is_unsafe()
4250 }
4251
4252 pub fn is_safe(&self) -> bool {
4253 self.safety().is_safe()
4254 }
4255
4256 pub fn safety(&self) -> Safety {
4257 match self.safety {
4258 HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4259 HeaderSafety::Normal(safety) => safety,
4260 }
4261 }
4262}
4263
4264#[derive(Debug, Clone, Copy, HashStable_Generic)]
4265pub enum ItemKind<'hir> {
4266 ExternCrate(Option<Symbol>, Ident),
4270
4271 Use(&'hir UsePath<'hir>, UseKind),
4277
4278 Static(Ident, &'hir Ty<'hir>, Mutability, BodyId),
4280 Const(Ident, &'hir Ty<'hir>, &'hir Generics<'hir>, BodyId),
4282 Fn {
4284 ident: Ident,
4285 sig: FnSig<'hir>,
4286 generics: &'hir Generics<'hir>,
4287 body: BodyId,
4288 has_body: bool,
4292 },
4293 Macro(Ident, &'hir ast::MacroDef, MacroKind),
4295 Mod(Ident, &'hir Mod<'hir>),
4297 ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemRef] },
4299 GlobalAsm {
4301 asm: &'hir InlineAsm<'hir>,
4302 fake_body: BodyId,
4308 },
4309 TyAlias(Ident, &'hir Ty<'hir>, &'hir Generics<'hir>),
4311 Enum(Ident, EnumDef<'hir>, &'hir Generics<'hir>),
4313 Struct(Ident, VariantData<'hir>, &'hir Generics<'hir>),
4315 Union(Ident, VariantData<'hir>, &'hir Generics<'hir>),
4317 Trait(IsAuto, Safety, Ident, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
4319 TraitAlias(Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4321
4322 Impl(&'hir Impl<'hir>),
4324}
4325
4326#[derive(Debug, Clone, Copy, HashStable_Generic)]
4331pub struct Impl<'hir> {
4332 pub constness: Constness,
4333 pub safety: Safety,
4334 pub polarity: ImplPolarity,
4335 pub defaultness: Defaultness,
4336 pub defaultness_span: Option<Span>,
4339 pub generics: &'hir Generics<'hir>,
4340
4341 pub of_trait: Option<TraitRef<'hir>>,
4343
4344 pub self_ty: &'hir Ty<'hir>,
4345 pub items: &'hir [ImplItemRef],
4346}
4347
4348impl ItemKind<'_> {
4349 pub fn ident(&self) -> Option<Ident> {
4350 match *self {
4351 ItemKind::ExternCrate(_, ident)
4352 | ItemKind::Use(_, UseKind::Single(ident))
4353 | ItemKind::Static(ident, ..)
4354 | ItemKind::Const(ident, ..)
4355 | ItemKind::Fn { ident, .. }
4356 | ItemKind::Macro(ident, ..)
4357 | ItemKind::Mod(ident, ..)
4358 | ItemKind::TyAlias(ident, ..)
4359 | ItemKind::Enum(ident, ..)
4360 | ItemKind::Struct(ident, ..)
4361 | ItemKind::Union(ident, ..)
4362 | ItemKind::Trait(_, _, ident, ..)
4363 | ItemKind::TraitAlias(ident, ..) => Some(ident),
4364
4365 ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4366 | ItemKind::ForeignMod { .. }
4367 | ItemKind::GlobalAsm { .. }
4368 | ItemKind::Impl(_) => None,
4369 }
4370 }
4371
4372 pub fn generics(&self) -> Option<&Generics<'_>> {
4373 Some(match self {
4374 ItemKind::Fn { generics, .. }
4375 | ItemKind::TyAlias(_, _, generics)
4376 | ItemKind::Const(_, _, generics, _)
4377 | ItemKind::Enum(_, _, generics)
4378 | ItemKind::Struct(_, _, generics)
4379 | ItemKind::Union(_, _, generics)
4380 | ItemKind::Trait(_, _, _, generics, _, _)
4381 | ItemKind::TraitAlias(_, generics, _)
4382 | ItemKind::Impl(Impl { generics, .. }) => generics,
4383 _ => return None,
4384 })
4385 }
4386
4387 pub fn descr(&self) -> &'static str {
4388 match self {
4389 ItemKind::ExternCrate(..) => "extern crate",
4390 ItemKind::Use(..) => "`use` import",
4391 ItemKind::Static(..) => "static item",
4392 ItemKind::Const(..) => "constant item",
4393 ItemKind::Fn { .. } => "function",
4394 ItemKind::Macro(..) => "macro",
4395 ItemKind::Mod(..) => "module",
4396 ItemKind::ForeignMod { .. } => "extern block",
4397 ItemKind::GlobalAsm { .. } => "global asm item",
4398 ItemKind::TyAlias(..) => "type alias",
4399 ItemKind::Enum(..) => "enum",
4400 ItemKind::Struct(..) => "struct",
4401 ItemKind::Union(..) => "union",
4402 ItemKind::Trait(..) => "trait",
4403 ItemKind::TraitAlias(..) => "trait alias",
4404 ItemKind::Impl(..) => "implementation",
4405 }
4406 }
4407}
4408
4409#[derive(Debug, Clone, Copy, HashStable_Generic)]
4416pub struct TraitItemRef {
4417 pub id: TraitItemId,
4418 pub ident: Ident,
4419 pub kind: AssocItemKind,
4420 pub span: Span,
4421}
4422
4423#[derive(Debug, Clone, Copy, HashStable_Generic)]
4430pub struct ImplItemRef {
4431 pub id: ImplItemId,
4432 pub ident: Ident,
4433 pub kind: AssocItemKind,
4434 pub span: Span,
4435 pub trait_item_def_id: Option<DefId>,
4437}
4438
4439#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
4440pub enum AssocItemKind {
4441 Const,
4442 Fn { has_self: bool },
4443 Type,
4444}
4445
4446#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4450pub struct ForeignItemId {
4451 pub owner_id: OwnerId,
4452}
4453
4454impl ForeignItemId {
4455 #[inline]
4456 pub fn hir_id(&self) -> HirId {
4457 HirId::make_owner(self.owner_id.def_id)
4459 }
4460}
4461
4462#[derive(Debug, Clone, Copy, HashStable_Generic)]
4469pub struct ForeignItemRef {
4470 pub id: ForeignItemId,
4471 pub ident: Ident,
4472 pub span: Span,
4473}
4474
4475#[derive(Debug, Clone, Copy, HashStable_Generic)]
4476pub struct ForeignItem<'hir> {
4477 pub ident: Ident,
4478 pub kind: ForeignItemKind<'hir>,
4479 pub owner_id: OwnerId,
4480 pub span: Span,
4481 pub vis_span: Span,
4482}
4483
4484impl ForeignItem<'_> {
4485 #[inline]
4486 pub fn hir_id(&self) -> HirId {
4487 HirId::make_owner(self.owner_id.def_id)
4489 }
4490
4491 pub fn foreign_item_id(&self) -> ForeignItemId {
4492 ForeignItemId { owner_id: self.owner_id }
4493 }
4494}
4495
4496#[derive(Debug, Clone, Copy, HashStable_Generic)]
4498pub enum ForeignItemKind<'hir> {
4499 Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4506 Static(&'hir Ty<'hir>, Mutability, Safety),
4508 Type,
4510}
4511
4512#[derive(Debug, Copy, Clone, HashStable_Generic)]
4514pub struct Upvar {
4515 pub span: Span,
4517}
4518
4519#[derive(Debug, Clone, HashStable_Generic)]
4523pub struct TraitCandidate {
4524 pub def_id: DefId,
4525 pub import_ids: SmallVec<[LocalDefId; 1]>,
4526}
4527
4528#[derive(Copy, Clone, Debug, HashStable_Generic)]
4529pub enum OwnerNode<'hir> {
4530 Item(&'hir Item<'hir>),
4531 ForeignItem(&'hir ForeignItem<'hir>),
4532 TraitItem(&'hir TraitItem<'hir>),
4533 ImplItem(&'hir ImplItem<'hir>),
4534 Crate(&'hir Mod<'hir>),
4535 Synthetic,
4536}
4537
4538impl<'hir> OwnerNode<'hir> {
4539 pub fn span(&self) -> Span {
4540 match self {
4541 OwnerNode::Item(Item { span, .. })
4542 | OwnerNode::ForeignItem(ForeignItem { span, .. })
4543 | OwnerNode::ImplItem(ImplItem { span, .. })
4544 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4545 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4546 OwnerNode::Synthetic => unreachable!(),
4547 }
4548 }
4549
4550 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4551 match self {
4552 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4553 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4554 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4555 | OwnerNode::ForeignItem(ForeignItem {
4556 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4557 }) => Some(fn_sig),
4558 _ => None,
4559 }
4560 }
4561
4562 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4563 match self {
4564 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4565 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4566 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4567 | OwnerNode::ForeignItem(ForeignItem {
4568 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4569 }) => Some(fn_sig.decl),
4570 _ => None,
4571 }
4572 }
4573
4574 pub fn body_id(&self) -> Option<BodyId> {
4575 match self {
4576 OwnerNode::Item(Item {
4577 kind:
4578 ItemKind::Static(_, _, _, body)
4579 | ItemKind::Const(_, _, _, body)
4580 | ItemKind::Fn { body, .. },
4581 ..
4582 })
4583 | OwnerNode::TraitItem(TraitItem {
4584 kind:
4585 TraitItemKind::Fn(_, TraitFn::Provided(body)) | TraitItemKind::Const(_, Some(body)),
4586 ..
4587 })
4588 | OwnerNode::ImplItem(ImplItem {
4589 kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, body),
4590 ..
4591 }) => Some(*body),
4592 _ => None,
4593 }
4594 }
4595
4596 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4597 Node::generics(self.into())
4598 }
4599
4600 pub fn def_id(self) -> OwnerId {
4601 match self {
4602 OwnerNode::Item(Item { owner_id, .. })
4603 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4604 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4605 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4606 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4607 OwnerNode::Synthetic => unreachable!(),
4608 }
4609 }
4610
4611 pub fn is_impl_block(&self) -> bool {
4613 matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4614 }
4615
4616 expect_methods_self! {
4617 expect_item, &'hir Item<'hir>, OwnerNode::Item(n), n;
4618 expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4619 expect_impl_item, &'hir ImplItem<'hir>, OwnerNode::ImplItem(n), n;
4620 expect_trait_item, &'hir TraitItem<'hir>, OwnerNode::TraitItem(n), n;
4621 }
4622}
4623
4624impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4625 fn from(val: &'hir Item<'hir>) -> Self {
4626 OwnerNode::Item(val)
4627 }
4628}
4629
4630impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4631 fn from(val: &'hir ForeignItem<'hir>) -> Self {
4632 OwnerNode::ForeignItem(val)
4633 }
4634}
4635
4636impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4637 fn from(val: &'hir ImplItem<'hir>) -> Self {
4638 OwnerNode::ImplItem(val)
4639 }
4640}
4641
4642impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4643 fn from(val: &'hir TraitItem<'hir>) -> Self {
4644 OwnerNode::TraitItem(val)
4645 }
4646}
4647
4648impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4649 fn from(val: OwnerNode<'hir>) -> Self {
4650 match val {
4651 OwnerNode::Item(n) => Node::Item(n),
4652 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4653 OwnerNode::ImplItem(n) => Node::ImplItem(n),
4654 OwnerNode::TraitItem(n) => Node::TraitItem(n),
4655 OwnerNode::Crate(n) => Node::Crate(n),
4656 OwnerNode::Synthetic => Node::Synthetic,
4657 }
4658 }
4659}
4660
4661#[derive(Copy, Clone, Debug, HashStable_Generic)]
4662pub enum Node<'hir> {
4663 Param(&'hir Param<'hir>),
4664 Item(&'hir Item<'hir>),
4665 ForeignItem(&'hir ForeignItem<'hir>),
4666 TraitItem(&'hir TraitItem<'hir>),
4667 ImplItem(&'hir ImplItem<'hir>),
4668 Variant(&'hir Variant<'hir>),
4669 Field(&'hir FieldDef<'hir>),
4670 AnonConst(&'hir AnonConst),
4671 ConstBlock(&'hir ConstBlock),
4672 ConstArg(&'hir ConstArg<'hir>),
4673 Expr(&'hir Expr<'hir>),
4674 ExprField(&'hir ExprField<'hir>),
4675 Stmt(&'hir Stmt<'hir>),
4676 PathSegment(&'hir PathSegment<'hir>),
4677 Ty(&'hir Ty<'hir>),
4678 AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4679 TraitRef(&'hir TraitRef<'hir>),
4680 OpaqueTy(&'hir OpaqueTy<'hir>),
4681 TyPat(&'hir TyPat<'hir>),
4682 Pat(&'hir Pat<'hir>),
4683 PatField(&'hir PatField<'hir>),
4684 PatExpr(&'hir PatExpr<'hir>),
4688 Arm(&'hir Arm<'hir>),
4689 Block(&'hir Block<'hir>),
4690 LetStmt(&'hir LetStmt<'hir>),
4691 Ctor(&'hir VariantData<'hir>),
4694 Lifetime(&'hir Lifetime),
4695 GenericParam(&'hir GenericParam<'hir>),
4696 Crate(&'hir Mod<'hir>),
4697 Infer(&'hir InferArg),
4698 WherePredicate(&'hir WherePredicate<'hir>),
4699 PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4700 Synthetic,
4702 Err(Span),
4703}
4704
4705impl<'hir> Node<'hir> {
4706 pub fn ident(&self) -> Option<Ident> {
4721 match self {
4722 Node::Item(item) => item.kind.ident(),
4723 Node::TraitItem(TraitItem { ident, .. })
4724 | Node::ImplItem(ImplItem { ident, .. })
4725 | Node::ForeignItem(ForeignItem { ident, .. })
4726 | Node::Field(FieldDef { ident, .. })
4727 | Node::Variant(Variant { ident, .. })
4728 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4729 Node::Lifetime(lt) => Some(lt.ident),
4730 Node::GenericParam(p) => Some(p.name.ident()),
4731 Node::AssocItemConstraint(c) => Some(c.ident),
4732 Node::PatField(f) => Some(f.ident),
4733 Node::ExprField(f) => Some(f.ident),
4734 Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4735 Node::Param(..)
4736 | Node::AnonConst(..)
4737 | Node::ConstBlock(..)
4738 | Node::ConstArg(..)
4739 | Node::Expr(..)
4740 | Node::Stmt(..)
4741 | Node::Block(..)
4742 | Node::Ctor(..)
4743 | Node::Pat(..)
4744 | Node::TyPat(..)
4745 | Node::PatExpr(..)
4746 | Node::Arm(..)
4747 | Node::LetStmt(..)
4748 | Node::Crate(..)
4749 | Node::Ty(..)
4750 | Node::TraitRef(..)
4751 | Node::OpaqueTy(..)
4752 | Node::Infer(..)
4753 | Node::WherePredicate(..)
4754 | Node::Synthetic
4755 | Node::Err(..) => None,
4756 }
4757 }
4758
4759 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4760 match self {
4761 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4762 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4763 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4764 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4765 Some(fn_sig.decl)
4766 }
4767 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4768 Some(fn_decl)
4769 }
4770 _ => None,
4771 }
4772 }
4773
4774 pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4776 if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4777 && let Some(trait_ref) = impl_block.of_trait
4778 && let Some(trait_id) = trait_ref.trait_def_id()
4779 && trait_id == trait_def_id
4780 {
4781 Some(impl_block)
4782 } else {
4783 None
4784 }
4785 }
4786
4787 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4788 match self {
4789 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4790 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4791 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4792 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4793 Some(fn_sig)
4794 }
4795 _ => None,
4796 }
4797 }
4798
4799 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4801 match self {
4802 Node::Item(it) => match it.kind {
4803 ItemKind::TyAlias(_, ty, _)
4804 | ItemKind::Static(_, ty, _, _)
4805 | ItemKind::Const(_, ty, _, _) => Some(ty),
4806 ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4807 _ => None,
4808 },
4809 Node::TraitItem(it) => match it.kind {
4810 TraitItemKind::Const(ty, _) => Some(ty),
4811 TraitItemKind::Type(_, ty) => ty,
4812 _ => None,
4813 },
4814 Node::ImplItem(it) => match it.kind {
4815 ImplItemKind::Const(ty, _) => Some(ty),
4816 ImplItemKind::Type(ty) => Some(ty),
4817 _ => None,
4818 },
4819 _ => None,
4820 }
4821 }
4822
4823 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4824 match self {
4825 Node::Item(Item { kind: ItemKind::TyAlias(_, ty, _), .. }) => Some(ty),
4826 _ => None,
4827 }
4828 }
4829
4830 #[inline]
4831 pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4832 match self {
4833 Node::Item(Item {
4834 owner_id,
4835 kind:
4836 ItemKind::Const(_, _, _, body)
4837 | ItemKind::Static(.., body)
4838 | ItemKind::Fn { body, .. },
4839 ..
4840 })
4841 | Node::TraitItem(TraitItem {
4842 owner_id,
4843 kind:
4844 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4845 ..
4846 })
4847 | Node::ImplItem(ImplItem {
4848 owner_id,
4849 kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
4850 ..
4851 }) => Some((owner_id.def_id, *body)),
4852
4853 Node::Item(Item {
4854 owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4855 }) => Some((owner_id.def_id, *fake_body)),
4856
4857 Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4858 Some((*def_id, *body))
4859 }
4860
4861 Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4862 Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4863
4864 _ => None,
4865 }
4866 }
4867
4868 pub fn body_id(&self) -> Option<BodyId> {
4869 Some(self.associated_body()?.1)
4870 }
4871
4872 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4873 match self {
4874 Node::ForeignItem(ForeignItem {
4875 kind: ForeignItemKind::Fn(_, _, generics), ..
4876 })
4877 | Node::TraitItem(TraitItem { generics, .. })
4878 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4879 Node::Item(item) => item.kind.generics(),
4880 _ => None,
4881 }
4882 }
4883
4884 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4885 match self {
4886 Node::Item(i) => Some(OwnerNode::Item(i)),
4887 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4888 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4889 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4890 Node::Crate(i) => Some(OwnerNode::Crate(i)),
4891 Node::Synthetic => Some(OwnerNode::Synthetic),
4892 _ => None,
4893 }
4894 }
4895
4896 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4897 match self {
4898 Node::Item(i) => match i.kind {
4899 ItemKind::Fn { ident, sig, generics, .. } => {
4900 Some(FnKind::ItemFn(ident, generics, sig.header))
4901 }
4902 _ => None,
4903 },
4904 Node::TraitItem(ti) => match ti.kind {
4905 TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4906 _ => None,
4907 },
4908 Node::ImplItem(ii) => match ii.kind {
4909 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4910 _ => None,
4911 },
4912 Node::Expr(e) => match e.kind {
4913 ExprKind::Closure { .. } => Some(FnKind::Closure),
4914 _ => None,
4915 },
4916 _ => None,
4917 }
4918 }
4919
4920 expect_methods_self! {
4921 expect_param, &'hir Param<'hir>, Node::Param(n), n;
4922 expect_item, &'hir Item<'hir>, Node::Item(n), n;
4923 expect_foreign_item, &'hir ForeignItem<'hir>, Node::ForeignItem(n), n;
4924 expect_trait_item, &'hir TraitItem<'hir>, Node::TraitItem(n), n;
4925 expect_impl_item, &'hir ImplItem<'hir>, Node::ImplItem(n), n;
4926 expect_variant, &'hir Variant<'hir>, Node::Variant(n), n;
4927 expect_field, &'hir FieldDef<'hir>, Node::Field(n), n;
4928 expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n;
4929 expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n;
4930 expect_expr, &'hir Expr<'hir>, Node::Expr(n), n;
4931 expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n;
4932 expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n;
4933 expect_path_segment, &'hir PathSegment<'hir>, Node::PathSegment(n), n;
4934 expect_ty, &'hir Ty<'hir>, Node::Ty(n), n;
4935 expect_assoc_item_constraint, &'hir AssocItemConstraint<'hir>, Node::AssocItemConstraint(n), n;
4936 expect_trait_ref, &'hir TraitRef<'hir>, Node::TraitRef(n), n;
4937 expect_opaque_ty, &'hir OpaqueTy<'hir>, Node::OpaqueTy(n), n;
4938 expect_pat, &'hir Pat<'hir>, Node::Pat(n), n;
4939 expect_pat_field, &'hir PatField<'hir>, Node::PatField(n), n;
4940 expect_arm, &'hir Arm<'hir>, Node::Arm(n), n;
4941 expect_block, &'hir Block<'hir>, Node::Block(n), n;
4942 expect_let_stmt, &'hir LetStmt<'hir>, Node::LetStmt(n), n;
4943 expect_ctor, &'hir VariantData<'hir>, Node::Ctor(n), n;
4944 expect_lifetime, &'hir Lifetime, Node::Lifetime(n), n;
4945 expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4946 expect_crate, &'hir Mod<'hir>, Node::Crate(n), n;
4947 expect_infer, &'hir InferArg, Node::Infer(n), n;
4948 expect_closure, &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4949 }
4950}
4951
4952#[cfg(target_pointer_width = "64")]
4954mod size_asserts {
4955 use rustc_data_structures::static_assert_size;
4956
4957 use super::*;
4958 static_assert_size!(Block<'_>, 48);
4960 static_assert_size!(Body<'_>, 24);
4961 static_assert_size!(Expr<'_>, 64);
4962 static_assert_size!(ExprKind<'_>, 48);
4963 static_assert_size!(FnDecl<'_>, 40);
4964 static_assert_size!(ForeignItem<'_>, 88);
4965 static_assert_size!(ForeignItemKind<'_>, 56);
4966 static_assert_size!(GenericArg<'_>, 16);
4967 static_assert_size!(GenericBound<'_>, 64);
4968 static_assert_size!(Generics<'_>, 56);
4969 static_assert_size!(Impl<'_>, 80);
4970 static_assert_size!(ImplItem<'_>, 88);
4971 static_assert_size!(ImplItemKind<'_>, 40);
4972 static_assert_size!(Item<'_>, 88);
4973 static_assert_size!(ItemKind<'_>, 64);
4974 static_assert_size!(LetStmt<'_>, 72);
4975 static_assert_size!(Param<'_>, 32);
4976 static_assert_size!(Pat<'_>, 72);
4977 static_assert_size!(Path<'_>, 40);
4978 static_assert_size!(PathSegment<'_>, 48);
4979 static_assert_size!(PatKind<'_>, 48);
4980 static_assert_size!(QPath<'_>, 24);
4981 static_assert_size!(Res, 12);
4982 static_assert_size!(Stmt<'_>, 32);
4983 static_assert_size!(StmtKind<'_>, 16);
4984 static_assert_size!(TraitItem<'_>, 88);
4985 static_assert_size!(TraitItemKind<'_>, 48);
4986 static_assert_size!(Ty<'_>, 48);
4987 static_assert_size!(TyKind<'_>, 32);
4988 }
4990
4991#[cfg(test)]
4992mod tests;