1use std::borrow::{Borrow, Cow};
22use std::{cmp, fmt};
23
24pub use GenericArgs::*;
25pub use UnsafeSource::*;
26pub use rustc_ast_ir::{FloatTy, IntTy, Movability, Mutability, Pinnedness, UintTy};
27use rustc_data_structures::packed::Pu128;
28use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29use rustc_data_structures::stack::ensure_sufficient_stack;
30use rustc_data_structures::tagged_ptr::Tag;
31use rustc_macros::{Decodable, Encodable, HashStable_Generic, Walkable};
32pub use rustc_span::AttrId;
33use rustc_span::source_map::{Spanned, respan};
34use rustc_span::{ByteSymbol, DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
35use thin_vec::{ThinVec, thin_vec};
36
37use crate::attr::data_structures::CfgEntry;
38pub use crate::format::*;
39use crate::token::{self, CommentKind, Delimiter};
40use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream};
41use crate::util::parser::{ExprPrecedence, Fixity};
42use crate::visit::{AssocCtxt, BoundKind, LifetimeCtxt};
43
44#[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq, Walkable)]
55pub struct Label {
56 pub ident: Ident,
57}
58
59impl fmt::Debug for Label {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "label({:?})", self.ident)
62 }
63}
64
65#[derive(Clone, Encodable, Decodable, Copy, PartialEq, Eq, Hash, Walkable)]
68pub struct Lifetime {
69 pub id: NodeId,
70 pub ident: Ident,
71}
72
73impl fmt::Debug for Lifetime {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 write!(f, "lifetime({}: {})", self.id, self)
76 }
77}
78
79impl fmt::Display for Lifetime {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(f, "{}", self.ident.name)
82 }
83}
84
85#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
92pub struct Path {
93 pub span: Span,
94 pub segments: ThinVec<PathSegment>,
97 pub tokens: Option<LazyAttrTokenStream>,
98}
99
100impl PartialEq<Symbol> for Path {
102 #[inline]
103 fn eq(&self, name: &Symbol) -> bool {
104 if let [segment] = self.segments.as_ref()
105 && segment == name
106 {
107 true
108 } else {
109 false
110 }
111 }
112}
113
114impl PartialEq<&[Symbol]> for Path {
116 #[inline]
117 fn eq(&self, names: &&[Symbol]) -> bool {
118 self.segments.iter().eq(*names)
119 }
120}
121
122impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
123 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
124 self.segments.len().hash_stable(hcx, hasher);
125 for segment in &self.segments {
126 segment.ident.hash_stable(hcx, hasher);
127 }
128 }
129}
130
131impl Path {
132 pub fn from_ident(ident: Ident) -> Path {
135 Path { segments: thin_vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
136 }
137
138 pub fn is_global(&self) -> bool {
139 self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
140 }
141
142 #[tracing::instrument(level = "debug", ret)]
148 pub fn is_potential_trivial_const_arg(&self) -> bool {
149 self.segments.len() == 1 && self.segments.iter().all(|seg| seg.args.is_none())
150 }
151}
152
153pub fn join_path_syms(path: impl IntoIterator<Item = impl Borrow<Symbol>>) -> String {
165 let mut iter = path.into_iter();
170 let len_hint = iter.size_hint().1.unwrap_or(1);
171 let mut s = String::with_capacity(len_hint * 8);
172
173 let first_sym = *iter.next().unwrap().borrow();
174 if first_sym != kw::PathRoot {
175 s.push_str(first_sym.as_str());
176 }
177 for sym in iter {
178 let sym = *sym.borrow();
179 debug_assert_ne!(sym, kw::PathRoot);
180 s.push_str("::");
181 s.push_str(sym.as_str());
182 }
183 s
184}
185
186pub fn join_path_idents(path: impl IntoIterator<Item = impl Borrow<Ident>>) -> String {
189 let mut iter = path.into_iter();
190 let len_hint = iter.size_hint().1.unwrap_or(1);
191 let mut s = String::with_capacity(len_hint * 8);
192
193 let first_ident = *iter.next().unwrap().borrow();
194 if first_ident.name != kw::PathRoot {
195 s.push_str(&first_ident.to_string());
196 }
197 for ident in iter {
198 let ident = *ident.borrow();
199 debug_assert_ne!(ident.name, kw::PathRoot);
200 s.push_str("::");
201 s.push_str(&ident.to_string());
202 }
203 s
204}
205
206#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
210pub struct PathSegment {
211 pub ident: Ident,
213
214 pub id: NodeId,
215
216 pub args: Option<Box<GenericArgs>>,
223}
224
225impl PartialEq<Symbol> for PathSegment {
227 #[inline]
228 fn eq(&self, name: &Symbol) -> bool {
229 self.args.is_none() && self.ident.name == *name
230 }
231}
232
233impl PathSegment {
234 pub fn from_ident(ident: Ident) -> Self {
235 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
236 }
237
238 pub fn path_root(span: Span) -> Self {
239 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
240 }
241
242 pub fn span(&self) -> Span {
243 match &self.args {
244 Some(args) => self.ident.span.to(args.span()),
245 None => self.ident.span,
246 }
247 }
248}
249
250#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
254pub enum GenericArgs {
255 AngleBracketed(AngleBracketedArgs),
257 Parenthesized(ParenthesizedArgs),
259 ParenthesizedElided(Span),
261}
262
263impl GenericArgs {
264 pub fn is_angle_bracketed(&self) -> bool {
265 matches!(self, AngleBracketed(..))
266 }
267
268 pub fn span(&self) -> Span {
269 match self {
270 AngleBracketed(data) => data.span,
271 Parenthesized(data) => data.span,
272 ParenthesizedElided(span) => *span,
273 }
274 }
275}
276
277#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
279pub enum GenericArg {
280 Lifetime(#[visitable(extra = LifetimeCtxt::GenericArg)] Lifetime),
282 Type(Box<Ty>),
284 Const(AnonConst),
286}
287
288impl GenericArg {
289 pub fn span(&self) -> Span {
290 match self {
291 GenericArg::Lifetime(lt) => lt.ident.span,
292 GenericArg::Type(ty) => ty.span,
293 GenericArg::Const(ct) => ct.value.span,
294 }
295 }
296}
297
298#[derive(Clone, Encodable, Decodable, Debug, Default, Walkable)]
300pub struct AngleBracketedArgs {
301 pub span: Span,
303 pub args: ThinVec<AngleBracketedArg>,
305}
306
307#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
309pub enum AngleBracketedArg {
310 Arg(GenericArg),
312 Constraint(AssocItemConstraint),
314}
315
316impl AngleBracketedArg {
317 pub fn span(&self) -> Span {
318 match self {
319 AngleBracketedArg::Arg(arg) => arg.span(),
320 AngleBracketedArg::Constraint(constraint) => constraint.span,
321 }
322 }
323}
324
325impl From<AngleBracketedArgs> for Box<GenericArgs> {
326 fn from(val: AngleBracketedArgs) -> Self {
327 Box::new(GenericArgs::AngleBracketed(val))
328 }
329}
330
331impl From<ParenthesizedArgs> for Box<GenericArgs> {
332 fn from(val: ParenthesizedArgs) -> Self {
333 Box::new(GenericArgs::Parenthesized(val))
334 }
335}
336
337#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
339pub struct ParenthesizedArgs {
340 pub span: Span,
345
346 pub inputs: ThinVec<Box<Ty>>,
348
349 pub inputs_span: Span,
354
355 pub output: FnRetTy,
357}
358
359impl ParenthesizedArgs {
360 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
361 let args = self
362 .inputs
363 .iter()
364 .cloned()
365 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
366 .collect();
367 AngleBracketedArgs { span: self.inputs_span, args }
368 }
369}
370
371pub use crate::node_id::{CRATE_NODE_ID, DUMMY_NODE_ID, NodeId};
372
373#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Walkable)]
375pub struct TraitBoundModifiers {
376 pub constness: BoundConstness,
377 pub asyncness: BoundAsyncness,
378 pub polarity: BoundPolarity,
379}
380
381impl TraitBoundModifiers {
382 pub const NONE: Self = Self {
383 constness: BoundConstness::Never,
384 asyncness: BoundAsyncness::Normal,
385 polarity: BoundPolarity::Positive,
386 };
387}
388
389#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
390pub enum GenericBound {
391 Trait(PolyTraitRef),
392 Outlives(#[visitable(extra = LifetimeCtxt::Bound)] Lifetime),
393 Use(ThinVec<PreciseCapturingArg>, Span),
395}
396
397impl GenericBound {
398 pub fn span(&self) -> Span {
399 match self {
400 GenericBound::Trait(t, ..) => t.span,
401 GenericBound::Outlives(l) => l.ident.span,
402 GenericBound::Use(_, span) => *span,
403 }
404 }
405}
406
407pub type GenericBounds = Vec<GenericBound>;
408
409#[derive(Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
413pub enum ParamKindOrd {
414 Lifetime,
415 TypeOrConst,
416}
417
418impl fmt::Display for ParamKindOrd {
419 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420 match self {
421 ParamKindOrd::Lifetime => "lifetime".fmt(f),
422 ParamKindOrd::TypeOrConst => "type and const".fmt(f),
423 }
424 }
425}
426
427#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
428pub enum GenericParamKind {
429 Lifetime,
431 Type {
432 default: Option<Box<Ty>>,
433 },
434 Const {
435 ty: Box<Ty>,
436 span: Span,
438 default: Option<AnonConst>,
440 },
441}
442
443#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
444pub struct GenericParam {
445 pub id: NodeId,
446 pub ident: Ident,
447 pub attrs: AttrVec,
448 #[visitable(extra = BoundKind::Bound)]
449 pub bounds: GenericBounds,
450 pub is_placeholder: bool,
451 pub kind: GenericParamKind,
452 pub colon_span: Option<Span>,
453}
454
455impl GenericParam {
456 pub fn span(&self) -> Span {
457 match &self.kind {
458 GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
459 self.ident.span
460 }
461 GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
462 GenericParamKind::Const { span, .. } => *span,
463 }
464 }
465}
466
467#[derive(Clone, Encodable, Decodable, Debug, Default, Walkable)]
470pub struct Generics {
471 pub params: ThinVec<GenericParam>,
472 pub where_clause: WhereClause,
473 pub span: Span,
474}
475
476#[derive(Clone, Encodable, Decodable, Debug, Default, Walkable)]
478pub struct WhereClause {
479 pub has_where_token: bool,
484 pub predicates: ThinVec<WherePredicate>,
485 pub span: Span,
486}
487
488impl WhereClause {
489 pub fn is_empty(&self) -> bool {
490 !self.has_where_token && self.predicates.is_empty()
491 }
492}
493
494#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
496pub struct WherePredicate {
497 pub attrs: AttrVec,
498 pub kind: WherePredicateKind,
499 pub id: NodeId,
500 pub span: Span,
501 pub is_placeholder: bool,
502}
503
504#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
506pub enum WherePredicateKind {
507 BoundPredicate(WhereBoundPredicate),
509 RegionPredicate(WhereRegionPredicate),
511 EqPredicate(WhereEqPredicate),
513}
514
515#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
519pub struct WhereBoundPredicate {
520 pub bound_generic_params: ThinVec<GenericParam>,
522 pub bounded_ty: Box<Ty>,
524 #[visitable(extra = BoundKind::Bound)]
526 pub bounds: GenericBounds,
527}
528
529#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
533pub struct WhereRegionPredicate {
534 #[visitable(extra = LifetimeCtxt::Bound)]
535 pub lifetime: Lifetime,
536 #[visitable(extra = BoundKind::Bound)]
537 pub bounds: GenericBounds,
538}
539
540#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
544pub struct WhereEqPredicate {
545 pub lhs_ty: Box<Ty>,
546 pub rhs_ty: Box<Ty>,
547}
548
549#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
550pub struct Crate {
551 pub id: NodeId,
554 pub attrs: AttrVec,
555 pub items: ThinVec<Box<Item>>,
556 pub spans: ModSpans,
557 pub is_placeholder: bool,
558}
559
560#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
567pub struct MetaItem {
568 pub unsafety: Safety,
569 pub path: Path,
570 pub kind: MetaItemKind,
571 pub span: Span,
572}
573
574#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
576pub enum MetaItemKind {
577 Word,
581
582 List(ThinVec<MetaItemInner>),
586
587 NameValue(MetaItemLit),
591}
592
593#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
597pub enum MetaItemInner {
598 MetaItem(MetaItem),
600
601 Lit(MetaItemLit),
605}
606
607#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
611pub struct Block {
612 pub stmts: ThinVec<Stmt>,
614 pub id: NodeId,
615 pub rules: BlockCheckMode,
617 pub span: Span,
618 pub tokens: Option<LazyAttrTokenStream>,
619}
620
621#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
625pub struct Pat {
626 pub id: NodeId,
627 pub kind: PatKind,
628 pub span: Span,
629 pub tokens: Option<LazyAttrTokenStream>,
630}
631
632impl Pat {
633 pub fn to_ty(&self) -> Option<Box<Ty>> {
636 let kind = match &self.kind {
637 PatKind::Missing => unreachable!(),
638 PatKind::Wild => TyKind::Infer,
640 PatKind::Ident(BindingMode::NONE, ident, None) => {
642 TyKind::Path(None, Path::from_ident(*ident))
643 }
644 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
645 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
646 PatKind::Ref(pat, pinned, mutbl) => pat.to_ty().map(|ty| match pinned {
648 Pinnedness::Not => TyKind::Ref(None, MutTy { ty, mutbl: *mutbl }),
649 Pinnedness::Pinned => TyKind::PinnedRef(None, MutTy { ty, mutbl: *mutbl }),
650 })?,
651 PatKind::Slice(pats) if let [pat] = pats.as_slice() => {
654 pat.to_ty().map(TyKind::Slice)?
655 }
656 PatKind::Tuple(pats) => {
659 let mut tys = ThinVec::with_capacity(pats.len());
660 for pat in pats {
662 tys.push(pat.to_ty()?);
663 }
664 TyKind::Tup(tys)
665 }
666 _ => return None,
667 };
668
669 Some(Box::new(Ty { kind, id: self.id, span: self.span, tokens: None }))
670 }
671
672 pub fn walk<'ast>(&'ast self, it: &mut impl FnMut(&'ast Pat) -> bool) {
676 if !it(self) {
677 return;
678 }
679
680 match &self.kind {
681 PatKind::Ident(_, _, Some(p)) => p.walk(it),
683
684 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
686
687 PatKind::TupleStruct(_, _, s)
689 | PatKind::Tuple(s)
690 | PatKind::Slice(s)
691 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
692
693 PatKind::Box(s)
695 | PatKind::Deref(s)
696 | PatKind::Ref(s, _, _)
697 | PatKind::Paren(s)
698 | PatKind::Guard(s, _) => s.walk(it),
699
700 PatKind::Missing
702 | PatKind::Wild
703 | PatKind::Rest
704 | PatKind::Never
705 | PatKind::Expr(_)
706 | PatKind::Range(..)
707 | PatKind::Ident(..)
708 | PatKind::Path(..)
709 | PatKind::MacCall(_)
710 | PatKind::Err(_) => {}
711 }
712 }
713
714 pub fn peel_refs(&self) -> &Pat {
716 let mut current = self;
717 while let PatKind::Ref(inner, _, _) = ¤t.kind {
718 current = inner;
719 }
720 current
721 }
722
723 pub fn is_rest(&self) -> bool {
725 matches!(self.kind, PatKind::Rest)
726 }
727
728 pub fn could_be_never_pattern(&self) -> bool {
731 let mut could_be_never_pattern = false;
732 self.walk(&mut |pat| match &pat.kind {
733 PatKind::Never | PatKind::MacCall(_) => {
734 could_be_never_pattern = true;
735 false
736 }
737 PatKind::Or(s) => {
738 could_be_never_pattern = s.iter().all(|p| p.could_be_never_pattern());
739 false
740 }
741 _ => true,
742 });
743 could_be_never_pattern
744 }
745
746 pub fn contains_never_pattern(&self) -> bool {
749 let mut contains_never_pattern = false;
750 self.walk(&mut |pat| {
751 if matches!(pat.kind, PatKind::Never) {
752 contains_never_pattern = true;
753 }
754 true
755 });
756 contains_never_pattern
757 }
758
759 pub fn descr(&self) -> Option<String> {
761 match &self.kind {
762 PatKind::Missing => unreachable!(),
763 PatKind::Wild => Some("_".to_string()),
764 PatKind::Ident(BindingMode::NONE, ident, None) => Some(format!("{ident}")),
765 PatKind::Ref(pat, pinned, mutbl) => {
766 pat.descr().map(|d| format!("&{}{d}", pinned.prefix_str(*mutbl)))
767 }
768 _ => None,
769 }
770 }
771}
772
773impl From<Box<Pat>> for Pat {
774 fn from(value: Box<Pat>) -> Self {
775 *value
776 }
777}
778
779#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
785pub struct PatField {
786 pub ident: Ident,
788 pub pat: Box<Pat>,
790 pub is_shorthand: bool,
791 pub attrs: AttrVec,
792 pub id: NodeId,
793 pub span: Span,
794 pub is_placeholder: bool,
795}
796
797#[derive(Clone, Copy, Debug, Eq, PartialEq)]
798#[derive(Encodable, Decodable, HashStable_Generic, Walkable)]
799pub enum ByRef {
800 Yes(Pinnedness, Mutability),
801 No,
802}
803
804impl ByRef {
805 #[must_use]
806 pub fn cap_ref_mutability(mut self, mutbl: Mutability) -> Self {
807 if let ByRef::Yes(_, old_mutbl) = &mut self {
808 *old_mutbl = cmp::min(*old_mutbl, mutbl);
809 }
810 self
811 }
812}
813
814#[derive(Clone, Copy, Debug, Eq, PartialEq)]
820#[derive(Encodable, Decodable, HashStable_Generic, Walkable)]
821pub struct BindingMode(pub ByRef, pub Mutability);
822
823impl BindingMode {
824 pub const NONE: Self = Self(ByRef::No, Mutability::Not);
825 pub const REF: Self = Self(ByRef::Yes(Pinnedness::Not, Mutability::Not), Mutability::Not);
826 pub const REF_PIN: Self =
827 Self(ByRef::Yes(Pinnedness::Pinned, Mutability::Not), Mutability::Not);
828 pub const MUT: Self = Self(ByRef::No, Mutability::Mut);
829 pub const REF_MUT: Self = Self(ByRef::Yes(Pinnedness::Not, Mutability::Mut), Mutability::Not);
830 pub const REF_PIN_MUT: Self =
831 Self(ByRef::Yes(Pinnedness::Pinned, Mutability::Mut), Mutability::Not);
832 pub const MUT_REF: Self = Self(ByRef::Yes(Pinnedness::Not, Mutability::Not), Mutability::Mut);
833 pub const MUT_REF_PIN: Self =
834 Self(ByRef::Yes(Pinnedness::Pinned, Mutability::Not), Mutability::Mut);
835 pub const MUT_REF_MUT: Self =
836 Self(ByRef::Yes(Pinnedness::Not, Mutability::Mut), Mutability::Mut);
837 pub const MUT_REF_PIN_MUT: Self =
838 Self(ByRef::Yes(Pinnedness::Pinned, Mutability::Mut), Mutability::Mut);
839
840 pub fn prefix_str(self) -> &'static str {
841 match self {
842 Self::NONE => "",
843 Self::REF => "ref ",
844 Self::REF_PIN => "ref pin const ",
845 Self::MUT => "mut ",
846 Self::REF_MUT => "ref mut ",
847 Self::REF_PIN_MUT => "ref pin mut ",
848 Self::MUT_REF => "mut ref ",
849 Self::MUT_REF_PIN => "mut ref pin ",
850 Self::MUT_REF_MUT => "mut ref mut ",
851 Self::MUT_REF_PIN_MUT => "mut ref pin mut ",
852 }
853 }
854}
855
856#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
857pub enum RangeEnd {
858 Included(RangeSyntax),
860 Excluded,
862}
863
864#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
865pub enum RangeSyntax {
866 DotDotDot,
868 DotDotEq,
870}
871
872#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
876pub enum PatKind {
877 Missing,
879
880 Wild,
882
883 Ident(BindingMode, Ident, Option<Box<Pat>>),
888
889 Struct(Option<Box<QSelf>>, Path, ThinVec<PatField>, PatFieldsRest),
891
892 TupleStruct(Option<Box<QSelf>>, Path, ThinVec<Pat>),
894
895 Or(ThinVec<Pat>),
898
899 Path(Option<Box<QSelf>>, Path),
904
905 Tuple(ThinVec<Pat>),
907
908 Box(Box<Pat>),
910
911 Deref(Box<Pat>),
913
914 Ref(Box<Pat>, Pinnedness, Mutability),
916
917 Expr(Box<Expr>),
919
920 Range(Option<Box<Expr>>, Option<Box<Expr>>, Spanned<RangeEnd>),
922
923 Slice(ThinVec<Pat>),
925
926 Rest,
939
940 Never,
942
943 Guard(Box<Pat>, Box<Expr>),
945
946 Paren(Box<Pat>),
948
949 MacCall(Box<MacCall>),
951
952 Err(ErrorGuaranteed),
954}
955
956#[derive(Clone, Copy, Encodable, Decodable, Debug, PartialEq, Walkable)]
958pub enum PatFieldsRest {
959 Rest(Span),
961 Recovered(ErrorGuaranteed),
963 None,
965}
966
967#[derive(Clone, Copy, PartialEq, Eq, Debug)]
970#[derive(Encodable, Decodable, HashStable_Generic, Walkable)]
971pub enum BorrowKind {
972 Ref,
976 Raw,
980 Pin,
984}
985
986#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic, Walkable)]
987pub enum BinOpKind {
988 Add,
990 Sub,
992 Mul,
994 Div,
996 Rem,
998 And,
1000 Or,
1002 BitXor,
1004 BitAnd,
1006 BitOr,
1008 Shl,
1010 Shr,
1012 Eq,
1014 Lt,
1016 Le,
1018 Ne,
1020 Ge,
1022 Gt,
1024}
1025
1026impl BinOpKind {
1027 pub fn as_str(&self) -> &'static str {
1028 use BinOpKind::*;
1029 match self {
1030 Add => "+",
1031 Sub => "-",
1032 Mul => "*",
1033 Div => "/",
1034 Rem => "%",
1035 And => "&&",
1036 Or => "||",
1037 BitXor => "^",
1038 BitAnd => "&",
1039 BitOr => "|",
1040 Shl => "<<",
1041 Shr => ">>",
1042 Eq => "==",
1043 Lt => "<",
1044 Le => "<=",
1045 Ne => "!=",
1046 Ge => ">=",
1047 Gt => ">",
1048 }
1049 }
1050
1051 pub fn is_lazy(&self) -> bool {
1052 matches!(self, BinOpKind::And | BinOpKind::Or)
1053 }
1054
1055 pub fn precedence(&self) -> ExprPrecedence {
1056 use BinOpKind::*;
1057 match *self {
1058 Mul | Div | Rem => ExprPrecedence::Product,
1059 Add | Sub => ExprPrecedence::Sum,
1060 Shl | Shr => ExprPrecedence::Shift,
1061 BitAnd => ExprPrecedence::BitAnd,
1062 BitXor => ExprPrecedence::BitXor,
1063 BitOr => ExprPrecedence::BitOr,
1064 Lt | Gt | Le | Ge | Eq | Ne => ExprPrecedence::Compare,
1065 And => ExprPrecedence::LAnd,
1066 Or => ExprPrecedence::LOr,
1067 }
1068 }
1069
1070 pub fn fixity(&self) -> Fixity {
1071 use BinOpKind::*;
1072 match self {
1073 Eq | Ne | Lt | Le | Gt | Ge => Fixity::None,
1074 Add | Sub | Mul | Div | Rem | And | Or | BitXor | BitAnd | BitOr | Shl | Shr => {
1075 Fixity::Left
1076 }
1077 }
1078 }
1079
1080 pub fn is_comparison(self) -> bool {
1081 use BinOpKind::*;
1082 match self {
1083 Eq | Ne | Lt | Le | Gt | Ge => true,
1084 Add | Sub | Mul | Div | Rem | And | Or | BitXor | BitAnd | BitOr | Shl | Shr => false,
1085 }
1086 }
1087
1088 pub fn is_by_value(self) -> bool {
1090 !self.is_comparison()
1091 }
1092}
1093
1094pub type BinOp = Spanned<BinOpKind>;
1095
1096impl From<AssignOpKind> for BinOpKind {
1100 fn from(op: AssignOpKind) -> BinOpKind {
1101 match op {
1102 AssignOpKind::AddAssign => BinOpKind::Add,
1103 AssignOpKind::SubAssign => BinOpKind::Sub,
1104 AssignOpKind::MulAssign => BinOpKind::Mul,
1105 AssignOpKind::DivAssign => BinOpKind::Div,
1106 AssignOpKind::RemAssign => BinOpKind::Rem,
1107 AssignOpKind::BitXorAssign => BinOpKind::BitXor,
1108 AssignOpKind::BitAndAssign => BinOpKind::BitAnd,
1109 AssignOpKind::BitOrAssign => BinOpKind::BitOr,
1110 AssignOpKind::ShlAssign => BinOpKind::Shl,
1111 AssignOpKind::ShrAssign => BinOpKind::Shr,
1112 }
1113 }
1114}
1115
1116#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic, Walkable)]
1117pub enum AssignOpKind {
1118 AddAssign,
1120 SubAssign,
1122 MulAssign,
1124 DivAssign,
1126 RemAssign,
1128 BitXorAssign,
1130 BitAndAssign,
1132 BitOrAssign,
1134 ShlAssign,
1136 ShrAssign,
1138}
1139
1140impl AssignOpKind {
1141 pub fn as_str(&self) -> &'static str {
1142 use AssignOpKind::*;
1143 match self {
1144 AddAssign => "+=",
1145 SubAssign => "-=",
1146 MulAssign => "*=",
1147 DivAssign => "/=",
1148 RemAssign => "%=",
1149 BitXorAssign => "^=",
1150 BitAndAssign => "&=",
1151 BitOrAssign => "|=",
1152 ShlAssign => "<<=",
1153 ShrAssign => ">>=",
1154 }
1155 }
1156
1157 pub fn is_by_value(self) -> bool {
1159 true
1160 }
1161}
1162
1163pub type AssignOp = Spanned<AssignOpKind>;
1164
1165#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic, Walkable)]
1169pub enum UnOp {
1170 Deref,
1172 Not,
1174 Neg,
1176}
1177
1178impl UnOp {
1179 pub fn as_str(&self) -> &'static str {
1180 match self {
1181 UnOp::Deref => "*",
1182 UnOp::Not => "!",
1183 UnOp::Neg => "-",
1184 }
1185 }
1186
1187 pub fn is_by_value(self) -> bool {
1189 matches!(self, Self::Neg | Self::Not)
1190 }
1191}
1192
1193#[derive(Clone, Encodable, Decodable, Debug)]
1197pub struct Stmt {
1198 pub id: NodeId,
1199 pub kind: StmtKind,
1200 pub span: Span,
1201}
1202
1203impl Stmt {
1204 pub fn has_trailing_semicolon(&self) -> bool {
1205 match &self.kind {
1206 StmtKind::Semi(_) => true,
1207 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
1208 _ => false,
1209 }
1210 }
1211
1212 pub fn add_trailing_semicolon(mut self) -> Self {
1220 self.kind = match self.kind {
1221 StmtKind::Expr(expr) => StmtKind::Semi(expr),
1222 StmtKind::MacCall(mut mac) => {
1223 mac.style = MacStmtStyle::Semicolon;
1224 StmtKind::MacCall(mac)
1225 }
1226 kind => kind,
1227 };
1228
1229 self
1230 }
1231
1232 pub fn is_item(&self) -> bool {
1233 matches!(self.kind, StmtKind::Item(_))
1234 }
1235
1236 pub fn is_expr(&self) -> bool {
1237 matches!(self.kind, StmtKind::Expr(_))
1238 }
1239}
1240
1241#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1243pub enum StmtKind {
1244 Let(Box<Local>),
1246 Item(Box<Item>),
1248 Expr(Box<Expr>),
1250 Semi(Box<Expr>),
1252 Empty,
1254 MacCall(Box<MacCallStmt>),
1256}
1257
1258impl StmtKind {
1259 pub fn descr(&self) -> &'static str {
1260 match self {
1261 StmtKind::Let(_) => "local",
1262 StmtKind::Item(_) => "item",
1263 StmtKind::Expr(_) => "expression",
1264 StmtKind::Semi(_) => "statement",
1265 StmtKind::Empty => "semicolon",
1266 StmtKind::MacCall(_) => "macro call",
1267 }
1268 }
1269}
1270
1271#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1272pub struct MacCallStmt {
1273 pub mac: Box<MacCall>,
1274 pub style: MacStmtStyle,
1275 pub attrs: AttrVec,
1276 pub tokens: Option<LazyAttrTokenStream>,
1277}
1278
1279#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, Walkable)]
1280pub enum MacStmtStyle {
1281 Semicolon,
1284 Braces,
1286 NoBraces,
1290}
1291
1292#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1294pub struct Local {
1295 pub id: NodeId,
1296 pub super_: Option<Span>,
1297 pub pat: Box<Pat>,
1298 pub ty: Option<Box<Ty>>,
1299 pub kind: LocalKind,
1300 pub span: Span,
1301 pub colon_sp: Option<Span>,
1302 pub attrs: AttrVec,
1303 pub tokens: Option<LazyAttrTokenStream>,
1304}
1305
1306#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1307pub enum LocalKind {
1308 Decl,
1311 Init(Box<Expr>),
1314 InitElse(Box<Expr>, Box<Block>),
1317}
1318
1319impl LocalKind {
1320 pub fn init(&self) -> Option<&Expr> {
1321 match self {
1322 Self::Decl => None,
1323 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1324 }
1325 }
1326
1327 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1328 match self {
1329 Self::Decl => None,
1330 Self::Init(init) => Some((init, None)),
1331 Self::InitElse(init, els) => Some((init, Some(els))),
1332 }
1333 }
1334}
1335
1336#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1347pub struct Arm {
1348 pub attrs: AttrVec,
1349 pub pat: Box<Pat>,
1351 pub guard: Option<Box<Expr>>,
1353 pub body: Option<Box<Expr>>,
1355 pub span: Span,
1356 pub id: NodeId,
1357 pub is_placeholder: bool,
1358}
1359
1360#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1362pub struct ExprField {
1363 pub attrs: AttrVec,
1364 pub id: NodeId,
1365 pub span: Span,
1366 pub ident: Ident,
1367 pub expr: Box<Expr>,
1368 pub is_shorthand: bool,
1369 pub is_placeholder: bool,
1370}
1371
1372#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Walkable)]
1373pub enum BlockCheckMode {
1374 Default,
1375 Unsafe(UnsafeSource),
1376}
1377
1378#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Walkable)]
1379pub enum UnsafeSource {
1380 CompilerGenerated,
1381 UserProvided,
1382}
1383
1384#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Walkable)]
1388pub enum MgcaDisambiguation {
1389 AnonConst,
1390 Direct,
1391}
1392
1393#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1399pub struct AnonConst {
1400 pub id: NodeId,
1401 pub value: Box<Expr>,
1402 pub mgca_disambiguation: MgcaDisambiguation,
1403}
1404
1405#[derive(Clone, Encodable, Decodable, Debug)]
1407pub struct Expr {
1408 pub id: NodeId,
1409 pub kind: ExprKind,
1410 pub span: Span,
1411 pub attrs: AttrVec,
1412 pub tokens: Option<LazyAttrTokenStream>,
1413}
1414
1415impl Expr {
1416 pub fn is_potential_trivial_const_arg(&self) -> bool {
1428 let this = self.maybe_unwrap_block();
1429 if let ExprKind::Path(None, path) = &this.kind
1430 && path.is_potential_trivial_const_arg()
1431 {
1432 true
1433 } else {
1434 false
1435 }
1436 }
1437
1438 pub fn maybe_unwrap_block(&self) -> &Expr {
1440 if let ExprKind::Block(block, None) = &self.kind
1441 && let [stmt] = block.stmts.as_slice()
1442 && let StmtKind::Expr(expr) = &stmt.kind
1443 {
1444 expr
1445 } else {
1446 self
1447 }
1448 }
1449
1450 pub fn optionally_braced_mac_call(
1456 &self,
1457 already_stripped_block: bool,
1458 ) -> Option<(bool, NodeId)> {
1459 match &self.kind {
1460 ExprKind::Block(block, None)
1461 if let [stmt] = &*block.stmts
1462 && !already_stripped_block =>
1463 {
1464 match &stmt.kind {
1465 StmtKind::MacCall(_) => Some((true, stmt.id)),
1466 StmtKind::Expr(expr) if let ExprKind::MacCall(_) = &expr.kind => {
1467 Some((true, expr.id))
1468 }
1469 _ => None,
1470 }
1471 }
1472 ExprKind::MacCall(_) => Some((already_stripped_block, self.id)),
1473 _ => None,
1474 }
1475 }
1476
1477 pub fn to_bound(&self) -> Option<GenericBound> {
1478 match &self.kind {
1479 ExprKind::Path(None, path) => Some(GenericBound::Trait(PolyTraitRef::new(
1480 ThinVec::new(),
1481 path.clone(),
1482 TraitBoundModifiers::NONE,
1483 self.span,
1484 Parens::No,
1485 ))),
1486 _ => None,
1487 }
1488 }
1489
1490 pub fn peel_parens(&self) -> &Expr {
1491 let mut expr = self;
1492 while let ExprKind::Paren(inner) = &expr.kind {
1493 expr = inner;
1494 }
1495 expr
1496 }
1497
1498 pub fn peel_parens_and_refs(&self) -> &Expr {
1499 let mut expr = self;
1500 while let ExprKind::Paren(inner) | ExprKind::AddrOf(BorrowKind::Ref, _, inner) = &expr.kind
1501 {
1502 expr = inner;
1503 }
1504 expr
1505 }
1506
1507 pub fn to_ty(&self) -> Option<Box<Ty>> {
1509 let kind = match &self.kind {
1510 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1512 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1513
1514 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1515
1516 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1517 expr.to_ty().map(|ty| TyKind::Ref(None, MutTy { ty, mutbl: *mutbl }))?
1518 }
1519
1520 ExprKind::Repeat(expr, expr_len) => {
1521 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1522 }
1523
1524 ExprKind::Array(exprs) if let [expr] = exprs.as_slice() => {
1525 expr.to_ty().map(TyKind::Slice)?
1526 }
1527
1528 ExprKind::Tup(exprs) => {
1529 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<ThinVec<_>>>()?;
1530 TyKind::Tup(tys)
1531 }
1532
1533 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1537 let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) else {
1538 return None;
1539 };
1540 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1541 }
1542
1543 ExprKind::Underscore => TyKind::Infer,
1544
1545 _ => return None,
1547 };
1548
1549 Some(Box::new(Ty { kind, id: self.id, span: self.span, tokens: None }))
1550 }
1551
1552 pub fn precedence(&self) -> ExprPrecedence {
1553 fn prefix_attrs_precedence(attrs: &AttrVec) -> ExprPrecedence {
1554 for attr in attrs {
1555 if let AttrStyle::Outer = attr.style {
1556 return ExprPrecedence::Prefix;
1557 }
1558 }
1559 ExprPrecedence::Unambiguous
1560 }
1561
1562 match &self.kind {
1563 ExprKind::Closure(closure) => {
1564 match closure.fn_decl.output {
1565 FnRetTy::Default(_) => ExprPrecedence::Jump,
1566 FnRetTy::Ty(_) => prefix_attrs_precedence(&self.attrs),
1567 }
1568 }
1569
1570 ExprKind::Break(_ , value)
1571 | ExprKind::Ret(value)
1572 | ExprKind::Yield(YieldKind::Prefix(value))
1573 | ExprKind::Yeet(value) => match value {
1574 Some(_) => ExprPrecedence::Jump,
1575 None => prefix_attrs_precedence(&self.attrs),
1576 },
1577
1578 ExprKind::Become(_) => ExprPrecedence::Jump,
1579
1580 ExprKind::Range(..) => ExprPrecedence::Range,
1585
1586 ExprKind::Binary(op, ..) => op.node.precedence(),
1588 ExprKind::Cast(..) => ExprPrecedence::Cast,
1589
1590 ExprKind::Assign(..) |
1591 ExprKind::AssignOp(..) => ExprPrecedence::Assign,
1592
1593 ExprKind::AddrOf(..)
1595 | ExprKind::Let(..)
1600 | ExprKind::Unary(..) => ExprPrecedence::Prefix,
1601
1602 ExprKind::Array(_)
1604 | ExprKind::Await(..)
1605 | ExprKind::Use(..)
1606 | ExprKind::Block(..)
1607 | ExprKind::Call(..)
1608 | ExprKind::ConstBlock(_)
1609 | ExprKind::Continue(..)
1610 | ExprKind::Field(..)
1611 | ExprKind::ForLoop { .. }
1612 | ExprKind::FormatArgs(..)
1613 | ExprKind::Gen(..)
1614 | ExprKind::If(..)
1615 | ExprKind::IncludedBytes(..)
1616 | ExprKind::Index(..)
1617 | ExprKind::InlineAsm(..)
1618 | ExprKind::Lit(_)
1619 | ExprKind::Loop(..)
1620 | ExprKind::MacCall(..)
1621 | ExprKind::Match(..)
1622 | ExprKind::MethodCall(..)
1623 | ExprKind::OffsetOf(..)
1624 | ExprKind::Paren(..)
1625 | ExprKind::Path(..)
1626 | ExprKind::Repeat(..)
1627 | ExprKind::Struct(..)
1628 | ExprKind::Try(..)
1629 | ExprKind::TryBlock(..)
1630 | ExprKind::Tup(_)
1631 | ExprKind::Type(..)
1632 | ExprKind::Underscore
1633 | ExprKind::UnsafeBinderCast(..)
1634 | ExprKind::While(..)
1635 | ExprKind::Yield(YieldKind::Postfix(..))
1636 | ExprKind::Err(_)
1637 | ExprKind::Dummy => prefix_attrs_precedence(&self.attrs),
1638 }
1639 }
1640
1641 pub fn is_approximately_pattern(&self) -> bool {
1643 matches!(
1644 &self.peel_parens().kind,
1645 ExprKind::Array(_)
1646 | ExprKind::Call(_, _)
1647 | ExprKind::Tup(_)
1648 | ExprKind::Lit(_)
1649 | ExprKind::Range(_, _, _)
1650 | ExprKind::Underscore
1651 | ExprKind::Path(_, _)
1652 | ExprKind::Struct(_)
1653 )
1654 }
1655
1656 pub fn dummy() -> Expr {
1660 Expr {
1661 id: DUMMY_NODE_ID,
1662 kind: ExprKind::Dummy,
1663 span: DUMMY_SP,
1664 attrs: ThinVec::new(),
1665 tokens: None,
1666 }
1667 }
1668}
1669
1670impl From<Box<Expr>> for Expr {
1671 fn from(value: Box<Expr>) -> Self {
1672 *value
1673 }
1674}
1675
1676#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1677pub struct Closure {
1678 pub binder: ClosureBinder,
1679 pub capture_clause: CaptureBy,
1680 pub constness: Const,
1681 pub coroutine_kind: Option<CoroutineKind>,
1682 pub movability: Movability,
1683 pub fn_decl: Box<FnDecl>,
1684 pub body: Box<Expr>,
1685 pub fn_decl_span: Span,
1687 pub fn_arg_span: Span,
1689}
1690
1691#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, Walkable)]
1693pub enum RangeLimits {
1694 HalfOpen,
1696 Closed,
1698}
1699
1700impl RangeLimits {
1701 pub fn as_str(&self) -> &'static str {
1702 match self {
1703 RangeLimits::HalfOpen => "..",
1704 RangeLimits::Closed => "..=",
1705 }
1706 }
1707}
1708
1709#[derive(Clone, Encodable, Decodable, Debug)]
1711pub struct MethodCall {
1712 pub seg: PathSegment,
1714 pub receiver: Box<Expr>,
1716 pub args: ThinVec<Box<Expr>>,
1718 pub span: Span,
1721}
1722
1723#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1724pub enum StructRest {
1725 Base(Box<Expr>),
1727 Rest(Span),
1729 None,
1731}
1732
1733#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1734pub struct StructExpr {
1735 pub qself: Option<Box<QSelf>>,
1736 pub path: Path,
1737 pub fields: ThinVec<ExprField>,
1738 pub rest: StructRest,
1739}
1740
1741#[derive(Clone, Encodable, Decodable, Debug)]
1743pub enum ExprKind {
1744 Array(ThinVec<Box<Expr>>),
1746 ConstBlock(AnonConst),
1748 Call(Box<Expr>, ThinVec<Box<Expr>>),
1755 MethodCall(Box<MethodCall>),
1757 Tup(ThinVec<Box<Expr>>),
1759 Binary(BinOp, Box<Expr>, Box<Expr>),
1761 Unary(UnOp, Box<Expr>),
1763 Lit(token::Lit),
1765 Cast(Box<Expr>, Box<Ty>),
1767 Type(Box<Expr>, Box<Ty>),
1772 Let(Box<Pat>, Box<Expr>, Span, Recovered),
1777 If(Box<Expr>, Box<Block>, Option<Box<Expr>>),
1784 While(Box<Expr>, Box<Block>, Option<Label>),
1788 ForLoop {
1794 pat: Box<Pat>,
1795 iter: Box<Expr>,
1796 body: Box<Block>,
1797 label: Option<Label>,
1798 kind: ForLoopKind,
1799 },
1800 Loop(Box<Block>, Option<Label>, Span),
1804 Match(Box<Expr>, ThinVec<Arm>, MatchKind),
1806 Closure(Box<Closure>),
1808 Block(Box<Block>, Option<Label>),
1810 Gen(CaptureBy, Box<Block>, GenBlockKind, Span),
1816 Await(Box<Expr>, Span),
1818 Use(Box<Expr>, Span),
1820
1821 TryBlock(Box<Block>, Option<Box<Ty>>),
1829
1830 Assign(Box<Expr>, Box<Expr>, Span),
1833 AssignOp(AssignOp, Box<Expr>, Box<Expr>),
1837 Field(Box<Expr>, Ident),
1839 Index(Box<Expr>, Box<Expr>, Span),
1842 Range(Option<Box<Expr>>, Option<Box<Expr>>, RangeLimits),
1844 Underscore,
1846
1847 Path(Option<Box<QSelf>>, Path),
1852
1853 AddrOf(BorrowKind, Mutability, Box<Expr>),
1855 Break(Option<Label>, Option<Box<Expr>>),
1857 Continue(Option<Label>),
1859 Ret(Option<Box<Expr>>),
1861
1862 InlineAsm(Box<InlineAsm>),
1864
1865 OffsetOf(Box<Ty>, Vec<Ident>),
1870
1871 MacCall(Box<MacCall>),
1873
1874 Struct(Box<StructExpr>),
1878
1879 Repeat(Box<Expr>, AnonConst),
1884
1885 Paren(Box<Expr>),
1887
1888 Try(Box<Expr>),
1890
1891 Yield(YieldKind),
1893
1894 Yeet(Option<Box<Expr>>),
1897
1898 Become(Box<Expr>),
1902
1903 IncludedBytes(ByteSymbol),
1915
1916 FormatArgs(Box<FormatArgs>),
1918
1919 UnsafeBinderCast(UnsafeBinderCastKind, Box<Expr>, Option<Box<Ty>>),
1920
1921 Err(ErrorGuaranteed),
1923
1924 Dummy,
1926}
1927
1928#[derive(Clone, Copy, Encodable, Decodable, Debug, PartialEq, Eq, Walkable)]
1930pub enum ForLoopKind {
1931 For,
1932 ForAwait,
1933}
1934
1935#[derive(Clone, Copy, Encodable, Decodable, Debug, PartialEq, Eq, Walkable)]
1937pub enum GenBlockKind {
1938 Async,
1939 Gen,
1940 AsyncGen,
1941}
1942
1943impl fmt::Display for GenBlockKind {
1944 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1945 self.modifier().fmt(f)
1946 }
1947}
1948
1949impl GenBlockKind {
1950 pub fn modifier(&self) -> &'static str {
1951 match self {
1952 GenBlockKind::Async => "async",
1953 GenBlockKind::Gen => "gen",
1954 GenBlockKind::AsyncGen => "async gen",
1955 }
1956 }
1957}
1958
1959#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1961#[derive(Encodable, Decodable, HashStable_Generic, Walkable)]
1962pub enum UnsafeBinderCastKind {
1963 Wrap,
1965 Unwrap,
1967}
1968
1969#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
1984pub struct QSelf {
1985 pub ty: Box<Ty>,
1986
1987 pub path_span: Span,
1991 pub position: usize,
1992}
1993
1994#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
1996pub enum CaptureBy {
1997 Value {
1999 move_kw: Span,
2001 },
2002 Ref,
2004 Use {
2010 use_kw: Span,
2012 },
2013}
2014
2015#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2017pub enum ClosureBinder {
2018 NotPresent,
2020 For {
2022 span: Span,
2029
2030 generic_params: ThinVec<GenericParam>,
2037 },
2038}
2039
2040#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2043pub struct MacCall {
2044 pub path: Path,
2045 pub args: Box<DelimArgs>,
2046}
2047
2048impl MacCall {
2049 pub fn span(&self) -> Span {
2050 self.path.span.to(self.args.dspan.entire())
2051 }
2052}
2053
2054#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2056pub enum AttrArgs {
2057 Empty,
2059 Delimited(DelimArgs),
2061 Eq {
2063 eq_span: Span,
2065 expr: Box<Expr>,
2066 },
2067}
2068
2069impl AttrArgs {
2070 pub fn span(&self) -> Option<Span> {
2071 match self {
2072 AttrArgs::Empty => None,
2073 AttrArgs::Delimited(args) => Some(args.dspan.entire()),
2074 AttrArgs::Eq { eq_span, expr } => Some(eq_span.to(expr.span)),
2075 }
2076 }
2077
2078 pub fn inner_tokens(&self) -> TokenStream {
2081 match self {
2082 AttrArgs::Empty => TokenStream::default(),
2083 AttrArgs::Delimited(args) => args.tokens.clone(),
2084 AttrArgs::Eq { expr, .. } => TokenStream::from_ast(expr),
2085 }
2086 }
2087}
2088
2089#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
2091pub struct DelimArgs {
2092 pub dspan: DelimSpan,
2093 pub delim: Delimiter, pub tokens: TokenStream,
2095}
2096
2097impl DelimArgs {
2098 pub fn need_semicolon(&self) -> bool {
2101 !matches!(self, DelimArgs { delim: Delimiter::Brace, .. })
2102 }
2103}
2104
2105#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
2107pub struct MacroDef {
2108 pub body: Box<DelimArgs>,
2109 pub macro_rules: bool,
2111
2112 pub eii_extern_target: Option<EiiExternTarget>,
2116}
2117
2118#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
2119pub struct EiiExternTarget {
2120 pub extern_item_path: Path,
2122 pub impl_unsafe: bool,
2123 pub span: Span,
2124}
2125
2126#[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
2127#[derive(HashStable_Generic, Walkable)]
2128pub enum StrStyle {
2129 Cooked,
2131 Raw(u8),
2135}
2136
2137#[derive(Clone, Copy, Encodable, Decodable, Debug, PartialEq, Walkable)]
2139pub enum MatchKind {
2140 Prefix,
2142 Postfix,
2144}
2145
2146#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2148pub enum YieldKind {
2149 Prefix(Option<Box<Expr>>),
2151 Postfix(Box<Expr>),
2153}
2154
2155impl YieldKind {
2156 pub const fn expr(&self) -> Option<&Box<Expr>> {
2160 match self {
2161 YieldKind::Prefix(expr) => expr.as_ref(),
2162 YieldKind::Postfix(expr) => Some(expr),
2163 }
2164 }
2165
2166 pub const fn expr_mut(&mut self) -> Option<&mut Box<Expr>> {
2168 match self {
2169 YieldKind::Prefix(expr) => expr.as_mut(),
2170 YieldKind::Postfix(expr) => Some(expr),
2171 }
2172 }
2173
2174 pub const fn same_kind(&self, other: &Self) -> bool {
2176 match (self, other) {
2177 (YieldKind::Prefix(_), YieldKind::Prefix(_)) => true,
2178 (YieldKind::Postfix(_), YieldKind::Postfix(_)) => true,
2179 _ => false,
2180 }
2181 }
2182}
2183
2184#[derive(Clone, Copy, Encodable, Decodable, Debug, HashStable_Generic)]
2186pub struct MetaItemLit {
2187 pub symbol: Symbol,
2189 pub suffix: Option<Symbol>,
2191 pub kind: LitKind,
2194 pub span: Span,
2195}
2196
2197#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
2199pub struct StrLit {
2200 pub symbol: Symbol,
2202 pub suffix: Option<Symbol>,
2204 pub symbol_unescaped: Symbol,
2206 pub style: StrStyle,
2207 pub span: Span,
2208}
2209
2210impl StrLit {
2211 pub fn as_token_lit(&self) -> token::Lit {
2212 let token_kind = match self.style {
2213 StrStyle::Cooked => token::Str,
2214 StrStyle::Raw(n) => token::StrRaw(n),
2215 };
2216 token::Lit::new(token_kind, self.symbol, self.suffix)
2217 }
2218}
2219
2220#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
2222#[derive(HashStable_Generic)]
2223pub enum LitIntType {
2224 Signed(IntTy),
2226 Unsigned(UintTy),
2228 Unsuffixed,
2230}
2231
2232#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
2234#[derive(HashStable_Generic)]
2235pub enum LitFloatType {
2236 Suffixed(FloatTy),
2238 Unsuffixed,
2240}
2241
2242#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
2249pub enum LitKind {
2250 Str(Symbol, StrStyle),
2253 ByteStr(ByteSymbol, StrStyle),
2256 CStr(ByteSymbol, StrStyle),
2260 Byte(u8),
2262 Char(char),
2264 Int(Pu128, LitIntType),
2266 Float(Symbol, LitFloatType),
2270 Bool(bool),
2272 Err(ErrorGuaranteed),
2274}
2275
2276impl LitKind {
2277 pub fn str(&self) -> Option<Symbol> {
2278 match *self {
2279 LitKind::Str(s, _) => Some(s),
2280 _ => None,
2281 }
2282 }
2283
2284 pub fn is_str(&self) -> bool {
2286 matches!(self, LitKind::Str(..))
2287 }
2288
2289 pub fn is_bytestr(&self) -> bool {
2291 matches!(self, LitKind::ByteStr(..))
2292 }
2293
2294 pub fn is_numeric(&self) -> bool {
2296 matches!(self, LitKind::Int(..) | LitKind::Float(..))
2297 }
2298
2299 pub fn is_unsuffixed(&self) -> bool {
2302 !self.is_suffixed()
2303 }
2304
2305 pub fn is_suffixed(&self) -> bool {
2307 match *self {
2308 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
2310 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
2311 LitKind::Str(..)
2313 | LitKind::ByteStr(..)
2314 | LitKind::CStr(..)
2315 | LitKind::Byte(..)
2316 | LitKind::Char(..)
2317 | LitKind::Int(_, LitIntType::Unsuffixed)
2318 | LitKind::Float(_, LitFloatType::Unsuffixed)
2319 | LitKind::Bool(..)
2320 | LitKind::Err(_) => false,
2321 }
2322 }
2323}
2324
2325#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2328pub struct MutTy {
2329 pub ty: Box<Ty>,
2330 pub mutbl: Mutability,
2331}
2332
2333#[derive(Clone, Encodable, Decodable, Debug)]
2336pub struct FnSig {
2337 pub header: FnHeader,
2338 pub decl: Box<FnDecl>,
2339 pub span: Span,
2340}
2341
2342impl FnSig {
2343 pub fn header_span(&self) -> Span {
2345 match self.header.ext {
2346 Extern::Implicit(span) | Extern::Explicit(_, span) => {
2347 return self.span.with_hi(span.hi());
2348 }
2349 Extern::None => {}
2350 }
2351
2352 match self.header.safety {
2353 Safety::Unsafe(span) | Safety::Safe(span) => return self.span.with_hi(span.hi()),
2354 Safety::Default => {}
2355 };
2356
2357 if let Some(coroutine_kind) = self.header.coroutine_kind {
2358 return self.span.with_hi(coroutine_kind.span().hi());
2359 }
2360
2361 if let Const::Yes(span) = self.header.constness {
2362 return self.span.with_hi(span.hi());
2363 }
2364
2365 self.span.shrink_to_lo()
2366 }
2367
2368 pub fn safety_span(&self) -> Span {
2370 match self.header.safety {
2371 Safety::Unsafe(span) | Safety::Safe(span) => span,
2372 Safety::Default => {
2373 if let Some(extern_span) = self.header.ext.span() {
2375 return extern_span.shrink_to_lo();
2376 }
2377
2378 self.header_span().shrink_to_hi()
2380 }
2381 }
2382 }
2383
2384 pub fn extern_span(&self) -> Span {
2386 self.header.ext.span().unwrap_or(self.safety_span().shrink_to_hi())
2387 }
2388}
2389
2390#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2401pub struct AssocItemConstraint {
2402 pub id: NodeId,
2403 pub ident: Ident,
2404 pub gen_args: Option<GenericArgs>,
2405 pub kind: AssocItemConstraintKind,
2406 pub span: Span,
2407}
2408
2409#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2410pub enum Term {
2411 Ty(Box<Ty>),
2412 Const(AnonConst),
2413}
2414
2415impl From<Box<Ty>> for Term {
2416 fn from(v: Box<Ty>) -> Self {
2417 Term::Ty(v)
2418 }
2419}
2420
2421impl From<AnonConst> for Term {
2422 fn from(v: AnonConst) -> Self {
2423 Term::Const(v)
2424 }
2425}
2426
2427#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2429pub enum AssocItemConstraintKind {
2430 Equality { term: Term },
2437 Bound {
2439 #[visitable(extra = BoundKind::Bound)]
2440 bounds: GenericBounds,
2441 },
2442}
2443
2444#[derive(Encodable, Decodable, Debug, Walkable)]
2445pub struct Ty {
2446 pub id: NodeId,
2447 pub kind: TyKind,
2448 pub span: Span,
2449 pub tokens: Option<LazyAttrTokenStream>,
2450}
2451
2452impl Clone for Ty {
2453 fn clone(&self) -> Self {
2454 ensure_sufficient_stack(|| Self {
2455 id: self.id,
2456 kind: self.kind.clone(),
2457 span: self.span,
2458 tokens: self.tokens.clone(),
2459 })
2460 }
2461}
2462
2463impl From<Box<Ty>> for Ty {
2464 fn from(value: Box<Ty>) -> Self {
2465 *value
2466 }
2467}
2468
2469impl Ty {
2470 pub fn peel_refs(&self) -> &Self {
2471 let mut final_ty = self;
2472 while let TyKind::Ref(_, MutTy { ty, .. }) | TyKind::Ptr(MutTy { ty, .. }) = &final_ty.kind
2473 {
2474 final_ty = ty;
2475 }
2476 final_ty
2477 }
2478
2479 pub fn is_maybe_parenthesised_infer(&self) -> bool {
2480 match &self.kind {
2481 TyKind::Infer => true,
2482 TyKind::Paren(inner) => inner.is_maybe_parenthesised_infer(),
2483 _ => false,
2484 }
2485 }
2486}
2487
2488#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2489pub struct FnPtrTy {
2490 pub safety: Safety,
2491 pub ext: Extern,
2492 pub generic_params: ThinVec<GenericParam>,
2493 pub decl: Box<FnDecl>,
2494 pub decl_span: Span,
2497}
2498
2499#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2500pub struct UnsafeBinderTy {
2501 pub generic_params: ThinVec<GenericParam>,
2502 pub inner_ty: Box<Ty>,
2503}
2504
2505#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2509pub enum TyKind {
2510 Slice(Box<Ty>),
2512 Array(Box<Ty>, AnonConst),
2514 Ptr(MutTy),
2516 Ref(#[visitable(extra = LifetimeCtxt::Ref)] Option<Lifetime>, MutTy),
2518 PinnedRef(#[visitable(extra = LifetimeCtxt::Ref)] Option<Lifetime>, MutTy),
2522 FnPtr(Box<FnPtrTy>),
2524 UnsafeBinder(Box<UnsafeBinderTy>),
2526 Never,
2528 Tup(ThinVec<Box<Ty>>),
2530 Path(Option<Box<QSelf>>, Path),
2535 TraitObject(#[visitable(extra = BoundKind::TraitObject)] GenericBounds, TraitObjectSyntax),
2538 ImplTrait(NodeId, #[visitable(extra = BoundKind::Impl)] GenericBounds),
2545 Paren(Box<Ty>),
2547 Infer,
2550 ImplicitSelf,
2552 MacCall(Box<MacCall>),
2554 CVarArgs,
2556 Pat(Box<Ty>, Box<TyPat>),
2559 Dummy,
2561 Err(ErrorGuaranteed),
2563}
2564
2565impl TyKind {
2566 pub fn is_implicit_self(&self) -> bool {
2567 matches!(self, TyKind::ImplicitSelf)
2568 }
2569
2570 pub fn is_unit(&self) -> bool {
2571 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2572 }
2573
2574 pub fn is_simple_path(&self) -> Option<Symbol> {
2575 if let TyKind::Path(None, Path { segments, .. }) = &self
2576 && let [segment] = &segments[..]
2577 && segment.args.is_none()
2578 {
2579 Some(segment.ident.name)
2580 } else {
2581 None
2582 }
2583 }
2584
2585 pub fn maybe_scalar(&self) -> bool {
2593 let Some(ty_sym) = self.is_simple_path() else {
2594 return self.is_unit();
2596 };
2597 matches!(
2598 ty_sym,
2599 sym::i8
2600 | sym::i16
2601 | sym::i32
2602 | sym::i64
2603 | sym::i128
2604 | sym::u8
2605 | sym::u16
2606 | sym::u32
2607 | sym::u64
2608 | sym::u128
2609 | sym::f16
2610 | sym::f32
2611 | sym::f64
2612 | sym::f128
2613 | sym::char
2614 | sym::bool
2615 )
2616 }
2617}
2618
2619#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2621pub struct TyPat {
2622 pub id: NodeId,
2623 pub kind: TyPatKind,
2624 pub span: Span,
2625 pub tokens: Option<LazyAttrTokenStream>,
2626}
2627
2628#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2632pub enum TyPatKind {
2633 Range(Option<Box<AnonConst>>, Option<Box<AnonConst>>, Spanned<RangeEnd>),
2635
2636 NotNull,
2638
2639 Or(ThinVec<TyPat>),
2640
2641 Err(ErrorGuaranteed),
2643}
2644
2645#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
2647#[repr(u8)]
2648pub enum TraitObjectSyntax {
2649 Dyn = 0,
2651 None = 1,
2652}
2653
2654unsafe impl Tag for TraitObjectSyntax {
2658 const BITS: u32 = 2;
2659
2660 fn into_usize(self) -> usize {
2661 self as u8 as usize
2662 }
2663
2664 unsafe fn from_usize(tag: usize) -> Self {
2665 match tag {
2666 0 => TraitObjectSyntax::Dyn,
2667 1 => TraitObjectSyntax::None,
2668 _ => unreachable!(),
2669 }
2670 }
2671}
2672
2673#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2674pub enum PreciseCapturingArg {
2675 Lifetime(#[visitable(extra = LifetimeCtxt::GenericArg)] Lifetime),
2677 Arg(Path, NodeId),
2679}
2680
2681#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
2685pub enum InlineAsmRegOrRegClass {
2686 Reg(Symbol),
2687 RegClass(Symbol),
2688}
2689
2690#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)]
2691pub struct InlineAsmOptions(u16);
2692bitflags::bitflags! {
2693 impl InlineAsmOptions: u16 {
2694 const PURE = 1 << 0;
2695 const NOMEM = 1 << 1;
2696 const READONLY = 1 << 2;
2697 const PRESERVES_FLAGS = 1 << 3;
2698 const NORETURN = 1 << 4;
2699 const NOSTACK = 1 << 5;
2700 const ATT_SYNTAX = 1 << 6;
2701 const RAW = 1 << 7;
2702 const MAY_UNWIND = 1 << 8;
2703 }
2704}
2705
2706impl InlineAsmOptions {
2707 pub const COUNT: usize = Self::all().bits().count_ones() as usize;
2708
2709 pub const GLOBAL_OPTIONS: Self = Self::ATT_SYNTAX.union(Self::RAW);
2710 pub const NAKED_OPTIONS: Self = Self::ATT_SYNTAX.union(Self::RAW);
2711
2712 pub fn human_readable_names(&self) -> Vec<&'static str> {
2713 let mut options = vec![];
2714
2715 if self.contains(InlineAsmOptions::PURE) {
2716 options.push("pure");
2717 }
2718 if self.contains(InlineAsmOptions::NOMEM) {
2719 options.push("nomem");
2720 }
2721 if self.contains(InlineAsmOptions::READONLY) {
2722 options.push("readonly");
2723 }
2724 if self.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2725 options.push("preserves_flags");
2726 }
2727 if self.contains(InlineAsmOptions::NORETURN) {
2728 options.push("noreturn");
2729 }
2730 if self.contains(InlineAsmOptions::NOSTACK) {
2731 options.push("nostack");
2732 }
2733 if self.contains(InlineAsmOptions::ATT_SYNTAX) {
2734 options.push("att_syntax");
2735 }
2736 if self.contains(InlineAsmOptions::RAW) {
2737 options.push("raw");
2738 }
2739 if self.contains(InlineAsmOptions::MAY_UNWIND) {
2740 options.push("may_unwind");
2741 }
2742
2743 options
2744 }
2745}
2746
2747impl std::fmt::Debug for InlineAsmOptions {
2748 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2749 bitflags::parser::to_writer(self, f)
2750 }
2751}
2752
2753#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic, Walkable)]
2754pub enum InlineAsmTemplatePiece {
2755 String(Cow<'static, str>),
2756 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2757}
2758
2759impl fmt::Display for InlineAsmTemplatePiece {
2760 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2761 match self {
2762 Self::String(s) => {
2763 for c in s.chars() {
2764 match c {
2765 '{' => f.write_str("{{")?,
2766 '}' => f.write_str("}}")?,
2767 _ => c.fmt(f)?,
2768 }
2769 }
2770 Ok(())
2771 }
2772 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2773 write!(f, "{{{operand_idx}:{modifier}}}")
2774 }
2775 Self::Placeholder { operand_idx, modifier: None, .. } => {
2776 write!(f, "{{{operand_idx}}}")
2777 }
2778 }
2779 }
2780}
2781
2782impl InlineAsmTemplatePiece {
2783 pub fn to_string(s: &[Self]) -> String {
2785 use fmt::Write;
2786 let mut out = String::new();
2787 for p in s.iter() {
2788 let _ = write!(out, "{p}");
2789 }
2790 out
2791 }
2792}
2793
2794#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2802pub struct InlineAsmSym {
2803 pub id: NodeId,
2804 pub qself: Option<Box<QSelf>>,
2805 pub path: Path,
2806}
2807
2808#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2812pub enum InlineAsmOperand {
2813 In {
2814 reg: InlineAsmRegOrRegClass,
2815 expr: Box<Expr>,
2816 },
2817 Out {
2818 reg: InlineAsmRegOrRegClass,
2819 late: bool,
2820 expr: Option<Box<Expr>>,
2821 },
2822 InOut {
2823 reg: InlineAsmRegOrRegClass,
2824 late: bool,
2825 expr: Box<Expr>,
2826 },
2827 SplitInOut {
2828 reg: InlineAsmRegOrRegClass,
2829 late: bool,
2830 in_expr: Box<Expr>,
2831 out_expr: Option<Box<Expr>>,
2832 },
2833 Const {
2834 anon_const: AnonConst,
2835 },
2836 Sym {
2837 sym: InlineAsmSym,
2838 },
2839 Label {
2840 block: Box<Block>,
2841 },
2842}
2843
2844impl InlineAsmOperand {
2845 pub fn reg(&self) -> Option<&InlineAsmRegOrRegClass> {
2846 match self {
2847 Self::In { reg, .. }
2848 | Self::Out { reg, .. }
2849 | Self::InOut { reg, .. }
2850 | Self::SplitInOut { reg, .. } => Some(reg),
2851 Self::Const { .. } | Self::Sym { .. } | Self::Label { .. } => None,
2852 }
2853 }
2854}
2855
2856#[derive(Clone, Copy, Encodable, Decodable, Debug, HashStable_Generic, Walkable, PartialEq, Eq)]
2857pub enum AsmMacro {
2858 Asm,
2860 GlobalAsm,
2862 NakedAsm,
2864}
2865
2866impl AsmMacro {
2867 pub const fn macro_name(self) -> &'static str {
2868 match self {
2869 AsmMacro::Asm => "asm",
2870 AsmMacro::GlobalAsm => "global_asm",
2871 AsmMacro::NakedAsm => "naked_asm",
2872 }
2873 }
2874
2875 pub const fn is_supported_option(self, option: InlineAsmOptions) -> bool {
2876 match self {
2877 AsmMacro::Asm => true,
2878 AsmMacro::GlobalAsm => InlineAsmOptions::GLOBAL_OPTIONS.contains(option),
2879 AsmMacro::NakedAsm => InlineAsmOptions::NAKED_OPTIONS.contains(option),
2880 }
2881 }
2882
2883 pub const fn diverges(self, options: InlineAsmOptions) -> bool {
2884 match self {
2885 AsmMacro::Asm => options.contains(InlineAsmOptions::NORETURN),
2886 AsmMacro::GlobalAsm => true,
2887 AsmMacro::NakedAsm => true,
2888 }
2889 }
2890}
2891
2892#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2896pub struct InlineAsm {
2897 pub asm_macro: AsmMacro,
2898 pub template: Vec<InlineAsmTemplatePiece>,
2899 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2900 pub operands: Vec<(InlineAsmOperand, Span)>,
2901 pub clobber_abis: Vec<(Symbol, Span)>,
2902 #[visitable(ignore)]
2903 pub options: InlineAsmOptions,
2904 pub line_spans: Vec<Span>,
2905}
2906
2907#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
2911pub struct Param {
2912 pub attrs: AttrVec,
2913 pub ty: Box<Ty>,
2914 pub pat: Box<Pat>,
2915 pub id: NodeId,
2916 pub span: Span,
2917 pub is_placeholder: bool,
2918}
2919
2920#[derive(Clone, Encodable, Decodable, Debug)]
2924pub enum SelfKind {
2925 Value(Mutability),
2927 Region(Option<Lifetime>, Mutability),
2929 Pinned(Option<Lifetime>, Mutability),
2931 Explicit(Box<Ty>, Mutability),
2933}
2934
2935impl SelfKind {
2936 pub fn to_ref_suggestion(&self) -> String {
2937 match self {
2938 SelfKind::Region(None, mutbl) => mutbl.ref_prefix_str().to_string(),
2939 SelfKind::Region(Some(lt), mutbl) => format!("&{lt} {}", mutbl.prefix_str()),
2940 SelfKind::Pinned(None, mutbl) => format!("&pin {}", mutbl.ptr_str()),
2941 SelfKind::Pinned(Some(lt), mutbl) => format!("&{lt} pin {}", mutbl.ptr_str()),
2942 SelfKind::Value(_) | SelfKind::Explicit(_, _) => {
2943 unreachable!("if we had an explicit self, we wouldn't be here")
2944 }
2945 }
2946 }
2947}
2948
2949pub type ExplicitSelf = Spanned<SelfKind>;
2950
2951impl Param {
2952 pub fn to_self(&self) -> Option<ExplicitSelf> {
2954 if let PatKind::Ident(BindingMode(ByRef::No, mutbl), ident, _) = self.pat.kind {
2955 if ident.name == kw::SelfLower {
2956 return match self.ty.kind {
2957 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2958 TyKind::Ref(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2959 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2960 }
2961 TyKind::PinnedRef(lt, MutTy { ref ty, mutbl })
2962 if ty.kind.is_implicit_self() =>
2963 {
2964 Some(respan(self.pat.span, SelfKind::Pinned(lt, mutbl)))
2965 }
2966 _ => Some(respan(
2967 self.pat.span.to(self.ty.span),
2968 SelfKind::Explicit(self.ty.clone(), mutbl),
2969 )),
2970 };
2971 }
2972 }
2973 None
2974 }
2975
2976 pub fn is_self(&self) -> bool {
2978 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2979 ident.name == kw::SelfLower
2980 } else {
2981 false
2982 }
2983 }
2984
2985 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2987 let span = eself.span.to(eself_ident.span);
2988 let infer_ty = Box::new(Ty {
2989 id: DUMMY_NODE_ID,
2990 kind: TyKind::ImplicitSelf,
2991 span: eself_ident.span,
2992 tokens: None,
2993 });
2994 let (mutbl, ty) = match eself.node {
2995 SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2996 SelfKind::Value(mutbl) => (mutbl, infer_ty),
2997 SelfKind::Region(lt, mutbl) => (
2998 Mutability::Not,
2999 Box::new(Ty {
3000 id: DUMMY_NODE_ID,
3001 kind: TyKind::Ref(lt, MutTy { ty: infer_ty, mutbl }),
3002 span,
3003 tokens: None,
3004 }),
3005 ),
3006 SelfKind::Pinned(lt, mutbl) => (
3007 mutbl,
3008 Box::new(Ty {
3009 id: DUMMY_NODE_ID,
3010 kind: TyKind::PinnedRef(lt, MutTy { ty: infer_ty, mutbl }),
3011 span,
3012 tokens: None,
3013 }),
3014 ),
3015 };
3016 Param {
3017 attrs,
3018 pat: Box::new(Pat {
3019 id: DUMMY_NODE_ID,
3020 kind: PatKind::Ident(BindingMode(ByRef::No, mutbl), eself_ident, None),
3021 span,
3022 tokens: None,
3023 }),
3024 span,
3025 ty,
3026 id: DUMMY_NODE_ID,
3027 is_placeholder: false,
3028 }
3029 }
3030}
3031
3032#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3039pub struct FnDecl {
3040 pub inputs: ThinVec<Param>,
3041 pub output: FnRetTy,
3042}
3043
3044impl FnDecl {
3045 pub fn has_self(&self) -> bool {
3046 self.inputs.get(0).is_some_and(Param::is_self)
3047 }
3048 pub fn c_variadic(&self) -> bool {
3049 self.inputs.last().is_some_and(|arg| matches!(arg.ty.kind, TyKind::CVarArgs))
3050 }
3051}
3052
3053#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
3055pub enum IsAuto {
3056 Yes,
3057 No,
3058}
3059
3060#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
3062#[derive(HashStable_Generic, Walkable)]
3063pub enum Safety {
3064 Unsafe(Span),
3066 Safe(Span),
3068 Default,
3071}
3072
3073#[derive(Copy, Clone, Encodable, Decodable, Debug, Walkable)]
3079pub enum CoroutineKind {
3080 Async { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
3082 Gen { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
3084 AsyncGen { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
3086}
3087
3088impl CoroutineKind {
3089 pub fn span(self) -> Span {
3090 match self {
3091 CoroutineKind::Async { span, .. } => span,
3092 CoroutineKind::Gen { span, .. } => span,
3093 CoroutineKind::AsyncGen { span, .. } => span,
3094 }
3095 }
3096
3097 pub fn as_str(self) -> &'static str {
3098 match self {
3099 CoroutineKind::Async { .. } => "async",
3100 CoroutineKind::Gen { .. } => "gen",
3101 CoroutineKind::AsyncGen { .. } => "async gen",
3102 }
3103 }
3104
3105 pub fn closure_id(self) -> NodeId {
3106 match self {
3107 CoroutineKind::Async { closure_id, .. }
3108 | CoroutineKind::Gen { closure_id, .. }
3109 | CoroutineKind::AsyncGen { closure_id, .. } => closure_id,
3110 }
3111 }
3112
3113 pub fn return_id(self) -> (NodeId, Span) {
3116 match self {
3117 CoroutineKind::Async { return_impl_trait_id, span, .. }
3118 | CoroutineKind::Gen { return_impl_trait_id, span, .. }
3119 | CoroutineKind::AsyncGen { return_impl_trait_id, span, .. } => {
3120 (return_impl_trait_id, span)
3121 }
3122 }
3123 }
3124}
3125
3126#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
3127#[derive(HashStable_Generic, Walkable)]
3128pub enum Const {
3129 Yes(Span),
3130 No,
3131}
3132
3133#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
3136pub enum Defaultness {
3137 Default(Span),
3138 Final,
3139}
3140
3141#[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic, Walkable)]
3142pub enum ImplPolarity {
3143 Positive,
3145 Negative(Span),
3147}
3148
3149impl fmt::Debug for ImplPolarity {
3150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3151 match *self {
3152 ImplPolarity::Positive => "positive".fmt(f),
3153 ImplPolarity::Negative(_) => "negative".fmt(f),
3154 }
3155 }
3156}
3157
3158#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash)]
3160#[derive(HashStable_Generic, Walkable)]
3161pub enum BoundPolarity {
3162 Positive,
3164 Negative(Span),
3166 Maybe(Span),
3168}
3169
3170impl BoundPolarity {
3171 pub fn as_str(self) -> &'static str {
3172 match self {
3173 Self::Positive => "",
3174 Self::Negative(_) => "!",
3175 Self::Maybe(_) => "?",
3176 }
3177 }
3178}
3179
3180#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash)]
3182#[derive(HashStable_Generic, Walkable)]
3183pub enum BoundConstness {
3184 Never,
3186 Always(Span),
3188 Maybe(Span),
3190}
3191
3192impl BoundConstness {
3193 pub fn as_str(self) -> &'static str {
3194 match self {
3195 Self::Never => "",
3196 Self::Always(_) => "const",
3197 Self::Maybe(_) => "[const]",
3198 }
3199 }
3200}
3201
3202#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
3204#[derive(HashStable_Generic, Walkable)]
3205pub enum BoundAsyncness {
3206 Normal,
3208 Async(Span),
3210}
3211
3212impl BoundAsyncness {
3213 pub fn as_str(self) -> &'static str {
3214 match self {
3215 Self::Normal => "",
3216 Self::Async(_) => "async",
3217 }
3218 }
3219}
3220
3221#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3222pub enum FnRetTy {
3223 Default(Span),
3228 Ty(Box<Ty>),
3230}
3231
3232impl FnRetTy {
3233 pub fn span(&self) -> Span {
3234 match self {
3235 &FnRetTy::Default(span) => span,
3236 FnRetTy::Ty(ty) => ty.span,
3237 }
3238 }
3239}
3240
3241#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, Walkable)]
3242pub enum Inline {
3243 Yes,
3244 No { had_parse_error: Result<(), ErrorGuaranteed> },
3245}
3246
3247#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3249pub enum ModKind {
3250 Loaded(ThinVec<Box<Item>>, Inline, ModSpans),
3255 Unloaded,
3257}
3258
3259#[derive(Copy, Clone, Encodable, Decodable, Debug, Default, Walkable)]
3260pub struct ModSpans {
3261 pub inner_span: Span,
3264 pub inject_use_span: Span,
3265}
3266
3267#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3271pub struct ForeignMod {
3272 pub extern_span: Span,
3274 pub safety: Safety,
3277 pub abi: Option<StrLit>,
3278 pub items: ThinVec<Box<ForeignItem>>,
3279}
3280
3281#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3282pub struct EnumDef {
3283 pub variants: ThinVec<Variant>,
3284}
3285
3286#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3288pub struct Variant {
3289 pub attrs: AttrVec,
3291 pub id: NodeId,
3293 pub span: Span,
3295 pub vis: Visibility,
3297 pub ident: Ident,
3299
3300 pub data: VariantData,
3302 pub disr_expr: Option<AnonConst>,
3304 pub is_placeholder: bool,
3306}
3307
3308#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3310pub enum UseTreeKind {
3311 Simple(Option<Ident>),
3313 Nested { items: ThinVec<(UseTree, NodeId)>, span: Span },
3322 Glob,
3324}
3325
3326#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3329pub struct UseTree {
3330 pub prefix: Path,
3331 pub kind: UseTreeKind,
3332 pub span: Span,
3333}
3334
3335impl UseTree {
3336 pub fn ident(&self) -> Ident {
3337 match self.kind {
3338 UseTreeKind::Simple(Some(rename)) => rename,
3339 UseTreeKind::Simple(None) => {
3340 self.prefix.segments.last().expect("empty prefix in a simple import").ident
3341 }
3342 _ => panic!("`UseTree::ident` can only be used on a simple import"),
3343 }
3344 }
3345}
3346
3347#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic, Walkable)]
3351pub enum AttrStyle {
3352 Outer,
3353 Inner,
3354}
3355
3356pub type AttrVec = ThinVec<Attribute>;
3358
3359#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3361pub struct Attribute {
3362 pub kind: AttrKind,
3363 pub id: AttrId,
3364 pub style: AttrStyle,
3367 pub span: Span,
3368}
3369
3370#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3371pub enum AttrKind {
3372 Normal(Box<NormalAttr>),
3374
3375 DocComment(CommentKind, Symbol),
3379}
3380
3381#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3382pub struct NormalAttr {
3383 pub item: AttrItem,
3384 pub tokens: Option<LazyAttrTokenStream>,
3386}
3387
3388impl NormalAttr {
3389 pub fn from_ident(ident: Ident) -> Self {
3390 Self {
3391 item: AttrItem {
3392 unsafety: Safety::Default,
3393 path: Path::from_ident(ident),
3394 args: AttrItemKind::Unparsed(AttrArgs::Empty),
3395 tokens: None,
3396 },
3397 tokens: None,
3398 }
3399 }
3400}
3401
3402#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3403pub struct AttrItem {
3404 pub unsafety: Safety,
3405 pub path: Path,
3406 pub args: AttrItemKind,
3407 pub tokens: Option<LazyAttrTokenStream>,
3409}
3410
3411#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3414pub enum AttrItemKind {
3415 Parsed(EarlyParsedAttribute),
3416 Unparsed(AttrArgs),
3417}
3418
3419impl AttrItemKind {
3420 pub fn unparsed(self) -> Option<AttrArgs> {
3421 match self {
3422 AttrItemKind::Unparsed(args) => Some(args),
3423 AttrItemKind::Parsed(_) => None,
3424 }
3425 }
3426
3427 pub fn unparsed_ref(&self) -> Option<&AttrArgs> {
3428 match self {
3429 AttrItemKind::Unparsed(args) => Some(args),
3430 AttrItemKind::Parsed(_) => None,
3431 }
3432 }
3433
3434 pub fn span(&self) -> Option<Span> {
3435 match self {
3436 AttrItemKind::Unparsed(args) => args.span(),
3437 AttrItemKind::Parsed(_) => None,
3438 }
3439 }
3440}
3441
3442#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
3448pub enum EarlyParsedAttribute {
3449 CfgTrace(CfgEntry),
3450 CfgAttrTrace,
3451}
3452
3453impl AttrItem {
3454 pub fn is_valid_for_outer_style(&self) -> bool {
3455 self.path == sym::cfg_attr
3456 || self.path == sym::cfg
3457 || self.path == sym::forbid
3458 || self.path == sym::warn
3459 || self.path == sym::allow
3460 || self.path == sym::deny
3461 }
3462}
3463
3464#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3471pub struct TraitRef {
3472 pub path: Path,
3473 pub ref_id: NodeId,
3474}
3475
3476#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3478pub enum Parens {
3479 Yes,
3480 No,
3481}
3482
3483#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3484pub struct PolyTraitRef {
3485 pub bound_generic_params: ThinVec<GenericParam>,
3487
3488 pub modifiers: TraitBoundModifiers,
3490
3491 pub trait_ref: TraitRef,
3493
3494 pub span: Span,
3495
3496 pub parens: Parens,
3499}
3500
3501impl PolyTraitRef {
3502 pub fn new(
3503 generic_params: ThinVec<GenericParam>,
3504 path: Path,
3505 modifiers: TraitBoundModifiers,
3506 span: Span,
3507 parens: Parens,
3508 ) -> Self {
3509 PolyTraitRef {
3510 bound_generic_params: generic_params,
3511 modifiers,
3512 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
3513 span,
3514 parens,
3515 }
3516 }
3517}
3518
3519#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3520pub struct Visibility {
3521 pub kind: VisibilityKind,
3522 pub span: Span,
3523 pub tokens: Option<LazyAttrTokenStream>,
3524}
3525
3526#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3527pub enum VisibilityKind {
3528 Public,
3529 Restricted { path: Box<Path>, id: NodeId, shorthand: bool },
3530 Inherited,
3531}
3532
3533impl VisibilityKind {
3534 pub fn is_pub(&self) -> bool {
3535 matches!(self, VisibilityKind::Public)
3536 }
3537}
3538
3539#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3543pub struct FieldDef {
3544 pub attrs: AttrVec,
3545 pub id: NodeId,
3546 pub span: Span,
3547 pub vis: Visibility,
3548 pub safety: Safety,
3549 pub ident: Option<Ident>,
3550
3551 pub ty: Box<Ty>,
3552 pub default: Option<AnonConst>,
3553 pub is_placeholder: bool,
3554}
3555
3556#[derive(Copy, Clone, Debug, Encodable, Decodable, HashStable_Generic, Walkable)]
3558pub enum Recovered {
3559 No,
3560 Yes(ErrorGuaranteed),
3561}
3562
3563#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3565pub enum VariantData {
3566 Struct { fields: ThinVec<FieldDef>, recovered: Recovered },
3570 Tuple(ThinVec<FieldDef>, NodeId),
3574 Unit(NodeId),
3578}
3579
3580impl VariantData {
3581 pub fn fields(&self) -> &[FieldDef] {
3583 match self {
3584 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, _) => fields,
3585 _ => &[],
3586 }
3587 }
3588
3589 pub fn ctor_node_id(&self) -> Option<NodeId> {
3591 match *self {
3592 VariantData::Struct { .. } => None,
3593 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
3594 }
3595 }
3596}
3597
3598#[derive(Clone, Encodable, Decodable, Debug)]
3600pub struct Item<K = ItemKind> {
3601 pub attrs: AttrVec,
3602 pub id: NodeId,
3603 pub span: Span,
3604 pub vis: Visibility,
3605
3606 pub kind: K,
3607
3608 pub tokens: Option<LazyAttrTokenStream>,
3616}
3617
3618impl Item {
3619 pub fn span_with_attributes(&self) -> Span {
3621 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
3622 }
3623
3624 pub fn opt_generics(&self) -> Option<&Generics> {
3625 match &self.kind {
3626 ItemKind::ExternCrate(..)
3627 | ItemKind::Use(_)
3628 | ItemKind::Mod(..)
3629 | ItemKind::ForeignMod(_)
3630 | ItemKind::GlobalAsm(_)
3631 | ItemKind::MacCall(_)
3632 | ItemKind::Delegation(_)
3633 | ItemKind::DelegationMac(_)
3634 | ItemKind::MacroDef(..) => None,
3635 ItemKind::Static(_) => None,
3636 ItemKind::Const(i) => Some(&i.generics),
3637 ItemKind::Fn(i) => Some(&i.generics),
3638 ItemKind::TyAlias(i) => Some(&i.generics),
3639 ItemKind::TraitAlias(i) => Some(&i.generics),
3640
3641 ItemKind::Enum(_, generics, _)
3642 | ItemKind::Struct(_, generics, _)
3643 | ItemKind::Union(_, generics, _) => Some(&generics),
3644 ItemKind::Trait(i) => Some(&i.generics),
3645 ItemKind::Impl(i) => Some(&i.generics),
3646 }
3647 }
3648}
3649
3650#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
3652pub enum Extern {
3653 None,
3657 Implicit(Span),
3663 Explicit(StrLit, Span),
3667}
3668
3669impl Extern {
3670 pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
3671 match abi {
3672 Some(name) => Extern::Explicit(name, span),
3673 None => Extern::Implicit(span),
3674 }
3675 }
3676
3677 pub fn span(self) -> Option<Span> {
3678 match self {
3679 Extern::None => None,
3680 Extern::Implicit(span) | Extern::Explicit(_, span) => Some(span),
3681 }
3682 }
3683}
3684
3685#[derive(Clone, Copy, Encodable, Decodable, Debug, Walkable)]
3690pub struct FnHeader {
3691 pub constness: Const,
3693 pub coroutine_kind: Option<CoroutineKind>,
3695 pub safety: Safety,
3697 pub ext: Extern,
3699}
3700
3701impl FnHeader {
3702 pub fn has_qualifiers(&self) -> bool {
3704 let Self { safety, coroutine_kind, constness, ext } = self;
3705 matches!(safety, Safety::Unsafe(_))
3706 || coroutine_kind.is_some()
3707 || matches!(constness, Const::Yes(_))
3708 || !matches!(ext, Extern::None)
3709 }
3710}
3711
3712impl Default for FnHeader {
3713 fn default() -> FnHeader {
3714 FnHeader {
3715 safety: Safety::Default,
3716 coroutine_kind: None,
3717 constness: Const::No,
3718 ext: Extern::None,
3719 }
3720 }
3721}
3722
3723#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3724pub struct TraitAlias {
3725 pub constness: Const,
3726 pub ident: Ident,
3727 pub generics: Generics,
3728 #[visitable(extra = BoundKind::Bound)]
3729 pub bounds: GenericBounds,
3730}
3731
3732#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3733pub struct Trait {
3734 pub constness: Const,
3735 pub safety: Safety,
3736 pub is_auto: IsAuto,
3737 pub ident: Ident,
3738 pub generics: Generics,
3739 #[visitable(extra = BoundKind::SuperTraits)]
3740 pub bounds: GenericBounds,
3741 #[visitable(extra = AssocCtxt::Trait)]
3742 pub items: ThinVec<Box<AssocItem>>,
3743}
3744
3745#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3746pub struct TyAlias {
3747 pub defaultness: Defaultness,
3748 pub ident: Ident,
3749 pub generics: Generics,
3750 pub after_where_clause: WhereClause,
3765 #[visitable(extra = BoundKind::Bound)]
3766 pub bounds: GenericBounds,
3767 pub ty: Option<Box<Ty>>,
3768}
3769
3770#[derive(Clone, Encodable, Decodable, Debug)]
3771pub struct Impl {
3772 pub generics: Generics,
3773 pub constness: Const,
3774 pub of_trait: Option<Box<TraitImplHeader>>,
3775 pub self_ty: Box<Ty>,
3776 pub items: ThinVec<Box<AssocItem>>,
3777}
3778
3779#[derive(Clone, Encodable, Decodable, Debug)]
3780pub struct TraitImplHeader {
3781 pub defaultness: Defaultness,
3782 pub safety: Safety,
3783 pub polarity: ImplPolarity,
3784 pub trait_ref: TraitRef,
3785}
3786
3787#[derive(Clone, Encodable, Decodable, Debug, Default, Walkable)]
3788pub struct FnContract {
3789 pub declarations: ThinVec<Stmt>,
3792 pub requires: Option<Box<Expr>>,
3793 pub ensures: Option<Box<Expr>>,
3794}
3795
3796#[derive(Clone, Encodable, Decodable, Debug)]
3797pub struct Fn {
3798 pub defaultness: Defaultness,
3799 pub ident: Ident,
3800 pub generics: Generics,
3801 pub sig: FnSig,
3802 pub contract: Option<Box<FnContract>>,
3803 pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
3804 pub body: Option<Box<Block>>,
3805
3806 pub eii_impls: ThinVec<EiiImpl>,
3810}
3811
3812#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3813pub struct EiiImpl {
3814 pub node_id: NodeId,
3815 pub eii_macro_path: Path,
3816 pub impl_safety: Safety,
3817 pub span: Span,
3818 pub inner_span: Span,
3819 pub is_default: bool,
3820}
3821
3822#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3823pub struct Delegation {
3824 pub id: NodeId,
3826 pub qself: Option<Box<QSelf>>,
3827 pub path: Path,
3828 pub ident: Ident,
3829 pub rename: Option<Ident>,
3830 pub body: Option<Box<Block>>,
3831 pub from_glob: bool,
3833}
3834
3835#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3836pub struct DelegationMac {
3837 pub qself: Option<Box<QSelf>>,
3838 pub prefix: Path,
3839 pub suffixes: Option<ThinVec<(Ident, Option<Ident>)>>,
3841 pub body: Option<Box<Block>>,
3842}
3843
3844#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3845pub struct StaticItem {
3846 pub ident: Ident,
3847 pub ty: Box<Ty>,
3848 pub safety: Safety,
3849 pub mutability: Mutability,
3850 pub expr: Option<Box<Expr>>,
3851 pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
3852}
3853
3854#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3855pub struct ConstItem {
3856 pub defaultness: Defaultness,
3857 pub ident: Ident,
3858 pub generics: Generics,
3859 pub ty: Box<Ty>,
3860 pub rhs: Option<ConstItemRhs>,
3861 pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
3862}
3863
3864#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3865pub enum ConstItemRhs {
3866 TypeConst(AnonConst),
3867 Body(Box<Expr>),
3868}
3869
3870impl ConstItemRhs {
3871 pub fn span(&self) -> Span {
3872 self.expr().span
3873 }
3874
3875 pub fn expr(&self) -> &Expr {
3876 match self {
3877 ConstItemRhs::TypeConst(anon_const) => &anon_const.value,
3878 ConstItemRhs::Body(expr) => expr,
3879 }
3880 }
3881}
3882
3883#[derive(Clone, Encodable, Decodable, Debug)]
3885pub enum ItemKind {
3886 ExternCrate(Option<Symbol>, Ident),
3890 Use(UseTree),
3894 Static(Box<StaticItem>),
3898 Const(Box<ConstItem>),
3902 Fn(Box<Fn>),
3906 Mod(Safety, Ident, ModKind),
3912 ForeignMod(ForeignMod),
3916 GlobalAsm(Box<InlineAsm>),
3918 TyAlias(Box<TyAlias>),
3922 Enum(Ident, Generics, EnumDef),
3926 Struct(Ident, Generics, VariantData),
3930 Union(Ident, Generics, VariantData),
3934 Trait(Box<Trait>),
3938 TraitAlias(Box<TraitAlias>),
3942 Impl(Impl),
3946 MacCall(Box<MacCall>),
3950 MacroDef(Ident, MacroDef),
3952 Delegation(Box<Delegation>),
3956 DelegationMac(Box<DelegationMac>),
3959}
3960
3961impl ItemKind {
3962 pub fn ident(&self) -> Option<Ident> {
3963 match *self {
3964 ItemKind::ExternCrate(_, ident)
3965 | ItemKind::Static(box StaticItem { ident, .. })
3966 | ItemKind::Const(box ConstItem { ident, .. })
3967 | ItemKind::Fn(box Fn { ident, .. })
3968 | ItemKind::Mod(_, ident, _)
3969 | ItemKind::TyAlias(box TyAlias { ident, .. })
3970 | ItemKind::Enum(ident, ..)
3971 | ItemKind::Struct(ident, ..)
3972 | ItemKind::Union(ident, ..)
3973 | ItemKind::Trait(box Trait { ident, .. })
3974 | ItemKind::TraitAlias(box TraitAlias { ident, .. })
3975 | ItemKind::MacroDef(ident, _)
3976 | ItemKind::Delegation(box Delegation { ident, .. }) => Some(ident),
3977
3978 ItemKind::Use(_)
3979 | ItemKind::ForeignMod(_)
3980 | ItemKind::GlobalAsm(_)
3981 | ItemKind::Impl(_)
3982 | ItemKind::MacCall(_)
3983 | ItemKind::DelegationMac(_) => None,
3984 }
3985 }
3986
3987 pub fn article(&self) -> &'static str {
3989 use ItemKind::*;
3990 match self {
3991 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
3992 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..)
3993 | Delegation(..) | DelegationMac(..) => "a",
3994 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
3995 }
3996 }
3997
3998 pub fn descr(&self) -> &'static str {
3999 match self {
4000 ItemKind::ExternCrate(..) => "extern crate",
4001 ItemKind::Use(..) => "`use` import",
4002 ItemKind::Static(..) => "static item",
4003 ItemKind::Const(..) => "constant item",
4004 ItemKind::Fn(..) => "function",
4005 ItemKind::Mod(..) => "module",
4006 ItemKind::ForeignMod(..) => "extern block",
4007 ItemKind::GlobalAsm(..) => "global asm item",
4008 ItemKind::TyAlias(..) => "type alias",
4009 ItemKind::Enum(..) => "enum",
4010 ItemKind::Struct(..) => "struct",
4011 ItemKind::Union(..) => "union",
4012 ItemKind::Trait(..) => "trait",
4013 ItemKind::TraitAlias(..) => "trait alias",
4014 ItemKind::MacCall(..) => "item macro invocation",
4015 ItemKind::MacroDef(..) => "macro definition",
4016 ItemKind::Impl { .. } => "implementation",
4017 ItemKind::Delegation(..) => "delegated function",
4018 ItemKind::DelegationMac(..) => "delegation",
4019 }
4020 }
4021
4022 pub fn generics(&self) -> Option<&Generics> {
4023 match self {
4024 Self::Fn(box Fn { generics, .. })
4025 | Self::TyAlias(box TyAlias { generics, .. })
4026 | Self::Const(box ConstItem { generics, .. })
4027 | Self::Enum(_, generics, _)
4028 | Self::Struct(_, generics, _)
4029 | Self::Union(_, generics, _)
4030 | Self::Trait(box Trait { generics, .. })
4031 | Self::TraitAlias(box TraitAlias { generics, .. })
4032 | Self::Impl(Impl { generics, .. }) => Some(generics),
4033 _ => None,
4034 }
4035 }
4036}
4037
4038pub type AssocItem = Item<AssocItemKind>;
4041
4042#[derive(Clone, Encodable, Decodable, Debug)]
4050pub enum AssocItemKind {
4051 Const(Box<ConstItem>),
4054 Fn(Box<Fn>),
4056 Type(Box<TyAlias>),
4058 MacCall(Box<MacCall>),
4060 Delegation(Box<Delegation>),
4062 DelegationMac(Box<DelegationMac>),
4064}
4065
4066impl AssocItemKind {
4067 pub fn ident(&self) -> Option<Ident> {
4068 match *self {
4069 AssocItemKind::Const(box ConstItem { ident, .. })
4070 | AssocItemKind::Fn(box Fn { ident, .. })
4071 | AssocItemKind::Type(box TyAlias { ident, .. })
4072 | AssocItemKind::Delegation(box Delegation { ident, .. }) => Some(ident),
4073
4074 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(_) => None,
4075 }
4076 }
4077
4078 pub fn defaultness(&self) -> Defaultness {
4079 match *self {
4080 Self::Const(box ConstItem { defaultness, .. })
4081 | Self::Fn(box Fn { defaultness, .. })
4082 | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
4083 Self::MacCall(..) | Self::Delegation(..) | Self::DelegationMac(..) => {
4084 Defaultness::Final
4085 }
4086 }
4087 }
4088}
4089
4090impl From<AssocItemKind> for ItemKind {
4091 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
4092 match assoc_item_kind {
4093 AssocItemKind::Const(item) => ItemKind::Const(item),
4094 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
4095 AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
4096 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
4097 AssocItemKind::Delegation(delegation) => ItemKind::Delegation(delegation),
4098 AssocItemKind::DelegationMac(delegation) => ItemKind::DelegationMac(delegation),
4099 }
4100 }
4101}
4102
4103impl TryFrom<ItemKind> for AssocItemKind {
4104 type Error = ItemKind;
4105
4106 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
4107 Ok(match item_kind {
4108 ItemKind::Const(item) => AssocItemKind::Const(item),
4109 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
4110 ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
4111 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
4112 ItemKind::Delegation(d) => AssocItemKind::Delegation(d),
4113 ItemKind::DelegationMac(d) => AssocItemKind::DelegationMac(d),
4114 _ => return Err(item_kind),
4115 })
4116 }
4117}
4118
4119#[derive(Clone, Encodable, Decodable, Debug)]
4121pub enum ForeignItemKind {
4122 Static(Box<StaticItem>),
4124 Fn(Box<Fn>),
4126 TyAlias(Box<TyAlias>),
4128 MacCall(Box<MacCall>),
4130}
4131
4132impl ForeignItemKind {
4133 pub fn ident(&self) -> Option<Ident> {
4134 match *self {
4135 ForeignItemKind::Static(box StaticItem { ident, .. })
4136 | ForeignItemKind::Fn(box Fn { ident, .. })
4137 | ForeignItemKind::TyAlias(box TyAlias { ident, .. }) => Some(ident),
4138
4139 ForeignItemKind::MacCall(_) => None,
4140 }
4141 }
4142}
4143
4144impl From<ForeignItemKind> for ItemKind {
4145 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
4146 match foreign_item_kind {
4147 ForeignItemKind::Static(box static_foreign_item) => {
4148 ItemKind::Static(Box::new(static_foreign_item))
4149 }
4150 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
4151 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
4152 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
4153 }
4154 }
4155}
4156
4157impl TryFrom<ItemKind> for ForeignItemKind {
4158 type Error = ItemKind;
4159
4160 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
4161 Ok(match item_kind {
4162 ItemKind::Static(box static_item) => ForeignItemKind::Static(Box::new(static_item)),
4163 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
4164 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
4165 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
4166 _ => return Err(item_kind),
4167 })
4168 }
4169}
4170
4171pub type ForeignItem = Item<ForeignItemKind>;
4172
4173#[cfg(target_pointer_width = "64")]
4175mod size_asserts {
4176 use rustc_data_structures::static_assert_size;
4177
4178 use super::*;
4179 static_assert_size!(AssocItem, 80);
4181 static_assert_size!(AssocItemKind, 16);
4182 static_assert_size!(Attribute, 32);
4183 static_assert_size!(Block, 32);
4184 static_assert_size!(Expr, 72);
4185 static_assert_size!(ExprKind, 40);
4186 static_assert_size!(Fn, 192);
4187 static_assert_size!(ForeignItem, 80);
4188 static_assert_size!(ForeignItemKind, 16);
4189 static_assert_size!(GenericArg, 24);
4190 static_assert_size!(GenericBound, 88);
4191 static_assert_size!(Generics, 40);
4192 static_assert_size!(Impl, 80);
4193 static_assert_size!(Item, 152);
4194 static_assert_size!(ItemKind, 88);
4195 static_assert_size!(LitKind, 24);
4196 static_assert_size!(Local, 96);
4197 static_assert_size!(MetaItemLit, 40);
4198 static_assert_size!(Param, 40);
4199 static_assert_size!(Pat, 80);
4200 static_assert_size!(PatKind, 56);
4201 static_assert_size!(Path, 24);
4202 static_assert_size!(PathSegment, 24);
4203 static_assert_size!(Stmt, 32);
4204 static_assert_size!(StmtKind, 16);
4205 static_assert_size!(TraitImplHeader, 72);
4206 static_assert_size!(Ty, 64);
4207 static_assert_size!(TyKind, 40);
4208 }