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`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
26 use crate::token::{self, CommentKind, Delimiter};
27 use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream};
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_data_structures::stack::ensure_sufficient_stack;
30 use rustc_data_structures::sync::Lrc;
31 use rustc_macros::HashStable_Generic;
32 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
33 use rustc_span::source_map::{respan, Spanned};
34 use rustc_span::symbol::{kw, sym, Ident, Symbol};
35 use rustc_span::{Span, DUMMY_SP};
38 use thin_vec::{thin_vec, ThinVec};
40 /// A "Label" is an identifier of some point in sources,
41 /// e.g. in the following code:
49 /// `'outer` is a label.
50 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
55 impl fmt::Debug for Label {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 write!(f, "label({:?})", self.ident)
61 /// A "Lifetime" is an annotation of the scope in which variable
62 /// can be used, e.g. `'a` in `&'a i32`.
63 #[derive(Clone, Encodable, Decodable, Copy, PartialEq, Eq)]
69 impl fmt::Debug for Lifetime {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 write!(f, "lifetime({}: {})", self.id, self)
75 impl fmt::Display for Lifetime {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "{}", self.ident.name)
81 /// A "Path" is essentially Rust's notion of a name.
83 /// It's represented as a sequence of identifiers,
84 /// along with a bunch of supporting information.
86 /// E.g., `std::cmp::PartialEq`.
87 #[derive(Clone, Encodable, Decodable, Debug)]
90 /// The segments in the path: the things separated by `::`.
91 /// Global paths begin with `kw::PathRoot`.
92 pub segments: ThinVec<PathSegment>,
93 pub tokens: Option<LazyAttrTokenStream>,
96 impl PartialEq<Symbol> for Path {
98 fn eq(&self, symbol: &Symbol) -> bool {
99 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
103 impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
104 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
105 self.segments.len().hash_stable(hcx, hasher);
106 for segment in &self.segments {
107 segment.ident.hash_stable(hcx, hasher);
113 /// Convert a span and an identifier to the corresponding
114 /// one-segment path.
115 pub fn from_ident(ident: Ident) -> Path {
116 Path { segments: thin_vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
119 pub fn is_global(&self) -> bool {
120 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
124 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
126 /// E.g., `std`, `String` or `Box<T>`.
127 #[derive(Clone, Encodable, Decodable, Debug)]
128 pub struct PathSegment {
129 /// The identifier portion of this path segment.
134 /// Type/lifetime parameters attached to this path. They come in
135 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
136 /// `None` means that no parameter list is supplied (`Path`),
137 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
138 /// but it can be empty (`Path<>`).
139 /// `P` is used as a size optimization for the common case with no parameters.
140 pub args: Option<P<GenericArgs>>,
144 pub fn from_ident(ident: Ident) -> Self {
145 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
148 pub fn path_root(span: Span) -> Self {
149 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
152 pub fn span(&self) -> Span {
154 Some(args) => self.ident.span.to(args.span()),
155 None => self.ident.span,
160 /// The arguments of a path segment.
162 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
163 #[derive(Clone, Encodable, Decodable, Debug)]
164 pub enum GenericArgs {
165 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
166 AngleBracketed(AngleBracketedArgs),
167 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
168 Parenthesized(ParenthesizedArgs),
172 pub fn is_angle_bracketed(&self) -> bool {
173 matches!(self, AngleBracketed(..))
176 pub fn span(&self) -> Span {
178 AngleBracketed(data) => data.span,
179 Parenthesized(data) => data.span,
184 /// Concrete argument in the sequence of generic args.
185 #[derive(Clone, Encodable, Decodable, Debug)]
186 pub enum GenericArg {
187 /// `'a` in `Foo<'a>`
189 /// `Bar` in `Foo<Bar>`
196 pub fn span(&self) -> Span {
198 GenericArg::Lifetime(lt) => lt.ident.span,
199 GenericArg::Type(ty) => ty.span,
200 GenericArg::Const(ct) => ct.value.span,
205 /// A path like `Foo<'a, T>`.
206 #[derive(Clone, Encodable, Decodable, Debug, Default)]
207 pub struct AngleBracketedArgs {
208 /// The overall span.
210 /// The comma separated parts in the `<...>`.
211 pub args: Vec<AngleBracketedArg>,
214 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
215 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
216 #[derive(Clone, Encodable, Decodable, Debug)]
217 pub enum AngleBracketedArg {
218 /// Argument for a generic parameter.
220 /// Constraint for an associated item.
221 Constraint(AssocConstraint),
224 impl AngleBracketedArg {
225 pub fn span(&self) -> Span {
227 AngleBracketedArg::Arg(arg) => arg.span(),
228 AngleBracketedArg::Constraint(constraint) => constraint.span,
233 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
234 fn into(self) -> Option<P<GenericArgs>> {
235 Some(P(GenericArgs::AngleBracketed(self)))
239 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
240 fn into(self) -> Option<P<GenericArgs>> {
241 Some(P(GenericArgs::Parenthesized(self)))
245 /// A path like `Foo(A, B) -> C`.
246 #[derive(Clone, Encodable, Decodable, Debug)]
247 pub struct ParenthesizedArgs {
255 pub inputs: Vec<P<Ty>>,
261 pub inputs_span: Span,
267 impl ParenthesizedArgs {
268 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
273 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
275 AngleBracketedArgs { span: self.inputs_span, args }
279 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
281 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
283 /// Negative bounds should also be handled here.
284 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
285 pub enum TraitBoundModifier {
297 // This parses but will be rejected during AST validation.
301 /// The AST represents all type param bounds as types.
302 /// `typeck::collect::compute_bounds` matches these against
303 /// the "special" built-in traits (see `middle::lang_items`) and
304 /// detects `Copy`, `Send` and `Sync`.
305 #[derive(Clone, Encodable, Decodable, Debug)]
306 pub enum GenericBound {
307 Trait(PolyTraitRef, TraitBoundModifier),
312 pub fn span(&self) -> Span {
314 GenericBound::Trait(t, ..) => t.span,
315 GenericBound::Outlives(l) => l.ident.span,
320 pub type GenericBounds = Vec<GenericBound>;
322 /// Specifies the enforced ordering for generic parameters. In the future,
323 /// if we wanted to relax this order, we could override `PartialEq` and
324 /// `PartialOrd`, to allow the kinds to be unordered.
325 #[derive(Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
326 pub enum ParamKindOrd {
331 impl fmt::Display for ParamKindOrd {
332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 ParamKindOrd::Lifetime => "lifetime".fmt(f),
335 ParamKindOrd::TypeOrConst => "type and const".fmt(f),
340 #[derive(Clone, Encodable, Decodable, Debug)]
341 pub enum GenericParamKind {
342 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
345 default: Option<P<Ty>>,
349 /// Span of the `const` keyword.
351 /// Optional default value for the const generic param
352 default: Option<AnonConst>,
356 #[derive(Clone, Encodable, Decodable, Debug)]
357 pub struct GenericParam {
361 pub bounds: GenericBounds,
362 pub is_placeholder: bool,
363 pub kind: GenericParamKind,
364 pub colon_span: Option<Span>,
368 pub fn span(&self) -> Span {
370 GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
373 GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
374 GenericParamKind::Const { kw_span, default: Some(default), .. } => {
375 kw_span.to(default.value.span)
377 GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
382 /// Represents lifetime, type and const parameters attached to a declaration of
383 /// a function, enum, trait, etc.
384 #[derive(Clone, Encodable, Decodable, Debug)]
385 pub struct Generics {
386 pub params: Vec<GenericParam>,
387 pub where_clause: WhereClause,
391 impl Default for Generics {
392 /// Creates an instance of `Generics`.
393 fn default() -> Generics {
394 Generics { params: Vec::new(), where_clause: Default::default(), span: DUMMY_SP }
398 /// A where-clause in a definition.
399 #[derive(Clone, Encodable, Decodable, Debug)]
400 pub struct WhereClause {
401 /// `true` if we ate a `where` token: this can happen
402 /// if we parsed no predicates (e.g. `struct Foo where {}`).
403 /// This allows us to pretty-print accurately.
404 pub has_where_token: bool,
405 pub predicates: Vec<WherePredicate>,
409 impl Default for WhereClause {
410 fn default() -> WhereClause {
411 WhereClause { has_where_token: false, predicates: Vec::new(), span: DUMMY_SP }
415 /// A single predicate in a where-clause.
416 #[derive(Clone, Encodable, Decodable, Debug)]
417 pub enum WherePredicate {
418 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
419 BoundPredicate(WhereBoundPredicate),
420 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
421 RegionPredicate(WhereRegionPredicate),
422 /// An equality predicate (unsupported).
423 EqPredicate(WhereEqPredicate),
426 impl WherePredicate {
427 pub fn span(&self) -> Span {
429 WherePredicate::BoundPredicate(p) => p.span,
430 WherePredicate::RegionPredicate(p) => p.span,
431 WherePredicate::EqPredicate(p) => p.span,
438 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
439 #[derive(Clone, Encodable, Decodable, Debug)]
440 pub struct WhereBoundPredicate {
442 /// Any generics from a `for` binding.
443 pub bound_generic_params: Vec<GenericParam>,
444 /// The type being bounded.
445 pub bounded_ty: P<Ty>,
446 /// Trait and lifetime bounds (`Clone + Send + 'static`).
447 pub bounds: GenericBounds,
450 /// A lifetime predicate.
452 /// E.g., `'a: 'b + 'c`.
453 #[derive(Clone, Encodable, Decodable, Debug)]
454 pub struct WhereRegionPredicate {
456 pub lifetime: Lifetime,
457 pub bounds: GenericBounds,
460 /// An equality predicate (unsupported).
463 #[derive(Clone, Encodable, Decodable, Debug)]
464 pub struct WhereEqPredicate {
470 #[derive(Clone, Encodable, Decodable, Debug)]
473 pub items: Vec<P<Item>>,
475 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
476 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
478 pub is_placeholder: bool,
481 /// A semantic representation of a meta item. A meta item is a slightly
482 /// restricted form of an attribute -- it can only contain expressions in
483 /// certain leaf positions, rather than arbitrary token streams -- that is used
484 /// for most built-in attributes.
486 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
487 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
488 pub struct MetaItem {
490 pub kind: MetaItemKind,
494 /// The meta item kind, containing the data after the initial path.
495 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
496 pub enum MetaItemKind {
499 /// E.g., `#[test]`, which lacks any arguments after `test`.
504 /// E.g., `#[derive(..)]`, where the field represents the `..`.
505 List(Vec<NestedMetaItem>),
507 /// Name value meta item.
509 /// E.g., `#[feature = "foo"]`, where the field represents the `"foo"`.
510 NameValue(MetaItemLit),
513 /// Values inside meta item lists.
515 /// E.g., each of `Clone`, `Copy` in `#[derive(Clone, Copy)]`.
516 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
517 pub enum NestedMetaItem {
518 /// A full MetaItem, for recursive meta items.
523 /// E.g., `"foo"`, `64`, `true`.
527 /// A block (`{ .. }`).
529 /// E.g., `{ .. }` as in `fn foo() { .. }`.
530 #[derive(Clone, Encodable, Decodable, Debug)]
532 /// The statements in the block.
533 pub stmts: Vec<Stmt>,
535 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
536 pub rules: BlockCheckMode,
538 pub tokens: Option<LazyAttrTokenStream>,
539 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
546 pub could_be_bare_literal: bool,
551 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
552 #[derive(Clone, Encodable, Decodable, Debug)]
557 pub tokens: Option<LazyAttrTokenStream>,
561 /// Attempt reparsing the pattern as a type.
562 /// This is intended for use by diagnostics.
563 pub fn to_ty(&self) -> Option<P<Ty>> {
564 let kind = match &self.kind {
565 // In a type expression `_` is an inference variable.
566 PatKind::Wild => TyKind::Infer,
567 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
568 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
569 TyKind::Path(None, Path::from_ident(*ident))
571 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
572 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
573 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
574 PatKind::Ref(pat, mutbl) => {
575 pat.to_ty().map(|ty| TyKind::Ref(None, MutTy { ty, mutbl: *mutbl }))?
577 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
578 // when `P` can be reparsed as a type `T`.
579 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
580 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
581 // assuming `T0` to `Tn` are all syntactically valid as types.
582 PatKind::Tuple(pats) => {
583 let mut tys = Vec::with_capacity(pats.len());
584 // FIXME(#48994) - could just be collected into an Option<Vec>
586 tys.push(pat.to_ty()?);
593 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
596 /// Walk top-down and call `it` in each place where a pattern occurs
597 /// starting with the root pattern `walk` is called on. If `it` returns
598 /// false then we will descend no further but siblings will be processed.
599 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
605 // Walk into the pattern associated with `Ident` (if any).
606 PatKind::Ident(_, _, Some(p)) => p.walk(it),
608 // Walk into each field of struct.
609 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
611 // Sequence of patterns.
612 PatKind::TupleStruct(_, _, s)
615 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
617 // Trivial wrappers over inner patterns.
618 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
620 // These patterns do not contain subpatterns, skip.
627 | PatKind::MacCall(_) => {}
631 /// Is this a `..` pattern?
632 pub fn is_rest(&self) -> bool {
633 matches!(self.kind, PatKind::Rest)
637 /// A single field in a struct pattern.
639 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
640 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
641 /// except when `is_shorthand` is true.
642 #[derive(Clone, Encodable, Decodable, Debug)]
643 pub struct PatField {
644 /// The identifier for the field.
646 /// The pattern the field is destructured to.
648 pub is_shorthand: bool,
652 pub is_placeholder: bool,
655 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
656 #[derive(Encodable, Decodable, HashStable_Generic)]
662 impl From<bool> for ByRef {
663 fn from(b: bool) -> ByRef {
671 /// Explicit binding annotations given in the HIR for a binding. Note
672 /// that this is not the final binding *mode* that we infer after type
674 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
675 #[derive(Encodable, Decodable, HashStable_Generic)]
676 pub struct BindingAnnotation(pub ByRef, pub Mutability);
678 impl BindingAnnotation {
679 pub const NONE: Self = Self(ByRef::No, Mutability::Not);
680 pub const REF: Self = Self(ByRef::Yes, Mutability::Not);
681 pub const MUT: Self = Self(ByRef::No, Mutability::Mut);
682 pub const REF_MUT: Self = Self(ByRef::Yes, Mutability::Mut);
684 pub fn prefix_str(self) -> &'static str {
689 Self::REF_MUT => "ref mut ",
694 #[derive(Clone, Encodable, Decodable, Debug)]
697 Included(RangeSyntax),
702 #[derive(Clone, Encodable, Decodable, Debug)]
703 pub enum RangeSyntax {
710 /// All the different flavors of pattern that Rust recognizes.
711 #[derive(Clone, Encodable, Decodable, Debug)]
713 /// Represents a wildcard pattern (`_`).
716 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
717 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
718 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
719 /// during name resolution.
720 Ident(BindingAnnotation, Ident, Option<P<Pat>>),
722 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
723 /// The `bool` is `true` in the presence of a `..`.
724 Struct(Option<P<QSelf>>, Path, Vec<PatField>, /* recovered */ bool),
726 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
727 TupleStruct(Option<P<QSelf>>, Path, Vec<P<Pat>>),
729 /// An or-pattern `A | B | C`.
730 /// Invariant: `pats.len() >= 2`.
733 /// A possibly qualified path pattern.
734 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
735 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
736 /// only legally refer to associated constants.
737 Path(Option<P<QSelf>>, Path),
739 /// A tuple pattern (`(a, b)`).
745 /// A reference pattern (e.g., `&mut (a, b)`).
746 Ref(P<Pat>, Mutability),
751 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
752 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
754 /// A slice pattern `[a, b, c]`.
757 /// A rest pattern `..`.
759 /// Syntactically it is valid anywhere.
761 /// Semantically however, it only has meaning immediately inside:
762 /// - a slice pattern: `[a, .., b]`,
763 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
764 /// - a tuple pattern: `(a, .., b)`,
765 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
767 /// In all of these cases, an additional restriction applies,
768 /// only one rest pattern may occur in the pattern sequences.
771 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
774 /// A macro pattern; pre-expansion.
778 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
779 #[derive(HashStable_Generic, Encodable, Decodable)]
780 pub enum Mutability {
781 // N.B. Order is deliberate, so that Not < Mut
787 pub fn invert(self) -> Self {
789 Mutability::Mut => Mutability::Not,
790 Mutability::Not => Mutability::Mut,
794 /// Returns `""` (empty string) or `"mut "` depending on the mutability.
795 pub fn prefix_str(self) -> &'static str {
797 Mutability::Mut => "mut ",
798 Mutability::Not => "",
802 /// Returns `"&"` or `"&mut "` depending on the mutability.
803 pub fn ref_prefix_str(self) -> &'static str {
805 Mutability::Not => "&",
806 Mutability::Mut => "&mut ",
810 /// Returns `""` (empty string) or `"mutably "` depending on the mutability.
811 pub fn mutably_str(self) -> &'static str {
813 Mutability::Not => "",
814 Mutability::Mut => "mutably ",
818 /// Return `true` if self is mutable
819 pub fn is_mut(self) -> bool {
820 matches!(self, Self::Mut)
823 /// Return `true` if self is **not** mutable
824 pub fn is_not(self) -> bool {
825 matches!(self, Self::Not)
829 /// The kind of borrow in an `AddrOf` expression,
830 /// e.g., `&place` or `&raw const place`.
831 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
832 #[derive(Encodable, Decodable, HashStable_Generic)]
833 pub enum BorrowKind {
834 /// A normal borrow, `&$expr` or `&mut $expr`.
835 /// The resulting type is either `&'a T` or `&'a mut T`
836 /// where `T = typeof($expr)` and `'a` is some lifetime.
838 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
839 /// The resulting type is either `*const T` or `*mut T`
840 /// where `T = typeof($expr)`.
844 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
846 /// The `+` operator (addition)
848 /// The `-` operator (subtraction)
850 /// The `*` operator (multiplication)
852 /// The `/` operator (division)
854 /// The `%` operator (modulus)
856 /// The `&&` operator (logical and)
858 /// The `||` operator (logical or)
860 /// The `^` operator (bitwise xor)
862 /// The `&` operator (bitwise and)
864 /// The `|` operator (bitwise or)
866 /// The `<<` operator (shift left)
868 /// The `>>` operator (shift right)
870 /// The `==` operator (equality)
872 /// The `<` operator (less than)
874 /// The `<=` operator (less than or equal to)
876 /// The `!=` operator (not equal to)
878 /// The `>=` operator (greater than or equal to)
880 /// The `>` operator (greater than)
885 pub fn to_string(&self) -> &'static str {
908 pub fn lazy(&self) -> bool {
909 matches!(self, BinOpKind::And | BinOpKind::Or)
912 pub fn is_comparison(&self) -> bool {
914 // Note for developers: please keep this as is;
915 // we want compilation to fail if another variant is added.
917 Eq | Lt | Le | Ne | Gt | Ge => true,
918 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
923 pub type BinOp = Spanned<BinOpKind>;
927 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
928 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
930 /// The `*` operator for dereferencing
932 /// The `!` operator for logical inversion
934 /// The `-` operator for negation
939 pub fn to_string(op: UnOp) -> &'static str {
949 #[derive(Clone, Encodable, Decodable, Debug)]
957 pub fn has_trailing_semicolon(&self) -> bool {
959 StmtKind::Semi(_) => true,
960 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
965 /// Converts a parsed `Stmt` to a `Stmt` with
966 /// a trailing semicolon.
968 /// This only modifies the parsed AST struct, not the attached
969 /// `LazyAttrTokenStream`. The parser is responsible for calling
970 /// `ToAttrTokenStream::add_trailing_semi` when there is actually
971 /// a semicolon in the tokenstream.
972 pub fn add_trailing_semicolon(mut self) -> Self {
973 self.kind = match self.kind {
974 StmtKind::Expr(expr) => StmtKind::Semi(expr),
975 StmtKind::MacCall(mac) => {
976 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
977 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
986 pub fn is_item(&self) -> bool {
987 matches!(self.kind, StmtKind::Item(_))
990 pub fn is_expr(&self) -> bool {
991 matches!(self.kind, StmtKind::Expr(_))
995 #[derive(Clone, Encodable, Decodable, Debug)]
997 /// A local (let) binding.
999 /// An item definition.
1001 /// Expr without trailing semi-colon.
1003 /// Expr with a trailing semi-colon.
1005 /// Just a trailing semi-colon.
1008 MacCall(P<MacCallStmt>),
1011 #[derive(Clone, Encodable, Decodable, Debug)]
1012 pub struct MacCallStmt {
1013 pub mac: P<MacCall>,
1014 pub style: MacStmtStyle,
1016 pub tokens: Option<LazyAttrTokenStream>,
1019 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1020 pub enum MacStmtStyle {
1021 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1022 /// `foo!(...);`, `foo![...];`).
1024 /// The macro statement had braces (e.g., `foo! { ... }`).
1026 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1027 /// `foo!(...)`). All of these will end up being converted into macro
1032 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1033 #[derive(Clone, Encodable, Decodable, Debug)]
1037 pub ty: Option<P<Ty>>,
1038 pub kind: LocalKind,
1041 pub tokens: Option<LazyAttrTokenStream>,
1044 #[derive(Clone, Encodable, Decodable, Debug)]
1045 pub enum LocalKind {
1046 /// Local declaration.
1047 /// Example: `let x;`
1049 /// Local declaration with an initializer.
1050 /// Example: `let x = y;`
1052 /// Local declaration with an initializer and an `else` clause.
1053 /// Example: `let Some(x) = y else { return };`
1054 InitElse(P<Expr>, P<Block>),
1058 pub fn init(&self) -> Option<&Expr> {
1061 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1065 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1068 Self::Init(init) => Some((init, None)),
1069 Self::InitElse(init, els) => Some((init, Some(els))),
1074 /// An arm of a 'match'.
1076 /// E.g., `0..=10 => { println!("match!") }` as in
1080 /// 0..=10 => { println!("match!") },
1081 /// _ => { println!("no match!") },
1084 #[derive(Clone, Encodable, Decodable, Debug)]
1087 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1089 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1090 pub guard: Option<P<Expr>>,
1095 pub is_placeholder: bool,
1098 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1099 #[derive(Clone, Encodable, Decodable, Debug)]
1100 pub struct ExprField {
1106 pub is_shorthand: bool,
1107 pub is_placeholder: bool,
1110 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1111 pub enum BlockCheckMode {
1113 Unsafe(UnsafeSource),
1116 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1117 pub enum UnsafeSource {
1122 /// A constant (expression) that's not an item or associated item,
1123 /// but needs its own `DefId` for type-checking, const-eval, etc.
1124 /// These are usually found nested inside types (e.g., array lengths)
1125 /// or expressions (e.g., repeat counts), and also used to define
1126 /// explicit discriminant values for enum variants.
1127 #[derive(Clone, Encodable, Decodable, Debug)]
1128 pub struct AnonConst {
1134 #[derive(Clone, Encodable, Decodable, Debug)]
1140 pub tokens: Option<LazyAttrTokenStream>,
1144 /// Is this expr either `N`, or `{ N }`.
1146 /// If this is not the case, name resolution does not resolve `N` when using
1147 /// `min_const_generics` as more complex expressions are not supported.
1148 pub fn is_potential_trivial_const_param(&self) -> bool {
1149 let this = if let ExprKind::Block(block, None) = &self.kind
1150 && block.stmts.len() == 1
1151 && let StmtKind::Expr(expr) = &block.stmts[0].kind
1158 if let ExprKind::Path(None, path) = &this.kind
1159 && path.segments.len() == 1
1160 && path.segments[0].args.is_none()
1168 pub fn to_bound(&self) -> Option<GenericBound> {
1170 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1171 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1172 TraitBoundModifier::None,
1178 pub fn peel_parens(&self) -> &Expr {
1179 let mut expr = self;
1180 while let ExprKind::Paren(inner) = &expr.kind {
1186 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1187 pub fn to_ty(&self) -> Option<P<Ty>> {
1188 let kind = match &self.kind {
1189 // Trivial conversions.
1190 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1191 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1193 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1195 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1196 expr.to_ty().map(|ty| TyKind::Ref(None, MutTy { ty, mutbl: *mutbl }))?
1199 ExprKind::Repeat(expr, expr_len) => {
1200 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1203 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1205 ExprKind::Tup(exprs) => {
1206 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1210 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1211 // then type of result is trait object.
1212 // Otherwise we don't assume the result type.
1213 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1214 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1215 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1221 ExprKind::Underscore => TyKind::Infer,
1223 // This expression doesn't look like a type syntactically.
1227 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1230 pub fn precedence(&self) -> ExprPrecedence {
1232 ExprKind::Box(_) => ExprPrecedence::Box,
1233 ExprKind::Array(_) => ExprPrecedence::Array,
1234 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1235 ExprKind::Call(..) => ExprPrecedence::Call,
1236 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1237 ExprKind::Tup(_) => ExprPrecedence::Tup,
1238 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1239 ExprKind::Unary(..) => ExprPrecedence::Unary,
1240 ExprKind::Lit(_) | ExprKind::IncludedBytes(..) => ExprPrecedence::Lit,
1241 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1242 ExprKind::Let(..) => ExprPrecedence::Let,
1243 ExprKind::If(..) => ExprPrecedence::If,
1244 ExprKind::While(..) => ExprPrecedence::While,
1245 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1246 ExprKind::Loop(..) => ExprPrecedence::Loop,
1247 ExprKind::Match(..) => ExprPrecedence::Match,
1248 ExprKind::Closure(..) => ExprPrecedence::Closure,
1249 ExprKind::Block(..) => ExprPrecedence::Block,
1250 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1251 ExprKind::Async(..) => ExprPrecedence::Async,
1252 ExprKind::Await(..) => ExprPrecedence::Await,
1253 ExprKind::Assign(..) => ExprPrecedence::Assign,
1254 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1255 ExprKind::Field(..) => ExprPrecedence::Field,
1256 ExprKind::Index(..) => ExprPrecedence::Index,
1257 ExprKind::Range(..) => ExprPrecedence::Range,
1258 ExprKind::Underscore => ExprPrecedence::Path,
1259 ExprKind::Path(..) => ExprPrecedence::Path,
1260 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1261 ExprKind::Break(..) => ExprPrecedence::Break,
1262 ExprKind::Continue(..) => ExprPrecedence::Continue,
1263 ExprKind::Ret(..) => ExprPrecedence::Ret,
1264 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1265 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1266 ExprKind::Struct(..) => ExprPrecedence::Struct,
1267 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1268 ExprKind::Paren(..) => ExprPrecedence::Paren,
1269 ExprKind::Try(..) => ExprPrecedence::Try,
1270 ExprKind::Yield(..) => ExprPrecedence::Yield,
1271 ExprKind::Yeet(..) => ExprPrecedence::Yeet,
1272 ExprKind::Err => ExprPrecedence::Err,
1276 pub fn take(&mut self) -> Self {
1281 kind: ExprKind::Err,
1283 attrs: AttrVec::new(),
1289 /// To a first-order approximation, is this a pattern?
1290 pub fn is_approximately_pattern(&self) -> bool {
1291 match &self.peel_parens().kind {
1293 | ExprKind::Array(_)
1294 | ExprKind::Call(_, _)
1297 | ExprKind::Range(_, _, _)
1298 | ExprKind::Underscore
1299 | ExprKind::Path(_, _)
1300 | ExprKind::Struct(_) => true,
1306 #[derive(Clone, Encodable, Decodable, Debug)]
1307 pub struct Closure {
1308 pub binder: ClosureBinder,
1309 pub capture_clause: CaptureBy,
1310 pub constness: Const,
1311 pub asyncness: Async,
1312 pub movability: Movability,
1313 pub fn_decl: P<FnDecl>,
1315 /// The span of the declaration block: 'move |...| -> ...'
1316 pub fn_decl_span: Span,
1317 /// The span of the argument block `|...|`
1318 pub fn_arg_span: Span,
1321 /// Limit types of a range (inclusive or exclusive)
1322 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1323 pub enum RangeLimits {
1324 /// Inclusive at the beginning, exclusive at the end
1326 /// Inclusive at the beginning and end
1330 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1331 #[derive(Clone, Encodable, Decodable, Debug)]
1332 pub struct MethodCall {
1333 /// The method name and its generic arguments, e.g. `foo::<Bar, Baz>`.
1334 pub seg: PathSegment,
1335 /// The receiver, e.g. `x`.
1336 pub receiver: P<Expr>,
1337 /// The arguments, e.g. `a, b, c`.
1338 pub args: Vec<P<Expr>>,
1339 /// The span of the function, without the dot and receiver e.g. `foo::<Bar,
1344 #[derive(Clone, Encodable, Decodable, Debug)]
1345 pub enum StructRest {
1350 /// No trailing `..` or expression.
1354 #[derive(Clone, Encodable, Decodable, Debug)]
1355 pub struct StructExpr {
1356 pub qself: Option<P<QSelf>>,
1358 pub fields: Vec<ExprField>,
1359 pub rest: StructRest,
1362 #[derive(Clone, Encodable, Decodable, Debug)]
1364 /// A `box x` expression.
1366 /// An array (`[a, b, c, d]`)
1367 Array(Vec<P<Expr>>),
1368 /// Allow anonymous constants from an inline `const` block
1369 ConstBlock(AnonConst),
1372 /// The first field resolves to the function itself,
1373 /// and the second field is the list of arguments.
1374 /// This also represents calling the constructor of
1375 /// tuple-like ADTs such as tuple structs and enum variants.
1376 Call(P<Expr>, Vec<P<Expr>>),
1377 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1378 MethodCall(Box<MethodCall>),
1379 /// A tuple (e.g., `(a, b, c, d)`).
1381 /// A binary operation (e.g., `a + b`, `a * b`).
1382 Binary(BinOp, P<Expr>, P<Expr>),
1383 /// A unary operation (e.g., `!x`, `*x`).
1384 Unary(UnOp, P<Expr>),
1385 /// A literal (e.g., `1`, `"foo"`).
1387 /// A cast (e.g., `foo as f64`).
1388 Cast(P<Expr>, P<Ty>),
1389 /// A type ascription (e.g., `42: usize`).
1390 Type(P<Expr>, P<Ty>),
1391 /// A `let pat = expr` expression that is only semantically allowed in the condition
1392 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1394 /// `Span` represents the whole `let pat = expr` statement.
1395 Let(P<Pat>, P<Expr>, Span),
1396 /// An `if` block, with an optional `else` block.
1398 /// `if expr { block } else { expr }`
1399 If(P<Expr>, P<Block>, Option<P<Expr>>),
1400 /// A while loop, with an optional label.
1402 /// `'label: while expr { block }`
1403 While(P<Expr>, P<Block>, Option<Label>),
1404 /// A `for` loop, with an optional label.
1406 /// `'label: for pat in expr { block }`
1408 /// This is desugared to a combination of `loop` and `match` expressions.
1409 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1410 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1412 /// `'label: loop { block }`
1413 Loop(P<Block>, Option<Label>, Span),
1414 /// A `match` block.
1415 Match(P<Expr>, Vec<Arm>),
1416 /// A closure (e.g., `move |a, b, c| a + b + c`).
1417 Closure(Box<Closure>),
1418 /// A block (`'label: { ... }`).
1419 Block(P<Block>, Option<Label>),
1420 /// An async block (`async move { ... }`).
1422 /// The `NodeId` is the `NodeId` for the closure that results from
1423 /// desugaring an async block, just like the NodeId field in the
1424 /// `Async::Yes` variant. This is necessary in order to create a def for the
1425 /// closure which can be used as a parent of any child defs. Defs
1426 /// created during lowering cannot be made the parent of any other
1427 /// preexisting defs.
1428 Async(CaptureBy, NodeId, P<Block>),
1429 /// An await expression (`my_future.await`).
1432 /// A try block (`try { ... }`).
1435 /// An assignment (`a = foo()`).
1436 /// The `Span` argument is the span of the `=` token.
1437 Assign(P<Expr>, P<Expr>, Span),
1438 /// An assignment with an operator.
1441 AssignOp(BinOp, P<Expr>, P<Expr>),
1442 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1443 Field(P<Expr>, Ident),
1444 /// An indexing operation (e.g., `foo[2]`).
1445 Index(P<Expr>, P<Expr>),
1446 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1447 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1448 /// An underscore, used in destructuring assignment to ignore a value.
1451 /// Variable reference, possibly containing `::` and/or type
1452 /// parameters (e.g., `foo::bar::<baz>`).
1454 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1455 Path(Option<P<QSelf>>, Path),
1457 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1458 AddrOf(BorrowKind, Mutability, P<Expr>),
1459 /// A `break`, with an optional label to break, and an optional expression.
1460 Break(Option<Label>, Option<P<Expr>>),
1461 /// A `continue`, with an optional label.
1462 Continue(Option<Label>),
1463 /// A `return`, with an optional value to be returned.
1464 Ret(Option<P<Expr>>),
1466 /// Output of the `asm!()` macro.
1467 InlineAsm(P<InlineAsm>),
1469 /// A macro invocation; pre-expansion.
1470 MacCall(P<MacCall>),
1472 /// A struct literal expression.
1474 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1475 Struct(P<StructExpr>),
1477 /// An array literal constructed from one repeated element.
1479 /// E.g., `[1; 5]`. The expression is the element to be
1480 /// repeated; the constant is the number of times to repeat it.
1481 Repeat(P<Expr>, AnonConst),
1483 /// No-op: used solely so we can pretty-print faithfully.
1486 /// A try expression (`expr?`).
1489 /// A `yield`, with an optional value to be yielded.
1490 Yield(Option<P<Expr>>),
1492 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1493 /// with an optional value to be returned.
1494 Yeet(Option<P<Expr>>),
1496 /// Bytes included via `include_bytes!`
1497 /// Added for optimization purposes to avoid the need to escape
1498 /// large binary blobs - should always behave like [`ExprKind::Lit`]
1499 /// with a `ByteStr` literal.
1500 IncludedBytes(Lrc<[u8]>),
1502 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1506 /// The explicit `Self` type in a "qualified path". The actual
1507 /// path, including the trait and the associated item, is stored
1508 /// separately. `position` represents the index of the associated
1509 /// item qualified with this `Self` type.
1511 /// ```ignore (only-for-syntax-highlight)
1512 /// <Vec<T> as a::b::Trait>::AssociatedItem
1513 /// ^~~~~ ~~~~~~~~~~~~~~^
1516 /// <Vec<T>>::AssociatedItem
1520 #[derive(Clone, Encodable, Decodable, Debug)]
1524 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1525 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1526 /// 0`, this is an empty span.
1527 pub path_span: Span,
1528 pub position: usize,
1531 /// A capture clause used in closures and `async` blocks.
1532 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1533 pub enum CaptureBy {
1534 /// `move |x| y + x`.
1536 /// `move` keyword was not specified.
1540 /// The movability of a generator / closure literal:
1541 /// whether a generator contains self-references, causing it to be `!Unpin`.
1542 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1543 #[derive(HashStable_Generic)]
1544 pub enum Movability {
1545 /// May contain self-references, `!Unpin`.
1547 /// Must not contain self-references, `Unpin`.
1551 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1552 #[derive(Clone, Encodable, Decodable, Debug)]
1553 pub enum ClosureBinder {
1554 /// The binder is not present, all closure lifetimes are inferred.
1556 /// The binder is present.
1558 /// Span of the whole `for<>` clause
1561 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1562 /// ^^^^^^^^^^^ -- this
1566 /// Lifetimes in the `for<>` closure
1569 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1572 generic_params: P<[GenericParam]>,
1576 /// Represents a macro invocation. The `path` indicates which macro
1577 /// is being invoked, and the `args` are arguments passed to it.
1578 #[derive(Clone, Encodable, Decodable, Debug)]
1579 pub struct MacCall {
1581 pub args: P<DelimArgs>,
1582 pub prior_type_ascription: Option<(Span, bool)>,
1586 pub fn span(&self) -> Span {
1587 self.path.span.to(self.args.dspan.entire())
1591 /// Arguments passed to an attribute macro.
1592 #[derive(Clone, Encodable, Decodable, Debug)]
1594 /// No arguments: `#[attr]`.
1596 /// Delimited arguments: `#[attr()/[]/{}]`.
1597 Delimited(DelimArgs),
1598 /// Arguments of a key-value attribute: `#[attr = "value"]`.
1600 /// Span of the `=` token.
1607 // The RHS of an `AttrArgs::Eq` starts out as an expression. Once macro
1608 // expansion is completed, all cases end up either as a meta item literal,
1609 // which is the form used after lowering to HIR, or as an error.
1610 #[derive(Clone, Encodable, Decodable, Debug)]
1611 pub enum AttrArgsEq {
1617 pub fn span(&self) -> Option<Span> {
1619 AttrArgs::Empty => None,
1620 AttrArgs::Delimited(args) => Some(args.dspan.entire()),
1621 AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1622 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
1623 unreachable!("in literal form when getting span: {:?}", lit);
1628 /// Tokens inside the delimiters or after `=`.
1629 /// Proc macros see these tokens, for example.
1630 pub fn inner_tokens(&self) -> TokenStream {
1632 AttrArgs::Empty => TokenStream::default(),
1633 AttrArgs::Delimited(args) => args.tokens.clone(),
1634 AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => TokenStream::from_ast(expr),
1635 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
1636 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1642 impl<CTX> HashStable<CTX> for AttrArgs
1644 CTX: crate::HashStableContext,
1646 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1647 mem::discriminant(self).hash_stable(ctx, hasher);
1649 AttrArgs::Empty => {}
1650 AttrArgs::Delimited(args) => args.hash_stable(ctx, hasher),
1651 AttrArgs::Eq(_eq_span, AttrArgsEq::Ast(expr)) => {
1652 unreachable!("hash_stable {:?}", expr);
1654 AttrArgs::Eq(eq_span, AttrArgsEq::Hir(lit)) => {
1655 eq_span.hash_stable(ctx, hasher);
1656 lit.hash_stable(ctx, hasher);
1662 /// Delimited arguments, as used in `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1663 #[derive(Clone, Encodable, Decodable, Debug)]
1664 pub struct DelimArgs {
1665 pub dspan: DelimSpan,
1666 pub delim: MacDelimiter,
1667 pub tokens: TokenStream,
1671 /// Whether a macro with these arguments needs a semicolon
1672 /// when used as a standalone item or statement.
1673 pub fn need_semicolon(&self) -> bool {
1674 !matches!(self, DelimArgs { delim: MacDelimiter::Brace, .. })
1678 impl<CTX> HashStable<CTX> for DelimArgs
1680 CTX: crate::HashStableContext,
1682 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1683 let DelimArgs { dspan, delim, tokens } = self;
1684 dspan.hash_stable(ctx, hasher);
1685 delim.hash_stable(ctx, hasher);
1686 tokens.hash_stable(ctx, hasher);
1690 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1691 pub enum MacDelimiter {
1698 pub fn to_token(self) -> Delimiter {
1700 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1701 MacDelimiter::Bracket => Delimiter::Bracket,
1702 MacDelimiter::Brace => Delimiter::Brace,
1706 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1708 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1709 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1710 Delimiter::Brace => Some(MacDelimiter::Brace),
1711 Delimiter::Invisible => None,
1716 /// Represents a macro definition.
1717 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1718 pub struct MacroDef {
1719 pub body: P<DelimArgs>,
1720 /// `true` if macro was defined with `macro_rules`.
1721 pub macro_rules: bool,
1724 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1725 #[derive(HashStable_Generic)]
1727 /// A regular string, like `"foo"`.
1729 /// A raw string, like `r##"foo"##`.
1731 /// The value is the number of `#` symbols used.
1735 /// A literal in a meta item.
1736 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1737 pub struct MetaItemLit {
1738 /// The original literal as written in the source code.
1740 /// The original suffix as written in the source code.
1741 pub suffix: Option<Symbol>,
1742 /// The "semantic" representation of the literal lowered from the original tokens.
1743 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1748 /// Similar to `MetaItemLit`, but restricted to string literals.
1749 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1751 /// The original literal as written in source code.
1753 /// The original suffix as written in source code.
1754 pub suffix: Option<Symbol>,
1755 /// The semantic (unescaped) representation of the literal.
1756 pub symbol_unescaped: Symbol,
1757 pub style: StrStyle,
1762 pub fn as_token_lit(&self) -> token::Lit {
1763 let token_kind = match self.style {
1764 StrStyle::Cooked => token::Str,
1765 StrStyle::Raw(n) => token::StrRaw(n),
1767 token::Lit::new(token_kind, self.symbol, self.suffix)
1771 /// Type of the integer literal based on provided suffix.
1772 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1773 #[derive(HashStable_Generic)]
1774 pub enum LitIntType {
1783 /// Type of the float literal based on provided suffix.
1784 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1785 #[derive(HashStable_Generic)]
1786 pub enum LitFloatType {
1787 /// A float literal with a suffix (`1f32` or `1E10f32`).
1789 /// A float literal without a suffix (`1.0 or 1.0E10`).
1793 /// This type is used within both `ast::MetaItemLit` and `hir::Lit`.
1795 /// Note that the entire literal (including the suffix) is considered when
1796 /// deciding the `LitKind`. This means that float literals like `1f32` are
1797 /// classified by this type as `Float`. This is different to `token::LitKind`
1798 /// which does *not* consider the suffix.
1799 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1801 /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
1802 /// from the original token's symbol.
1803 Str(Symbol, StrStyle),
1804 /// A byte string (`b"foo"`). Not stored as a symbol because it might be
1805 /// non-utf8, and symbols only allow utf8 strings.
1806 ByteStr(Lrc<[u8]>, StrStyle),
1807 /// A byte char (`b'f'`).
1809 /// A character literal (`'a'`).
1811 /// An integer literal (`1`).
1812 Int(u128, LitIntType),
1813 /// A float literal (`1.0`, `1f64` or `1E10f64`). The pre-suffix part is
1814 /// stored as a symbol rather than `f64` so that `LitKind` can impl `Eq`
1816 Float(Symbol, LitFloatType),
1817 /// A boolean literal (`true`, `false`).
1819 /// Placeholder for a literal that wasn't well-formed in some way.
1824 /// Returns `true` if this literal is a string.
1825 pub fn is_str(&self) -> bool {
1826 matches!(self, LitKind::Str(..))
1829 /// Returns `true` if this literal is byte literal string.
1830 pub fn is_bytestr(&self) -> bool {
1831 matches!(self, LitKind::ByteStr(..))
1834 /// Returns `true` if this is a numeric literal.
1835 pub fn is_numeric(&self) -> bool {
1836 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1839 /// Returns `true` if this literal has no suffix.
1840 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1841 pub fn is_unsuffixed(&self) -> bool {
1845 /// Returns `true` if this literal has a suffix.
1846 pub fn is_suffixed(&self) -> bool {
1848 // suffixed variants
1849 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1850 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1851 // unsuffixed variants
1853 | LitKind::ByteStr(..)
1856 | LitKind::Int(_, LitIntType::Unsuffixed)
1857 | LitKind::Float(_, LitFloatType::Unsuffixed)
1859 | LitKind::Err => false,
1864 // N.B., If you change this, you'll probably want to change the corresponding
1865 // type structure in `middle/ty.rs` as well.
1866 #[derive(Clone, Encodable, Decodable, Debug)]
1869 pub mutbl: Mutability,
1872 /// Represents a function's signature in a trait declaration,
1873 /// trait implementation, or free function.
1874 #[derive(Clone, Encodable, Decodable, Debug)]
1876 pub header: FnHeader,
1877 pub decl: P<FnDecl>,
1881 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1882 #[derive(Encodable, Decodable, HashStable_Generic)]
1889 pub fn name_str(self) -> &'static str {
1891 FloatTy::F32 => "f32",
1892 FloatTy::F64 => "f64",
1896 pub fn name(self) -> Symbol {
1898 FloatTy::F32 => sym::f32,
1899 FloatTy::F64 => sym::f64,
1904 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1905 #[derive(Encodable, Decodable, HashStable_Generic)]
1916 pub fn name_str(&self) -> &'static str {
1918 IntTy::Isize => "isize",
1920 IntTy::I16 => "i16",
1921 IntTy::I32 => "i32",
1922 IntTy::I64 => "i64",
1923 IntTy::I128 => "i128",
1927 pub fn name(&self) -> Symbol {
1929 IntTy::Isize => sym::isize,
1930 IntTy::I8 => sym::i8,
1931 IntTy::I16 => sym::i16,
1932 IntTy::I32 => sym::i32,
1933 IntTy::I64 => sym::i64,
1934 IntTy::I128 => sym::i128,
1939 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1940 #[derive(Encodable, Decodable, HashStable_Generic)]
1951 pub fn name_str(&self) -> &'static str {
1953 UintTy::Usize => "usize",
1955 UintTy::U16 => "u16",
1956 UintTy::U32 => "u32",
1957 UintTy::U64 => "u64",
1958 UintTy::U128 => "u128",
1962 pub fn name(&self) -> Symbol {
1964 UintTy::Usize => sym::usize,
1965 UintTy::U8 => sym::u8,
1966 UintTy::U16 => sym::u16,
1967 UintTy::U32 => sym::u32,
1968 UintTy::U64 => sym::u64,
1969 UintTy::U128 => sym::u128,
1974 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1975 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1976 #[derive(Clone, Encodable, Decodable, Debug)]
1977 pub struct AssocConstraint {
1980 pub gen_args: Option<GenericArgs>,
1981 pub kind: AssocConstraintKind,
1985 /// The kinds of an `AssocConstraint`.
1986 #[derive(Clone, Encodable, Decodable, Debug)]
1992 impl From<P<Ty>> for Term {
1993 fn from(v: P<Ty>) -> Self {
1998 impl From<AnonConst> for Term {
1999 fn from(v: AnonConst) -> Self {
2004 /// The kinds of an `AssocConstraint`.
2005 #[derive(Clone, Encodable, Decodable, Debug)]
2006 pub enum AssocConstraintKind {
2007 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
2008 Equality { term: Term },
2009 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
2010 Bound { bounds: GenericBounds },
2013 #[derive(Encodable, Decodable, Debug)]
2018 pub tokens: Option<LazyAttrTokenStream>,
2022 fn clone(&self) -> Self {
2023 ensure_sufficient_stack(|| Self {
2025 kind: self.kind.clone(),
2027 tokens: self.tokens.clone(),
2033 pub fn peel_refs(&self) -> &Self {
2034 let mut final_ty = self;
2035 while let TyKind::Ref(_, MutTy { ty, .. }) | TyKind::Ptr(MutTy { ty, .. }) = &final_ty.kind
2043 #[derive(Clone, Encodable, Decodable, Debug)]
2044 pub struct BareFnTy {
2045 pub unsafety: Unsafe,
2047 pub generic_params: Vec<GenericParam>,
2048 pub decl: P<FnDecl>,
2049 /// Span of the `fn(...) -> ...` part.
2050 pub decl_span: Span,
2053 /// The various kinds of type recognized by the compiler.
2054 #[derive(Clone, Encodable, Decodable, Debug)]
2056 /// A variable-length slice (`[T]`).
2058 /// A fixed length array (`[T; n]`).
2059 Array(P<Ty>, AnonConst),
2060 /// A raw pointer (`*const T` or `*mut T`).
2062 /// A reference (`&'a T` or `&'a mut T`).
2063 Ref(Option<Lifetime>, MutTy),
2064 /// A bare function (e.g., `fn(usize) -> bool`).
2065 BareFn(P<BareFnTy>),
2066 /// The never type (`!`).
2068 /// A tuple (`(A, B, C, D,...)`).
2070 /// A path (`module::module::...::Type`), optionally
2071 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2073 /// Type parameters are stored in the `Path` itself.
2074 Path(Option<P<QSelf>>, Path),
2075 /// A trait object type `Bound1 + Bound2 + Bound3`
2076 /// where `Bound` is a trait or a lifetime.
2077 TraitObject(GenericBounds, TraitObjectSyntax),
2078 /// An `impl Bound1 + Bound2 + Bound3` type
2079 /// where `Bound` is a trait or a lifetime.
2081 /// The `NodeId` exists to prevent lowering from having to
2082 /// generate `NodeId`s on the fly, which would complicate
2083 /// the generation of opaque `type Foo = impl Trait` items significantly.
2084 ImplTrait(NodeId, GenericBounds),
2085 /// No-op; kept solely so that we can pretty-print faithfully.
2089 /// This means the type should be inferred instead of it having been
2090 /// specified. This can appear anywhere in a type.
2092 /// Inferred type of a `self` or `&self` argument in a method.
2094 /// A macro in the type position.
2095 MacCall(P<MacCall>),
2096 /// Placeholder for a kind that has failed to be defined.
2098 /// Placeholder for a `va_list`.
2103 pub fn is_implicit_self(&self) -> bool {
2104 matches!(self, TyKind::ImplicitSelf)
2107 pub fn is_unit(&self) -> bool {
2108 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2111 pub fn is_simple_path(&self) -> Option<Symbol> {
2112 if let TyKind::Path(None, Path { segments, .. }) = &self
2113 && let [segment] = &segments[..]
2114 && segment.args.is_none()
2116 Some(segment.ident.name)
2123 /// Syntax used to declare a trait object.
2124 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2125 pub enum TraitObjectSyntax {
2131 /// Inline assembly operand explicit register or register class.
2133 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2134 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2135 pub enum InlineAsmRegOrRegClass {
2140 bitflags::bitflags! {
2141 #[derive(Encodable, Decodable, HashStable_Generic)]
2142 pub struct InlineAsmOptions: u16 {
2143 const PURE = 1 << 0;
2144 const NOMEM = 1 << 1;
2145 const READONLY = 1 << 2;
2146 const PRESERVES_FLAGS = 1 << 3;
2147 const NORETURN = 1 << 4;
2148 const NOSTACK = 1 << 5;
2149 const ATT_SYNTAX = 1 << 6;
2151 const MAY_UNWIND = 1 << 8;
2155 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2156 pub enum InlineAsmTemplatePiece {
2158 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2161 impl fmt::Display for InlineAsmTemplatePiece {
2162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2164 Self::String(s) => {
2165 for c in s.chars() {
2167 '{' => f.write_str("{{")?,
2168 '}' => f.write_str("}}")?,
2174 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2175 write!(f, "{{{operand_idx}:{modifier}}}")
2177 Self::Placeholder { operand_idx, modifier: None, .. } => {
2178 write!(f, "{{{operand_idx}}}")
2184 impl InlineAsmTemplatePiece {
2185 /// Rebuilds the asm template string from its pieces.
2186 pub fn to_string(s: &[Self]) -> String {
2188 let mut out = String::new();
2190 let _ = write!(out, "{p}");
2196 /// Inline assembly symbol operands get their own AST node that is somewhat
2197 /// similar to `AnonConst`.
2199 /// The main difference is that we specifically don't assign it `DefId` in
2200 /// `DefCollector`. Instead this is deferred until AST lowering where we
2201 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2202 /// depending on what the path resolves to.
2203 #[derive(Clone, Encodable, Decodable, Debug)]
2204 pub struct InlineAsmSym {
2206 pub qself: Option<P<QSelf>>,
2210 /// Inline assembly operand.
2212 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2213 #[derive(Clone, Encodable, Decodable, Debug)]
2214 pub enum InlineAsmOperand {
2216 reg: InlineAsmRegOrRegClass,
2220 reg: InlineAsmRegOrRegClass,
2222 expr: Option<P<Expr>>,
2225 reg: InlineAsmRegOrRegClass,
2230 reg: InlineAsmRegOrRegClass,
2233 out_expr: Option<P<Expr>>,
2236 anon_const: AnonConst,
2243 /// Inline assembly.
2245 /// E.g., `asm!("NOP");`.
2246 #[derive(Clone, Encodable, Decodable, Debug)]
2247 pub struct InlineAsm {
2248 pub template: Vec<InlineAsmTemplatePiece>,
2249 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2250 pub operands: Vec<(InlineAsmOperand, Span)>,
2251 pub clobber_abis: Vec<(Symbol, Span)>,
2252 pub options: InlineAsmOptions,
2253 pub line_spans: Vec<Span>,
2256 /// A parameter in a function header.
2258 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2259 #[derive(Clone, Encodable, Decodable, Debug)]
2266 pub is_placeholder: bool,
2269 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2271 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2272 #[derive(Clone, Encodable, Decodable, Debug)]
2274 /// `self`, `mut self`
2276 /// `&'lt self`, `&'lt mut self`
2277 Region(Option<Lifetime>, Mutability),
2278 /// `self: TYPE`, `mut self: TYPE`
2279 Explicit(P<Ty>, Mutability),
2282 pub type ExplicitSelf = Spanned<SelfKind>;
2285 /// Attempts to cast parameter to `ExplicitSelf`.
2286 pub fn to_self(&self) -> Option<ExplicitSelf> {
2287 if let PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), ident, _) = self.pat.kind {
2288 if ident.name == kw::SelfLower {
2289 return match self.ty.kind {
2290 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2291 TyKind::Ref(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2292 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2295 self.pat.span.to(self.ty.span),
2296 SelfKind::Explicit(self.ty.clone(), mutbl),
2304 /// Returns `true` if parameter is `self`.
2305 pub fn is_self(&self) -> bool {
2306 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2307 ident.name == kw::SelfLower
2313 /// Builds a `Param` object from `ExplicitSelf`.
2314 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2315 let span = eself.span.to(eself_ident.span);
2316 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2317 let (mutbl, ty) = match eself.node {
2318 SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2319 SelfKind::Value(mutbl) => (mutbl, infer_ty),
2320 SelfKind::Region(lt, mutbl) => (
2324 kind: TyKind::Ref(lt, MutTy { ty: infer_ty, mutbl }),
2334 kind: PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), eself_ident, None),
2341 is_placeholder: false,
2346 /// A signature (not the body) of a function declaration.
2348 /// E.g., `fn foo(bar: baz)`.
2350 /// Please note that it's different from `FnHeader` structure
2351 /// which contains metadata about function safety, asyncness, constness and ABI.
2352 #[derive(Clone, Encodable, Decodable, Debug)]
2354 pub inputs: Vec<Param>,
2355 pub output: FnRetTy,
2359 pub fn has_self(&self) -> bool {
2360 self.inputs.get(0).map_or(false, Param::is_self)
2362 pub fn c_variadic(&self) -> bool {
2363 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2367 /// Is the trait definition an auto trait?
2368 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2374 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2375 #[derive(HashStable_Generic)]
2381 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2383 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2388 pub fn is_async(self) -> bool {
2389 matches!(self, Async::Yes { .. })
2392 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2393 pub fn opt_return_id(self) -> Option<(NodeId, Span)> {
2395 Async::Yes { return_impl_trait_id, span, .. } => Some((return_impl_trait_id, span)),
2401 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2402 #[derive(HashStable_Generic)]
2408 /// Item defaultness.
2409 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2410 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2411 pub enum Defaultness {
2416 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2417 pub enum ImplPolarity {
2418 /// `impl Trait for Type`
2420 /// `impl !Trait for Type`
2424 impl fmt::Debug for ImplPolarity {
2425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2427 ImplPolarity::Positive => "positive".fmt(f),
2428 ImplPolarity::Negative(_) => "negative".fmt(f),
2433 #[derive(Clone, Encodable, Decodable, Debug)]
2435 /// Returns type is not specified.
2437 /// Functions default to `()` and closures default to inference.
2438 /// Span points to where return type would be inserted.
2440 /// Everything else.
2445 pub fn span(&self) -> Span {
2447 &FnRetTy::Default(span) => span,
2448 FnRetTy::Ty(ty) => ty.span,
2453 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2459 /// Module item kind.
2460 #[derive(Clone, Encodable, Decodable, Debug)]
2462 /// Module with inlined definition `mod foo { ... }`,
2463 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2464 /// The inner span is from the first token past `{` to the last token until `}`,
2465 /// or from the first to the last token in the loaded file.
2466 Loaded(Vec<P<Item>>, Inline, ModSpans),
2467 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2471 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2472 pub struct ModSpans {
2473 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2474 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2475 pub inner_span: Span,
2476 pub inject_use_span: Span,
2479 /// Foreign module declaration.
2481 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2482 #[derive(Clone, Encodable, Decodable, Debug)]
2483 pub struct ForeignMod {
2484 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2485 /// semantically by Rust.
2486 pub unsafety: Unsafe,
2487 pub abi: Option<StrLit>,
2488 pub items: Vec<P<ForeignItem>>,
2491 #[derive(Clone, Encodable, Decodable, Debug)]
2492 pub struct EnumDef {
2493 pub variants: Vec<Variant>,
2496 #[derive(Clone, Encodable, Decodable, Debug)]
2497 pub struct Variant {
2498 /// Attributes of the variant.
2500 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2504 /// The visibility of the variant. Syntactically accepted but not semantically.
2505 pub vis: Visibility,
2506 /// Name of the variant.
2509 /// Fields and constructor id of the variant.
2510 pub data: VariantData,
2511 /// Explicit discriminant, e.g., `Foo = 1`.
2512 pub disr_expr: Option<AnonConst>,
2513 /// Is a macro placeholder
2514 pub is_placeholder: bool,
2517 /// Part of `use` item to the right of its prefix.
2518 #[derive(Clone, Encodable, Decodable, Debug)]
2519 pub enum UseTreeKind {
2520 /// `use prefix` or `use prefix as rename`
2521 Simple(Option<Ident>),
2522 /// `use prefix::{...}`
2523 Nested(Vec<(UseTree, NodeId)>),
2528 /// A tree of paths sharing common prefixes.
2529 /// Used in `use` items both at top-level and inside of braces in import groups.
2530 #[derive(Clone, Encodable, Decodable, Debug)]
2531 pub struct UseTree {
2533 pub kind: UseTreeKind,
2538 pub fn ident(&self) -> Ident {
2540 UseTreeKind::Simple(Some(rename)) => rename,
2541 UseTreeKind::Simple(None) => {
2542 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2544 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2549 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2550 /// are contained as statements within items. These two cases need to be
2551 /// distinguished for pretty-printing.
2552 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2553 pub enum AttrStyle {
2558 rustc_index::newtype_index! {
2560 #[debug_format = "AttrId({})]"]
2561 pub struct AttrId {}
2564 impl<S: Encoder> Encodable<S> for AttrId {
2565 fn encode(&self, _s: &mut S) {}
2568 impl<D: Decoder> Decodable<D> for AttrId {
2569 default fn decode(_: &mut D) -> AttrId {
2570 panic!("cannot decode `AttrId` with `{}`", std::any::type_name::<D>());
2574 /// A list of attributes.
2575 pub type AttrVec = ThinVec<Attribute>;
2577 /// A syntax-level representation of an attribute.
2578 #[derive(Clone, Encodable, Decodable, Debug)]
2579 pub struct Attribute {
2582 /// Denotes if the attribute decorates the following construct (outer)
2583 /// or the construct this attribute is contained within (inner).
2584 pub style: AttrStyle,
2588 #[derive(Clone, Encodable, Decodable, Debug)]
2590 /// A normal attribute.
2591 Normal(P<NormalAttr>),
2593 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2594 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2595 /// variant (which is much less compact and thus more expensive).
2596 DocComment(CommentKind, Symbol),
2599 #[derive(Clone, Encodable, Decodable, Debug)]
2600 pub struct NormalAttr {
2602 pub tokens: Option<LazyAttrTokenStream>,
2605 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2606 pub struct AttrItem {
2609 pub tokens: Option<LazyAttrTokenStream>,
2612 /// `TraitRef`s appear in impls.
2614 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2615 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2616 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2617 /// same as the impl's `NodeId`).
2618 #[derive(Clone, Encodable, Decodable, Debug)]
2619 pub struct TraitRef {
2624 #[derive(Clone, Encodable, Decodable, Debug)]
2625 pub struct PolyTraitRef {
2626 /// The `'a` in `for<'a> Foo<&'a T>`.
2627 pub bound_generic_params: Vec<GenericParam>,
2629 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2630 pub trait_ref: TraitRef,
2636 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2638 bound_generic_params: generic_params,
2639 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2645 #[derive(Clone, Encodable, Decodable, Debug)]
2646 pub struct Visibility {
2647 pub kind: VisibilityKind,
2649 pub tokens: Option<LazyAttrTokenStream>,
2652 #[derive(Clone, Encodable, Decodable, Debug)]
2653 pub enum VisibilityKind {
2655 Restricted { path: P<Path>, id: NodeId, shorthand: bool },
2659 impl VisibilityKind {
2660 pub fn is_pub(&self) -> bool {
2661 matches!(self, VisibilityKind::Public)
2665 /// Field definition in a struct, variant or union.
2667 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2668 #[derive(Clone, Encodable, Decodable, Debug)]
2669 pub struct FieldDef {
2673 pub vis: Visibility,
2674 pub ident: Option<Ident>,
2677 pub is_placeholder: bool,
2680 /// Fields and constructor ids of enum variants and structs.
2681 #[derive(Clone, Encodable, Decodable, Debug)]
2682 pub enum VariantData {
2685 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2686 Struct(Vec<FieldDef>, bool),
2689 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2690 Tuple(Vec<FieldDef>, NodeId),
2693 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2698 /// Return the fields of this variant.
2699 pub fn fields(&self) -> &[FieldDef] {
2701 VariantData::Struct(fields, ..) | VariantData::Tuple(fields, _) => fields,
2706 /// Return the `NodeId` of this variant's constructor, if it has one.
2707 pub fn ctor_node_id(&self) -> Option<NodeId> {
2709 VariantData::Struct(..) => None,
2710 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2715 /// An item definition.
2716 #[derive(Clone, Encodable, Decodable, Debug)]
2717 pub struct Item<K = ItemKind> {
2721 pub vis: Visibility,
2722 /// The name of the item.
2723 /// It might be a dummy name in case of anonymous items.
2728 /// Original tokens this item was parsed from. This isn't necessarily
2729 /// available for all items, although over time more and more items should
2730 /// have this be `Some`. Right now this is primarily used for procedural
2731 /// macros, notably custom attributes.
2733 /// Note that the tokens here do not include the outer attributes, but will
2734 /// include inner attributes.
2735 pub tokens: Option<LazyAttrTokenStream>,
2739 /// Return the span that encompasses the attributes.
2740 pub fn span_with_attributes(&self) -> Span {
2741 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2745 /// `extern` qualifier on a function item or function type.
2746 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2748 /// No explicit extern keyword was used
2750 /// E.g. `fn foo() {}`
2752 /// An explicit extern keyword was used, but with implicit ABI
2754 /// E.g. `extern fn foo() {}`
2756 /// This is just `extern "C"` (see `rustc_target::spec::abi::Abi::FALLBACK`)
2758 /// An explicit extern keyword was used with an explicit ABI
2760 /// E.g. `extern "C" fn foo() {}`
2761 Explicit(StrLit, Span),
2765 pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2767 Some(name) => Extern::Explicit(name, span),
2768 None => Extern::Implicit(span),
2773 /// A function header.
2775 /// All the information between the visibility and the name of the function is
2776 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2777 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2778 pub struct FnHeader {
2779 /// The `unsafe` keyword, if any
2780 pub unsafety: Unsafe,
2781 /// The `async` keyword, if any
2782 pub asyncness: Async,
2783 /// The `const` keyword, if any
2784 pub constness: Const,
2785 /// The `extern` keyword and corresponding ABI string, if any
2790 /// Does this function header have any qualifiers or is it empty?
2791 pub fn has_qualifiers(&self) -> bool {
2792 let Self { unsafety, asyncness, constness, ext } = self;
2793 matches!(unsafety, Unsafe::Yes(_))
2794 || asyncness.is_async()
2795 || matches!(constness, Const::Yes(_))
2796 || !matches!(ext, Extern::None)
2800 impl Default for FnHeader {
2801 fn default() -> FnHeader {
2803 unsafety: Unsafe::No,
2804 asyncness: Async::No,
2805 constness: Const::No,
2811 #[derive(Clone, Encodable, Decodable, Debug)]
2813 pub unsafety: Unsafe,
2814 pub is_auto: IsAuto,
2815 pub generics: Generics,
2816 pub bounds: GenericBounds,
2817 pub items: Vec<P<AssocItem>>,
2820 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2821 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2822 /// are two locations for where clause on type aliases, but their predicates
2823 /// are concatenated together.
2825 /// Take this example:
2826 /// ```ignore (only-for-syntax-highlight)
2828 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2830 /// impl Foo for () {
2831 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2832 /// // ^^^^^^^^^^^^^^ first where clause
2833 /// // ^^^^^^^^^^^^^^ second where clause
2837 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2838 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2839 pub struct TyAliasWhereClause(pub bool, pub Span);
2841 #[derive(Clone, Encodable, Decodable, Debug)]
2842 pub struct TyAlias {
2843 pub defaultness: Defaultness,
2844 pub generics: Generics,
2845 /// The span information for the two where clauses (before equals, after equals)
2846 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2847 /// The index in `generics.where_clause.predicates` that would split into
2848 /// predicates from the where clause before the equals and the predicates
2849 /// from the where clause after the equals
2850 pub where_predicates_split: usize,
2851 pub bounds: GenericBounds,
2852 pub ty: Option<P<Ty>>,
2855 #[derive(Clone, Encodable, Decodable, Debug)]
2857 pub defaultness: Defaultness,
2858 pub unsafety: Unsafe,
2859 pub generics: Generics,
2860 pub constness: Const,
2861 pub polarity: ImplPolarity,
2862 /// The trait being implemented, if any.
2863 pub of_trait: Option<TraitRef>,
2865 pub items: Vec<P<AssocItem>>,
2868 #[derive(Clone, Encodable, Decodable, Debug)]
2870 pub defaultness: Defaultness,
2871 pub generics: Generics,
2873 pub body: Option<P<Block>>,
2876 #[derive(Clone, Encodable, Decodable, Debug)]
2878 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2880 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2881 ExternCrate(Option<Symbol>),
2882 /// A use declaration item (`use`).
2884 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2886 /// A static item (`static`).
2888 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2889 Static(P<Ty>, Mutability, Option<P<Expr>>),
2890 /// A constant item (`const`).
2892 /// E.g., `const FOO: i32 = 42;`.
2893 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2894 /// A function declaration (`fn`).
2896 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2898 /// A module declaration (`mod`).
2900 /// E.g., `mod foo;` or `mod foo { .. }`.
2901 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2902 /// semantically by Rust.
2903 Mod(Unsafe, ModKind),
2904 /// An external module (`extern`).
2906 /// E.g., `extern {}` or `extern "C" {}`.
2907 ForeignMod(ForeignMod),
2908 /// Module-level inline assembly (from `global_asm!()`).
2909 GlobalAsm(Box<InlineAsm>),
2910 /// A type alias (`type`).
2912 /// E.g., `type Foo = Bar<u8>;`.
2913 TyAlias(Box<TyAlias>),
2914 /// An enum definition (`enum`).
2916 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2917 Enum(EnumDef, Generics),
2918 /// A struct definition (`struct`).
2920 /// E.g., `struct Foo<A> { x: A }`.
2921 Struct(VariantData, Generics),
2922 /// A union definition (`union`).
2924 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2925 Union(VariantData, Generics),
2926 /// A trait declaration (`trait`).
2928 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2932 /// E.g., `trait Foo = Bar + Quux;`.
2933 TraitAlias(Generics, GenericBounds),
2934 /// An implementation.
2936 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2938 /// A macro invocation.
2940 /// E.g., `foo!(..)`.
2941 MacCall(P<MacCall>),
2943 /// A macro definition.
2948 pub fn article(&self) -> &str {
2951 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2952 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2953 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2957 pub fn descr(&self) -> &str {
2959 ItemKind::ExternCrate(..) => "extern crate",
2960 ItemKind::Use(..) => "`use` import",
2961 ItemKind::Static(..) => "static item",
2962 ItemKind::Const(..) => "constant item",
2963 ItemKind::Fn(..) => "function",
2964 ItemKind::Mod(..) => "module",
2965 ItemKind::ForeignMod(..) => "extern block",
2966 ItemKind::GlobalAsm(..) => "global asm item",
2967 ItemKind::TyAlias(..) => "type alias",
2968 ItemKind::Enum(..) => "enum",
2969 ItemKind::Struct(..) => "struct",
2970 ItemKind::Union(..) => "union",
2971 ItemKind::Trait(..) => "trait",
2972 ItemKind::TraitAlias(..) => "trait alias",
2973 ItemKind::MacCall(..) => "item macro invocation",
2974 ItemKind::MacroDef(..) => "macro definition",
2975 ItemKind::Impl { .. } => "implementation",
2979 pub fn generics(&self) -> Option<&Generics> {
2981 Self::Fn(box Fn { generics, .. })
2982 | Self::TyAlias(box TyAlias { generics, .. })
2983 | Self::Enum(_, generics)
2984 | Self::Struct(_, generics)
2985 | Self::Union(_, generics)
2986 | Self::Trait(box Trait { generics, .. })
2987 | Self::TraitAlias(generics, _)
2988 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2994 /// Represents associated items.
2995 /// These include items in `impl` and `trait` definitions.
2996 pub type AssocItem = Item<AssocItemKind>;
2998 /// Represents associated item kinds.
3000 /// The term "provided" in the variants below refers to the item having a default
3001 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
3002 /// In an implementation, all items must be provided.
3003 /// The `Option`s below denote the bodies, where `Some(_)`
3004 /// means "provided" and conversely `None` means "required".
3005 #[derive(Clone, Encodable, Decodable, Debug)]
3006 pub enum AssocItemKind {
3007 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
3008 /// If `def` is parsed, then the constant is provided, and otherwise required.
3009 Const(Defaultness, P<Ty>, Option<P<Expr>>),
3010 /// An associated function.
3012 /// An associated type.
3014 /// A macro expanding to associated items.
3015 MacCall(P<MacCall>),
3018 impl AssocItemKind {
3019 pub fn defaultness(&self) -> Defaultness {
3021 Self::Const(defaultness, ..)
3022 | Self::Fn(box Fn { defaultness, .. })
3023 | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
3024 Self::MacCall(..) => Defaultness::Final,
3029 impl From<AssocItemKind> for ItemKind {
3030 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
3031 match assoc_item_kind {
3032 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
3033 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3034 AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3035 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
3040 impl TryFrom<ItemKind> for AssocItemKind {
3041 type Error = ItemKind;
3043 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
3044 Ok(match item_kind {
3045 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
3046 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
3047 ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
3048 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
3049 _ => return Err(item_kind),
3054 /// An item in `extern` block.
3055 #[derive(Clone, Encodable, Decodable, Debug)]
3056 pub enum ForeignItemKind {
3057 /// A foreign static item (`static FOO: u8`).
3058 Static(P<Ty>, Mutability, Option<P<Expr>>),
3059 /// An foreign function.
3061 /// An foreign type.
3062 TyAlias(Box<TyAlias>),
3063 /// A macro expanding to foreign items.
3064 MacCall(P<MacCall>),
3067 impl From<ForeignItemKind> for ItemKind {
3068 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3069 match foreign_item_kind {
3070 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3071 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3072 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3073 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3078 impl TryFrom<ItemKind> for ForeignItemKind {
3079 type Error = ItemKind;
3081 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3082 Ok(match item_kind {
3083 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3084 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3085 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3086 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3087 _ => return Err(item_kind),
3092 pub type ForeignItem = Item<ForeignItemKind>;
3094 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3095 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3098 use rustc_data_structures::static_assert_size;
3099 // tidy-alphabetical-start
3100 static_assert_size!(AssocItem, 104);
3101 static_assert_size!(AssocItemKind, 32);
3102 static_assert_size!(Attribute, 32);
3103 static_assert_size!(Block, 48);
3104 static_assert_size!(Expr, 72);
3105 static_assert_size!(ExprKind, 40);
3106 static_assert_size!(Fn, 184);
3107 static_assert_size!(ForeignItem, 96);
3108 static_assert_size!(ForeignItemKind, 24);
3109 static_assert_size!(GenericArg, 24);
3110 static_assert_size!(GenericBound, 72);
3111 static_assert_size!(Generics, 72);
3112 static_assert_size!(Impl, 184);
3113 static_assert_size!(Item, 184);
3114 static_assert_size!(ItemKind, 112);
3115 static_assert_size!(LitKind, 24);
3116 static_assert_size!(Local, 72);
3117 static_assert_size!(MetaItemLit, 40);
3118 static_assert_size!(Param, 40);
3119 static_assert_size!(Pat, 88);
3120 static_assert_size!(Path, 24);
3121 static_assert_size!(PathSegment, 24);
3122 static_assert_size!(PatKind, 64);
3123 static_assert_size!(Stmt, 32);
3124 static_assert_size!(StmtKind, 16);
3125 static_assert_size!(Ty, 64);
3126 static_assert_size!(TyKind, 40);
3127 // tidy-alphabetical-end