1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`MetaItemLit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
21 pub use crate::format
::*;
22 pub use crate::util
::parser
::ExprPrecedence
;
23 pub use GenericArgs
::*;
24 pub use UnsafeSource
::*;
27 use crate::token
::{self, CommentKind, Delimiter}
;
28 use crate::tokenstream
::{DelimSpan, LazyAttrTokenStream, TokenStream}
;
29 use rustc_data_structures
::stable_hasher
::{HashStable, StableHasher}
;
30 use rustc_data_structures
::stack
::ensure_sufficient_stack
;
31 use rustc_data_structures
::sync
::Lrc
;
32 use rustc_macros
::HashStable_Generic
;
33 use rustc_serialize
::{Decodable, Decoder, Encodable, Encoder}
;
34 use rustc_span
::source_map
::{respan, Spanned}
;
35 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
36 use rustc_span
::{Span, DUMMY_SP}
;
39 use thin_vec
::{thin_vec, ThinVec}
;
41 /// A "Label" is an identifier of some point in sources,
42 /// e.g. in the following code:
50 /// `'outer` is a label.
51 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
56 impl fmt
::Debug
for Label
{
57 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
58 write
!(f
, "label({:?})", self.ident
)
62 /// A "Lifetime" is an annotation of the scope in which variable
63 /// can be used, e.g. `'a` in `&'a i32`.
64 #[derive(Clone, Encodable, Decodable, Copy, PartialEq, Eq)]
70 impl fmt
::Debug
for Lifetime
{
71 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
72 write
!(f
, "lifetime({}: {})", self.id
, self)
76 impl fmt
::Display
for Lifetime
{
77 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
78 write
!(f
, "{}", self.ident
.name
)
82 /// A "Path" is essentially Rust's notion of a name.
84 /// It's represented as a sequence of identifiers,
85 /// along with a bunch of supporting information.
87 /// E.g., `std::cmp::PartialEq`.
88 #[derive(Clone, Encodable, Decodable, Debug)]
91 /// The segments in the path: the things separated by `::`.
92 /// Global paths begin with `kw::PathRoot`.
93 pub segments
: ThinVec
<PathSegment
>,
94 pub tokens
: Option
<LazyAttrTokenStream
>,
97 impl PartialEq
<Symbol
> for Path
{
99 fn eq(&self, symbol
: &Symbol
) -> bool
{
100 self.segments
.len() == 1 && { self.segments[0].ident.name == *symbol }
104 impl<CTX
: rustc_span
::HashStableContext
> HashStable
<CTX
> for Path
{
105 fn hash_stable(&self, hcx
: &mut CTX
, hasher
: &mut StableHasher
) {
106 self.segments
.len().hash_stable(hcx
, hasher
);
107 for segment
in &self.segments
{
108 segment
.ident
.hash_stable(hcx
, hasher
);
114 /// Convert a span and an identifier to the corresponding
115 /// one-segment path.
116 pub fn from_ident(ident
: Ident
) -> Path
{
117 Path { segments: thin_vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
120 pub fn is_global(&self) -> bool
{
121 !self.segments
.is_empty() && self.segments
[0].ident
.name
== kw
::PathRoot
124 /// If this path is a single identifier with no arguments, does not ensure
125 /// that the path resolves to a const param, the caller should check this.
126 pub fn is_potential_trivial_const_arg(&self) -> bool
{
127 self.segments
.len() == 1 && self.segments
[0].args
.is_none()
131 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
133 /// E.g., `std`, `String` or `Box<T>`.
134 #[derive(Clone, Encodable, Decodable, Debug)]
135 pub struct PathSegment
{
136 /// The identifier portion of this path segment.
141 /// Type/lifetime parameters attached to this path. They come in
142 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
143 /// `None` means that no parameter list is supplied (`Path`),
144 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
145 /// but it can be empty (`Path<>`).
146 /// `P` is used as a size optimization for the common case with no parameters.
147 pub args
: Option
<P
<GenericArgs
>>,
151 pub fn from_ident(ident
: Ident
) -> Self {
152 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
155 pub fn path_root(span
: Span
) -> Self {
156 PathSegment
::from_ident(Ident
::new(kw
::PathRoot
, span
))
159 pub fn span(&self) -> Span
{
161 Some(args
) => self.ident
.span
.to(args
.span()),
162 None
=> self.ident
.span
,
167 /// The arguments of a path segment.
169 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
170 #[derive(Clone, Encodable, Decodable, Debug)]
171 pub enum GenericArgs
{
172 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
173 AngleBracketed(AngleBracketedArgs
),
174 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
175 Parenthesized(ParenthesizedArgs
),
179 pub fn is_angle_bracketed(&self) -> bool
{
180 matches
!(self, AngleBracketed(..))
183 pub fn span(&self) -> Span
{
185 AngleBracketed(data
) => data
.span
,
186 Parenthesized(data
) => data
.span
,
191 /// Concrete argument in the sequence of generic args.
192 #[derive(Clone, Encodable, Decodable, Debug)]
193 pub enum GenericArg
{
194 /// `'a` in `Foo<'a>`
196 /// `Bar` in `Foo<Bar>`
203 pub fn span(&self) -> Span
{
205 GenericArg
::Lifetime(lt
) => lt
.ident
.span
,
206 GenericArg
::Type(ty
) => ty
.span
,
207 GenericArg
::Const(ct
) => ct
.value
.span
,
212 /// A path like `Foo<'a, T>`.
213 #[derive(Clone, Encodable, Decodable, Debug, Default)]
214 pub struct AngleBracketedArgs
{
215 /// The overall span.
217 /// The comma separated parts in the `<...>`.
218 pub args
: ThinVec
<AngleBracketedArg
>,
221 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
222 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
223 #[derive(Clone, Encodable, Decodable, Debug)]
224 pub enum AngleBracketedArg
{
225 /// Argument for a generic parameter.
227 /// Constraint for an associated item.
228 Constraint(AssocConstraint
),
231 impl AngleBracketedArg
{
232 pub fn span(&self) -> Span
{
234 AngleBracketedArg
::Arg(arg
) => arg
.span(),
235 AngleBracketedArg
::Constraint(constraint
) => constraint
.span
,
240 impl Into
<P
<GenericArgs
>> for AngleBracketedArgs
{
241 fn into(self) -> P
<GenericArgs
> {
242 P(GenericArgs
::AngleBracketed(self))
246 impl Into
<P
<GenericArgs
>> for ParenthesizedArgs
{
247 fn into(self) -> P
<GenericArgs
> {
248 P(GenericArgs
::Parenthesized(self))
252 /// A path like `Foo(A, B) -> C`.
253 #[derive(Clone, Encodable, Decodable, Debug)]
254 pub struct ParenthesizedArgs
{
262 pub inputs
: ThinVec
<P
<Ty
>>,
268 pub inputs_span
: Span
,
274 impl ParenthesizedArgs
{
275 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs
{
280 .map(|input
| AngleBracketedArg
::Arg(GenericArg
::Type(input
)))
282 AngleBracketedArgs { span: self.inputs_span, args }
286 pub use crate::node_id
::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID}
;
288 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
290 /// Negative bounds should also be handled here.
291 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
292 pub enum TraitBoundModifier
{
307 // This parses but will be rejected during AST validation.
312 // This parses but will be rejected during AST validation.
316 impl TraitBoundModifier
{
317 pub fn to_constness(self) -> Const
{
319 // FIXME(effects) span
320 Self::MaybeConst
=> Const
::Yes(DUMMY_SP
),
326 /// The AST represents all type param bounds as types.
327 /// `typeck::collect::compute_bounds` matches these against
328 /// the "special" built-in traits (see `middle::lang_items`) and
329 /// detects `Copy`, `Send` and `Sync`.
330 #[derive(Clone, Encodable, Decodable, Debug)]
331 pub enum GenericBound
{
332 Trait(PolyTraitRef
, TraitBoundModifier
),
337 pub fn span(&self) -> Span
{
339 GenericBound
::Trait(t
, ..) => t
.span
,
340 GenericBound
::Outlives(l
) => l
.ident
.span
,
345 pub type GenericBounds
= Vec
<GenericBound
>;
347 /// Specifies the enforced ordering for generic parameters. In the future,
348 /// if we wanted to relax this order, we could override `PartialEq` and
349 /// `PartialOrd`, to allow the kinds to be unordered.
350 #[derive(Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
351 pub enum ParamKindOrd
{
356 impl fmt
::Display
for ParamKindOrd
{
357 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
359 ParamKindOrd
::Lifetime
=> "lifetime".fmt(f
),
360 ParamKindOrd
::TypeOrConst
=> "type and const".fmt(f
),
365 #[derive(Clone, Encodable, Decodable, Debug)]
366 pub enum GenericParamKind
{
367 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
370 default: Option
<P
<Ty
>>,
374 /// Span of the `const` keyword.
376 /// Optional default value for the const generic param
377 default: Option
<AnonConst
>,
381 #[derive(Clone, Encodable, Decodable, Debug)]
382 pub struct GenericParam
{
386 pub bounds
: GenericBounds
,
387 pub is_placeholder
: bool
,
388 pub kind
: GenericParamKind
,
389 pub colon_span
: Option
<Span
>,
393 pub fn span(&self) -> Span
{
395 GenericParamKind
::Lifetime
| GenericParamKind
::Type { default: None }
=> {
398 GenericParamKind
::Type { default: Some(ty) }
=> self.ident
.span
.to(ty
.span
),
399 GenericParamKind
::Const { kw_span, default: Some(default), .. }
=> {
400 kw_span
.to(default.value
.span
)
402 GenericParamKind
::Const { kw_span, default: None, ty }
=> kw_span
.to(ty
.span
),
407 /// Represents lifetime, type and const parameters attached to a declaration of
408 /// a function, enum, trait, etc.
409 #[derive(Clone, Encodable, Decodable, Debug)]
410 pub struct Generics
{
411 pub params
: ThinVec
<GenericParam
>,
412 pub where_clause
: WhereClause
,
416 impl Default
for Generics
{
417 /// Creates an instance of `Generics`.
418 fn default() -> Generics
{
419 Generics { params: ThinVec::new(), where_clause: Default::default(), span: DUMMY_SP }
423 /// A where-clause in a definition.
424 #[derive(Clone, Encodable, Decodable, Debug)]
425 pub struct WhereClause
{
426 /// `true` if we ate a `where` token: this can happen
427 /// if we parsed no predicates (e.g. `struct Foo where {}`).
428 /// This allows us to pretty-print accurately.
429 pub has_where_token
: bool
,
430 pub predicates
: ThinVec
<WherePredicate
>,
434 impl Default
for WhereClause
{
435 fn default() -> WhereClause
{
436 WhereClause { has_where_token: false, predicates: ThinVec::new(), span: DUMMY_SP }
440 /// A single predicate in a where-clause.
441 #[derive(Clone, Encodable, Decodable, Debug)]
442 pub enum WherePredicate
{
443 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
444 BoundPredicate(WhereBoundPredicate
),
445 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
446 RegionPredicate(WhereRegionPredicate
),
447 /// An equality predicate (unsupported).
448 EqPredicate(WhereEqPredicate
),
451 impl WherePredicate
{
452 pub fn span(&self) -> Span
{
454 WherePredicate
::BoundPredicate(p
) => p
.span
,
455 WherePredicate
::RegionPredicate(p
) => p
.span
,
456 WherePredicate
::EqPredicate(p
) => p
.span
,
463 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
464 #[derive(Clone, Encodable, Decodable, Debug)]
465 pub struct WhereBoundPredicate
{
467 /// Any generics from a `for` binding.
468 pub bound_generic_params
: ThinVec
<GenericParam
>,
469 /// The type being bounded.
470 pub bounded_ty
: P
<Ty
>,
471 /// Trait and lifetime bounds (`Clone + Send + 'static`).
472 pub bounds
: GenericBounds
,
475 /// A lifetime predicate.
477 /// E.g., `'a: 'b + 'c`.
478 #[derive(Clone, Encodable, Decodable, Debug)]
479 pub struct WhereRegionPredicate
{
481 pub lifetime
: Lifetime
,
482 pub bounds
: GenericBounds
,
485 /// An equality predicate (unsupported).
488 #[derive(Clone, Encodable, Decodable, Debug)]
489 pub struct WhereEqPredicate
{
495 #[derive(Clone, Encodable, Decodable, Debug)]
498 pub items
: ThinVec
<P
<Item
>>,
500 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
501 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
503 pub is_placeholder
: bool
,
506 /// A semantic representation of a meta item. A meta item is a slightly
507 /// restricted form of an attribute -- it can only contain expressions in
508 /// certain leaf positions, rather than arbitrary token streams -- that is used
509 /// for most built-in attributes.
511 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
512 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
513 pub struct MetaItem
{
515 pub kind
: MetaItemKind
,
519 /// The meta item kind, containing the data after the initial path.
520 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
521 pub enum MetaItemKind
{
524 /// E.g., `#[test]`, which lacks any arguments after `test`.
529 /// E.g., `#[derive(..)]`, where the field represents the `..`.
530 List(ThinVec
<NestedMetaItem
>),
532 /// Name value meta item.
534 /// E.g., `#[feature = "foo"]`, where the field represents the `"foo"`.
535 NameValue(MetaItemLit
),
538 /// Values inside meta item lists.
540 /// E.g., each of `Clone`, `Copy` in `#[derive(Clone, Copy)]`.
541 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
542 pub enum NestedMetaItem
{
543 /// A full MetaItem, for recursive meta items.
548 /// E.g., `"foo"`, `64`, `true`.
552 /// A block (`{ .. }`).
554 /// E.g., `{ .. }` as in `fn foo() { .. }`.
555 #[derive(Clone, Encodable, Decodable, Debug)]
557 /// The statements in the block.
558 pub stmts
: ThinVec
<Stmt
>,
560 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
561 pub rules
: BlockCheckMode
,
563 pub tokens
: Option
<LazyAttrTokenStream
>,
564 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
571 pub could_be_bare_literal
: bool
,
576 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
577 #[derive(Clone, Encodable, Decodable, Debug)]
582 pub tokens
: Option
<LazyAttrTokenStream
>,
586 /// Attempt reparsing the pattern as a type.
587 /// This is intended for use by diagnostics.
588 pub fn to_ty(&self) -> Option
<P
<Ty
>> {
589 let kind
= match &self.kind
{
590 // In a type expression `_` is an inference variable.
591 PatKind
::Wild
=> TyKind
::Infer
,
592 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
593 PatKind
::Ident(BindingAnnotation
::NONE
, ident
, None
) => {
594 TyKind
::Path(None
, Path
::from_ident(*ident
))
596 PatKind
::Path(qself
, path
) => TyKind
::Path(qself
.clone(), path
.clone()),
597 PatKind
::MacCall(mac
) => TyKind
::MacCall(mac
.clone()),
598 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
599 PatKind
::Ref(pat
, mutbl
) => {
600 pat
.to_ty().map(|ty
| TyKind
::Ref(None
, MutTy { ty, mutbl: *mutbl }
))?
602 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
603 // when `P` can be reparsed as a type `T`.
604 PatKind
::Slice(pats
) if pats
.len() == 1 => pats
[0].to_ty().map(TyKind
::Slice
)?
,
605 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
606 // assuming `T0` to `Tn` are all syntactically valid as types.
607 PatKind
::Tuple(pats
) => {
608 let mut tys
= ThinVec
::with_capacity(pats
.len());
609 // FIXME(#48994) - could just be collected into an Option<Vec>
611 tys
.push(pat
.to_ty()?
);
618 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }
))
621 /// Walk top-down and call `it` in each place where a pattern occurs
622 /// starting with the root pattern `walk` is called on. If `it` returns
623 /// false then we will descend no further but siblings will be processed.
624 pub fn walk(&self, it
: &mut impl FnMut(&Pat
) -> bool
) {
630 // Walk into the pattern associated with `Ident` (if any).
631 PatKind
::Ident(_
, _
, Some(p
)) => p
.walk(it
),
633 // Walk into each field of struct.
634 PatKind
::Struct(_
, _
, fields
, _
) => fields
.iter().for_each(|field
| field
.pat
.walk(it
)),
636 // Sequence of patterns.
637 PatKind
::TupleStruct(_
, _
, s
)
640 | PatKind
::Or(s
) => s
.iter().for_each(|p
| p
.walk(it
)),
642 // Trivial wrappers over inner patterns.
643 PatKind
::Box(s
) | PatKind
::Ref(s
, _
) | PatKind
::Paren(s
) => s
.walk(it
),
645 // These patterns do not contain subpatterns, skip.
652 | PatKind
::MacCall(_
) => {}
656 /// Is this a `..` pattern?
657 pub fn is_rest(&self) -> bool
{
658 matches
!(self.kind
, PatKind
::Rest
)
662 /// A single field in a struct pattern.
664 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
665 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
666 /// except when `is_shorthand` is true.
667 #[derive(Clone, Encodable, Decodable, Debug)]
668 pub struct PatField
{
669 /// The identifier for the field.
671 /// The pattern the field is destructured to.
673 pub is_shorthand
: bool
,
677 pub is_placeholder
: bool
,
680 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
681 #[derive(Encodable, Decodable, HashStable_Generic)]
687 impl From
<bool
> for ByRef
{
688 fn from(b
: bool
) -> ByRef
{
696 /// Explicit binding annotations given in the HIR for a binding. Note
697 /// that this is not the final binding *mode* that we infer after type
699 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
700 #[derive(Encodable, Decodable, HashStable_Generic)]
701 pub struct BindingAnnotation(pub ByRef
, pub Mutability
);
703 impl BindingAnnotation
{
704 pub const NONE
: Self = Self(ByRef
::No
, Mutability
::Not
);
705 pub const REF
: Self = Self(ByRef
::Yes
, Mutability
::Not
);
706 pub const MUT
: Self = Self(ByRef
::No
, Mutability
::Mut
);
707 pub const REF_MUT
: Self = Self(ByRef
::Yes
, Mutability
::Mut
);
709 pub fn prefix_str(self) -> &'
static str {
714 Self::REF_MUT
=> "ref mut ",
719 #[derive(Clone, Encodable, Decodable, Debug)]
722 Included(RangeSyntax
),
727 #[derive(Clone, Encodable, Decodable, Debug)]
728 pub enum RangeSyntax
{
735 /// All the different flavors of pattern that Rust recognizes.
736 #[derive(Clone, Encodable, Decodable, Debug)]
738 /// Represents a wildcard pattern (`_`).
741 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
742 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
743 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
744 /// during name resolution.
745 Ident(BindingAnnotation
, Ident
, Option
<P
<Pat
>>),
747 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
748 /// The `bool` is `true` in the presence of a `..`.
749 Struct(Option
<P
<QSelf
>>, Path
, ThinVec
<PatField
>, /* recovered */ bool
),
751 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
752 TupleStruct(Option
<P
<QSelf
>>, Path
, ThinVec
<P
<Pat
>>),
754 /// An or-pattern `A | B | C`.
755 /// Invariant: `pats.len() >= 2`.
758 /// A possibly qualified path pattern.
759 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
760 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
761 /// only legally refer to associated constants.
762 Path(Option
<P
<QSelf
>>, Path
),
764 /// A tuple pattern (`(a, b)`).
765 Tuple(ThinVec
<P
<Pat
>>),
770 /// A reference pattern (e.g., `&mut (a, b)`).
771 Ref(P
<Pat
>, Mutability
),
776 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
777 Range(Option
<P
<Expr
>>, Option
<P
<Expr
>>, Spanned
<RangeEnd
>),
779 /// A slice pattern `[a, b, c]`.
780 Slice(ThinVec
<P
<Pat
>>),
782 /// A rest pattern `..`.
784 /// Syntactically it is valid anywhere.
786 /// Semantically however, it only has meaning immediately inside:
787 /// - a slice pattern: `[a, .., b]`,
788 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
789 /// - a tuple pattern: `(a, .., b)`,
790 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
792 /// In all of these cases, an additional restriction applies,
793 /// only one rest pattern may occur in the pattern sequences.
796 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
799 /// A macro pattern; pre-expansion.
803 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
804 #[derive(HashStable_Generic, Encodable, Decodable)]
805 pub enum Mutability
{
806 // N.B. Order is deliberate, so that Not < Mut
812 pub fn invert(self) -> Self {
814 Mutability
::Mut
=> Mutability
::Not
,
815 Mutability
::Not
=> Mutability
::Mut
,
819 /// Returns `""` (empty string) or `"mut "` depending on the mutability.
820 pub fn prefix_str(self) -> &'
static str {
822 Mutability
::Mut
=> "mut ",
823 Mutability
::Not
=> "",
827 /// Returns `"&"` or `"&mut "` depending on the mutability.
828 pub fn ref_prefix_str(self) -> &'
static str {
830 Mutability
::Not
=> "&",
831 Mutability
::Mut
=> "&mut ",
835 /// Returns `""` (empty string) or `"mutably "` depending on the mutability.
836 pub fn mutably_str(self) -> &'
static str {
838 Mutability
::Not
=> "",
839 Mutability
::Mut
=> "mutably ",
843 /// Return `true` if self is mutable
844 pub fn is_mut(self) -> bool
{
845 matches
!(self, Self::Mut
)
848 /// Return `true` if self is **not** mutable
849 pub fn is_not(self) -> bool
{
850 matches
!(self, Self::Not
)
854 /// The kind of borrow in an `AddrOf` expression,
855 /// e.g., `&place` or `&raw const place`.
856 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
857 #[derive(Encodable, Decodable, HashStable_Generic)]
858 pub enum BorrowKind
{
859 /// A normal borrow, `&$expr` or `&mut $expr`.
860 /// The resulting type is either `&'a T` or `&'a mut T`
861 /// where `T = typeof($expr)` and `'a` is some lifetime.
863 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
864 /// The resulting type is either `*const T` or `*mut T`
865 /// where `T = typeof($expr)`.
869 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
871 /// The `+` operator (addition)
873 /// The `-` operator (subtraction)
875 /// The `*` operator (multiplication)
877 /// The `/` operator (division)
879 /// The `%` operator (modulus)
881 /// The `&&` operator (logical and)
883 /// The `||` operator (logical or)
885 /// The `^` operator (bitwise xor)
887 /// The `&` operator (bitwise and)
889 /// The `|` operator (bitwise or)
891 /// The `<<` operator (shift left)
893 /// The `>>` operator (shift right)
895 /// The `==` operator (equality)
897 /// The `<` operator (less than)
899 /// The `<=` operator (less than or equal to)
901 /// The `!=` operator (not equal to)
903 /// The `>=` operator (greater than or equal to)
905 /// The `>` operator (greater than)
910 pub fn to_string(&self) -> &'
static str {
933 pub fn lazy(&self) -> bool
{
934 matches
!(self, BinOpKind
::And
| BinOpKind
::Or
)
937 pub fn is_comparison(&self) -> bool
{
939 // Note for developers: please keep this as is;
940 // we want compilation to fail if another variant is added.
942 Eq
| Lt
| Le
| Ne
| Gt
| Ge
=> true,
943 And
| Or
| Add
| Sub
| Mul
| Div
| Rem
| BitXor
| BitAnd
| BitOr
| Shl
| Shr
=> false,
948 pub type BinOp
= Spanned
<BinOpKind
>;
952 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
953 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
955 /// The `*` operator for dereferencing
957 /// The `!` operator for logical inversion
959 /// The `-` operator for negation
964 pub fn to_string(op
: UnOp
) -> &'
static str {
974 #[derive(Clone, Encodable, Decodable, Debug)]
982 pub fn has_trailing_semicolon(&self) -> bool
{
984 StmtKind
::Semi(_
) => true,
985 StmtKind
::MacCall(mac
) => matches
!(mac
.style
, MacStmtStyle
::Semicolon
),
990 /// Converts a parsed `Stmt` to a `Stmt` with
991 /// a trailing semicolon.
993 /// This only modifies the parsed AST struct, not the attached
994 /// `LazyAttrTokenStream`. The parser is responsible for calling
995 /// `ToAttrTokenStream::add_trailing_semi` when there is actually
996 /// a semicolon in the tokenstream.
997 pub fn add_trailing_semicolon(mut self) -> Self {
998 self.kind
= match self.kind
{
999 StmtKind
::Expr(expr
) => StmtKind
::Semi(expr
),
1000 StmtKind
::MacCall(mac
) => {
1001 StmtKind
::MacCall(mac
.map(|MacCallStmt { mac, style: _, attrs, tokens }
| {
1002 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
1011 pub fn is_item(&self) -> bool
{
1012 matches
!(self.kind
, StmtKind
::Item(_
))
1015 pub fn is_expr(&self) -> bool
{
1016 matches
!(self.kind
, StmtKind
::Expr(_
))
1020 #[derive(Clone, Encodable, Decodable, Debug)]
1022 /// A local (let) binding.
1024 /// An item definition.
1026 /// Expr without trailing semi-colon.
1028 /// Expr with a trailing semi-colon.
1030 /// Just a trailing semi-colon.
1033 MacCall(P
<MacCallStmt
>),
1036 #[derive(Clone, Encodable, Decodable, Debug)]
1037 pub struct MacCallStmt
{
1038 pub mac
: P
<MacCall
>,
1039 pub style
: MacStmtStyle
,
1041 pub tokens
: Option
<LazyAttrTokenStream
>,
1044 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1045 pub enum MacStmtStyle
{
1046 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1047 /// `foo!(...);`, `foo![...];`).
1049 /// The macro statement had braces (e.g., `foo! { ... }`).
1051 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1052 /// `foo!(...)`). All of these will end up being converted into macro
1057 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1058 #[derive(Clone, Encodable, Decodable, Debug)]
1062 pub ty
: Option
<P
<Ty
>>,
1063 pub kind
: LocalKind
,
1066 pub tokens
: Option
<LazyAttrTokenStream
>,
1069 #[derive(Clone, Encodable, Decodable, Debug)]
1070 pub enum LocalKind
{
1071 /// Local declaration.
1072 /// Example: `let x;`
1074 /// Local declaration with an initializer.
1075 /// Example: `let x = y;`
1077 /// Local declaration with an initializer and an `else` clause.
1078 /// Example: `let Some(x) = y else { return };`
1079 InitElse(P
<Expr
>, P
<Block
>),
1083 pub fn init(&self) -> Option
<&Expr
> {
1086 Self::Init(i
) | Self::InitElse(i
, _
) => Some(i
),
1090 pub fn init_else_opt(&self) -> Option
<(&Expr
, Option
<&Block
>)> {
1093 Self::Init(init
) => Some((init
, None
)),
1094 Self::InitElse(init
, els
) => Some((init
, Some(els
))),
1099 /// An arm of a 'match'.
1101 /// E.g., `0..=10 => { println!("match!") }` as in
1105 /// 0..=10 => { println!("match!") },
1106 /// _ => { println!("no match!") },
1109 #[derive(Clone, Encodable, Decodable, Debug)]
1112 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1114 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1115 pub guard
: Option
<P
<Expr
>>,
1120 pub is_placeholder
: bool
,
1123 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1124 #[derive(Clone, Encodable, Decodable, Debug)]
1125 pub struct ExprField
{
1131 pub is_shorthand
: bool
,
1132 pub is_placeholder
: bool
,
1135 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1136 pub enum BlockCheckMode
{
1138 Unsafe(UnsafeSource
),
1141 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1142 pub enum UnsafeSource
{
1147 /// A constant (expression) that's not an item or associated item,
1148 /// but needs its own `DefId` for type-checking, const-eval, etc.
1149 /// These are usually found nested inside types (e.g., array lengths)
1150 /// or expressions (e.g., repeat counts), and also used to define
1151 /// explicit discriminant values for enum variants.
1152 #[derive(Clone, Encodable, Decodable, Debug)]
1153 pub struct AnonConst
{
1159 #[derive(Clone, Encodable, Decodable, Debug)]
1165 pub tokens
: Option
<LazyAttrTokenStream
>,
1169 /// Is this expr either `N`, or `{ N }`.
1171 /// If this is not the case, name resolution does not resolve `N` when using
1172 /// `min_const_generics` as more complex expressions are not supported.
1174 /// Does not ensure that the path resolves to a const param, the caller should check this.
1175 pub fn is_potential_trivial_const_arg(&self) -> bool
{
1176 let this
= if let ExprKind
::Block(block
, None
) = &self.kind
1177 && block
.stmts
.len() == 1
1178 && let StmtKind
::Expr(expr
) = &block
.stmts
[0].kind
1185 if let ExprKind
::Path(None
, path
) = &this
.kind
1186 && path
.is_potential_trivial_const_arg()
1194 pub fn to_bound(&self) -> Option
<GenericBound
> {
1196 ExprKind
::Path(None
, path
) => Some(GenericBound
::Trait(
1197 PolyTraitRef
::new(ThinVec
::new(), path
.clone(), self.span
),
1198 TraitBoundModifier
::None
,
1204 pub fn peel_parens(&self) -> &Expr
{
1205 let mut expr
= self;
1206 while let ExprKind
::Paren(inner
) = &expr
.kind
{
1212 pub fn peel_parens_and_refs(&self) -> &Expr
{
1213 let mut expr
= self;
1214 while let ExprKind
::Paren(inner
) | ExprKind
::AddrOf(BorrowKind
::Ref
, _
, inner
) = &expr
.kind
1221 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1222 pub fn to_ty(&self) -> Option
<P
<Ty
>> {
1223 let kind
= match &self.kind
{
1224 // Trivial conversions.
1225 ExprKind
::Path(qself
, path
) => TyKind
::Path(qself
.clone(), path
.clone()),
1226 ExprKind
::MacCall(mac
) => TyKind
::MacCall(mac
.clone()),
1228 ExprKind
::Paren(expr
) => expr
.to_ty().map(TyKind
::Paren
)?
,
1230 ExprKind
::AddrOf(BorrowKind
::Ref
, mutbl
, expr
) => {
1231 expr
.to_ty().map(|ty
| TyKind
::Ref(None
, MutTy { ty, mutbl: *mutbl }
))?
1234 ExprKind
::Repeat(expr
, expr_len
) => {
1235 expr
.to_ty().map(|ty
| TyKind
::Array(ty
, expr_len
.clone()))?
1238 ExprKind
::Array(exprs
) if exprs
.len() == 1 => exprs
[0].to_ty().map(TyKind
::Slice
)?
,
1240 ExprKind
::Tup(exprs
) => {
1241 let tys
= exprs
.iter().map(|expr
| expr
.to_ty()).collect
::<Option
<ThinVec
<_
>>>()?
;
1245 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1246 // then type of result is trait object.
1247 // Otherwise we don't assume the result type.
1248 ExprKind
::Binary(binop
, lhs
, rhs
) if binop
.node
== BinOpKind
::Add
=> {
1249 if let (Some(lhs
), Some(rhs
)) = (lhs
.to_bound(), rhs
.to_bound()) {
1250 TyKind
::TraitObject(vec
![lhs
, rhs
], TraitObjectSyntax
::None
)
1256 ExprKind
::Underscore
=> TyKind
::Infer
,
1258 // This expression doesn't look like a type syntactically.
1262 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }
))
1265 pub fn precedence(&self) -> ExprPrecedence
{
1267 ExprKind
::Array(_
) => ExprPrecedence
::Array
,
1268 ExprKind
::ConstBlock(_
) => ExprPrecedence
::ConstBlock
,
1269 ExprKind
::Call(..) => ExprPrecedence
::Call
,
1270 ExprKind
::MethodCall(..) => ExprPrecedence
::MethodCall
,
1271 ExprKind
::Tup(_
) => ExprPrecedence
::Tup
,
1272 ExprKind
::Binary(op
, ..) => ExprPrecedence
::Binary(op
.node
),
1273 ExprKind
::Unary(..) => ExprPrecedence
::Unary
,
1274 ExprKind
::Lit(_
) | ExprKind
::IncludedBytes(..) => ExprPrecedence
::Lit
,
1275 ExprKind
::Type(..) | ExprKind
::Cast(..) => ExprPrecedence
::Cast
,
1276 ExprKind
::Let(..) => ExprPrecedence
::Let
,
1277 ExprKind
::If(..) => ExprPrecedence
::If
,
1278 ExprKind
::While(..) => ExprPrecedence
::While
,
1279 ExprKind
::ForLoop(..) => ExprPrecedence
::ForLoop
,
1280 ExprKind
::Loop(..) => ExprPrecedence
::Loop
,
1281 ExprKind
::Match(..) => ExprPrecedence
::Match
,
1282 ExprKind
::Closure(..) => ExprPrecedence
::Closure
,
1283 ExprKind
::Block(..) => ExprPrecedence
::Block
,
1284 ExprKind
::TryBlock(..) => ExprPrecedence
::TryBlock
,
1285 ExprKind
::Async(..) => ExprPrecedence
::Async
,
1286 ExprKind
::Await(..) => ExprPrecedence
::Await
,
1287 ExprKind
::Assign(..) => ExprPrecedence
::Assign
,
1288 ExprKind
::AssignOp(..) => ExprPrecedence
::AssignOp
,
1289 ExprKind
::Field(..) => ExprPrecedence
::Field
,
1290 ExprKind
::Index(..) => ExprPrecedence
::Index
,
1291 ExprKind
::Range(..) => ExprPrecedence
::Range
,
1292 ExprKind
::Underscore
=> ExprPrecedence
::Path
,
1293 ExprKind
::Path(..) => ExprPrecedence
::Path
,
1294 ExprKind
::AddrOf(..) => ExprPrecedence
::AddrOf
,
1295 ExprKind
::Break(..) => ExprPrecedence
::Break
,
1296 ExprKind
::Continue(..) => ExprPrecedence
::Continue
,
1297 ExprKind
::Ret(..) => ExprPrecedence
::Ret
,
1298 ExprKind
::InlineAsm(..) => ExprPrecedence
::InlineAsm
,
1299 ExprKind
::OffsetOf(..) => ExprPrecedence
::OffsetOf
,
1300 ExprKind
::MacCall(..) => ExprPrecedence
::Mac
,
1301 ExprKind
::Struct(..) => ExprPrecedence
::Struct
,
1302 ExprKind
::Repeat(..) => ExprPrecedence
::Repeat
,
1303 ExprKind
::Paren(..) => ExprPrecedence
::Paren
,
1304 ExprKind
::Try(..) => ExprPrecedence
::Try
,
1305 ExprKind
::Yield(..) => ExprPrecedence
::Yield
,
1306 ExprKind
::Yeet(..) => ExprPrecedence
::Yeet
,
1307 ExprKind
::FormatArgs(..) => ExprPrecedence
::FormatArgs
,
1308 ExprKind
::Become(..) => ExprPrecedence
::Become
,
1309 ExprKind
::Err
=> ExprPrecedence
::Err
,
1313 pub fn take(&mut self) -> Self {
1318 kind
: ExprKind
::Err
,
1320 attrs
: AttrVec
::new(),
1326 /// To a first-order approximation, is this a pattern?
1327 pub fn is_approximately_pattern(&self) -> bool
{
1329 &self.peel_parens().kind
,
1331 | ExprKind
::Call(_
, _
)
1334 | ExprKind
::Range(_
, _
, _
)
1335 | ExprKind
::Underscore
1336 | ExprKind
::Path(_
, _
)
1337 | ExprKind
::Struct(_
)
1342 #[derive(Clone, Encodable, Decodable, Debug)]
1343 pub struct Closure
{
1344 pub binder
: ClosureBinder
,
1345 pub capture_clause
: CaptureBy
,
1346 pub constness
: Const
,
1347 pub asyncness
: Async
,
1348 pub movability
: Movability
,
1349 pub fn_decl
: P
<FnDecl
>,
1351 /// The span of the declaration block: 'move |...| -> ...'
1352 pub fn_decl_span
: Span
,
1353 /// The span of the argument block `|...|`
1354 pub fn_arg_span
: Span
,
1357 /// Limit types of a range (inclusive or exclusive)
1358 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1359 pub enum RangeLimits
{
1360 /// Inclusive at the beginning, exclusive at the end
1362 /// Inclusive at the beginning and end
1366 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1367 #[derive(Clone, Encodable, Decodable, Debug)]
1368 pub struct MethodCall
{
1369 /// The method name and its generic arguments, e.g. `foo::<Bar, Baz>`.
1370 pub seg
: PathSegment
,
1371 /// The receiver, e.g. `x`.
1372 pub receiver
: P
<Expr
>,
1373 /// The arguments, e.g. `a, b, c`.
1374 pub args
: ThinVec
<P
<Expr
>>,
1375 /// The span of the function, without the dot and receiver e.g. `foo::<Bar,
1380 #[derive(Clone, Encodable, Decodable, Debug)]
1381 pub enum StructRest
{
1386 /// No trailing `..` or expression.
1390 #[derive(Clone, Encodable, Decodable, Debug)]
1391 pub struct StructExpr
{
1392 pub qself
: Option
<P
<QSelf
>>,
1394 pub fields
: ThinVec
<ExprField
>,
1395 pub rest
: StructRest
,
1398 #[derive(Clone, Encodable, Decodable, Debug)]
1400 /// An array (`[a, b, c, d]`)
1401 Array(ThinVec
<P
<Expr
>>),
1402 /// Allow anonymous constants from an inline `const` block
1403 ConstBlock(AnonConst
),
1406 /// The first field resolves to the function itself,
1407 /// and the second field is the list of arguments.
1408 /// This also represents calling the constructor of
1409 /// tuple-like ADTs such as tuple structs and enum variants.
1410 Call(P
<Expr
>, ThinVec
<P
<Expr
>>),
1411 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1412 MethodCall(Box
<MethodCall
>),
1413 /// A tuple (e.g., `(a, b, c, d)`).
1414 Tup(ThinVec
<P
<Expr
>>),
1415 /// A binary operation (e.g., `a + b`, `a * b`).
1416 Binary(BinOp
, P
<Expr
>, P
<Expr
>),
1417 /// A unary operation (e.g., `!x`, `*x`).
1418 Unary(UnOp
, P
<Expr
>),
1419 /// A literal (e.g., `1`, `"foo"`).
1421 /// A cast (e.g., `foo as f64`).
1422 Cast(P
<Expr
>, P
<Ty
>),
1423 /// A type ascription (e.g., `42: usize`).
1424 Type(P
<Expr
>, P
<Ty
>),
1425 /// A `let pat = expr` expression that is only semantically allowed in the condition
1426 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1428 /// `Span` represents the whole `let pat = expr` statement.
1429 Let(P
<Pat
>, P
<Expr
>, Span
),
1430 /// An `if` block, with an optional `else` block.
1432 /// `if expr { block } else { expr }`
1433 If(P
<Expr
>, P
<Block
>, Option
<P
<Expr
>>),
1434 /// A while loop, with an optional label.
1436 /// `'label: while expr { block }`
1437 While(P
<Expr
>, P
<Block
>, Option
<Label
>),
1438 /// A `for` loop, with an optional label.
1440 /// `'label: for pat in expr { block }`
1442 /// This is desugared to a combination of `loop` and `match` expressions.
1443 ForLoop(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<Label
>),
1444 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1446 /// `'label: loop { block }`
1447 Loop(P
<Block
>, Option
<Label
>, Span
),
1448 /// A `match` block.
1449 Match(P
<Expr
>, ThinVec
<Arm
>),
1450 /// A closure (e.g., `move |a, b, c| a + b + c`).
1451 Closure(Box
<Closure
>),
1452 /// A block (`'label: { ... }`).
1453 Block(P
<Block
>, Option
<Label
>),
1454 /// An async block (`async move { ... }`).
1456 /// The async block used to have a `NodeId`, which was removed in favor of
1457 /// using the parent `NodeId` of the parent `Expr`.
1458 Async(CaptureBy
, P
<Block
>),
1459 /// An await expression (`my_future.await`). Span is of await keyword.
1460 Await(P
<Expr
>, Span
),
1462 /// A try block (`try { ... }`).
1465 /// An assignment (`a = foo()`).
1466 /// The `Span` argument is the span of the `=` token.
1467 Assign(P
<Expr
>, P
<Expr
>, Span
),
1468 /// An assignment with an operator.
1471 AssignOp(BinOp
, P
<Expr
>, P
<Expr
>),
1472 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1473 Field(P
<Expr
>, Ident
),
1474 /// An indexing operation (e.g., `foo[2]`).
1475 /// The span represents the span of the `[2]`, including brackets.
1476 Index(P
<Expr
>, P
<Expr
>, Span
),
1477 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1478 Range(Option
<P
<Expr
>>, Option
<P
<Expr
>>, RangeLimits
),
1479 /// An underscore, used in destructuring assignment to ignore a value.
1482 /// Variable reference, possibly containing `::` and/or type
1483 /// parameters (e.g., `foo::bar::<baz>`).
1485 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1486 Path(Option
<P
<QSelf
>>, Path
),
1488 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1489 AddrOf(BorrowKind
, Mutability
, P
<Expr
>),
1490 /// A `break`, with an optional label to break, and an optional expression.
1491 Break(Option
<Label
>, Option
<P
<Expr
>>),
1492 /// A `continue`, with an optional label.
1493 Continue(Option
<Label
>),
1494 /// A `return`, with an optional value to be returned.
1495 Ret(Option
<P
<Expr
>>),
1497 /// Output of the `asm!()` macro.
1498 InlineAsm(P
<InlineAsm
>),
1500 /// Output of the `offset_of!()` macro.
1501 OffsetOf(P
<Ty
>, P
<[Ident
]>),
1503 /// A macro invocation; pre-expansion.
1504 MacCall(P
<MacCall
>),
1506 /// A struct literal expression.
1508 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1509 Struct(P
<StructExpr
>),
1511 /// An array literal constructed from one repeated element.
1513 /// E.g., `[1; 5]`. The expression is the element to be
1514 /// repeated; the constant is the number of times to repeat it.
1515 Repeat(P
<Expr
>, AnonConst
),
1517 /// No-op: used solely so we can pretty-print faithfully.
1520 /// A try expression (`expr?`).
1523 /// A `yield`, with an optional value to be yielded.
1524 Yield(Option
<P
<Expr
>>),
1526 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1527 /// with an optional value to be returned.
1528 Yeet(Option
<P
<Expr
>>),
1530 /// A tail call return, with the value to be returned.
1532 /// While `.0` must be a function call, we check this later, after parsing.
1535 /// Bytes included via `include_bytes!`
1536 /// Added for optimization purposes to avoid the need to escape
1537 /// large binary blobs - should always behave like [`ExprKind::Lit`]
1538 /// with a `ByteStr` literal.
1539 IncludedBytes(Lrc
<[u8]>),
1541 /// A `format_args!()` expression.
1542 FormatArgs(P
<FormatArgs
>),
1544 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1548 /// The explicit `Self` type in a "qualified path". The actual
1549 /// path, including the trait and the associated item, is stored
1550 /// separately. `position` represents the index of the associated
1551 /// item qualified with this `Self` type.
1553 /// ```ignore (only-for-syntax-highlight)
1554 /// <Vec<T> as a::b::Trait>::AssociatedItem
1555 /// ^~~~~ ~~~~~~~~~~~~~~^
1558 /// <Vec<T>>::AssociatedItem
1562 #[derive(Clone, Encodable, Decodable, Debug)]
1566 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1567 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1568 /// 0`, this is an empty span.
1569 pub path_span
: Span
,
1570 pub position
: usize,
1573 /// A capture clause used in closures and `async` blocks.
1574 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1575 pub enum CaptureBy
{
1576 /// `move |x| y + x`.
1578 /// `move` keyword was not specified.
1582 /// The movability of a generator / closure literal:
1583 /// whether a generator contains self-references, causing it to be `!Unpin`.
1584 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1585 #[derive(HashStable_Generic)]
1586 pub enum Movability
{
1587 /// May contain self-references, `!Unpin`.
1589 /// Must not contain self-references, `Unpin`.
1593 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1594 #[derive(Clone, Encodable, Decodable, Debug)]
1595 pub enum ClosureBinder
{
1596 /// The binder is not present, all closure lifetimes are inferred.
1598 /// The binder is present.
1600 /// Span of the whole `for<>` clause
1603 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1604 /// ^^^^^^^^^^^ -- this
1608 /// Lifetimes in the `for<>` closure
1611 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1614 generic_params
: ThinVec
<GenericParam
>,
1618 /// Represents a macro invocation. The `path` indicates which macro
1619 /// is being invoked, and the `args` are arguments passed to it.
1620 #[derive(Clone, Encodable, Decodable, Debug)]
1621 pub struct MacCall
{
1623 pub args
: P
<DelimArgs
>,
1627 pub fn span(&self) -> Span
{
1628 self.path
.span
.to(self.args
.dspan
.entire())
1632 /// Arguments passed to an attribute macro.
1633 #[derive(Clone, Encodable, Decodable, Debug)]
1635 /// No arguments: `#[attr]`.
1637 /// Delimited arguments: `#[attr()/[]/{}]`.
1638 Delimited(DelimArgs
),
1639 /// Arguments of a key-value attribute: `#[attr = "value"]`.
1641 /// Span of the `=` token.
1648 // The RHS of an `AttrArgs::Eq` starts out as an expression. Once macro
1649 // expansion is completed, all cases end up either as a meta item literal,
1650 // which is the form used after lowering to HIR, or as an error.
1651 #[derive(Clone, Encodable, Decodable, Debug)]
1652 pub enum AttrArgsEq
{
1658 pub fn span(&self) -> Option
<Span
> {
1660 AttrArgs
::Empty
=> None
,
1661 AttrArgs
::Delimited(args
) => Some(args
.dspan
.entire()),
1662 AttrArgs
::Eq(eq_span
, AttrArgsEq
::Ast(expr
)) => Some(eq_span
.to(expr
.span
)),
1663 AttrArgs
::Eq(_
, AttrArgsEq
::Hir(lit
)) => {
1664 unreachable
!("in literal form when getting span: {:?}", lit
);
1669 /// Tokens inside the delimiters or after `=`.
1670 /// Proc macros see these tokens, for example.
1671 pub fn inner_tokens(&self) -> TokenStream
{
1673 AttrArgs
::Empty
=> TokenStream
::default(),
1674 AttrArgs
::Delimited(args
) => args
.tokens
.clone(),
1675 AttrArgs
::Eq(_
, AttrArgsEq
::Ast(expr
)) => TokenStream
::from_ast(expr
),
1676 AttrArgs
::Eq(_
, AttrArgsEq
::Hir(lit
)) => {
1677 unreachable
!("in literal form when getting inner tokens: {:?}", lit
)
1683 impl<CTX
> HashStable
<CTX
> for AttrArgs
1685 CTX
: crate::HashStableContext
,
1687 fn hash_stable(&self, ctx
: &mut CTX
, hasher
: &mut StableHasher
) {
1688 mem
::discriminant(self).hash_stable(ctx
, hasher
);
1690 AttrArgs
::Empty
=> {}
1691 AttrArgs
::Delimited(args
) => args
.hash_stable(ctx
, hasher
),
1692 AttrArgs
::Eq(_eq_span
, AttrArgsEq
::Ast(expr
)) => {
1693 unreachable
!("hash_stable {:?}", expr
);
1695 AttrArgs
::Eq(eq_span
, AttrArgsEq
::Hir(lit
)) => {
1696 eq_span
.hash_stable(ctx
, hasher
);
1697 lit
.hash_stable(ctx
, hasher
);
1703 /// Delimited arguments, as used in `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1704 #[derive(Clone, Encodable, Decodable, Debug)]
1705 pub struct DelimArgs
{
1706 pub dspan
: DelimSpan
,
1707 pub delim
: Delimiter
, // Note: `Delimiter::Invisible` never occurs
1708 pub tokens
: TokenStream
,
1712 /// Whether a macro with these arguments needs a semicolon
1713 /// when used as a standalone item or statement.
1714 pub fn need_semicolon(&self) -> bool
{
1715 !matches
!(self, DelimArgs { delim: Delimiter::Brace, .. }
)
1719 impl<CTX
> HashStable
<CTX
> for DelimArgs
1721 CTX
: crate::HashStableContext
,
1723 fn hash_stable(&self, ctx
: &mut CTX
, hasher
: &mut StableHasher
) {
1724 let DelimArgs { dspan, delim, tokens }
= self;
1725 dspan
.hash_stable(ctx
, hasher
);
1726 delim
.hash_stable(ctx
, hasher
);
1727 tokens
.hash_stable(ctx
, hasher
);
1731 /// Represents a macro definition.
1732 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1733 pub struct MacroDef
{
1734 pub body
: P
<DelimArgs
>,
1735 /// `true` if macro was defined with `macro_rules`.
1736 pub macro_rules
: bool
,
1739 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1740 #[derive(HashStable_Generic)]
1742 /// A regular string, like `"foo"`.
1744 /// A raw string, like `r##"foo"##`.
1746 /// The value is the number of `#` symbols used.
1750 /// A literal in a meta item.
1751 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1752 pub struct MetaItemLit
{
1753 /// The original literal as written in the source code.
1755 /// The original suffix as written in the source code.
1756 pub suffix
: Option
<Symbol
>,
1757 /// The "semantic" representation of the literal lowered from the original tokens.
1758 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1763 /// Similar to `MetaItemLit`, but restricted to string literals.
1764 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1766 /// The original literal as written in source code.
1768 /// The original suffix as written in source code.
1769 pub suffix
: Option
<Symbol
>,
1770 /// The semantic (unescaped) representation of the literal.
1771 pub symbol_unescaped
: Symbol
,
1772 pub style
: StrStyle
,
1777 pub fn as_token_lit(&self) -> token
::Lit
{
1778 let token_kind
= match self.style
{
1779 StrStyle
::Cooked
=> token
::Str
,
1780 StrStyle
::Raw(n
) => token
::StrRaw(n
),
1782 token
::Lit
::new(token_kind
, self.symbol
, self.suffix
)
1786 /// Type of the integer literal based on provided suffix.
1787 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1788 #[derive(HashStable_Generic)]
1789 pub enum LitIntType
{
1798 /// Type of the float literal based on provided suffix.
1799 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1800 #[derive(HashStable_Generic)]
1801 pub enum LitFloatType
{
1802 /// A float literal with a suffix (`1f32` or `1E10f32`).
1804 /// A float literal without a suffix (`1.0 or 1.0E10`).
1808 /// This type is used within both `ast::MetaItemLit` and `hir::Lit`.
1810 /// Note that the entire literal (including the suffix) is considered when
1811 /// deciding the `LitKind`. This means that float literals like `1f32` are
1812 /// classified by this type as `Float`. This is different to `token::LitKind`
1813 /// which does *not* consider the suffix.
1814 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1816 /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
1817 /// from the original token's symbol.
1818 Str(Symbol
, StrStyle
),
1819 /// A byte string (`b"foo"`). Not stored as a symbol because it might be
1820 /// non-utf8, and symbols only allow utf8 strings.
1821 ByteStr(Lrc
<[u8]>, StrStyle
),
1822 /// A C String (`c"foo"`). Guaranteed to only have `\0` at the end.
1823 CStr(Lrc
<[u8]>, StrStyle
),
1824 /// A byte char (`b'f'`).
1826 /// A character literal (`'a'`).
1828 /// An integer literal (`1`).
1829 Int(u128
, LitIntType
),
1830 /// A float literal (`1.0`, `1f64` or `1E10f64`). The pre-suffix part is
1831 /// stored as a symbol rather than `f64` so that `LitKind` can impl `Eq`
1833 Float(Symbol
, LitFloatType
),
1834 /// A boolean literal (`true`, `false`).
1836 /// Placeholder for a literal that wasn't well-formed in some way.
1841 pub fn str(&self) -> Option
<Symbol
> {
1843 LitKind
::Str(s
, _
) => Some(s
),
1848 /// Returns `true` if this literal is a string.
1849 pub fn is_str(&self) -> bool
{
1850 matches
!(self, LitKind
::Str(..))
1853 /// Returns `true` if this literal is byte literal string.
1854 pub fn is_bytestr(&self) -> bool
{
1855 matches
!(self, LitKind
::ByteStr(..))
1858 /// Returns `true` if this is a numeric literal.
1859 pub fn is_numeric(&self) -> bool
{
1860 matches
!(self, LitKind
::Int(..) | LitKind
::Float(..))
1863 /// Returns `true` if this literal has no suffix.
1864 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1865 pub fn is_unsuffixed(&self) -> bool
{
1869 /// Returns `true` if this literal has a suffix.
1870 pub fn is_suffixed(&self) -> bool
{
1872 // suffixed variants
1873 LitKind
::Int(_
, LitIntType
::Signed(..) | LitIntType
::Unsigned(..))
1874 | LitKind
::Float(_
, LitFloatType
::Suffixed(..)) => true,
1875 // unsuffixed variants
1877 | LitKind
::ByteStr(..)
1881 | LitKind
::Int(_
, LitIntType
::Unsuffixed
)
1882 | LitKind
::Float(_
, LitFloatType
::Unsuffixed
)
1884 | LitKind
::Err
=> false,
1889 // N.B., If you change this, you'll probably want to change the corresponding
1890 // type structure in `middle/ty.rs` as well.
1891 #[derive(Clone, Encodable, Decodable, Debug)]
1894 pub mutbl
: Mutability
,
1897 /// Represents a function's signature in a trait declaration,
1898 /// trait implementation, or free function.
1899 #[derive(Clone, Encodable, Decodable, Debug)]
1901 pub header
: FnHeader
,
1902 pub decl
: P
<FnDecl
>,
1906 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1907 #[derive(Encodable, Decodable, HashStable_Generic)]
1914 pub fn name_str(self) -> &'
static str {
1916 FloatTy
::F32
=> "f32",
1917 FloatTy
::F64
=> "f64",
1921 pub fn name(self) -> Symbol
{
1923 FloatTy
::F32
=> sym
::f32,
1924 FloatTy
::F64
=> sym
::f64,
1929 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1930 #[derive(Encodable, Decodable, HashStable_Generic)]
1941 pub fn name_str(&self) -> &'
static str {
1943 IntTy
::Isize
=> "isize",
1945 IntTy
::I16
=> "i16",
1946 IntTy
::I32
=> "i32",
1947 IntTy
::I64
=> "i64",
1948 IntTy
::I128
=> "i128",
1952 pub fn name(&self) -> Symbol
{
1954 IntTy
::Isize
=> sym
::isize,
1955 IntTy
::I8
=> sym
::i8,
1956 IntTy
::I16
=> sym
::i16,
1957 IntTy
::I32
=> sym
::i32,
1958 IntTy
::I64
=> sym
::i64,
1959 IntTy
::I128
=> sym
::i128
,
1964 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1965 #[derive(Encodable, Decodable, HashStable_Generic)]
1976 pub fn name_str(&self) -> &'
static str {
1978 UintTy
::Usize
=> "usize",
1980 UintTy
::U16
=> "u16",
1981 UintTy
::U32
=> "u32",
1982 UintTy
::U64
=> "u64",
1983 UintTy
::U128
=> "u128",
1987 pub fn name(&self) -> Symbol
{
1989 UintTy
::Usize
=> sym
::usize,
1990 UintTy
::U8
=> sym
::u8,
1991 UintTy
::U16
=> sym
::u16,
1992 UintTy
::U32
=> sym
::u32,
1993 UintTy
::U64
=> sym
::u64,
1994 UintTy
::U128
=> sym
::u128
,
1999 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
2000 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
2001 #[derive(Clone, Encodable, Decodable, Debug)]
2002 pub struct AssocConstraint
{
2005 pub gen_args
: Option
<GenericArgs
>,
2006 pub kind
: AssocConstraintKind
,
2010 /// The kinds of an `AssocConstraint`.
2011 #[derive(Clone, Encodable, Decodable, Debug)]
2017 impl From
<P
<Ty
>> for Term
{
2018 fn from(v
: P
<Ty
>) -> Self {
2023 impl From
<AnonConst
> for Term
{
2024 fn from(v
: AnonConst
) -> Self {
2029 /// The kinds of an `AssocConstraint`.
2030 #[derive(Clone, Encodable, Decodable, Debug)]
2031 pub enum AssocConstraintKind
{
2032 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
2033 Equality { term: Term }
,
2034 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
2035 Bound { bounds: GenericBounds }
,
2038 #[derive(Encodable, Decodable, Debug)]
2043 pub tokens
: Option
<LazyAttrTokenStream
>,
2047 fn clone(&self) -> Self {
2048 ensure_sufficient_stack(|| Self {
2050 kind
: self.kind
.clone(),
2052 tokens
: self.tokens
.clone(),
2058 pub fn peel_refs(&self) -> &Self {
2059 let mut final_ty
= self;
2060 while let TyKind
::Ref(_
, MutTy { ty, .. }
) | TyKind
::Ptr(MutTy { ty, .. }
) = &final_ty
.kind
2068 #[derive(Clone, Encodable, Decodable, Debug)]
2069 pub struct BareFnTy
{
2070 pub unsafety
: Unsafe
,
2072 pub generic_params
: ThinVec
<GenericParam
>,
2073 pub decl
: P
<FnDecl
>,
2074 /// Span of the `fn(...) -> ...` part.
2075 pub decl_span
: Span
,
2078 /// The various kinds of type recognized by the compiler.
2079 #[derive(Clone, Encodable, Decodable, Debug)]
2081 /// A variable-length slice (`[T]`).
2083 /// A fixed length array (`[T; n]`).
2084 Array(P
<Ty
>, AnonConst
),
2085 /// A raw pointer (`*const T` or `*mut T`).
2087 /// A reference (`&'a T` or `&'a mut T`).
2088 Ref(Option
<Lifetime
>, MutTy
),
2089 /// A bare function (e.g., `fn(usize) -> bool`).
2090 BareFn(P
<BareFnTy
>),
2091 /// The never type (`!`).
2093 /// A tuple (`(A, B, C, D,...)`).
2094 Tup(ThinVec
<P
<Ty
>>),
2095 /// A path (`module::module::...::Type`), optionally
2096 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2098 /// Type parameters are stored in the `Path` itself.
2099 Path(Option
<P
<QSelf
>>, Path
),
2100 /// A trait object type `Bound1 + Bound2 + Bound3`
2101 /// where `Bound` is a trait or a lifetime.
2102 TraitObject(GenericBounds
, TraitObjectSyntax
),
2103 /// An `impl Bound1 + Bound2 + Bound3` type
2104 /// where `Bound` is a trait or a lifetime.
2106 /// The `NodeId` exists to prevent lowering from having to
2107 /// generate `NodeId`s on the fly, which would complicate
2108 /// the generation of opaque `type Foo = impl Trait` items significantly.
2109 ImplTrait(NodeId
, GenericBounds
),
2110 /// No-op; kept solely so that we can pretty-print faithfully.
2114 /// This means the type should be inferred instead of it having been
2115 /// specified. This can appear anywhere in a type.
2117 /// Inferred type of a `self` or `&self` argument in a method.
2119 /// A macro in the type position.
2120 MacCall(P
<MacCall
>),
2121 /// Placeholder for a kind that has failed to be defined.
2123 /// Placeholder for a `va_list`.
2128 pub fn is_implicit_self(&self) -> bool
{
2129 matches
!(self, TyKind
::ImplicitSelf
)
2132 pub fn is_unit(&self) -> bool
{
2133 matches
!(self, TyKind
::Tup(tys
) if tys
.is_empty())
2136 pub fn is_simple_path(&self) -> Option
<Symbol
> {
2137 if let TyKind
::Path(None
, Path { segments, .. }
) = &self
2138 && let [segment
] = &segments
[..]
2139 && segment
.args
.is_none()
2141 Some(segment
.ident
.name
)
2148 /// Syntax used to declare a trait object.
2149 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2150 pub enum TraitObjectSyntax
{
2156 /// Inline assembly operand explicit register or register class.
2158 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2159 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2160 pub enum InlineAsmRegOrRegClass
{
2165 bitflags
::bitflags
! {
2166 #[derive(Encodable, Decodable, HashStable_Generic)]
2167 pub struct InlineAsmOptions
: u16 {
2168 const PURE
= 1 << 0;
2169 const NOMEM
= 1 << 1;
2170 const READONLY
= 1 << 2;
2171 const PRESERVES_FLAGS
= 1 << 3;
2172 const NORETURN
= 1 << 4;
2173 const NOSTACK
= 1 << 5;
2174 const ATT_SYNTAX
= 1 << 6;
2176 const MAY_UNWIND
= 1 << 8;
2180 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2181 pub enum InlineAsmTemplatePiece
{
2183 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span }
,
2186 impl fmt
::Display
for InlineAsmTemplatePiece
{
2187 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2189 Self::String(s
) => {
2190 for c
in s
.chars() {
2192 '
{'
=> f
.write_str("{{")?
,
2193 '
}'
=> f
.write_str("}}")?
,
2199 Self::Placeholder { operand_idx, modifier: Some(modifier), .. }
=> {
2200 write
!(f
, "{{{operand_idx}:{modifier}}}")
2202 Self::Placeholder { operand_idx, modifier: None, .. }
=> {
2203 write
!(f
, "{{{operand_idx}}}")
2209 impl InlineAsmTemplatePiece
{
2210 /// Rebuilds the asm template string from its pieces.
2211 pub fn to_string(s
: &[Self]) -> String
{
2213 let mut out
= String
::new();
2215 let _
= write
!(out
, "{p}");
2221 /// Inline assembly symbol operands get their own AST node that is somewhat
2222 /// similar to `AnonConst`.
2224 /// The main difference is that we specifically don't assign it `DefId` in
2225 /// `DefCollector`. Instead this is deferred until AST lowering where we
2226 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2227 /// depending on what the path resolves to.
2228 #[derive(Clone, Encodable, Decodable, Debug)]
2229 pub struct InlineAsmSym
{
2231 pub qself
: Option
<P
<QSelf
>>,
2235 /// Inline assembly operand.
2237 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2238 #[derive(Clone, Encodable, Decodable, Debug)]
2239 pub enum InlineAsmOperand
{
2241 reg
: InlineAsmRegOrRegClass
,
2245 reg
: InlineAsmRegOrRegClass
,
2247 expr
: Option
<P
<Expr
>>,
2250 reg
: InlineAsmRegOrRegClass
,
2255 reg
: InlineAsmRegOrRegClass
,
2258 out_expr
: Option
<P
<Expr
>>,
2261 anon_const
: AnonConst
,
2268 /// Inline assembly.
2270 /// E.g., `asm!("NOP");`.
2271 #[derive(Clone, Encodable, Decodable, Debug)]
2272 pub struct InlineAsm
{
2273 pub template
: Vec
<InlineAsmTemplatePiece
>,
2274 pub template_strs
: Box
<[(Symbol
, Option
<Symbol
>, Span
)]>,
2275 pub operands
: Vec
<(InlineAsmOperand
, Span
)>,
2276 pub clobber_abis
: Vec
<(Symbol
, Span
)>,
2277 pub options
: InlineAsmOptions
,
2278 pub line_spans
: Vec
<Span
>,
2281 /// A parameter in a function header.
2283 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2284 #[derive(Clone, Encodable, Decodable, Debug)]
2291 pub is_placeholder
: bool
,
2294 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2296 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2297 #[derive(Clone, Encodable, Decodable, Debug)]
2299 /// `self`, `mut self`
2301 /// `&'lt self`, `&'lt mut self`
2302 Region(Option
<Lifetime
>, Mutability
),
2303 /// `self: TYPE`, `mut self: TYPE`
2304 Explicit(P
<Ty
>, Mutability
),
2307 pub type ExplicitSelf
= Spanned
<SelfKind
>;
2310 /// Attempts to cast parameter to `ExplicitSelf`.
2311 pub fn to_self(&self) -> Option
<ExplicitSelf
> {
2312 if let PatKind
::Ident(BindingAnnotation(ByRef
::No
, mutbl
), ident
, _
) = self.pat
.kind
{
2313 if ident
.name
== kw
::SelfLower
{
2314 return match self.ty
.kind
{
2315 TyKind
::ImplicitSelf
=> Some(respan(self.pat
.span
, SelfKind
::Value(mutbl
))),
2316 TyKind
::Ref(lt
, MutTy { ref ty, mutbl }
) if ty
.kind
.is_implicit_self() => {
2317 Some(respan(self.pat
.span
, SelfKind
::Region(lt
, mutbl
)))
2320 self.pat
.span
.to(self.ty
.span
),
2321 SelfKind
::Explicit(self.ty
.clone(), mutbl
),
2329 /// Returns `true` if parameter is `self`.
2330 pub fn is_self(&self) -> bool
{
2331 if let PatKind
::Ident(_
, ident
, _
) = self.pat
.kind
{
2332 ident
.name
== kw
::SelfLower
2338 /// Builds a `Param` object from `ExplicitSelf`.
2339 pub fn from_self(attrs
: AttrVec
, eself
: ExplicitSelf
, eself_ident
: Ident
) -> Param
{
2340 let span
= eself
.span
.to(eself_ident
.span
);
2341 let infer_ty
= P(Ty
{
2343 kind
: TyKind
::ImplicitSelf
,
2344 span
: eself_ident
.span
,
2347 let (mutbl
, ty
) = match eself
.node
{
2348 SelfKind
::Explicit(ty
, mutbl
) => (mutbl
, ty
),
2349 SelfKind
::Value(mutbl
) => (mutbl
, infer_ty
),
2350 SelfKind
::Region(lt
, mutbl
) => (
2354 kind
: TyKind
::Ref(lt
, MutTy { ty: infer_ty, mutbl }
),
2364 kind
: PatKind
::Ident(BindingAnnotation(ByRef
::No
, mutbl
), eself_ident
, None
),
2371 is_placeholder
: false,
2376 /// A signature (not the body) of a function declaration.
2378 /// E.g., `fn foo(bar: baz)`.
2380 /// Please note that it's different from `FnHeader` structure
2381 /// which contains metadata about function safety, asyncness, constness and ABI.
2382 #[derive(Clone, Encodable, Decodable, Debug)]
2384 pub inputs
: ThinVec
<Param
>,
2385 pub output
: FnRetTy
,
2389 pub fn has_self(&self) -> bool
{
2390 self.inputs
.get(0).is_some_and(Param
::is_self
)
2392 pub fn c_variadic(&self) -> bool
{
2393 self.inputs
.last().is_some_and(|arg
| matches
!(arg
.ty
.kind
, TyKind
::CVarArgs
))
2397 /// Is the trait definition an auto trait?
2398 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2404 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2405 #[derive(HashStable_Generic)]
2411 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2413 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId }
,
2418 pub fn is_async(self) -> bool
{
2419 matches
!(self, Async
::Yes { .. }
)
2422 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2423 pub fn opt_return_id(self) -> Option
<(NodeId
, Span
)> {
2425 Async
::Yes { return_impl_trait_id, span, .. }
=> Some((return_impl_trait_id
, span
)),
2431 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2432 #[derive(HashStable_Generic)]
2438 /// Item defaultness.
2439 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2440 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2441 pub enum Defaultness
{
2446 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2447 pub enum ImplPolarity
{
2448 /// `impl Trait for Type`
2450 /// `impl !Trait for Type`
2454 impl fmt
::Debug
for ImplPolarity
{
2455 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2457 ImplPolarity
::Positive
=> "positive".fmt(f
),
2458 ImplPolarity
::Negative(_
) => "negative".fmt(f
),
2463 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2464 pub enum BoundPolarity
{
2473 #[derive(Clone, Encodable, Decodable, Debug)]
2475 /// Returns type is not specified.
2477 /// Functions default to `()` and closures default to inference.
2478 /// Span points to where return type would be inserted.
2480 /// Everything else.
2485 pub fn span(&self) -> Span
{
2487 &FnRetTy
::Default(span
) => span
,
2488 FnRetTy
::Ty(ty
) => ty
.span
,
2493 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2499 /// Module item kind.
2500 #[derive(Clone, Encodable, Decodable, Debug)]
2502 /// Module with inlined definition `mod foo { ... }`,
2503 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2504 /// The inner span is from the first token past `{` to the last token until `}`,
2505 /// or from the first to the last token in the loaded file.
2506 Loaded(ThinVec
<P
<Item
>>, Inline
, ModSpans
),
2507 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2511 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2512 pub struct ModSpans
{
2513 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2514 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2515 pub inner_span
: Span
,
2516 pub inject_use_span
: Span
,
2519 /// Foreign module declaration.
2521 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2522 #[derive(Clone, Encodable, Decodable, Debug)]
2523 pub struct ForeignMod
{
2524 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2525 /// semantically by Rust.
2526 pub unsafety
: Unsafe
,
2527 pub abi
: Option
<StrLit
>,
2528 pub items
: ThinVec
<P
<ForeignItem
>>,
2531 #[derive(Clone, Encodable, Decodable, Debug)]
2532 pub struct EnumDef
{
2533 pub variants
: ThinVec
<Variant
>,
2536 #[derive(Clone, Encodable, Decodable, Debug)]
2537 pub struct Variant
{
2538 /// Attributes of the variant.
2540 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2544 /// The visibility of the variant. Syntactically accepted but not semantically.
2545 pub vis
: Visibility
,
2546 /// Name of the variant.
2549 /// Fields and constructor id of the variant.
2550 pub data
: VariantData
,
2551 /// Explicit discriminant, e.g., `Foo = 1`.
2552 pub disr_expr
: Option
<AnonConst
>,
2553 /// Is a macro placeholder
2554 pub is_placeholder
: bool
,
2557 /// Part of `use` item to the right of its prefix.
2558 #[derive(Clone, Encodable, Decodable, Debug)]
2559 pub enum UseTreeKind
{
2560 /// `use prefix` or `use prefix as rename`
2561 Simple(Option
<Ident
>),
2562 /// `use prefix::{...}`
2563 Nested(ThinVec
<(UseTree
, NodeId
)>),
2568 /// A tree of paths sharing common prefixes.
2569 /// Used in `use` items both at top-level and inside of braces in import groups.
2570 #[derive(Clone, Encodable, Decodable, Debug)]
2571 pub struct UseTree
{
2573 pub kind
: UseTreeKind
,
2578 pub fn ident(&self) -> Ident
{
2580 UseTreeKind
::Simple(Some(rename
)) => rename
,
2581 UseTreeKind
::Simple(None
) => {
2582 self.prefix
.segments
.last().expect("empty prefix in a simple import").ident
2584 _
=> panic
!("`UseTree::ident` can only be used on a simple import"),
2589 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2590 /// are contained as statements within items. These two cases need to be
2591 /// distinguished for pretty-printing.
2592 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2593 pub enum AttrStyle
{
2598 rustc_index
::newtype_index
! {
2600 #[debug_format = "AttrId({})"]
2601 pub struct AttrId {}
2604 impl<S
: Encoder
> Encodable
<S
> for AttrId
{
2605 fn encode(&self, _s
: &mut S
) {}
2608 impl<D
: Decoder
> Decodable
<D
> for AttrId
{
2609 default fn decode(_
: &mut D
) -> AttrId
{
2610 panic
!("cannot decode `AttrId` with `{}`", std
::any
::type_name
::<D
>());
2614 /// A list of attributes.
2615 pub type AttrVec
= ThinVec
<Attribute
>;
2617 /// A syntax-level representation of an attribute.
2618 #[derive(Clone, Encodable, Decodable, Debug)]
2619 pub struct Attribute
{
2622 /// Denotes if the attribute decorates the following construct (outer)
2623 /// or the construct this attribute is contained within (inner).
2624 pub style
: AttrStyle
,
2628 #[derive(Clone, Encodable, Decodable, Debug)]
2630 /// A normal attribute.
2631 Normal(P
<NormalAttr
>),
2633 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2634 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2635 /// variant (which is much less compact and thus more expensive).
2636 DocComment(CommentKind
, Symbol
),
2639 #[derive(Clone, Encodable, Decodable, Debug)]
2640 pub struct NormalAttr
{
2642 pub tokens
: Option
<LazyAttrTokenStream
>,
2646 pub fn from_ident(ident
: Ident
) -> Self {
2648 item
: AttrItem { path: Path::from_ident(ident), args: AttrArgs::Empty, tokens: None }
,
2654 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2655 pub struct AttrItem
{
2658 pub tokens
: Option
<LazyAttrTokenStream
>,
2661 /// `TraitRef`s appear in impls.
2663 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2664 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2665 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2666 /// same as the impl's `NodeId`).
2667 #[derive(Clone, Encodable, Decodable, Debug)]
2668 pub struct TraitRef
{
2673 #[derive(Clone, Encodable, Decodable, Debug)]
2674 pub struct PolyTraitRef
{
2675 /// The `'a` in `for<'a> Foo<&'a T>`.
2676 pub bound_generic_params
: ThinVec
<GenericParam
>,
2678 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2679 pub trait_ref
: TraitRef
,
2685 pub fn new(generic_params
: ThinVec
<GenericParam
>, path
: Path
, span
: Span
) -> Self {
2687 bound_generic_params
: generic_params
,
2688 trait_ref
: TraitRef { path, ref_id: DUMMY_NODE_ID }
,
2694 #[derive(Clone, Encodable, Decodable, Debug)]
2695 pub struct Visibility
{
2696 pub kind
: VisibilityKind
,
2698 pub tokens
: Option
<LazyAttrTokenStream
>,
2701 #[derive(Clone, Encodable, Decodable, Debug)]
2702 pub enum VisibilityKind
{
2704 Restricted { path: P<Path>, id: NodeId, shorthand: bool }
,
2708 impl VisibilityKind
{
2709 pub fn is_pub(&self) -> bool
{
2710 matches
!(self, VisibilityKind
::Public
)
2714 /// Field definition in a struct, variant or union.
2716 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2717 #[derive(Clone, Encodable, Decodable, Debug)]
2718 pub struct FieldDef
{
2722 pub vis
: Visibility
,
2723 pub ident
: Option
<Ident
>,
2726 pub is_placeholder
: bool
,
2729 /// Fields and constructor ids of enum variants and structs.
2730 #[derive(Clone, Encodable, Decodable, Debug)]
2731 pub enum VariantData
{
2734 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2735 Struct(ThinVec
<FieldDef
>, bool
),
2738 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2739 Tuple(ThinVec
<FieldDef
>, NodeId
),
2742 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2747 /// Return the fields of this variant.
2748 pub fn fields(&self) -> &[FieldDef
] {
2750 VariantData
::Struct(fields
, ..) | VariantData
::Tuple(fields
, _
) => fields
,
2755 /// Return the `NodeId` of this variant's constructor, if it has one.
2756 pub fn ctor_node_id(&self) -> Option
<NodeId
> {
2758 VariantData
::Struct(..) => None
,
2759 VariantData
::Tuple(_
, id
) | VariantData
::Unit(id
) => Some(id
),
2764 /// An item definition.
2765 #[derive(Clone, Encodable, Decodable, Debug)]
2766 pub struct Item
<K
= ItemKind
> {
2770 pub vis
: Visibility
,
2771 /// The name of the item.
2772 /// It might be a dummy name in case of anonymous items.
2777 /// Original tokens this item was parsed from. This isn't necessarily
2778 /// available for all items, although over time more and more items should
2779 /// have this be `Some`. Right now this is primarily used for procedural
2780 /// macros, notably custom attributes.
2782 /// Note that the tokens here do not include the outer attributes, but will
2783 /// include inner attributes.
2784 pub tokens
: Option
<LazyAttrTokenStream
>,
2788 /// Return the span that encompasses the attributes.
2789 pub fn span_with_attributes(&self) -> Span
{
2790 self.attrs
.iter().fold(self.span
, |acc
, attr
| acc
.to(attr
.span
))
2794 /// `extern` qualifier on a function item or function type.
2795 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2797 /// No explicit extern keyword was used
2799 /// E.g. `fn foo() {}`
2801 /// An explicit extern keyword was used, but with implicit ABI
2803 /// E.g. `extern fn foo() {}`
2805 /// This is just `extern "C"` (see `rustc_target::spec::abi::Abi::FALLBACK`)
2807 /// An explicit extern keyword was used with an explicit ABI
2809 /// E.g. `extern "C" fn foo() {}`
2810 Explicit(StrLit
, Span
),
2814 pub fn from_abi(abi
: Option
<StrLit
>, span
: Span
) -> Extern
{
2816 Some(name
) => Extern
::Explicit(name
, span
),
2817 None
=> Extern
::Implicit(span
),
2822 /// A function header.
2824 /// All the information between the visibility and the name of the function is
2825 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2826 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2827 pub struct FnHeader
{
2828 /// The `unsafe` keyword, if any
2829 pub unsafety
: Unsafe
,
2830 /// The `async` keyword, if any
2831 pub asyncness
: Async
,
2832 /// The `const` keyword, if any
2833 pub constness
: Const
,
2834 /// The `extern` keyword and corresponding ABI string, if any
2839 /// Does this function header have any qualifiers or is it empty?
2840 pub fn has_qualifiers(&self) -> bool
{
2841 let Self { unsafety, asyncness, constness, ext }
= self;
2842 matches
!(unsafety
, Unsafe
::Yes(_
))
2843 || asyncness
.is_async()
2844 || matches
!(constness
, Const
::Yes(_
))
2845 || !matches
!(ext
, Extern
::None
)
2849 impl Default
for FnHeader
{
2850 fn default() -> FnHeader
{
2852 unsafety
: Unsafe
::No
,
2853 asyncness
: Async
::No
,
2854 constness
: Const
::No
,
2860 #[derive(Clone, Encodable, Decodable, Debug)]
2862 pub unsafety
: Unsafe
,
2863 pub is_auto
: IsAuto
,
2864 pub generics
: Generics
,
2865 pub bounds
: GenericBounds
,
2866 pub items
: ThinVec
<P
<AssocItem
>>,
2869 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2870 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2871 /// are two locations for where clause on type aliases, but their predicates
2872 /// are concatenated together.
2874 /// Take this example:
2875 /// ```ignore (only-for-syntax-highlight)
2877 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2879 /// impl Foo for () {
2880 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2881 /// // ^^^^^^^^^^^^^^ first where clause
2882 /// // ^^^^^^^^^^^^^^ second where clause
2886 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2887 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2888 pub struct TyAliasWhereClause(pub bool
, pub Span
);
2890 #[derive(Clone, Encodable, Decodable, Debug)]
2891 pub struct TyAlias
{
2892 pub defaultness
: Defaultness
,
2893 pub generics
: Generics
,
2894 /// The span information for the two where clauses (before equals, after equals)
2895 pub where_clauses
: (TyAliasWhereClause
, TyAliasWhereClause
),
2896 /// The index in `generics.where_clause.predicates` that would split into
2897 /// predicates from the where clause before the equals and the predicates
2898 /// from the where clause after the equals
2899 pub where_predicates_split
: usize,
2900 pub bounds
: GenericBounds
,
2901 pub ty
: Option
<P
<Ty
>>,
2904 #[derive(Clone, Encodable, Decodable, Debug)]
2906 pub defaultness
: Defaultness
,
2907 pub unsafety
: Unsafe
,
2908 pub generics
: Generics
,
2909 pub constness
: Const
,
2910 pub polarity
: ImplPolarity
,
2911 /// The trait being implemented, if any.
2912 pub of_trait
: Option
<TraitRef
>,
2914 pub items
: ThinVec
<P
<AssocItem
>>,
2917 #[derive(Clone, Encodable, Decodable, Debug)]
2919 pub defaultness
: Defaultness
,
2920 pub generics
: Generics
,
2922 pub body
: Option
<P
<Block
>>,
2925 #[derive(Clone, Encodable, Decodable, Debug)]
2926 pub struct StaticItem
{
2928 pub mutability
: Mutability
,
2929 pub expr
: Option
<P
<Expr
>>,
2932 #[derive(Clone, Encodable, Decodable, Debug)]
2933 pub struct ConstItem
{
2934 pub defaultness
: Defaultness
,
2935 pub generics
: Generics
,
2937 pub expr
: Option
<P
<Expr
>>,
2940 #[derive(Clone, Encodable, Decodable, Debug)]
2942 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2944 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2945 ExternCrate(Option
<Symbol
>),
2946 /// A use declaration item (`use`).
2948 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2950 /// A static item (`static`).
2952 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2953 Static(Box
<StaticItem
>),
2954 /// A constant item (`const`).
2956 /// E.g., `const FOO: i32 = 42;`.
2957 Const(Box
<ConstItem
>),
2958 /// A function declaration (`fn`).
2960 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2962 /// A module declaration (`mod`).
2964 /// E.g., `mod foo;` or `mod foo { .. }`.
2965 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2966 /// semantically by Rust.
2967 Mod(Unsafe
, ModKind
),
2968 /// An external module (`extern`).
2970 /// E.g., `extern {}` or `extern "C" {}`.
2971 ForeignMod(ForeignMod
),
2972 /// Module-level inline assembly (from `global_asm!()`).
2973 GlobalAsm(Box
<InlineAsm
>),
2974 /// A type alias (`type`).
2976 /// E.g., `type Foo = Bar<u8>;`.
2977 TyAlias(Box
<TyAlias
>),
2978 /// An enum definition (`enum`).
2980 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2981 Enum(EnumDef
, Generics
),
2982 /// A struct definition (`struct`).
2984 /// E.g., `struct Foo<A> { x: A }`.
2985 Struct(VariantData
, Generics
),
2986 /// A union definition (`union`).
2988 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2989 Union(VariantData
, Generics
),
2990 /// A trait declaration (`trait`).
2992 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2996 /// E.g., `trait Foo = Bar + Quux;`.
2997 TraitAlias(Generics
, GenericBounds
),
2998 /// An implementation.
3000 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
3002 /// A macro invocation.
3004 /// E.g., `foo!(..)`.
3005 MacCall(P
<MacCall
>),
3007 /// A macro definition.
3012 pub fn article(&self) -> &'
static str {
3015 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
3016 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
3017 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. }
=> "an",
3021 pub fn descr(&self) -> &'
static str {
3023 ItemKind
::ExternCrate(..) => "extern crate",
3024 ItemKind
::Use(..) => "`use` import",
3025 ItemKind
::Static(..) => "static item",
3026 ItemKind
::Const(..) => "constant item",
3027 ItemKind
::Fn(..) => "function",
3028 ItemKind
::Mod(..) => "module",
3029 ItemKind
::ForeignMod(..) => "extern block",
3030 ItemKind
::GlobalAsm(..) => "global asm item",
3031 ItemKind
::TyAlias(..) => "type alias",
3032 ItemKind
::Enum(..) => "enum",
3033 ItemKind
::Struct(..) => "struct",
3034 ItemKind
::Union(..) => "union",
3035 ItemKind
::Trait(..) => "trait",
3036 ItemKind
::TraitAlias(..) => "trait alias",
3037 ItemKind
::MacCall(..) => "item macro invocation",
3038 ItemKind
::MacroDef(..) => "macro definition",
3039 ItemKind
::Impl { .. }
=> "implementation",
3043 pub fn generics(&self) -> Option
<&Generics
> {
3045 Self::Fn(box Fn { generics, .. }
)
3046 | Self::TyAlias(box TyAlias { generics, .. }
)
3047 | Self::Const(box ConstItem { generics, .. }
)
3048 | Self::Enum(_
, generics
)
3049 | Self::Struct(_
, generics
)
3050 | Self::Union(_
, generics
)
3051 | Self::Trait(box Trait { generics, .. }
)
3052 | Self::TraitAlias(generics
, _
)
3053 | Self::Impl(box Impl { generics, .. }
) => Some(generics
),
3059 /// Represents associated items.
3060 /// These include items in `impl` and `trait` definitions.
3061 pub type AssocItem
= Item
<AssocItemKind
>;
3063 /// Represents associated item kinds.
3065 /// The term "provided" in the variants below refers to the item having a default
3066 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
3067 /// In an implementation, all items must be provided.
3068 /// The `Option`s below denote the bodies, where `Some(_)`
3069 /// means "provided" and conversely `None` means "required".
3070 #[derive(Clone, Encodable, Decodable, Debug)]
3071 pub enum AssocItemKind
{
3072 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
3073 /// If `def` is parsed, then the constant is provided, and otherwise required.
3074 Const(Box
<ConstItem
>),
3075 /// An associated function.
3077 /// An associated type.
3079 /// A macro expanding to associated items.
3080 MacCall(P
<MacCall
>),
3083 impl AssocItemKind
{
3084 pub fn defaultness(&self) -> Defaultness
{
3086 Self::Const(box ConstItem { defaultness, .. }
)
3087 | Self::Fn(box Fn { defaultness, .. }
)
3088 | Self::Type(box TyAlias { defaultness, .. }
) => defaultness
,
3089 Self::MacCall(..) => Defaultness
::Final
,
3094 impl From
<AssocItemKind
> for ItemKind
{
3095 fn from(assoc_item_kind
: AssocItemKind
) -> ItemKind
{
3096 match assoc_item_kind
{
3097 AssocItemKind
::Const(item
) => ItemKind
::Const(item
),
3098 AssocItemKind
::Fn(fn_kind
) => ItemKind
::Fn(fn_kind
),
3099 AssocItemKind
::Type(ty_alias_kind
) => ItemKind
::TyAlias(ty_alias_kind
),
3100 AssocItemKind
::MacCall(a
) => ItemKind
::MacCall(a
),
3105 impl TryFrom
<ItemKind
> for AssocItemKind
{
3106 type Error
= ItemKind
;
3108 fn try_from(item_kind
: ItemKind
) -> Result
<AssocItemKind
, ItemKind
> {
3109 Ok(match item_kind
{
3110 ItemKind
::Const(item
) => AssocItemKind
::Const(item
),
3111 ItemKind
::Fn(fn_kind
) => AssocItemKind
::Fn(fn_kind
),
3112 ItemKind
::TyAlias(ty_kind
) => AssocItemKind
::Type(ty_kind
),
3113 ItemKind
::MacCall(a
) => AssocItemKind
::MacCall(a
),
3114 _
=> return Err(item_kind
),
3119 /// An item in `extern` block.
3120 #[derive(Clone, Encodable, Decodable, Debug)]
3121 pub enum ForeignItemKind
{
3122 /// A foreign static item (`static FOO: u8`).
3123 Static(P
<Ty
>, Mutability
, Option
<P
<Expr
>>),
3124 /// An foreign function.
3126 /// An foreign type.
3127 TyAlias(Box
<TyAlias
>),
3128 /// A macro expanding to foreign items.
3129 MacCall(P
<MacCall
>),
3132 impl From
<ForeignItemKind
> for ItemKind
{
3133 fn from(foreign_item_kind
: ForeignItemKind
) -> ItemKind
{
3134 match foreign_item_kind
{
3135 ForeignItemKind
::Static(a
, b
, c
) => {
3136 ItemKind
::Static(StaticItem { ty: a, mutability: b, expr: c }
.into())
3138 ForeignItemKind
::Fn(fn_kind
) => ItemKind
::Fn(fn_kind
),
3139 ForeignItemKind
::TyAlias(ty_alias_kind
) => ItemKind
::TyAlias(ty_alias_kind
),
3140 ForeignItemKind
::MacCall(a
) => ItemKind
::MacCall(a
),
3145 impl TryFrom
<ItemKind
> for ForeignItemKind
{
3146 type Error
= ItemKind
;
3148 fn try_from(item_kind
: ItemKind
) -> Result
<ForeignItemKind
, ItemKind
> {
3149 Ok(match item_kind
{
3150 ItemKind
::Static(box StaticItem { ty: a, mutability: b, expr: c }
) => {
3151 ForeignItemKind
::Static(a
, b
, c
)
3153 ItemKind
::Fn(fn_kind
) => ForeignItemKind
::Fn(fn_kind
),
3154 ItemKind
::TyAlias(ty_alias_kind
) => ForeignItemKind
::TyAlias(ty_alias_kind
),
3155 ItemKind
::MacCall(a
) => ForeignItemKind
::MacCall(a
),
3156 _
=> return Err(item_kind
),
3161 pub type ForeignItem
= Item
<ForeignItemKind
>;
3163 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3164 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3167 use rustc_data_structures
::static_assert_size
;
3168 // tidy-alphabetical-start
3169 static_assert_size
!(AssocItem
, 88);
3170 static_assert_size
!(AssocItemKind
, 16);
3171 static_assert_size
!(Attribute
, 32);
3172 static_assert_size
!(Block
, 32);
3173 static_assert_size
!(Expr
, 72);
3174 static_assert_size
!(ExprKind
, 40);
3175 static_assert_size
!(Fn
, 152);
3176 static_assert_size
!(ForeignItem
, 96);
3177 static_assert_size
!(ForeignItemKind
, 24);
3178 static_assert_size
!(GenericArg
, 24);
3179 static_assert_size
!(GenericBound
, 56);
3180 static_assert_size
!(Generics
, 40);
3181 static_assert_size
!(Impl
, 136);
3182 static_assert_size
!(Item
, 136);
3183 static_assert_size
!(ItemKind
, 64);
3184 static_assert_size
!(LitKind
, 24);
3185 static_assert_size
!(Local
, 72);
3186 static_assert_size
!(MetaItemLit
, 40);
3187 static_assert_size
!(Param
, 40);
3188 static_assert_size
!(Pat
, 72);
3189 static_assert_size
!(Path
, 24);
3190 static_assert_size
!(PathSegment
, 24);
3191 static_assert_size
!(PatKind
, 48);
3192 static_assert_size
!(Stmt
, 32);
3193 static_assert_size
!(StmtKind
, 16);
3194 static_assert_size
!(Ty
, 64);
3195 static_assert_size
!(TyKind
, 40);
3196 // tidy-alphabetical-end