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 AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind, BoundConstness, BoundPolarity,
14 ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto, MetaItemInner, MetaItemLit, Movability,
15 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, HashStable_Generic)]
39pub struct Lifetime {
40 #[stable_hasher(ignore)]
41 pub hir_id: HirId,
42
43 pub ident: Ident,
49
50 pub res: LifetimeName,
52}
53
54#[derive(Debug, Copy, Clone, HashStable_Generic)]
55pub enum ParamName {
56 Plain(Ident),
58
59 Error(Ident),
65
66 Fresh,
81}
82
83impl ParamName {
84 pub fn ident(&self) -> Ident {
85 match *self {
86 ParamName::Plain(ident) | ParamName::Error(ident) => ident,
87 ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
88 }
89 }
90}
91
92#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
93pub enum LifetimeName {
94 Param(LocalDefId),
96
97 ImplicitObjectLifetimeDefault,
109
110 Error,
113
114 Infer,
117
118 Static,
120}
121
122impl LifetimeName {
123 fn is_elided(&self) -> bool {
124 match self {
125 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true,
126
127 LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
132 }
133 }
134}
135
136impl fmt::Display for Lifetime {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 if self.ident.name != kw::Empty { self.ident.name.fmt(f) } else { "'_".fmt(f) }
139 }
140}
141
142pub enum LifetimeSuggestionPosition {
143 Normal,
145 Ampersand,
147 ElidedPath,
149 ElidedPathArgument,
151 ObjectDefault,
153}
154
155impl Lifetime {
156 pub fn is_elided(&self) -> bool {
157 self.res.is_elided()
158 }
159
160 pub fn is_anonymous(&self) -> bool {
161 self.ident.name == kw::Empty || self.ident.name == kw::UnderscoreLifetime
162 }
163
164 pub fn suggestion_position(&self) -> (LifetimeSuggestionPosition, Span) {
165 if self.ident.name == kw::Empty {
166 if self.ident.span.is_empty() {
167 (LifetimeSuggestionPosition::ElidedPathArgument, self.ident.span)
168 } else {
169 (LifetimeSuggestionPosition::ElidedPath, self.ident.span.shrink_to_hi())
170 }
171 } else if self.res == LifetimeName::ImplicitObjectLifetimeDefault {
172 (LifetimeSuggestionPosition::ObjectDefault, self.ident.span)
173 } else if self.ident.span.is_empty() {
174 (LifetimeSuggestionPosition::Ampersand, self.ident.span)
175 } else {
176 (LifetimeSuggestionPosition::Normal, self.ident.span)
177 }
178 }
179
180 pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
181 debug_assert!(new_lifetime.starts_with('\''));
182 let (pos, span) = self.suggestion_position();
183 let code = match pos {
184 LifetimeSuggestionPosition::Normal => format!("{new_lifetime}"),
185 LifetimeSuggestionPosition::Ampersand => format!("{new_lifetime} "),
186 LifetimeSuggestionPosition::ElidedPath => format!("<{new_lifetime}>"),
187 LifetimeSuggestionPosition::ElidedPathArgument => format!("{new_lifetime}, "),
188 LifetimeSuggestionPosition::ObjectDefault => format!("+ {new_lifetime}"),
189 };
190 (span, code)
191 }
192}
193
194#[derive(Debug, Clone, Copy, HashStable_Generic)]
198pub struct Path<'hir, R = Res> {
199 pub span: Span,
200 pub res: R,
202 pub segments: &'hir [PathSegment<'hir>],
204}
205
206pub type UsePath<'hir> = Path<'hir, SmallVec<[Res; 3]>>;
208
209impl Path<'_> {
210 pub fn is_global(&self) -> bool {
211 self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
212 }
213}
214
215#[derive(Debug, Clone, Copy, HashStable_Generic)]
218pub struct PathSegment<'hir> {
219 pub ident: Ident,
221 #[stable_hasher(ignore)]
222 pub hir_id: HirId,
223 pub res: Res,
224
225 pub args: Option<&'hir GenericArgs<'hir>>,
231
232 pub infer_args: bool,
237}
238
239impl<'hir> PathSegment<'hir> {
240 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
242 PathSegment { ident, hir_id, res, infer_args: true, args: None }
243 }
244
245 pub fn invalid() -> Self {
246 Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
247 }
248
249 pub fn args(&self) -> &GenericArgs<'hir> {
250 if let Some(ref args) = self.args {
251 args
252 } else {
253 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
254 DUMMY
255 }
256 }
257}
258
259#[derive(Clone, Copy, Debug, HashStable_Generic)]
275#[repr(C)]
276pub struct ConstArg<'hir, Unambig = ()> {
277 #[stable_hasher(ignore)]
278 pub hir_id: HirId,
279 pub kind: ConstArgKind<'hir, Unambig>,
280}
281
282impl<'hir> ConstArg<'hir, AmbigArg> {
283 pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
294 let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
297 unsafe { &*ptr }
298 }
299}
300
301impl<'hir> ConstArg<'hir> {
302 pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
308 if let ConstArgKind::Infer(_, ()) = self.kind {
309 return None;
310 }
311
312 let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
316 Some(unsafe { &*ptr })
317 }
318}
319
320impl<'hir, Unambig> ConstArg<'hir, Unambig> {
321 pub fn anon_const_hir_id(&self) -> Option<HirId> {
322 match self.kind {
323 ConstArgKind::Anon(ac) => Some(ac.hir_id),
324 _ => None,
325 }
326 }
327
328 pub fn span(&self) -> Span {
329 match self.kind {
330 ConstArgKind::Path(path) => path.span(),
331 ConstArgKind::Anon(anon) => anon.span,
332 ConstArgKind::Infer(span, _) => span,
333 }
334 }
335}
336
337#[derive(Clone, Copy, Debug, HashStable_Generic)]
339#[repr(u8, C)]
340pub enum ConstArgKind<'hir, Unambig = ()> {
341 Path(QPath<'hir>),
347 Anon(&'hir AnonConst),
348 Infer(Span, Unambig),
351}
352
353#[derive(Clone, Copy, Debug, HashStable_Generic)]
354pub struct InferArg {
355 #[stable_hasher(ignore)]
356 pub hir_id: HirId,
357 pub span: Span,
358}
359
360impl InferArg {
361 pub fn to_ty(&self) -> Ty<'static> {
362 Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
363 }
364}
365
366#[derive(Debug, Clone, Copy, HashStable_Generic)]
367pub enum GenericArg<'hir> {
368 Lifetime(&'hir Lifetime),
369 Type(&'hir Ty<'hir, AmbigArg>),
370 Const(&'hir ConstArg<'hir, AmbigArg>),
371 Infer(InferArg),
381}
382
383impl GenericArg<'_> {
384 pub fn span(&self) -> Span {
385 match self {
386 GenericArg::Lifetime(l) => l.ident.span,
387 GenericArg::Type(t) => t.span,
388 GenericArg::Const(c) => c.span(),
389 GenericArg::Infer(i) => i.span,
390 }
391 }
392
393 pub fn hir_id(&self) -> HirId {
394 match self {
395 GenericArg::Lifetime(l) => l.hir_id,
396 GenericArg::Type(t) => t.hir_id,
397 GenericArg::Const(c) => c.hir_id,
398 GenericArg::Infer(i) => i.hir_id,
399 }
400 }
401
402 pub fn descr(&self) -> &'static str {
403 match self {
404 GenericArg::Lifetime(_) => "lifetime",
405 GenericArg::Type(_) => "type",
406 GenericArg::Const(_) => "constant",
407 GenericArg::Infer(_) => "placeholder",
408 }
409 }
410
411 pub fn to_ord(&self) -> ast::ParamKindOrd {
412 match self {
413 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
414 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
415 ast::ParamKindOrd::TypeOrConst
416 }
417 }
418 }
419
420 pub fn is_ty_or_const(&self) -> bool {
421 match self {
422 GenericArg::Lifetime(_) => false,
423 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
424 }
425 }
426}
427
428#[derive(Debug, Clone, Copy, HashStable_Generic)]
430pub struct GenericArgs<'hir> {
431 pub args: &'hir [GenericArg<'hir>],
433 pub constraints: &'hir [AssocItemConstraint<'hir>],
435 pub parenthesized: GenericArgsParentheses,
440 pub span_ext: Span,
453}
454
455impl<'hir> GenericArgs<'hir> {
456 pub const fn none() -> Self {
457 Self {
458 args: &[],
459 constraints: &[],
460 parenthesized: GenericArgsParentheses::No,
461 span_ext: DUMMY_SP,
462 }
463 }
464
465 pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
470 if self.parenthesized != GenericArgsParentheses::ParenSugar {
471 return None;
472 }
473
474 let inputs = self
475 .args
476 .iter()
477 .find_map(|arg| {
478 let GenericArg::Type(ty) = arg else { return None };
479 let TyKind::Tup(tys) = &ty.kind else { return None };
480 Some(tys)
481 })
482 .unwrap();
483
484 Some((inputs, self.paren_sugar_output_inner()))
485 }
486
487 pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
492 (self.parenthesized == GenericArgsParentheses::ParenSugar)
493 .then(|| self.paren_sugar_output_inner())
494 }
495
496 fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
497 let [constraint] = self.constraints.try_into().unwrap();
498 debug_assert_eq!(constraint.ident.name, sym::Output);
499 constraint.ty().unwrap()
500 }
501
502 pub fn has_err(&self) -> Option<ErrorGuaranteed> {
503 self.args
504 .iter()
505 .find_map(|arg| {
506 let GenericArg::Type(ty) = arg else { return None };
507 let TyKind::Err(guar) = ty.kind else { return None };
508 Some(guar)
509 })
510 .or_else(|| {
511 self.constraints.iter().find_map(|constraint| {
512 let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
513 Some(guar)
514 })
515 })
516 }
517
518 #[inline]
519 pub fn num_lifetime_params(&self) -> usize {
520 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
521 }
522
523 #[inline]
524 pub fn has_lifetime_params(&self) -> bool {
525 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
526 }
527
528 #[inline]
529 pub fn num_generic_params(&self) -> usize {
532 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
533 }
534
535 pub fn span(&self) -> Option<Span> {
541 let span_ext = self.span_ext()?;
542 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
543 }
544
545 pub fn span_ext(&self) -> Option<Span> {
547 Some(self.span_ext).filter(|span| !span.is_empty())
548 }
549
550 pub fn is_empty(&self) -> bool {
551 self.args.is_empty()
552 }
553}
554
555#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)]
556pub enum GenericArgsParentheses {
557 No,
558 ReturnTypeNotation,
561 ParenSugar,
563}
564
565#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
567pub struct TraitBoundModifiers {
568 pub constness: BoundConstness,
569 pub polarity: BoundPolarity,
570}
571
572impl TraitBoundModifiers {
573 pub const NONE: Self =
574 TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
575}
576
577#[derive(Clone, Copy, Debug, HashStable_Generic)]
578pub enum GenericBound<'hir> {
579 Trait(PolyTraitRef<'hir>),
580 Outlives(&'hir Lifetime),
581 Use(&'hir [PreciseCapturingArg<'hir>], Span),
582}
583
584impl GenericBound<'_> {
585 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
586 match self {
587 GenericBound::Trait(data) => Some(&data.trait_ref),
588 _ => None,
589 }
590 }
591
592 pub fn span(&self) -> Span {
593 match self {
594 GenericBound::Trait(t, ..) => t.span,
595 GenericBound::Outlives(l) => l.ident.span,
596 GenericBound::Use(_, span) => *span,
597 }
598 }
599}
600
601pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
602
603#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, Debug)]
604pub enum MissingLifetimeKind {
605 Underscore,
607 Ampersand,
609 Comma,
611 Brackets,
613}
614
615#[derive(Copy, Clone, Debug, HashStable_Generic)]
616pub enum LifetimeParamKind {
617 Explicit,
620
621 Elided(MissingLifetimeKind),
624
625 Error,
627}
628
629#[derive(Debug, Clone, Copy, HashStable_Generic)]
630pub enum GenericParamKind<'hir> {
631 Lifetime {
633 kind: LifetimeParamKind,
634 },
635 Type {
636 default: Option<&'hir Ty<'hir>>,
637 synthetic: bool,
638 },
639 Const {
640 ty: &'hir Ty<'hir>,
641 default: Option<&'hir ConstArg<'hir>>,
643 synthetic: bool,
644 },
645}
646
647#[derive(Debug, Clone, Copy, HashStable_Generic)]
648pub struct GenericParam<'hir> {
649 #[stable_hasher(ignore)]
650 pub hir_id: HirId,
651 pub def_id: LocalDefId,
652 pub name: ParamName,
653 pub span: Span,
654 pub pure_wrt_drop: bool,
655 pub kind: GenericParamKind<'hir>,
656 pub colon_span: Option<Span>,
657 pub source: GenericParamSource,
658}
659
660impl<'hir> GenericParam<'hir> {
661 pub fn is_impl_trait(&self) -> bool {
665 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
666 }
667
668 pub fn is_elided_lifetime(&self) -> bool {
672 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
673 }
674}
675
676#[derive(Debug, Clone, Copy, HashStable_Generic)]
683pub enum GenericParamSource {
684 Generics,
686 Binder,
688}
689
690#[derive(Default)]
691pub struct GenericParamCount {
692 pub lifetimes: usize,
693 pub types: usize,
694 pub consts: usize,
695 pub infer: usize,
696}
697
698#[derive(Debug, Clone, Copy, HashStable_Generic)]
701pub struct Generics<'hir> {
702 pub params: &'hir [GenericParam<'hir>],
703 pub predicates: &'hir [WherePredicate<'hir>],
704 pub has_where_clause_predicates: bool,
705 pub where_clause_span: Span,
706 pub span: Span,
707}
708
709impl<'hir> Generics<'hir> {
710 pub const fn empty() -> &'hir Generics<'hir> {
711 const NOPE: Generics<'_> = Generics {
712 params: &[],
713 predicates: &[],
714 has_where_clause_predicates: false,
715 where_clause_span: DUMMY_SP,
716 span: DUMMY_SP,
717 };
718 &NOPE
719 }
720
721 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
722 self.params.iter().find(|¶m| name == param.name.ident().name)
723 }
724
725 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
727 if let Some(first) = self.params.first()
728 && self.span.contains(first.span)
729 {
730 Some(first.span.shrink_to_lo())
733 } else {
734 None
735 }
736 }
737
738 pub fn span_for_param_suggestion(&self) -> Option<Span> {
740 self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
741 self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
744 })
745 }
746
747 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
750 let end = self.where_clause_span.shrink_to_hi();
751 if self.has_where_clause_predicates {
752 self.predicates
753 .iter()
754 .rfind(|&p| p.kind.in_where_clause())
755 .map_or(end, |p| p.span)
756 .shrink_to_hi()
757 .to(end)
758 } else {
759 end
760 }
761 }
762
763 pub fn add_where_or_trailing_comma(&self) -> &'static str {
764 if self.has_where_clause_predicates {
765 ","
766 } else if self.where_clause_span.is_empty() {
767 " where"
768 } else {
769 ""
771 }
772 }
773
774 pub fn bounds_for_param(
775 &self,
776 param_def_id: LocalDefId,
777 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
778 self.predicates.iter().filter_map(move |pred| match pred.kind {
779 WherePredicateKind::BoundPredicate(bp)
780 if bp.is_param_bound(param_def_id.to_def_id()) =>
781 {
782 Some(bp)
783 }
784 _ => None,
785 })
786 }
787
788 pub fn outlives_for_param(
789 &self,
790 param_def_id: LocalDefId,
791 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
792 self.predicates.iter().filter_map(move |pred| match pred.kind {
793 WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
794 _ => None,
795 })
796 }
797
798 pub fn bounds_span_for_suggestions(
809 &self,
810 param_def_id: LocalDefId,
811 ) -> Option<(Span, Option<Span>)> {
812 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
813 |bound| {
814 let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
815 && let [.., segment] = trait_ref.path.segments
816 && let Some(ret_ty) = segment.args().paren_sugar_output()
817 && let ret_ty = ret_ty.peel_refs()
818 && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
819 && let TraitObjectSyntax::Dyn | TraitObjectSyntax::DynStar = tagged_ptr.tag()
820 && ret_ty.span.can_be_used_for_suggestions()
821 {
822 Some(ret_ty.span)
823 } else {
824 None
825 };
826
827 span_for_parentheses.map_or_else(
828 || {
829 let bs = bound.span();
832 bs.can_be_used_for_suggestions().then(|| (bs.shrink_to_hi(), None))
833 },
834 |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
835 )
836 },
837 )
838 }
839
840 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
841 let predicate = &self.predicates[pos];
842 let span = predicate.span;
843
844 if !predicate.kind.in_where_clause() {
845 return span;
848 }
849
850 if pos < self.predicates.len() - 1 {
852 let next_pred = &self.predicates[pos + 1];
853 if next_pred.kind.in_where_clause() {
854 return span.until(next_pred.span);
857 }
858 }
859
860 if pos > 0 {
861 let prev_pred = &self.predicates[pos - 1];
862 if prev_pred.kind.in_where_clause() {
863 return prev_pred.span.shrink_to_hi().to(span);
866 }
867 }
868
869 self.where_clause_span
873 }
874
875 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
876 let predicate = &self.predicates[predicate_pos];
877 let bounds = predicate.kind.bounds();
878
879 if bounds.len() == 1 {
880 return self.span_for_predicate_removal(predicate_pos);
881 }
882
883 let bound_span = bounds[bound_pos].span();
884 if bound_pos < bounds.len() - 1 {
885 bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
891 } else {
892 bound_span.with_lo(bounds[bound_pos - 1].span().hi())
898 }
899 }
900}
901
902#[derive(Debug, Clone, Copy, HashStable_Generic)]
904pub struct WherePredicate<'hir> {
905 #[stable_hasher(ignore)]
906 pub hir_id: HirId,
907 pub span: Span,
908 pub kind: &'hir WherePredicateKind<'hir>,
909}
910
911#[derive(Debug, Clone, Copy, HashStable_Generic)]
913pub enum WherePredicateKind<'hir> {
914 BoundPredicate(WhereBoundPredicate<'hir>),
916 RegionPredicate(WhereRegionPredicate<'hir>),
918 EqPredicate(WhereEqPredicate<'hir>),
920}
921
922impl<'hir> WherePredicateKind<'hir> {
923 pub fn in_where_clause(&self) -> bool {
924 match self {
925 WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
926 WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
927 WherePredicateKind::EqPredicate(_) => false,
928 }
929 }
930
931 pub fn bounds(&self) -> GenericBounds<'hir> {
932 match self {
933 WherePredicateKind::BoundPredicate(p) => p.bounds,
934 WherePredicateKind::RegionPredicate(p) => p.bounds,
935 WherePredicateKind::EqPredicate(_) => &[],
936 }
937 }
938}
939
940#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
941pub enum PredicateOrigin {
942 WhereClause,
943 GenericParam,
944 ImplTrait,
945}
946
947#[derive(Debug, Clone, Copy, HashStable_Generic)]
949pub struct WhereBoundPredicate<'hir> {
950 pub origin: PredicateOrigin,
952 pub bound_generic_params: &'hir [GenericParam<'hir>],
954 pub bounded_ty: &'hir Ty<'hir>,
956 pub bounds: GenericBounds<'hir>,
958}
959
960impl<'hir> WhereBoundPredicate<'hir> {
961 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
963 self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
964 }
965}
966
967#[derive(Debug, Clone, Copy, HashStable_Generic)]
969pub struct WhereRegionPredicate<'hir> {
970 pub in_where_clause: bool,
971 pub lifetime: &'hir Lifetime,
972 pub bounds: GenericBounds<'hir>,
973}
974
975impl<'hir> WhereRegionPredicate<'hir> {
976 fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
978 self.lifetime.res == LifetimeName::Param(param_def_id)
979 }
980}
981
982#[derive(Debug, Clone, Copy, HashStable_Generic)]
984pub struct WhereEqPredicate<'hir> {
985 pub lhs_ty: &'hir Ty<'hir>,
986 pub rhs_ty: &'hir Ty<'hir>,
987}
988
989#[derive(Clone, Copy, Debug)]
993pub struct ParentedNode<'tcx> {
994 pub parent: ItemLocalId,
995 pub node: Node<'tcx>,
996}
997
998#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1000pub enum AttrArgs {
1001 Empty,
1003 Delimited(DelimArgs),
1005 Eq {
1007 eq_span: Span,
1009 expr: MetaItemLit,
1011 },
1012}
1013
1014#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1015pub struct AttrPath {
1016 pub segments: Box<[Ident]>,
1017 pub span: Span,
1018}
1019
1020impl AttrPath {
1021 pub fn from_ast(path: &ast::Path) -> Self {
1022 AttrPath {
1023 segments: path.segments.iter().map(|i| i.ident).collect::<Vec<_>>().into_boxed_slice(),
1024 span: path.span,
1025 }
1026 }
1027}
1028
1029impl fmt::Display for AttrPath {
1030 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1031 write!(f, "{}", self.segments.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("::"))
1032 }
1033}
1034
1035#[derive(Clone, Debug, HashStable_Generic, Encodable, Decodable)]
1036pub struct AttrItem {
1037 pub path: AttrPath,
1039 pub args: AttrArgs,
1040 pub id: HashIgnoredAttrId,
1041 pub style: AttrStyle,
1044 pub span: Span,
1046}
1047
1048#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1051pub struct HashIgnoredAttrId {
1052 pub attr_id: AttrId,
1053}
1054
1055#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
1056pub enum Attribute {
1057 Parsed(AttributeKind),
1063
1064 Unparsed(Box<AttrItem>),
1067}
1068
1069impl Attribute {
1070 pub fn get_normal_item(&self) -> &AttrItem {
1071 match &self {
1072 Attribute::Unparsed(normal) => &normal,
1073 _ => panic!("unexpected parsed attribute"),
1074 }
1075 }
1076
1077 pub fn unwrap_normal_item(self) -> AttrItem {
1078 match self {
1079 Attribute::Unparsed(normal) => *normal,
1080 _ => panic!("unexpected parsed attribute"),
1081 }
1082 }
1083
1084 pub fn value_lit(&self) -> Option<&MetaItemLit> {
1085 match &self {
1086 Attribute::Unparsed(n) => match n.as_ref() {
1087 AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1088 _ => None,
1089 },
1090 _ => None,
1091 }
1092 }
1093}
1094
1095impl AttributeExt for Attribute {
1096 #[inline]
1097 fn id(&self) -> AttrId {
1098 match &self {
1099 Attribute::Unparsed(u) => u.id.attr_id,
1100 _ => panic!(),
1101 }
1102 }
1103
1104 #[inline]
1105 fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1106 match &self {
1107 Attribute::Unparsed(n) => match n.as_ref() {
1108 AttrItem { args: AttrArgs::Delimited(d), .. } => {
1109 ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1110 }
1111 _ => None,
1112 },
1113 _ => None,
1114 }
1115 }
1116
1117 #[inline]
1118 fn value_str(&self) -> Option<Symbol> {
1119 self.value_lit().and_then(|x| x.value_str())
1120 }
1121
1122 #[inline]
1123 fn value_span(&self) -> Option<Span> {
1124 self.value_lit().map(|i| i.span)
1125 }
1126
1127 #[inline]
1129 fn ident(&self) -> Option<Ident> {
1130 match &self {
1131 Attribute::Unparsed(n) => {
1132 if let [ident] = n.path.segments.as_ref() {
1133 Some(*ident)
1134 } else {
1135 None
1136 }
1137 }
1138 _ => None,
1139 }
1140 }
1141
1142 #[inline]
1143 fn path_matches(&self, name: &[Symbol]) -> bool {
1144 match &self {
1145 Attribute::Unparsed(n) => {
1146 n.path.segments.len() == name.len()
1147 && n.path.segments.iter().zip(name).all(|(s, n)| s.name == *n)
1148 }
1149 _ => false,
1150 }
1151 }
1152
1153 #[inline]
1154 fn is_doc_comment(&self) -> bool {
1155 matches!(self, Attribute::Parsed(AttributeKind::DocComment { .. }))
1156 }
1157
1158 #[inline]
1159 fn span(&self) -> Span {
1160 match &self {
1161 Attribute::Unparsed(u) => u.span,
1162 Attribute::Parsed(AttributeKind::Deprecation { span, .. }) => *span,
1164 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1165 a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1166 }
1167 }
1168
1169 #[inline]
1170 fn is_word(&self) -> bool {
1171 match &self {
1172 Attribute::Unparsed(n) => {
1173 matches!(n.args, AttrArgs::Empty)
1174 }
1175 _ => false,
1176 }
1177 }
1178
1179 #[inline]
1180 fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1181 match &self {
1182 Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1183 _ => None,
1184 }
1185 }
1186
1187 #[inline]
1188 fn doc_str(&self) -> Option<Symbol> {
1189 match &self {
1190 Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1191 Attribute::Unparsed(_) if self.has_name(sym::doc) => self.value_str(),
1192 _ => None,
1193 }
1194 }
1195 #[inline]
1196 fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1197 match &self {
1198 Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1199 Some((*comment, *kind))
1200 }
1201 Attribute::Unparsed(_) if self.name_or_empty() == sym::doc => {
1202 self.value_str().map(|s| (s, CommentKind::Line))
1203 }
1204 _ => None,
1205 }
1206 }
1207
1208 #[inline]
1209 fn style(&self) -> AttrStyle {
1210 match &self {
1211 Attribute::Unparsed(u) => u.style,
1212 Attribute::Parsed(AttributeKind::DocComment { style, .. }) => *style,
1213 _ => panic!(),
1214 }
1215 }
1216}
1217
1218impl Attribute {
1220 #[inline]
1221 pub fn id(&self) -> AttrId {
1222 AttributeExt::id(self)
1223 }
1224
1225 #[inline]
1226 pub fn name_or_empty(&self) -> Symbol {
1227 AttributeExt::name_or_empty(self)
1228 }
1229
1230 #[inline]
1231 pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1232 AttributeExt::meta_item_list(self)
1233 }
1234
1235 #[inline]
1236 pub fn value_str(&self) -> Option<Symbol> {
1237 AttributeExt::value_str(self)
1238 }
1239
1240 #[inline]
1241 pub fn value_span(&self) -> Option<Span> {
1242 AttributeExt::value_span(self)
1243 }
1244
1245 #[inline]
1246 pub fn ident(&self) -> Option<Ident> {
1247 AttributeExt::ident(self)
1248 }
1249
1250 #[inline]
1251 pub fn path_matches(&self, name: &[Symbol]) -> bool {
1252 AttributeExt::path_matches(self, name)
1253 }
1254
1255 #[inline]
1256 pub fn is_doc_comment(&self) -> bool {
1257 AttributeExt::is_doc_comment(self)
1258 }
1259
1260 #[inline]
1261 pub fn has_name(&self, name: Symbol) -> bool {
1262 AttributeExt::has_name(self, name)
1263 }
1264
1265 #[inline]
1266 pub fn span(&self) -> Span {
1267 AttributeExt::span(self)
1268 }
1269
1270 #[inline]
1271 pub fn is_word(&self) -> bool {
1272 AttributeExt::is_word(self)
1273 }
1274
1275 #[inline]
1276 pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1277 AttributeExt::path(self)
1278 }
1279
1280 #[inline]
1281 pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
1282 AttributeExt::ident_path(self)
1283 }
1284
1285 #[inline]
1286 pub fn doc_str(&self) -> Option<Symbol> {
1287 AttributeExt::doc_str(self)
1288 }
1289
1290 #[inline]
1291 pub fn is_proc_macro_attr(&self) -> bool {
1292 AttributeExt::is_proc_macro_attr(self)
1293 }
1294
1295 #[inline]
1296 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
1297 AttributeExt::doc_str_and_comment_kind(self)
1298 }
1299
1300 #[inline]
1301 pub fn style(&self) -> AttrStyle {
1302 AttributeExt::style(self)
1303 }
1304}
1305
1306#[derive(Debug)]
1308pub struct AttributeMap<'tcx> {
1309 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1310 pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1312 pub opt_hash: Option<Fingerprint>,
1314}
1315
1316impl<'tcx> AttributeMap<'tcx> {
1317 pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1318 map: SortedMap::new(),
1319 opt_hash: Some(Fingerprint::ZERO),
1320 define_opaque: None,
1321 };
1322
1323 #[inline]
1324 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1325 self.map.get(&id).copied().unwrap_or(&[])
1326 }
1327}
1328
1329pub struct OwnerNodes<'tcx> {
1333 pub opt_hash_including_bodies: Option<Fingerprint>,
1336 pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1341 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1343}
1344
1345impl<'tcx> OwnerNodes<'tcx> {
1346 pub fn node(&self) -> OwnerNode<'tcx> {
1347 self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1349 }
1350}
1351
1352impl fmt::Debug for OwnerNodes<'_> {
1353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1354 f.debug_struct("OwnerNodes")
1355 .field("node", &self.nodes[ItemLocalId::ZERO])
1357 .field(
1358 "parents",
1359 &fmt::from_fn(|f| {
1360 f.debug_list()
1361 .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1362 fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1363 }))
1364 .finish()
1365 }),
1366 )
1367 .field("bodies", &self.bodies)
1368 .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1369 .finish()
1370 }
1371}
1372
1373#[derive(Debug, HashStable_Generic)]
1375pub struct OwnerInfo<'hir> {
1376 pub nodes: OwnerNodes<'hir>,
1378 pub parenting: LocalDefIdMap<ItemLocalId>,
1380 pub attrs: AttributeMap<'hir>,
1382 pub trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
1385}
1386
1387impl<'tcx> OwnerInfo<'tcx> {
1388 #[inline]
1389 pub fn node(&self) -> OwnerNode<'tcx> {
1390 self.nodes.node()
1391 }
1392}
1393
1394#[derive(Copy, Clone, Debug, HashStable_Generic)]
1395pub enum MaybeOwner<'tcx> {
1396 Owner(&'tcx OwnerInfo<'tcx>),
1397 NonOwner(HirId),
1398 Phantom,
1400}
1401
1402impl<'tcx> MaybeOwner<'tcx> {
1403 pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1404 match self {
1405 MaybeOwner::Owner(i) => Some(i),
1406 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1407 }
1408 }
1409
1410 pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1411 self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1412 }
1413}
1414
1415#[derive(Debug)]
1422pub struct Crate<'hir> {
1423 pub owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
1424 pub opt_hir_hash: Option<Fingerprint>,
1426}
1427
1428#[derive(Debug, Clone, Copy, HashStable_Generic)]
1429pub struct Closure<'hir> {
1430 pub def_id: LocalDefId,
1431 pub binder: ClosureBinder,
1432 pub constness: Constness,
1433 pub capture_clause: CaptureBy,
1434 pub bound_generic_params: &'hir [GenericParam<'hir>],
1435 pub fn_decl: &'hir FnDecl<'hir>,
1436 pub body: BodyId,
1437 pub fn_decl_span: Span,
1439 pub fn_arg_span: Option<Span>,
1441 pub kind: ClosureKind,
1442}
1443
1444#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1445pub enum ClosureKind {
1446 Closure,
1448 Coroutine(CoroutineKind),
1453 CoroutineClosure(CoroutineDesugaring),
1458}
1459
1460#[derive(Debug, Clone, Copy, HashStable_Generic)]
1464pub struct Block<'hir> {
1465 pub stmts: &'hir [Stmt<'hir>],
1467 pub expr: Option<&'hir Expr<'hir>>,
1470 #[stable_hasher(ignore)]
1471 pub hir_id: HirId,
1472 pub rules: BlockCheckMode,
1474 pub span: Span,
1476 pub targeted_by_break: bool,
1480}
1481
1482impl<'hir> Block<'hir> {
1483 pub fn innermost_block(&self) -> &Block<'hir> {
1484 let mut block = self;
1485 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1486 block = inner_block;
1487 }
1488 block
1489 }
1490}
1491
1492#[derive(Debug, Clone, Copy, HashStable_Generic)]
1493pub struct TyPat<'hir> {
1494 #[stable_hasher(ignore)]
1495 pub hir_id: HirId,
1496 pub kind: TyPatKind<'hir>,
1497 pub span: Span,
1498}
1499
1500#[derive(Debug, Clone, Copy, HashStable_Generic)]
1501pub struct Pat<'hir> {
1502 #[stable_hasher(ignore)]
1503 pub hir_id: HirId,
1504 pub kind: PatKind<'hir>,
1505 pub span: Span,
1506 pub default_binding_modes: bool,
1509}
1510
1511impl<'hir> Pat<'hir> {
1512 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1513 if !it(self) {
1514 return false;
1515 }
1516
1517 use PatKind::*;
1518 match self.kind {
1519 Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1520 Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_short_(it),
1521 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1522 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1523 Slice(before, slice, after) => {
1524 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1525 }
1526 }
1527 }
1528
1529 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1536 self.walk_short_(&mut it)
1537 }
1538
1539 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1540 if !it(self) {
1541 return;
1542 }
1543
1544 use PatKind::*;
1545 match self.kind {
1546 Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1547 Box(s) | Deref(s) | Ref(s, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1548 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1549 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1550 Slice(before, slice, after) => {
1551 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1552 }
1553 }
1554 }
1555
1556 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1560 self.walk_(&mut it)
1561 }
1562
1563 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1567 self.walk(|p| {
1568 it(p);
1569 true
1570 })
1571 }
1572
1573 pub fn is_never_pattern(&self) -> bool {
1575 let mut is_never_pattern = false;
1576 self.walk(|pat| match &pat.kind {
1577 PatKind::Never => {
1578 is_never_pattern = true;
1579 false
1580 }
1581 PatKind::Or(s) => {
1582 is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1583 false
1584 }
1585 _ => true,
1586 });
1587 is_never_pattern
1588 }
1589}
1590
1591#[derive(Debug, Clone, Copy, HashStable_Generic)]
1597pub struct PatField<'hir> {
1598 #[stable_hasher(ignore)]
1599 pub hir_id: HirId,
1600 pub ident: Ident,
1602 pub pat: &'hir Pat<'hir>,
1604 pub is_shorthand: bool,
1605 pub span: Span,
1606}
1607
1608#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic, Hash, Eq, Encodable, Decodable)]
1609pub enum RangeEnd {
1610 Included,
1611 Excluded,
1612}
1613
1614impl fmt::Display for RangeEnd {
1615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1616 f.write_str(match self {
1617 RangeEnd::Included => "..=",
1618 RangeEnd::Excluded => "..",
1619 })
1620 }
1621}
1622
1623#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1627pub struct DotDotPos(u32);
1628
1629impl DotDotPos {
1630 pub fn new(n: Option<usize>) -> Self {
1632 match n {
1633 Some(n) => {
1634 assert!(n < u32::MAX as usize);
1635 Self(n as u32)
1636 }
1637 None => Self(u32::MAX),
1638 }
1639 }
1640
1641 pub fn as_opt_usize(&self) -> Option<usize> {
1642 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1643 }
1644}
1645
1646impl fmt::Debug for DotDotPos {
1647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1648 self.as_opt_usize().fmt(f)
1649 }
1650}
1651
1652#[derive(Debug, Clone, Copy, HashStable_Generic)]
1653pub struct PatExpr<'hir> {
1654 #[stable_hasher(ignore)]
1655 pub hir_id: HirId,
1656 pub span: Span,
1657 pub kind: PatExprKind<'hir>,
1658}
1659
1660#[derive(Debug, Clone, Copy, HashStable_Generic)]
1661pub enum PatExprKind<'hir> {
1662 Lit {
1663 lit: &'hir Lit,
1664 negated: bool,
1667 },
1668 ConstBlock(ConstBlock),
1669 Path(QPath<'hir>),
1671}
1672
1673#[derive(Debug, Clone, Copy, HashStable_Generic)]
1674pub enum TyPatKind<'hir> {
1675 Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1677
1678 Err(ErrorGuaranteed),
1680}
1681
1682#[derive(Debug, Clone, Copy, HashStable_Generic)]
1683pub enum PatKind<'hir> {
1684 Wild,
1686
1687 Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
1698
1699 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1702
1703 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1707
1708 Or(&'hir [Pat<'hir>]),
1711
1712 Never,
1714
1715 Tuple(&'hir [Pat<'hir>], DotDotPos),
1719
1720 Box(&'hir Pat<'hir>),
1722
1723 Deref(&'hir Pat<'hir>),
1725
1726 Ref(&'hir Pat<'hir>, Mutability),
1728
1729 Expr(&'hir PatExpr<'hir>),
1731
1732 Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
1734
1735 Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
1737
1738 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1748
1749 Err(ErrorGuaranteed),
1751}
1752
1753#[derive(Debug, Clone, Copy, HashStable_Generic)]
1755pub struct Stmt<'hir> {
1756 #[stable_hasher(ignore)]
1757 pub hir_id: HirId,
1758 pub kind: StmtKind<'hir>,
1759 pub span: Span,
1760}
1761
1762#[derive(Debug, Clone, Copy, HashStable_Generic)]
1764pub enum StmtKind<'hir> {
1765 Let(&'hir LetStmt<'hir>),
1767
1768 Item(ItemId),
1770
1771 Expr(&'hir Expr<'hir>),
1773
1774 Semi(&'hir Expr<'hir>),
1776}
1777
1778#[derive(Debug, Clone, Copy, HashStable_Generic)]
1780pub struct LetStmt<'hir> {
1781 pub pat: &'hir Pat<'hir>,
1782 pub ty: Option<&'hir Ty<'hir>>,
1784 pub init: Option<&'hir Expr<'hir>>,
1786 pub els: Option<&'hir Block<'hir>>,
1788 #[stable_hasher(ignore)]
1789 pub hir_id: HirId,
1790 pub span: Span,
1791 pub source: LocalSource,
1795}
1796
1797#[derive(Debug, Clone, Copy, HashStable_Generic)]
1800pub struct Arm<'hir> {
1801 #[stable_hasher(ignore)]
1802 pub hir_id: HirId,
1803 pub span: Span,
1804 pub pat: &'hir Pat<'hir>,
1806 pub guard: Option<&'hir Expr<'hir>>,
1808 pub body: &'hir Expr<'hir>,
1810}
1811
1812#[derive(Debug, Clone, Copy, HashStable_Generic)]
1818pub struct LetExpr<'hir> {
1819 pub span: Span,
1820 pub pat: &'hir Pat<'hir>,
1821 pub ty: Option<&'hir Ty<'hir>>,
1822 pub init: &'hir Expr<'hir>,
1823 pub recovered: ast::Recovered,
1826}
1827
1828#[derive(Debug, Clone, Copy, HashStable_Generic)]
1829pub struct ExprField<'hir> {
1830 #[stable_hasher(ignore)]
1831 pub hir_id: HirId,
1832 pub ident: Ident,
1833 pub expr: &'hir Expr<'hir>,
1834 pub span: Span,
1835 pub is_shorthand: bool,
1836}
1837
1838#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
1839pub enum BlockCheckMode {
1840 DefaultBlock,
1841 UnsafeBlock(UnsafeSource),
1842}
1843
1844#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
1845pub enum UnsafeSource {
1846 CompilerGenerated,
1847 UserProvided,
1848}
1849
1850#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1851pub struct BodyId {
1852 pub hir_id: HirId,
1853}
1854
1855#[derive(Debug, Clone, Copy, HashStable_Generic)]
1877pub struct Body<'hir> {
1878 pub params: &'hir [Param<'hir>],
1879 pub value: &'hir Expr<'hir>,
1880}
1881
1882impl<'hir> Body<'hir> {
1883 pub fn id(&self) -> BodyId {
1884 BodyId { hir_id: self.value.hir_id }
1885 }
1886}
1887
1888#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1890pub enum CoroutineKind {
1891 Desugared(CoroutineDesugaring, CoroutineSource),
1893
1894 Coroutine(Movability),
1896}
1897
1898impl CoroutineKind {
1899 pub fn movability(self) -> Movability {
1900 match self {
1901 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
1902 | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
1903 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
1904 CoroutineKind::Coroutine(mov) => mov,
1905 }
1906 }
1907}
1908
1909impl CoroutineKind {
1910 pub fn is_fn_like(self) -> bool {
1911 matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
1912 }
1913}
1914
1915impl fmt::Display for CoroutineKind {
1916 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1917 match self {
1918 CoroutineKind::Desugared(d, k) => {
1919 d.fmt(f)?;
1920 k.fmt(f)
1921 }
1922 CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
1923 }
1924 }
1925}
1926
1927#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, HashStable_Generic, Encodable, Decodable)]
1933pub enum CoroutineSource {
1934 Block,
1936
1937 Closure,
1939
1940 Fn,
1942}
1943
1944impl fmt::Display for CoroutineSource {
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946 match self {
1947 CoroutineSource::Block => "block",
1948 CoroutineSource::Closure => "closure body",
1949 CoroutineSource::Fn => "fn body",
1950 }
1951 .fmt(f)
1952 }
1953}
1954
1955#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, HashStable_Generic, Encodable, Decodable)]
1956pub enum CoroutineDesugaring {
1957 Async,
1959
1960 Gen,
1962
1963 AsyncGen,
1966}
1967
1968impl fmt::Display for CoroutineDesugaring {
1969 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1970 match self {
1971 CoroutineDesugaring::Async => {
1972 if f.alternate() {
1973 f.write_str("`async` ")?;
1974 } else {
1975 f.write_str("async ")?
1976 }
1977 }
1978 CoroutineDesugaring::Gen => {
1979 if f.alternate() {
1980 f.write_str("`gen` ")?;
1981 } else {
1982 f.write_str("gen ")?
1983 }
1984 }
1985 CoroutineDesugaring::AsyncGen => {
1986 if f.alternate() {
1987 f.write_str("`async gen` ")?;
1988 } else {
1989 f.write_str("async gen ")?
1990 }
1991 }
1992 }
1993
1994 Ok(())
1995 }
1996}
1997
1998#[derive(Copy, Clone, Debug)]
1999pub enum BodyOwnerKind {
2000 Fn,
2002
2003 Closure,
2005
2006 Const { inline: bool },
2008
2009 Static(Mutability),
2011
2012 GlobalAsm,
2014}
2015
2016impl BodyOwnerKind {
2017 pub fn is_fn_or_closure(self) -> bool {
2018 match self {
2019 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2020 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2021 false
2022 }
2023 }
2024 }
2025}
2026
2027#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2029pub enum ConstContext {
2030 ConstFn,
2032
2033 Static(Mutability),
2035
2036 Const { inline: bool },
2046}
2047
2048impl ConstContext {
2049 pub fn keyword_name(self) -> &'static str {
2053 match self {
2054 Self::Const { .. } => "const",
2055 Self::Static(Mutability::Not) => "static",
2056 Self::Static(Mutability::Mut) => "static mut",
2057 Self::ConstFn => "const fn",
2058 }
2059 }
2060}
2061
2062impl fmt::Display for ConstContext {
2065 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2066 match *self {
2067 Self::Const { .. } => write!(f, "constant"),
2068 Self::Static(_) => write!(f, "static"),
2069 Self::ConstFn => write!(f, "constant function"),
2070 }
2071 }
2072}
2073
2074pub type Lit = Spanned<LitKind>;
2079
2080#[derive(Copy, Clone, Debug, HashStable_Generic)]
2089pub struct AnonConst {
2090 #[stable_hasher(ignore)]
2091 pub hir_id: HirId,
2092 pub def_id: LocalDefId,
2093 pub body: BodyId,
2094 pub span: Span,
2095}
2096
2097#[derive(Copy, Clone, Debug, HashStable_Generic)]
2099pub struct ConstBlock {
2100 #[stable_hasher(ignore)]
2101 pub hir_id: HirId,
2102 pub def_id: LocalDefId,
2103 pub body: BodyId,
2104}
2105
2106#[derive(Debug, Clone, Copy, HashStable_Generic)]
2115pub struct Expr<'hir> {
2116 #[stable_hasher(ignore)]
2117 pub hir_id: HirId,
2118 pub kind: ExprKind<'hir>,
2119 pub span: Span,
2120}
2121
2122impl Expr<'_> {
2123 pub fn precedence(&self) -> ExprPrecedence {
2124 match &self.kind {
2125 ExprKind::Closure(closure) => {
2126 match closure.fn_decl.output {
2127 FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2128 FnRetTy::Return(_) => ExprPrecedence::Unambiguous,
2129 }
2130 }
2131
2132 ExprKind::Break(..)
2133 | ExprKind::Ret(..)
2134 | ExprKind::Yield(..)
2135 | ExprKind::Become(..) => ExprPrecedence::Jump,
2136
2137 ExprKind::Binary(op, ..) => op.node.precedence(),
2139 ExprKind::Cast(..) => ExprPrecedence::Cast,
2140
2141 ExprKind::Assign(..) |
2142 ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2143
2144 ExprKind::AddrOf(..)
2146 | ExprKind::Let(..)
2151 | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2152
2153 ExprKind::Array(_)
2155 | ExprKind::Block(..)
2156 | ExprKind::Call(..)
2157 | ExprKind::ConstBlock(_)
2158 | ExprKind::Continue(..)
2159 | ExprKind::Field(..)
2160 | ExprKind::If(..)
2161 | ExprKind::Index(..)
2162 | ExprKind::InlineAsm(..)
2163 | ExprKind::Lit(_)
2164 | ExprKind::Loop(..)
2165 | ExprKind::Match(..)
2166 | ExprKind::MethodCall(..)
2167 | ExprKind::OffsetOf(..)
2168 | ExprKind::Path(..)
2169 | ExprKind::Repeat(..)
2170 | ExprKind::Struct(..)
2171 | ExprKind::Tup(_)
2172 | ExprKind::Type(..)
2173 | ExprKind::UnsafeBinderCast(..)
2174 | ExprKind::Use(..)
2175 | ExprKind::Err(_) => ExprPrecedence::Unambiguous,
2176
2177 ExprKind::DropTemps(expr, ..) => expr.precedence(),
2178 }
2179 }
2180
2181 pub fn is_syntactic_place_expr(&self) -> bool {
2186 self.is_place_expr(|_| true)
2187 }
2188
2189 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2194 match self.kind {
2195 ExprKind::Path(QPath::Resolved(_, ref path)) => {
2196 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2197 }
2198
2199 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2203
2204 ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2206
2207 ExprKind::Unary(UnOp::Deref, _) => true,
2208
2209 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2210 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2211 }
2212
2213 ExprKind::Path(QPath::LangItem(..)) => false,
2215
2216 ExprKind::Path(QPath::TypeRelative(..))
2219 | ExprKind::Call(..)
2220 | ExprKind::MethodCall(..)
2221 | ExprKind::Use(..)
2222 | ExprKind::Struct(..)
2223 | ExprKind::Tup(..)
2224 | ExprKind::If(..)
2225 | ExprKind::Match(..)
2226 | ExprKind::Closure { .. }
2227 | ExprKind::Block(..)
2228 | ExprKind::Repeat(..)
2229 | ExprKind::Array(..)
2230 | ExprKind::Break(..)
2231 | ExprKind::Continue(..)
2232 | ExprKind::Ret(..)
2233 | ExprKind::Become(..)
2234 | ExprKind::Let(..)
2235 | ExprKind::Loop(..)
2236 | ExprKind::Assign(..)
2237 | ExprKind::InlineAsm(..)
2238 | ExprKind::OffsetOf(..)
2239 | ExprKind::AssignOp(..)
2240 | ExprKind::Lit(_)
2241 | ExprKind::ConstBlock(..)
2242 | ExprKind::Unary(..)
2243 | ExprKind::AddrOf(..)
2244 | ExprKind::Binary(..)
2245 | ExprKind::Yield(..)
2246 | ExprKind::Cast(..)
2247 | ExprKind::DropTemps(..)
2248 | ExprKind::Err(_) => false,
2249 }
2250 }
2251
2252 pub fn is_size_lit(&self) -> bool {
2255 matches!(
2256 self.kind,
2257 ExprKind::Lit(Lit {
2258 node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2259 ..
2260 })
2261 )
2262 }
2263
2264 pub fn peel_drop_temps(&self) -> &Self {
2270 let mut expr = self;
2271 while let ExprKind::DropTemps(inner) = &expr.kind {
2272 expr = inner;
2273 }
2274 expr
2275 }
2276
2277 pub fn peel_blocks(&self) -> &Self {
2278 let mut expr = self;
2279 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2280 expr = inner;
2281 }
2282 expr
2283 }
2284
2285 pub fn peel_borrows(&self) -> &Self {
2286 let mut expr = self;
2287 while let ExprKind::AddrOf(.., inner) = &expr.kind {
2288 expr = inner;
2289 }
2290 expr
2291 }
2292
2293 pub fn can_have_side_effects(&self) -> bool {
2294 match self.peel_drop_temps().kind {
2295 ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2296 false
2297 }
2298 ExprKind::Type(base, _)
2299 | ExprKind::Unary(_, base)
2300 | ExprKind::Field(base, _)
2301 | ExprKind::Index(base, _, _)
2302 | ExprKind::AddrOf(.., base)
2303 | ExprKind::Cast(base, _)
2304 | ExprKind::UnsafeBinderCast(_, base, _) => {
2305 base.can_have_side_effects()
2309 }
2310 ExprKind::Struct(_, fields, init) => {
2311 let init_side_effects = match init {
2312 StructTailExpr::Base(init) => init.can_have_side_effects(),
2313 StructTailExpr::DefaultFields(_) | StructTailExpr::None => false,
2314 };
2315 fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2316 || init_side_effects
2317 }
2318
2319 ExprKind::Array(args)
2320 | ExprKind::Tup(args)
2321 | ExprKind::Call(
2322 Expr {
2323 kind:
2324 ExprKind::Path(QPath::Resolved(
2325 None,
2326 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2327 )),
2328 ..
2329 },
2330 args,
2331 ) => args.iter().any(|arg| arg.can_have_side_effects()),
2332 ExprKind::If(..)
2333 | ExprKind::Match(..)
2334 | ExprKind::MethodCall(..)
2335 | ExprKind::Call(..)
2336 | ExprKind::Closure { .. }
2337 | ExprKind::Block(..)
2338 | ExprKind::Repeat(..)
2339 | ExprKind::Break(..)
2340 | ExprKind::Continue(..)
2341 | ExprKind::Ret(..)
2342 | ExprKind::Become(..)
2343 | ExprKind::Let(..)
2344 | ExprKind::Loop(..)
2345 | ExprKind::Assign(..)
2346 | ExprKind::InlineAsm(..)
2347 | ExprKind::AssignOp(..)
2348 | ExprKind::ConstBlock(..)
2349 | ExprKind::Binary(..)
2350 | ExprKind::Yield(..)
2351 | ExprKind::DropTemps(..)
2352 | ExprKind::Err(_) => true,
2353 }
2354 }
2355
2356 pub fn is_approximately_pattern(&self) -> bool {
2358 match &self.kind {
2359 ExprKind::Array(_)
2360 | ExprKind::Call(..)
2361 | ExprKind::Tup(_)
2362 | ExprKind::Lit(_)
2363 | ExprKind::Path(_)
2364 | ExprKind::Struct(..) => true,
2365 _ => false,
2366 }
2367 }
2368
2369 pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2374 match (self.kind, other.kind) {
2375 (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2376 (
2377 ExprKind::Path(QPath::LangItem(item1, _)),
2378 ExprKind::Path(QPath::LangItem(item2, _)),
2379 ) => item1 == item2,
2380 (
2381 ExprKind::Path(QPath::Resolved(None, path1)),
2382 ExprKind::Path(QPath::Resolved(None, path2)),
2383 ) => path1.res == path2.res,
2384 (
2385 ExprKind::Struct(
2386 QPath::LangItem(LangItem::RangeTo, _),
2387 [val1],
2388 StructTailExpr::None,
2389 ),
2390 ExprKind::Struct(
2391 QPath::LangItem(LangItem::RangeTo, _),
2392 [val2],
2393 StructTailExpr::None,
2394 ),
2395 )
2396 | (
2397 ExprKind::Struct(
2398 QPath::LangItem(LangItem::RangeToInclusive, _),
2399 [val1],
2400 StructTailExpr::None,
2401 ),
2402 ExprKind::Struct(
2403 QPath::LangItem(LangItem::RangeToInclusive, _),
2404 [val2],
2405 StructTailExpr::None,
2406 ),
2407 )
2408 | (
2409 ExprKind::Struct(
2410 QPath::LangItem(LangItem::RangeFrom, _),
2411 [val1],
2412 StructTailExpr::None,
2413 ),
2414 ExprKind::Struct(
2415 QPath::LangItem(LangItem::RangeFrom, _),
2416 [val2],
2417 StructTailExpr::None,
2418 ),
2419 )
2420 | (
2421 ExprKind::Struct(
2422 QPath::LangItem(LangItem::RangeFromCopy, _),
2423 [val1],
2424 StructTailExpr::None,
2425 ),
2426 ExprKind::Struct(
2427 QPath::LangItem(LangItem::RangeFromCopy, _),
2428 [val2],
2429 StructTailExpr::None,
2430 ),
2431 ) => val1.expr.equivalent_for_indexing(val2.expr),
2432 (
2433 ExprKind::Struct(
2434 QPath::LangItem(LangItem::Range, _),
2435 [val1, val3],
2436 StructTailExpr::None,
2437 ),
2438 ExprKind::Struct(
2439 QPath::LangItem(LangItem::Range, _),
2440 [val2, val4],
2441 StructTailExpr::None,
2442 ),
2443 )
2444 | (
2445 ExprKind::Struct(
2446 QPath::LangItem(LangItem::RangeCopy, _),
2447 [val1, val3],
2448 StructTailExpr::None,
2449 ),
2450 ExprKind::Struct(
2451 QPath::LangItem(LangItem::RangeCopy, _),
2452 [val2, val4],
2453 StructTailExpr::None,
2454 ),
2455 )
2456 | (
2457 ExprKind::Struct(
2458 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2459 [val1, val3],
2460 StructTailExpr::None,
2461 ),
2462 ExprKind::Struct(
2463 QPath::LangItem(LangItem::RangeInclusiveCopy, _),
2464 [val2, val4],
2465 StructTailExpr::None,
2466 ),
2467 ) => {
2468 val1.expr.equivalent_for_indexing(val2.expr)
2469 && val3.expr.equivalent_for_indexing(val4.expr)
2470 }
2471 _ => false,
2472 }
2473 }
2474
2475 pub fn method_ident(&self) -> Option<Ident> {
2476 match self.kind {
2477 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2478 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2479 _ => None,
2480 }
2481 }
2482}
2483
2484pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2487 match expr.kind {
2488 ExprKind::Struct(ref qpath, _, _) => matches!(
2490 **qpath,
2491 QPath::LangItem(
2492 LangItem::Range
2493 | LangItem::RangeTo
2494 | LangItem::RangeFrom
2495 | LangItem::RangeFull
2496 | LangItem::RangeToInclusive
2497 | LangItem::RangeCopy
2498 | LangItem::RangeFromCopy
2499 | LangItem::RangeInclusiveCopy,
2500 ..
2501 )
2502 ),
2503
2504 ExprKind::Call(ref func, _) => {
2506 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
2507 }
2508
2509 _ => false,
2510 }
2511}
2512
2513pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2520 match expr.kind {
2521 ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2523 _ if is_range_literal(expr) => true,
2525 _ => false,
2526 }
2527}
2528
2529#[derive(Debug, Clone, Copy, HashStable_Generic)]
2530pub enum ExprKind<'hir> {
2531 ConstBlock(ConstBlock),
2533 Array(&'hir [Expr<'hir>]),
2535 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2542 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2559 Use(&'hir Expr<'hir>, Span),
2561 Tup(&'hir [Expr<'hir>]),
2563 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2565 Unary(UnOp, &'hir Expr<'hir>),
2567 Lit(&'hir Lit),
2569 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2571 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2573 DropTemps(&'hir Expr<'hir>),
2579 Let(&'hir LetExpr<'hir>),
2584 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2588 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2594 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2597 Closure(&'hir Closure<'hir>),
2604 Block(&'hir Block<'hir>, Option<Label>),
2606
2607 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2609 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2613 Field(&'hir Expr<'hir>, Ident),
2615 Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2619
2620 Path(QPath<'hir>),
2622
2623 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2625 Break(Destination, Option<&'hir Expr<'hir>>),
2627 Continue(Destination),
2629 Ret(Option<&'hir Expr<'hir>>),
2631 Become(&'hir Expr<'hir>),
2633
2634 InlineAsm(&'hir InlineAsm<'hir>),
2636
2637 OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2639
2640 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2645
2646 Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2651
2652 Yield(&'hir Expr<'hir>, YieldSource),
2654
2655 UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2658
2659 Err(rustc_span::ErrorGuaranteed),
2661}
2662
2663#[derive(Debug, Clone, Copy, HashStable_Generic)]
2664pub enum StructTailExpr<'hir> {
2665 None,
2667 Base(&'hir Expr<'hir>),
2670 DefaultFields(Span),
2674}
2675
2676#[derive(Debug, Clone, Copy, HashStable_Generic)]
2682pub enum QPath<'hir> {
2683 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2690
2691 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2698
2699 LangItem(LangItem, Span),
2701}
2702
2703impl<'hir> QPath<'hir> {
2704 pub fn span(&self) -> Span {
2706 match *self {
2707 QPath::Resolved(_, path) => path.span,
2708 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2709 QPath::LangItem(_, span) => span,
2710 }
2711 }
2712
2713 pub fn qself_span(&self) -> Span {
2716 match *self {
2717 QPath::Resolved(_, path) => path.span,
2718 QPath::TypeRelative(qself, _) => qself.span,
2719 QPath::LangItem(_, span) => span,
2720 }
2721 }
2722}
2723
2724#[derive(Copy, Clone, Debug, HashStable_Generic)]
2726pub enum LocalSource {
2727 Normal,
2729 AsyncFn,
2740 AwaitDesugar,
2742 AssignDesugar(Span),
2745 Contract,
2747}
2748
2749#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
2751pub enum MatchSource {
2752 Normal,
2754 Postfix,
2756 ForLoopDesugar,
2758 TryDesugar(HirId),
2760 AwaitDesugar,
2762 FormatArgs,
2764}
2765
2766impl MatchSource {
2767 #[inline]
2768 pub const fn name(self) -> &'static str {
2769 use MatchSource::*;
2770 match self {
2771 Normal => "match",
2772 Postfix => ".match",
2773 ForLoopDesugar => "for",
2774 TryDesugar(_) => "?",
2775 AwaitDesugar => ".await",
2776 FormatArgs => "format_args!()",
2777 }
2778 }
2779}
2780
2781#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
2783pub enum LoopSource {
2784 Loop,
2786 While,
2788 ForLoop,
2790}
2791
2792impl LoopSource {
2793 pub fn name(self) -> &'static str {
2794 match self {
2795 LoopSource::Loop => "loop",
2796 LoopSource::While => "while",
2797 LoopSource::ForLoop => "for",
2798 }
2799 }
2800}
2801
2802#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
2803pub enum LoopIdError {
2804 OutsideLoopScope,
2805 UnlabeledCfInWhileCondition,
2806 UnresolvedLabel,
2807}
2808
2809impl fmt::Display for LoopIdError {
2810 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2811 f.write_str(match self {
2812 LoopIdError::OutsideLoopScope => "not inside loop scope",
2813 LoopIdError::UnlabeledCfInWhileCondition => {
2814 "unlabeled control flow (break or continue) in while condition"
2815 }
2816 LoopIdError::UnresolvedLabel => "label not found",
2817 })
2818 }
2819}
2820
2821#[derive(Copy, Clone, Debug, HashStable_Generic)]
2822pub struct Destination {
2823 pub label: Option<Label>,
2825
2826 pub target_id: Result<HirId, LoopIdError>,
2829}
2830
2831#[derive(Copy, Clone, Debug, HashStable_Generic)]
2833pub enum YieldSource {
2834 Await { expr: Option<HirId> },
2836 Yield,
2838}
2839
2840impl fmt::Display for YieldSource {
2841 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2842 f.write_str(match self {
2843 YieldSource::Await { .. } => "`await`",
2844 YieldSource::Yield => "`yield`",
2845 })
2846 }
2847}
2848
2849#[derive(Debug, Clone, Copy, HashStable_Generic)]
2852pub struct MutTy<'hir> {
2853 pub ty: &'hir Ty<'hir>,
2854 pub mutbl: Mutability,
2855}
2856
2857#[derive(Debug, Clone, Copy, HashStable_Generic)]
2860pub struct FnSig<'hir> {
2861 pub header: FnHeader,
2862 pub decl: &'hir FnDecl<'hir>,
2863 pub span: Span,
2864}
2865
2866#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2870pub struct TraitItemId {
2871 pub owner_id: OwnerId,
2872}
2873
2874impl TraitItemId {
2875 #[inline]
2876 pub fn hir_id(&self) -> HirId {
2877 HirId::make_owner(self.owner_id.def_id)
2879 }
2880}
2881
2882#[derive(Debug, Clone, Copy, HashStable_Generic)]
2887pub struct TraitItem<'hir> {
2888 pub ident: Ident,
2889 pub owner_id: OwnerId,
2890 pub generics: &'hir Generics<'hir>,
2891 pub kind: TraitItemKind<'hir>,
2892 pub span: Span,
2893 pub defaultness: Defaultness,
2894}
2895
2896macro_rules! expect_methods_self_kind {
2897 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
2898 $(
2899 #[track_caller]
2900 pub fn $name(&self) -> $ret_ty {
2901 let $pat = &self.kind else { expect_failed(stringify!($ident), self) };
2902 $ret_val
2903 }
2904 )*
2905 }
2906}
2907
2908macro_rules! expect_methods_self {
2909 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
2910 $(
2911 #[track_caller]
2912 pub fn $name(&self) -> $ret_ty {
2913 let $pat = self else { expect_failed(stringify!($ident), self) };
2914 $ret_val
2915 }
2916 )*
2917 }
2918}
2919
2920#[track_caller]
2921fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
2922 panic!("{ident}: found {found:?}")
2923}
2924
2925impl<'hir> TraitItem<'hir> {
2926 #[inline]
2927 pub fn hir_id(&self) -> HirId {
2928 HirId::make_owner(self.owner_id.def_id)
2930 }
2931
2932 pub fn trait_item_id(&self) -> TraitItemId {
2933 TraitItemId { owner_id: self.owner_id }
2934 }
2935
2936 expect_methods_self_kind! {
2937 expect_const, (&'hir Ty<'hir>, Option<BodyId>),
2938 TraitItemKind::Const(ty, body), (ty, *body);
2939
2940 expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
2941 TraitItemKind::Fn(ty, trfn), (ty, trfn);
2942
2943 expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2944 TraitItemKind::Type(bounds, ty), (bounds, *ty);
2945 }
2946}
2947
2948#[derive(Debug, Clone, Copy, HashStable_Generic)]
2950pub enum TraitFn<'hir> {
2951 Required(&'hir [Ident]),
2953
2954 Provided(BodyId),
2956}
2957
2958#[derive(Debug, Clone, Copy, HashStable_Generic)]
2960pub enum TraitItemKind<'hir> {
2961 Const(&'hir Ty<'hir>, Option<BodyId>),
2963 Fn(FnSig<'hir>, TraitFn<'hir>),
2965 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2968}
2969
2970#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2974pub struct ImplItemId {
2975 pub owner_id: OwnerId,
2976}
2977
2978impl ImplItemId {
2979 #[inline]
2980 pub fn hir_id(&self) -> HirId {
2981 HirId::make_owner(self.owner_id.def_id)
2983 }
2984}
2985
2986#[derive(Debug, Clone, Copy, HashStable_Generic)]
2990pub struct ImplItem<'hir> {
2991 pub ident: Ident,
2992 pub owner_id: OwnerId,
2993 pub generics: &'hir Generics<'hir>,
2994 pub kind: ImplItemKind<'hir>,
2995 pub defaultness: Defaultness,
2996 pub span: Span,
2997 pub vis_span: Span,
2998}
2999
3000impl<'hir> ImplItem<'hir> {
3001 #[inline]
3002 pub fn hir_id(&self) -> HirId {
3003 HirId::make_owner(self.owner_id.def_id)
3005 }
3006
3007 pub fn impl_item_id(&self) -> ImplItemId {
3008 ImplItemId { owner_id: self.owner_id }
3009 }
3010
3011 expect_methods_self_kind! {
3012 expect_const, (&'hir Ty<'hir>, BodyId), ImplItemKind::Const(ty, body), (ty, *body);
3013 expect_fn, (&FnSig<'hir>, BodyId), ImplItemKind::Fn(ty, body), (ty, *body);
3014 expect_type, &'hir Ty<'hir>, ImplItemKind::Type(ty), ty;
3015 }
3016}
3017
3018#[derive(Debug, Clone, Copy, HashStable_Generic)]
3020pub enum ImplItemKind<'hir> {
3021 Const(&'hir Ty<'hir>, BodyId),
3024 Fn(FnSig<'hir>, BodyId),
3026 Type(&'hir Ty<'hir>),
3028}
3029
3030#[derive(Debug, Clone, Copy, HashStable_Generic)]
3041pub struct AssocItemConstraint<'hir> {
3042 #[stable_hasher(ignore)]
3043 pub hir_id: HirId,
3044 pub ident: Ident,
3045 pub gen_args: &'hir GenericArgs<'hir>,
3046 pub kind: AssocItemConstraintKind<'hir>,
3047 pub span: Span,
3048}
3049
3050impl<'hir> AssocItemConstraint<'hir> {
3051 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3053 match self.kind {
3054 AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3055 _ => None,
3056 }
3057 }
3058
3059 pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3061 match self.kind {
3062 AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3063 _ => None,
3064 }
3065 }
3066}
3067
3068#[derive(Debug, Clone, Copy, HashStable_Generic)]
3069pub enum Term<'hir> {
3070 Ty(&'hir Ty<'hir>),
3071 Const(&'hir ConstArg<'hir>),
3072}
3073
3074impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3075 fn from(ty: &'hir Ty<'hir>) -> Self {
3076 Term::Ty(ty)
3077 }
3078}
3079
3080impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3081 fn from(c: &'hir ConstArg<'hir>) -> Self {
3082 Term::Const(c)
3083 }
3084}
3085
3086#[derive(Debug, Clone, Copy, HashStable_Generic)]
3088pub enum AssocItemConstraintKind<'hir> {
3089 Equality { term: Term<'hir> },
3096 Bound { bounds: &'hir [GenericBound<'hir>] },
3098}
3099
3100impl<'hir> AssocItemConstraintKind<'hir> {
3101 pub fn descr(&self) -> &'static str {
3102 match self {
3103 AssocItemConstraintKind::Equality { .. } => "binding",
3104 AssocItemConstraintKind::Bound { .. } => "constraint",
3105 }
3106 }
3107}
3108
3109#[derive(Debug, Clone, Copy, HashStable_Generic)]
3113pub enum AmbigArg {}
3114
3115#[derive(Debug, Clone, Copy, HashStable_Generic)]
3116#[repr(C)]
3117pub struct Ty<'hir, Unambig = ()> {
3124 #[stable_hasher(ignore)]
3125 pub hir_id: HirId,
3126 pub span: Span,
3127 pub kind: TyKind<'hir, Unambig>,
3128}
3129
3130impl<'hir> Ty<'hir, AmbigArg> {
3131 pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3142 let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3145 unsafe { &*ptr }
3146 }
3147}
3148
3149impl<'hir> Ty<'hir> {
3150 pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3156 if let TyKind::Infer(()) = self.kind {
3157 return None;
3158 }
3159
3160 let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3164 Some(unsafe { &*ptr })
3165 }
3166}
3167
3168impl<'hir> Ty<'hir, AmbigArg> {
3169 pub fn peel_refs(&self) -> &Ty<'hir> {
3170 let mut final_ty = self.as_unambig_ty();
3171 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3172 final_ty = ty;
3173 }
3174 final_ty
3175 }
3176}
3177
3178impl<'hir> Ty<'hir> {
3179 pub fn peel_refs(&self) -> &Self {
3180 let mut final_ty = self;
3181 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3182 final_ty = ty;
3183 }
3184 final_ty
3185 }
3186
3187 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3189 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3190 return None;
3191 };
3192 let [segment] = &path.segments else {
3193 return None;
3194 };
3195 match path.res {
3196 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3197 Some((def_id, segment.ident))
3198 }
3199 _ => None,
3200 }
3201 }
3202
3203 pub fn find_self_aliases(&self) -> Vec<Span> {
3204 use crate::intravisit::Visitor;
3205 struct MyVisitor(Vec<Span>);
3206 impl<'v> Visitor<'v> for MyVisitor {
3207 fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3208 if matches!(
3209 &t.kind,
3210 TyKind::Path(QPath::Resolved(
3211 _,
3212 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3213 ))
3214 ) {
3215 self.0.push(t.span);
3216 return;
3217 }
3218 crate::intravisit::walk_ty(self, t);
3219 }
3220 }
3221
3222 let mut my_visitor = MyVisitor(vec![]);
3223 my_visitor.visit_ty_unambig(self);
3224 my_visitor.0
3225 }
3226
3227 pub fn is_suggestable_infer_ty(&self) -> bool {
3230 fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3231 generic_args.iter().any(|arg| match arg {
3232 GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3233 GenericArg::Infer(_) => true,
3234 _ => false,
3235 })
3236 }
3237 debug!(?self);
3238 match &self.kind {
3239 TyKind::Infer(()) => true,
3240 TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3241 TyKind::Array(ty, length) => {
3242 ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3243 }
3244 TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3245 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3246 TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3247 ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3248 }
3249 TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3250 ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3251 || segments
3252 .iter()
3253 .any(|segment| are_suggestable_generic_args(segment.args().args))
3254 }
3255 _ => false,
3256 }
3257 }
3258}
3259
3260#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
3262pub enum PrimTy {
3263 Int(IntTy),
3264 Uint(UintTy),
3265 Float(FloatTy),
3266 Str,
3267 Bool,
3268 Char,
3269}
3270
3271impl PrimTy {
3272 pub const ALL: [Self; 19] = [
3274 Self::Int(IntTy::I8),
3276 Self::Int(IntTy::I16),
3277 Self::Int(IntTy::I32),
3278 Self::Int(IntTy::I64),
3279 Self::Int(IntTy::I128),
3280 Self::Int(IntTy::Isize),
3281 Self::Uint(UintTy::U8),
3282 Self::Uint(UintTy::U16),
3283 Self::Uint(UintTy::U32),
3284 Self::Uint(UintTy::U64),
3285 Self::Uint(UintTy::U128),
3286 Self::Uint(UintTy::Usize),
3287 Self::Float(FloatTy::F16),
3288 Self::Float(FloatTy::F32),
3289 Self::Float(FloatTy::F64),
3290 Self::Float(FloatTy::F128),
3291 Self::Bool,
3292 Self::Char,
3293 Self::Str,
3294 ];
3295
3296 pub fn name_str(self) -> &'static str {
3300 match self {
3301 PrimTy::Int(i) => i.name_str(),
3302 PrimTy::Uint(u) => u.name_str(),
3303 PrimTy::Float(f) => f.name_str(),
3304 PrimTy::Str => "str",
3305 PrimTy::Bool => "bool",
3306 PrimTy::Char => "char",
3307 }
3308 }
3309
3310 pub fn name(self) -> Symbol {
3311 match self {
3312 PrimTy::Int(i) => i.name(),
3313 PrimTy::Uint(u) => u.name(),
3314 PrimTy::Float(f) => f.name(),
3315 PrimTy::Str => sym::str,
3316 PrimTy::Bool => sym::bool,
3317 PrimTy::Char => sym::char,
3318 }
3319 }
3320
3321 pub fn from_name(name: Symbol) -> Option<Self> {
3324 let ty = match name {
3325 sym::i8 => Self::Int(IntTy::I8),
3327 sym::i16 => Self::Int(IntTy::I16),
3328 sym::i32 => Self::Int(IntTy::I32),
3329 sym::i64 => Self::Int(IntTy::I64),
3330 sym::i128 => Self::Int(IntTy::I128),
3331 sym::isize => Self::Int(IntTy::Isize),
3332 sym::u8 => Self::Uint(UintTy::U8),
3333 sym::u16 => Self::Uint(UintTy::U16),
3334 sym::u32 => Self::Uint(UintTy::U32),
3335 sym::u64 => Self::Uint(UintTy::U64),
3336 sym::u128 => Self::Uint(UintTy::U128),
3337 sym::usize => Self::Uint(UintTy::Usize),
3338 sym::f16 => Self::Float(FloatTy::F16),
3339 sym::f32 => Self::Float(FloatTy::F32),
3340 sym::f64 => Self::Float(FloatTy::F64),
3341 sym::f128 => Self::Float(FloatTy::F128),
3342 sym::bool => Self::Bool,
3343 sym::char => Self::Char,
3344 sym::str => Self::Str,
3345 _ => return None,
3346 };
3347 Some(ty)
3348 }
3349}
3350
3351#[derive(Debug, Clone, Copy, HashStable_Generic)]
3352pub struct BareFnTy<'hir> {
3353 pub safety: Safety,
3354 pub abi: ExternAbi,
3355 pub generic_params: &'hir [GenericParam<'hir>],
3356 pub decl: &'hir FnDecl<'hir>,
3357 pub param_names: &'hir [Ident],
3358}
3359
3360#[derive(Debug, Clone, Copy, HashStable_Generic)]
3361pub struct UnsafeBinderTy<'hir> {
3362 pub generic_params: &'hir [GenericParam<'hir>],
3363 pub inner_ty: &'hir Ty<'hir>,
3364}
3365
3366#[derive(Debug, Clone, Copy, HashStable_Generic)]
3367pub struct OpaqueTy<'hir> {
3368 #[stable_hasher(ignore)]
3369 pub hir_id: HirId,
3370 pub def_id: LocalDefId,
3371 pub bounds: GenericBounds<'hir>,
3372 pub origin: OpaqueTyOrigin<LocalDefId>,
3373 pub span: Span,
3374}
3375
3376#[derive(Debug, Clone, Copy, HashStable_Generic, Encodable, Decodable)]
3377pub enum PreciseCapturingArgKind<T, U> {
3378 Lifetime(T),
3379 Param(U),
3381}
3382
3383pub type PreciseCapturingArg<'hir> =
3384 PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3385
3386impl PreciseCapturingArg<'_> {
3387 pub fn hir_id(self) -> HirId {
3388 match self {
3389 PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3390 PreciseCapturingArg::Param(param) => param.hir_id,
3391 }
3392 }
3393
3394 pub fn name(self) -> Symbol {
3395 match self {
3396 PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3397 PreciseCapturingArg::Param(param) => param.ident.name,
3398 }
3399 }
3400}
3401
3402#[derive(Debug, Clone, Copy, HashStable_Generic)]
3407pub struct PreciseCapturingNonLifetimeArg {
3408 #[stable_hasher(ignore)]
3409 pub hir_id: HirId,
3410 pub ident: Ident,
3411 pub res: Res,
3412}
3413
3414#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3415#[derive(HashStable_Generic, Encodable, Decodable)]
3416pub enum RpitContext {
3417 Trait,
3418 TraitImpl,
3419}
3420
3421#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3423#[derive(HashStable_Generic, Encodable, Decodable)]
3424pub enum OpaqueTyOrigin<D> {
3425 FnReturn {
3427 parent: D,
3429 in_trait_or_impl: Option<RpitContext>,
3431 },
3432 AsyncFn {
3434 parent: D,
3436 in_trait_or_impl: Option<RpitContext>,
3438 },
3439 TyAlias {
3441 parent: D,
3443 in_assoc_ty: bool,
3445 },
3446}
3447
3448#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable_Generic)]
3449pub enum InferDelegationKind {
3450 Input(usize),
3451 Output,
3452}
3453
3454#[derive(Debug, Clone, Copy, HashStable_Generic)]
3456#[repr(u8, C)]
3458pub enum TyKind<'hir, Unambig = ()> {
3459 InferDelegation(DefId, InferDelegationKind),
3461 Slice(&'hir Ty<'hir>),
3463 Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3465 Ptr(MutTy<'hir>),
3467 Ref(&'hir Lifetime, MutTy<'hir>),
3469 BareFn(&'hir BareFnTy<'hir>),
3471 UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3473 Never,
3475 Tup(&'hir [Ty<'hir>]),
3477 Path(QPath<'hir>),
3482 OpaqueDef(&'hir OpaqueTy<'hir>),
3484 TraitAscription(GenericBounds<'hir>),
3486 TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3492 Typeof(&'hir AnonConst),
3494 Err(rustc_span::ErrorGuaranteed),
3496 Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3498 Infer(Unambig),
3504}
3505
3506#[derive(Debug, Clone, Copy, HashStable_Generic)]
3507pub enum InlineAsmOperand<'hir> {
3508 In {
3509 reg: InlineAsmRegOrRegClass,
3510 expr: &'hir Expr<'hir>,
3511 },
3512 Out {
3513 reg: InlineAsmRegOrRegClass,
3514 late: bool,
3515 expr: Option<&'hir Expr<'hir>>,
3516 },
3517 InOut {
3518 reg: InlineAsmRegOrRegClass,
3519 late: bool,
3520 expr: &'hir Expr<'hir>,
3521 },
3522 SplitInOut {
3523 reg: InlineAsmRegOrRegClass,
3524 late: bool,
3525 in_expr: &'hir Expr<'hir>,
3526 out_expr: Option<&'hir Expr<'hir>>,
3527 },
3528 Const {
3529 anon_const: ConstBlock,
3530 },
3531 SymFn {
3532 expr: &'hir Expr<'hir>,
3533 },
3534 SymStatic {
3535 path: QPath<'hir>,
3536 def_id: DefId,
3537 },
3538 Label {
3539 block: &'hir Block<'hir>,
3540 },
3541}
3542
3543impl<'hir> InlineAsmOperand<'hir> {
3544 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3545 match *self {
3546 Self::In { reg, .. }
3547 | Self::Out { reg, .. }
3548 | Self::InOut { reg, .. }
3549 | Self::SplitInOut { reg, .. } => Some(reg),
3550 Self::Const { .. }
3551 | Self::SymFn { .. }
3552 | Self::SymStatic { .. }
3553 | Self::Label { .. } => None,
3554 }
3555 }
3556
3557 pub fn is_clobber(&self) -> bool {
3558 matches!(
3559 self,
3560 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3561 )
3562 }
3563}
3564
3565#[derive(Debug, Clone, Copy, HashStable_Generic)]
3566pub struct InlineAsm<'hir> {
3567 pub asm_macro: ast::AsmMacro,
3568 pub template: &'hir [InlineAsmTemplatePiece],
3569 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3570 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3571 pub options: InlineAsmOptions,
3572 pub line_spans: &'hir [Span],
3573}
3574
3575impl InlineAsm<'_> {
3576 pub fn contains_label(&self) -> bool {
3577 self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3578 }
3579}
3580
3581#[derive(Debug, Clone, Copy, HashStable_Generic)]
3583pub struct Param<'hir> {
3584 #[stable_hasher(ignore)]
3585 pub hir_id: HirId,
3586 pub pat: &'hir Pat<'hir>,
3587 pub ty_span: Span,
3588 pub span: Span,
3589}
3590
3591#[derive(Debug, Clone, Copy, HashStable_Generic)]
3593pub struct FnDecl<'hir> {
3594 pub inputs: &'hir [Ty<'hir>],
3598 pub output: FnRetTy<'hir>,
3599 pub c_variadic: bool,
3600 pub implicit_self: ImplicitSelfKind,
3602 pub lifetime_elision_allowed: bool,
3604}
3605
3606impl<'hir> FnDecl<'hir> {
3607 pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
3608 if let FnRetTy::Return(ty) = self.output
3609 && let TyKind::InferDelegation(sig_id, _) = ty.kind
3610 {
3611 return Some(sig_id);
3612 }
3613 None
3614 }
3615}
3616
3617#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3619pub enum ImplicitSelfKind {
3620 Imm,
3622 Mut,
3624 RefImm,
3626 RefMut,
3628 None,
3631}
3632
3633impl ImplicitSelfKind {
3634 pub fn has_implicit_self(&self) -> bool {
3636 !matches!(*self, ImplicitSelfKind::None)
3637 }
3638}
3639
3640#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3641pub enum IsAsync {
3642 Async(Span),
3643 NotAsync,
3644}
3645
3646impl IsAsync {
3647 pub fn is_async(self) -> bool {
3648 matches!(self, IsAsync::Async(_))
3649 }
3650}
3651
3652#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
3653pub enum Defaultness {
3654 Default { has_value: bool },
3655 Final,
3656}
3657
3658impl Defaultness {
3659 pub fn has_value(&self) -> bool {
3660 match *self {
3661 Defaultness::Default { has_value } => has_value,
3662 Defaultness::Final => true,
3663 }
3664 }
3665
3666 pub fn is_final(&self) -> bool {
3667 *self == Defaultness::Final
3668 }
3669
3670 pub fn is_default(&self) -> bool {
3671 matches!(*self, Defaultness::Default { .. })
3672 }
3673}
3674
3675#[derive(Debug, Clone, Copy, HashStable_Generic)]
3676pub enum FnRetTy<'hir> {
3677 DefaultReturn(Span),
3683 Return(&'hir Ty<'hir>),
3685}
3686
3687impl<'hir> FnRetTy<'hir> {
3688 #[inline]
3689 pub fn span(&self) -> Span {
3690 match *self {
3691 Self::DefaultReturn(span) => span,
3692 Self::Return(ref ty) => ty.span,
3693 }
3694 }
3695
3696 pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
3697 if let Self::Return(ty) = self
3698 && ty.is_suggestable_infer_ty()
3699 {
3700 return Some(*ty);
3701 }
3702 None
3703 }
3704}
3705
3706#[derive(Copy, Clone, Debug, HashStable_Generic)]
3708pub enum ClosureBinder {
3709 Default,
3711 For { span: Span },
3715}
3716
3717#[derive(Debug, Clone, Copy, HashStable_Generic)]
3718pub struct Mod<'hir> {
3719 pub spans: ModSpans,
3720 pub item_ids: &'hir [ItemId],
3721}
3722
3723#[derive(Copy, Clone, Debug, HashStable_Generic)]
3724pub struct ModSpans {
3725 pub inner_span: Span,
3729 pub inject_use_span: Span,
3730}
3731
3732#[derive(Debug, Clone, Copy, HashStable_Generic)]
3733pub struct EnumDef<'hir> {
3734 pub variants: &'hir [Variant<'hir>],
3735}
3736
3737#[derive(Debug, Clone, Copy, HashStable_Generic)]
3738pub struct Variant<'hir> {
3739 pub ident: Ident,
3741 #[stable_hasher(ignore)]
3743 pub hir_id: HirId,
3744 pub def_id: LocalDefId,
3745 pub data: VariantData<'hir>,
3747 pub disr_expr: Option<&'hir AnonConst>,
3749 pub span: Span,
3751}
3752
3753#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
3754pub enum UseKind {
3755 Single(Ident),
3762
3763 Glob,
3765
3766 ListStem,
3770}
3771
3772#[derive(Clone, Debug, Copy, HashStable_Generic)]
3779pub struct TraitRef<'hir> {
3780 pub path: &'hir Path<'hir>,
3781 #[stable_hasher(ignore)]
3783 pub hir_ref_id: HirId,
3784}
3785
3786impl TraitRef<'_> {
3787 pub fn trait_def_id(&self) -> Option<DefId> {
3789 match self.path.res {
3790 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
3791 Res::Err => None,
3792 res => panic!("{res:?} did not resolve to a trait or trait alias"),
3793 }
3794 }
3795}
3796
3797#[derive(Clone, Debug, Copy, HashStable_Generic)]
3798pub struct PolyTraitRef<'hir> {
3799 pub bound_generic_params: &'hir [GenericParam<'hir>],
3801
3802 pub modifiers: TraitBoundModifiers,
3806
3807 pub trait_ref: TraitRef<'hir>,
3809
3810 pub span: Span,
3811}
3812
3813#[derive(Debug, Clone, Copy, HashStable_Generic)]
3814pub struct FieldDef<'hir> {
3815 pub span: Span,
3816 pub vis_span: Span,
3817 pub ident: Ident,
3818 #[stable_hasher(ignore)]
3819 pub hir_id: HirId,
3820 pub def_id: LocalDefId,
3821 pub ty: &'hir Ty<'hir>,
3822 pub safety: Safety,
3823 pub default: Option<&'hir AnonConst>,
3824}
3825
3826impl FieldDef<'_> {
3827 pub fn is_positional(&self) -> bool {
3829 self.ident.as_str().as_bytes()[0].is_ascii_digit()
3830 }
3831}
3832
3833#[derive(Debug, Clone, Copy, HashStable_Generic)]
3835pub enum VariantData<'hir> {
3836 Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
3840 Tuple(&'hir [FieldDef<'hir>], #[stable_hasher(ignore)] HirId, LocalDefId),
3844 Unit(#[stable_hasher(ignore)] HirId, LocalDefId),
3848}
3849
3850impl<'hir> VariantData<'hir> {
3851 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
3853 match *self {
3854 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
3855 _ => &[],
3856 }
3857 }
3858
3859 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
3860 match *self {
3861 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
3862 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
3863 VariantData::Struct { .. } => None,
3864 }
3865 }
3866
3867 #[inline]
3868 pub fn ctor_kind(&self) -> Option<CtorKind> {
3869 self.ctor().map(|(kind, ..)| kind)
3870 }
3871
3872 #[inline]
3874 pub fn ctor_hir_id(&self) -> Option<HirId> {
3875 self.ctor().map(|(_, hir_id, _)| hir_id)
3876 }
3877
3878 #[inline]
3880 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
3881 self.ctor().map(|(.., def_id)| def_id)
3882 }
3883}
3884
3885#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
3889pub struct ItemId {
3890 pub owner_id: OwnerId,
3891}
3892
3893impl ItemId {
3894 #[inline]
3895 pub fn hir_id(&self) -> HirId {
3896 HirId::make_owner(self.owner_id.def_id)
3898 }
3899}
3900
3901#[derive(Debug, Clone, Copy, HashStable_Generic)]
3910pub struct Item<'hir> {
3911 pub owner_id: OwnerId,
3912 pub kind: ItemKind<'hir>,
3913 pub span: Span,
3914 pub vis_span: Span,
3915}
3916
3917impl<'hir> Item<'hir> {
3918 #[inline]
3919 pub fn hir_id(&self) -> HirId {
3920 HirId::make_owner(self.owner_id.def_id)
3922 }
3923
3924 pub fn item_id(&self) -> ItemId {
3925 ItemId { owner_id: self.owner_id }
3926 }
3927
3928 pub fn is_adt(&self) -> bool {
3931 matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
3932 }
3933
3934 pub fn is_struct_or_union(&self) -> bool {
3936 matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
3937 }
3938
3939 expect_methods_self_kind! {
3940 expect_extern_crate, (Option<Symbol>, Ident),
3941 ItemKind::ExternCrate(s, ident), (*s, *ident);
3942
3943 expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
3944
3945 expect_static, (Ident, &'hir Ty<'hir>, Mutability, BodyId),
3946 ItemKind::Static(ident, ty, mutbl, body), (*ident, ty, *mutbl, *body);
3947
3948 expect_const, (Ident, &'hir Ty<'hir>, &'hir Generics<'hir>, BodyId),
3949 ItemKind::Const(ident, ty, generics, body), (*ident, ty, generics, *body);
3950
3951 expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3952 ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
3953
3954 expect_macro, (Ident, &ast::MacroDef, MacroKind),
3955 ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
3956
3957 expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
3958
3959 expect_foreign_mod, (ExternAbi, &'hir [ForeignItemRef]),
3960 ItemKind::ForeignMod { abi, items }, (*abi, items);
3961
3962 expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
3963
3964 expect_ty_alias, (Ident, &'hir Ty<'hir>, &'hir Generics<'hir>),
3965 ItemKind::TyAlias(ident, ty, generics), (*ident, ty, generics);
3966
3967 expect_enum, (Ident, &EnumDef<'hir>, &'hir Generics<'hir>),
3968 ItemKind::Enum(ident, def, generics), (*ident, def, generics);
3969
3970 expect_struct, (Ident, &VariantData<'hir>, &'hir Generics<'hir>),
3971 ItemKind::Struct(ident, data, generics), (*ident, data, generics);
3972
3973 expect_union, (Ident, &VariantData<'hir>, &'hir Generics<'hir>),
3974 ItemKind::Union(ident, data, generics), (*ident, data, generics);
3975
3976 expect_trait,
3977 (
3978 IsAuto,
3979 Safety,
3980 Ident,
3981 &'hir Generics<'hir>,
3982 GenericBounds<'hir>,
3983 &'hir [TraitItemRef]
3984 ),
3985 ItemKind::Trait(is_auto, safety, ident, generics, bounds, items),
3986 (*is_auto, *safety, *ident, generics, bounds, items);
3987
3988 expect_trait_alias, (Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
3989 ItemKind::TraitAlias(ident, generics, bounds), (*ident, generics, bounds);
3990
3991 expect_impl, &'hir Impl<'hir>, ItemKind::Impl(imp), imp;
3992 }
3993}
3994
3995#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3996#[derive(Encodable, Decodable, HashStable_Generic)]
3997pub enum Safety {
3998 Unsafe,
3999 Safe,
4000}
4001
4002impl Safety {
4003 pub fn prefix_str(self) -> &'static str {
4004 match self {
4005 Self::Unsafe => "unsafe ",
4006 Self::Safe => "",
4007 }
4008 }
4009
4010 #[inline]
4011 pub fn is_unsafe(self) -> bool {
4012 !self.is_safe()
4013 }
4014
4015 #[inline]
4016 pub fn is_safe(self) -> bool {
4017 match self {
4018 Self::Unsafe => false,
4019 Self::Safe => true,
4020 }
4021 }
4022}
4023
4024impl fmt::Display for Safety {
4025 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4026 f.write_str(match *self {
4027 Self::Unsafe => "unsafe",
4028 Self::Safe => "safe",
4029 })
4030 }
4031}
4032
4033#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
4034pub enum Constness {
4035 Const,
4036 NotConst,
4037}
4038
4039impl fmt::Display for Constness {
4040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4041 f.write_str(match *self {
4042 Self::Const => "const",
4043 Self::NotConst => "non-const",
4044 })
4045 }
4046}
4047
4048#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
4053pub enum HeaderSafety {
4054 SafeTargetFeatures,
4060 Normal(Safety),
4061}
4062
4063impl From<Safety> for HeaderSafety {
4064 fn from(v: Safety) -> Self {
4065 Self::Normal(v)
4066 }
4067}
4068
4069#[derive(Copy, Clone, Debug, HashStable_Generic)]
4070pub struct FnHeader {
4071 pub safety: HeaderSafety,
4072 pub constness: Constness,
4073 pub asyncness: IsAsync,
4074 pub abi: ExternAbi,
4075}
4076
4077impl FnHeader {
4078 pub fn is_async(&self) -> bool {
4079 matches!(self.asyncness, IsAsync::Async(_))
4080 }
4081
4082 pub fn is_const(&self) -> bool {
4083 matches!(self.constness, Constness::Const)
4084 }
4085
4086 pub fn is_unsafe(&self) -> bool {
4087 self.safety().is_unsafe()
4088 }
4089
4090 pub fn is_safe(&self) -> bool {
4091 self.safety().is_safe()
4092 }
4093
4094 pub fn safety(&self) -> Safety {
4095 match self.safety {
4096 HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4097 HeaderSafety::Normal(safety) => safety,
4098 }
4099 }
4100}
4101
4102#[derive(Debug, Clone, Copy, HashStable_Generic)]
4103pub enum ItemKind<'hir> {
4104 ExternCrate(Option<Symbol>, Ident),
4108
4109 Use(&'hir UsePath<'hir>, UseKind),
4115
4116 Static(Ident, &'hir Ty<'hir>, Mutability, BodyId),
4118 Const(Ident, &'hir Ty<'hir>, &'hir Generics<'hir>, BodyId),
4120 Fn {
4122 ident: Ident,
4123 sig: FnSig<'hir>,
4124 generics: &'hir Generics<'hir>,
4125 body: BodyId,
4126 has_body: bool,
4130 },
4131 Macro(Ident, &'hir ast::MacroDef, MacroKind),
4133 Mod(Ident, &'hir Mod<'hir>),
4135 ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemRef] },
4137 GlobalAsm {
4139 asm: &'hir InlineAsm<'hir>,
4140 fake_body: BodyId,
4146 },
4147 TyAlias(Ident, &'hir Ty<'hir>, &'hir Generics<'hir>),
4149 Enum(Ident, EnumDef<'hir>, &'hir Generics<'hir>),
4151 Struct(Ident, VariantData<'hir>, &'hir Generics<'hir>),
4153 Union(Ident, VariantData<'hir>, &'hir Generics<'hir>),
4155 Trait(IsAuto, Safety, Ident, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
4157 TraitAlias(Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4159
4160 Impl(&'hir Impl<'hir>),
4162}
4163
4164#[derive(Debug, Clone, Copy, HashStable_Generic)]
4169pub struct Impl<'hir> {
4170 pub constness: Constness,
4171 pub safety: Safety,
4172 pub polarity: ImplPolarity,
4173 pub defaultness: Defaultness,
4174 pub defaultness_span: Option<Span>,
4177 pub generics: &'hir Generics<'hir>,
4178
4179 pub of_trait: Option<TraitRef<'hir>>,
4181
4182 pub self_ty: &'hir Ty<'hir>,
4183 pub items: &'hir [ImplItemRef],
4184}
4185
4186impl ItemKind<'_> {
4187 pub fn ident(&self) -> Option<Ident> {
4188 match *self {
4189 ItemKind::ExternCrate(_, ident)
4190 | ItemKind::Use(_, UseKind::Single(ident))
4191 | ItemKind::Static(ident, ..)
4192 | ItemKind::Const(ident, ..)
4193 | ItemKind::Fn { ident, .. }
4194 | ItemKind::Macro(ident, ..)
4195 | ItemKind::Mod(ident, ..)
4196 | ItemKind::TyAlias(ident, ..)
4197 | ItemKind::Enum(ident, ..)
4198 | ItemKind::Struct(ident, ..)
4199 | ItemKind::Union(ident, ..)
4200 | ItemKind::Trait(_, _, ident, ..)
4201 | ItemKind::TraitAlias(ident, ..) => Some(ident),
4202
4203 ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4204 | ItemKind::ForeignMod { .. }
4205 | ItemKind::GlobalAsm { .. }
4206 | ItemKind::Impl(_) => None,
4207 }
4208 }
4209
4210 pub fn generics(&self) -> Option<&Generics<'_>> {
4211 Some(match self {
4212 ItemKind::Fn { generics, .. }
4213 | ItemKind::TyAlias(_, _, generics)
4214 | ItemKind::Const(_, _, generics, _)
4215 | ItemKind::Enum(_, _, generics)
4216 | ItemKind::Struct(_, _, generics)
4217 | ItemKind::Union(_, _, generics)
4218 | ItemKind::Trait(_, _, _, generics, _, _)
4219 | ItemKind::TraitAlias(_, generics, _)
4220 | ItemKind::Impl(Impl { generics, .. }) => generics,
4221 _ => return None,
4222 })
4223 }
4224
4225 pub fn descr(&self) -> &'static str {
4226 match self {
4227 ItemKind::ExternCrate(..) => "extern crate",
4228 ItemKind::Use(..) => "`use` import",
4229 ItemKind::Static(..) => "static item",
4230 ItemKind::Const(..) => "constant item",
4231 ItemKind::Fn { .. } => "function",
4232 ItemKind::Macro(..) => "macro",
4233 ItemKind::Mod(..) => "module",
4234 ItemKind::ForeignMod { .. } => "extern block",
4235 ItemKind::GlobalAsm { .. } => "global asm item",
4236 ItemKind::TyAlias(..) => "type alias",
4237 ItemKind::Enum(..) => "enum",
4238 ItemKind::Struct(..) => "struct",
4239 ItemKind::Union(..) => "union",
4240 ItemKind::Trait(..) => "trait",
4241 ItemKind::TraitAlias(..) => "trait alias",
4242 ItemKind::Impl(..) => "implementation",
4243 }
4244 }
4245}
4246
4247#[derive(Debug, Clone, Copy, HashStable_Generic)]
4254pub struct TraitItemRef {
4255 pub id: TraitItemId,
4256 pub ident: Ident,
4257 pub kind: AssocItemKind,
4258 pub span: Span,
4259}
4260
4261#[derive(Debug, Clone, Copy, HashStable_Generic)]
4268pub struct ImplItemRef {
4269 pub id: ImplItemId,
4270 pub ident: Ident,
4271 pub kind: AssocItemKind,
4272 pub span: Span,
4273 pub trait_item_def_id: Option<DefId>,
4275}
4276
4277#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)]
4278pub enum AssocItemKind {
4279 Const,
4280 Fn { has_self: bool },
4281 Type,
4282}
4283
4284#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
4288pub struct ForeignItemId {
4289 pub owner_id: OwnerId,
4290}
4291
4292impl ForeignItemId {
4293 #[inline]
4294 pub fn hir_id(&self) -> HirId {
4295 HirId::make_owner(self.owner_id.def_id)
4297 }
4298}
4299
4300#[derive(Debug, Clone, Copy, HashStable_Generic)]
4307pub struct ForeignItemRef {
4308 pub id: ForeignItemId,
4309 pub ident: Ident,
4310 pub span: Span,
4311}
4312
4313#[derive(Debug, Clone, Copy, HashStable_Generic)]
4314pub struct ForeignItem<'hir> {
4315 pub ident: Ident,
4316 pub kind: ForeignItemKind<'hir>,
4317 pub owner_id: OwnerId,
4318 pub span: Span,
4319 pub vis_span: Span,
4320}
4321
4322impl ForeignItem<'_> {
4323 #[inline]
4324 pub fn hir_id(&self) -> HirId {
4325 HirId::make_owner(self.owner_id.def_id)
4327 }
4328
4329 pub fn foreign_item_id(&self) -> ForeignItemId {
4330 ForeignItemId { owner_id: self.owner_id }
4331 }
4332}
4333
4334#[derive(Debug, Clone, Copy, HashStable_Generic)]
4336pub enum ForeignItemKind<'hir> {
4337 Fn(FnSig<'hir>, &'hir [Ident], &'hir Generics<'hir>),
4339 Static(&'hir Ty<'hir>, Mutability, Safety),
4341 Type,
4343}
4344
4345#[derive(Debug, Copy, Clone, HashStable_Generic)]
4347pub struct Upvar {
4348 pub span: Span,
4350}
4351
4352#[derive(Debug, Clone, HashStable_Generic)]
4356pub struct TraitCandidate {
4357 pub def_id: DefId,
4358 pub import_ids: SmallVec<[LocalDefId; 1]>,
4359}
4360
4361#[derive(Copy, Clone, Debug, HashStable_Generic)]
4362pub enum OwnerNode<'hir> {
4363 Item(&'hir Item<'hir>),
4364 ForeignItem(&'hir ForeignItem<'hir>),
4365 TraitItem(&'hir TraitItem<'hir>),
4366 ImplItem(&'hir ImplItem<'hir>),
4367 Crate(&'hir Mod<'hir>),
4368 Synthetic,
4369}
4370
4371impl<'hir> OwnerNode<'hir> {
4372 pub fn span(&self) -> Span {
4373 match self {
4374 OwnerNode::Item(Item { span, .. })
4375 | OwnerNode::ForeignItem(ForeignItem { span, .. })
4376 | OwnerNode::ImplItem(ImplItem { span, .. })
4377 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4378 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4379 OwnerNode::Synthetic => unreachable!(),
4380 }
4381 }
4382
4383 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4384 match self {
4385 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4386 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4387 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4388 | OwnerNode::ForeignItem(ForeignItem {
4389 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4390 }) => Some(fn_sig),
4391 _ => None,
4392 }
4393 }
4394
4395 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4396 match self {
4397 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4398 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4399 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4400 | OwnerNode::ForeignItem(ForeignItem {
4401 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4402 }) => Some(fn_sig.decl),
4403 _ => None,
4404 }
4405 }
4406
4407 pub fn body_id(&self) -> Option<BodyId> {
4408 match self {
4409 OwnerNode::Item(Item {
4410 kind:
4411 ItemKind::Static(_, _, _, body)
4412 | ItemKind::Const(_, _, _, body)
4413 | ItemKind::Fn { body, .. },
4414 ..
4415 })
4416 | OwnerNode::TraitItem(TraitItem {
4417 kind:
4418 TraitItemKind::Fn(_, TraitFn::Provided(body)) | TraitItemKind::Const(_, Some(body)),
4419 ..
4420 })
4421 | OwnerNode::ImplItem(ImplItem {
4422 kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, body),
4423 ..
4424 }) => Some(*body),
4425 _ => None,
4426 }
4427 }
4428
4429 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4430 Node::generics(self.into())
4431 }
4432
4433 pub fn def_id(self) -> OwnerId {
4434 match self {
4435 OwnerNode::Item(Item { owner_id, .. })
4436 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4437 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4438 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4439 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4440 OwnerNode::Synthetic => unreachable!(),
4441 }
4442 }
4443
4444 pub fn is_impl_block(&self) -> bool {
4446 matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4447 }
4448
4449 expect_methods_self! {
4450 expect_item, &'hir Item<'hir>, OwnerNode::Item(n), n;
4451 expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4452 expect_impl_item, &'hir ImplItem<'hir>, OwnerNode::ImplItem(n), n;
4453 expect_trait_item, &'hir TraitItem<'hir>, OwnerNode::TraitItem(n), n;
4454 }
4455}
4456
4457impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4458 fn from(val: &'hir Item<'hir>) -> Self {
4459 OwnerNode::Item(val)
4460 }
4461}
4462
4463impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4464 fn from(val: &'hir ForeignItem<'hir>) -> Self {
4465 OwnerNode::ForeignItem(val)
4466 }
4467}
4468
4469impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4470 fn from(val: &'hir ImplItem<'hir>) -> Self {
4471 OwnerNode::ImplItem(val)
4472 }
4473}
4474
4475impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4476 fn from(val: &'hir TraitItem<'hir>) -> Self {
4477 OwnerNode::TraitItem(val)
4478 }
4479}
4480
4481impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4482 fn from(val: OwnerNode<'hir>) -> Self {
4483 match val {
4484 OwnerNode::Item(n) => Node::Item(n),
4485 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4486 OwnerNode::ImplItem(n) => Node::ImplItem(n),
4487 OwnerNode::TraitItem(n) => Node::TraitItem(n),
4488 OwnerNode::Crate(n) => Node::Crate(n),
4489 OwnerNode::Synthetic => Node::Synthetic,
4490 }
4491 }
4492}
4493
4494#[derive(Copy, Clone, Debug, HashStable_Generic)]
4495pub enum Node<'hir> {
4496 Param(&'hir Param<'hir>),
4497 Item(&'hir Item<'hir>),
4498 ForeignItem(&'hir ForeignItem<'hir>),
4499 TraitItem(&'hir TraitItem<'hir>),
4500 ImplItem(&'hir ImplItem<'hir>),
4501 Variant(&'hir Variant<'hir>),
4502 Field(&'hir FieldDef<'hir>),
4503 AnonConst(&'hir AnonConst),
4504 ConstBlock(&'hir ConstBlock),
4505 ConstArg(&'hir ConstArg<'hir>),
4506 Expr(&'hir Expr<'hir>),
4507 ExprField(&'hir ExprField<'hir>),
4508 Stmt(&'hir Stmt<'hir>),
4509 PathSegment(&'hir PathSegment<'hir>),
4510 Ty(&'hir Ty<'hir>),
4511 AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
4512 TraitRef(&'hir TraitRef<'hir>),
4513 OpaqueTy(&'hir OpaqueTy<'hir>),
4514 TyPat(&'hir TyPat<'hir>),
4515 Pat(&'hir Pat<'hir>),
4516 PatField(&'hir PatField<'hir>),
4517 PatExpr(&'hir PatExpr<'hir>),
4521 Arm(&'hir Arm<'hir>),
4522 Block(&'hir Block<'hir>),
4523 LetStmt(&'hir LetStmt<'hir>),
4524 Ctor(&'hir VariantData<'hir>),
4527 Lifetime(&'hir Lifetime),
4528 GenericParam(&'hir GenericParam<'hir>),
4529 Crate(&'hir Mod<'hir>),
4530 Infer(&'hir InferArg),
4531 WherePredicate(&'hir WherePredicate<'hir>),
4532 PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
4533 Synthetic,
4535 Err(Span),
4536}
4537
4538impl<'hir> Node<'hir> {
4539 pub fn ident(&self) -> Option<Ident> {
4554 match self {
4555 Node::Item(item) => item.kind.ident(),
4556 Node::TraitItem(TraitItem { ident, .. })
4557 | Node::ImplItem(ImplItem { ident, .. })
4558 | Node::ForeignItem(ForeignItem { ident, .. })
4559 | Node::Field(FieldDef { ident, .. })
4560 | Node::Variant(Variant { ident, .. })
4561 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
4562 Node::Lifetime(lt) => Some(lt.ident),
4563 Node::GenericParam(p) => Some(p.name.ident()),
4564 Node::AssocItemConstraint(c) => Some(c.ident),
4565 Node::PatField(f) => Some(f.ident),
4566 Node::ExprField(f) => Some(f.ident),
4567 Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
4568 Node::Param(..)
4569 | Node::AnonConst(..)
4570 | Node::ConstBlock(..)
4571 | Node::ConstArg(..)
4572 | Node::Expr(..)
4573 | Node::Stmt(..)
4574 | Node::Block(..)
4575 | Node::Ctor(..)
4576 | Node::Pat(..)
4577 | Node::TyPat(..)
4578 | Node::PatExpr(..)
4579 | Node::Arm(..)
4580 | Node::LetStmt(..)
4581 | Node::Crate(..)
4582 | Node::Ty(..)
4583 | Node::TraitRef(..)
4584 | Node::OpaqueTy(..)
4585 | Node::Infer(..)
4586 | Node::WherePredicate(..)
4587 | Node::Synthetic
4588 | Node::Err(..) => None,
4589 }
4590 }
4591
4592 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4593 match self {
4594 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4595 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4596 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4597 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4598 Some(fn_sig.decl)
4599 }
4600 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
4601 Some(fn_decl)
4602 }
4603 _ => None,
4604 }
4605 }
4606
4607 pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
4609 if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
4610 && let Some(trait_ref) = impl_block.of_trait
4611 && let Some(trait_id) = trait_ref.trait_def_id()
4612 && trait_id == trait_def_id
4613 {
4614 Some(impl_block)
4615 } else {
4616 None
4617 }
4618 }
4619
4620 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4621 match self {
4622 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4623 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4624 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4625 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
4626 Some(fn_sig)
4627 }
4628 _ => None,
4629 }
4630 }
4631
4632 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
4634 match self {
4635 Node::Item(it) => match it.kind {
4636 ItemKind::TyAlias(_, ty, _)
4637 | ItemKind::Static(_, ty, _, _)
4638 | ItemKind::Const(_, ty, _, _) => Some(ty),
4639 ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
4640 _ => None,
4641 },
4642 Node::TraitItem(it) => match it.kind {
4643 TraitItemKind::Const(ty, _) => Some(ty),
4644 TraitItemKind::Type(_, ty) => ty,
4645 _ => None,
4646 },
4647 Node::ImplItem(it) => match it.kind {
4648 ImplItemKind::Const(ty, _) => Some(ty),
4649 ImplItemKind::Type(ty) => Some(ty),
4650 _ => None,
4651 },
4652 _ => None,
4653 }
4654 }
4655
4656 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
4657 match self {
4658 Node::Item(Item { kind: ItemKind::TyAlias(_, ty, _), .. }) => Some(ty),
4659 _ => None,
4660 }
4661 }
4662
4663 #[inline]
4664 pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
4665 match self {
4666 Node::Item(Item {
4667 owner_id,
4668 kind:
4669 ItemKind::Const(_, _, _, body)
4670 | ItemKind::Static(.., body)
4671 | ItemKind::Fn { body, .. },
4672 ..
4673 })
4674 | Node::TraitItem(TraitItem {
4675 owner_id,
4676 kind:
4677 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
4678 ..
4679 })
4680 | Node::ImplItem(ImplItem {
4681 owner_id,
4682 kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
4683 ..
4684 }) => Some((owner_id.def_id, *body)),
4685
4686 Node::Item(Item {
4687 owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
4688 }) => Some((owner_id.def_id, *fake_body)),
4689
4690 Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
4691 Some((*def_id, *body))
4692 }
4693
4694 Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
4695 Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
4696
4697 _ => None,
4698 }
4699 }
4700
4701 pub fn body_id(&self) -> Option<BodyId> {
4702 Some(self.associated_body()?.1)
4703 }
4704
4705 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4706 match self {
4707 Node::ForeignItem(ForeignItem {
4708 kind: ForeignItemKind::Fn(_, _, generics), ..
4709 })
4710 | Node::TraitItem(TraitItem { generics, .. })
4711 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
4712 Node::Item(item) => item.kind.generics(),
4713 _ => None,
4714 }
4715 }
4716
4717 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
4718 match self {
4719 Node::Item(i) => Some(OwnerNode::Item(i)),
4720 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
4721 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
4722 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
4723 Node::Crate(i) => Some(OwnerNode::Crate(i)),
4724 Node::Synthetic => Some(OwnerNode::Synthetic),
4725 _ => None,
4726 }
4727 }
4728
4729 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
4730 match self {
4731 Node::Item(i) => match i.kind {
4732 ItemKind::Fn { ident, sig, generics, .. } => {
4733 Some(FnKind::ItemFn(ident, generics, sig.header))
4734 }
4735 _ => None,
4736 },
4737 Node::TraitItem(ti) => match ti.kind {
4738 TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
4739 _ => None,
4740 },
4741 Node::ImplItem(ii) => match ii.kind {
4742 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
4743 _ => None,
4744 },
4745 Node::Expr(e) => match e.kind {
4746 ExprKind::Closure { .. } => Some(FnKind::Closure),
4747 _ => None,
4748 },
4749 _ => None,
4750 }
4751 }
4752
4753 expect_methods_self! {
4754 expect_param, &'hir Param<'hir>, Node::Param(n), n;
4755 expect_item, &'hir Item<'hir>, Node::Item(n), n;
4756 expect_foreign_item, &'hir ForeignItem<'hir>, Node::ForeignItem(n), n;
4757 expect_trait_item, &'hir TraitItem<'hir>, Node::TraitItem(n), n;
4758 expect_impl_item, &'hir ImplItem<'hir>, Node::ImplItem(n), n;
4759 expect_variant, &'hir Variant<'hir>, Node::Variant(n), n;
4760 expect_field, &'hir FieldDef<'hir>, Node::Field(n), n;
4761 expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n;
4762 expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n;
4763 expect_expr, &'hir Expr<'hir>, Node::Expr(n), n;
4764 expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n;
4765 expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n;
4766 expect_path_segment, &'hir PathSegment<'hir>, Node::PathSegment(n), n;
4767 expect_ty, &'hir Ty<'hir>, Node::Ty(n), n;
4768 expect_assoc_item_constraint, &'hir AssocItemConstraint<'hir>, Node::AssocItemConstraint(n), n;
4769 expect_trait_ref, &'hir TraitRef<'hir>, Node::TraitRef(n), n;
4770 expect_opaque_ty, &'hir OpaqueTy<'hir>, Node::OpaqueTy(n), n;
4771 expect_pat, &'hir Pat<'hir>, Node::Pat(n), n;
4772 expect_pat_field, &'hir PatField<'hir>, Node::PatField(n), n;
4773 expect_arm, &'hir Arm<'hir>, Node::Arm(n), n;
4774 expect_block, &'hir Block<'hir>, Node::Block(n), n;
4775 expect_let_stmt, &'hir LetStmt<'hir>, Node::LetStmt(n), n;
4776 expect_ctor, &'hir VariantData<'hir>, Node::Ctor(n), n;
4777 expect_lifetime, &'hir Lifetime, Node::Lifetime(n), n;
4778 expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
4779 expect_crate, &'hir Mod<'hir>, Node::Crate(n), n;
4780 expect_infer, &'hir InferArg, Node::Infer(n), n;
4781 expect_closure, &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
4782 }
4783}
4784
4785#[cfg(target_pointer_width = "64")]
4787mod size_asserts {
4788 use rustc_data_structures::static_assert_size;
4789
4790 use super::*;
4791 static_assert_size!(Block<'_>, 48);
4793 static_assert_size!(Body<'_>, 24);
4794 static_assert_size!(Expr<'_>, 64);
4795 static_assert_size!(ExprKind<'_>, 48);
4796 static_assert_size!(FnDecl<'_>, 40);
4797 static_assert_size!(ForeignItem<'_>, 88);
4798 static_assert_size!(ForeignItemKind<'_>, 56);
4799 static_assert_size!(GenericArg<'_>, 16);
4800 static_assert_size!(GenericBound<'_>, 64);
4801 static_assert_size!(Generics<'_>, 56);
4802 static_assert_size!(Impl<'_>, 80);
4803 static_assert_size!(ImplItem<'_>, 88);
4804 static_assert_size!(ImplItemKind<'_>, 40);
4805 static_assert_size!(Item<'_>, 88);
4806 static_assert_size!(ItemKind<'_>, 64);
4807 static_assert_size!(LetStmt<'_>, 64);
4808 static_assert_size!(Param<'_>, 32);
4809 static_assert_size!(Pat<'_>, 72);
4810 static_assert_size!(Path<'_>, 40);
4811 static_assert_size!(PathSegment<'_>, 48);
4812 static_assert_size!(PatKind<'_>, 48);
4813 static_assert_size!(QPath<'_>, 24);
4814 static_assert_size!(Res, 12);
4815 static_assert_size!(Stmt<'_>, 32);
4816 static_assert_size!(StmtKind<'_>, 16);
4817 static_assert_size!(TraitItem<'_>, 88);
4818 static_assert_size!(TraitItemKind<'_>, 48);
4819 static_assert_size!(Ty<'_>, 48);
4820 static_assert_size!(TyKind<'_>, 32);
4821 }
4823
4824#[cfg(test)]
4825mod tests;