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::Rptr(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::Rptr(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 asyncness: Async,
1311 pub movability: Movability,
1312 pub fn_decl: P<FnDecl>,
1314 /// The span of the declaration block: 'move |...| -> ...'
1315 pub fn_decl_span: Span,
1316 /// The span of the argument block `|...|`
1317 pub fn_arg_span: Span,
1320 /// Limit types of a range (inclusive or exclusive)
1321 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1322 pub enum RangeLimits {
1323 /// Inclusive at the beginning, exclusive at the end
1325 /// Inclusive at the beginning and end
1329 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1330 #[derive(Clone, Encodable, Decodable, Debug)]
1331 pub struct MethodCall {
1332 /// The method name and its generic arguments, e.g. `foo::<Bar, Baz>`.
1333 pub seg: PathSegment,
1334 /// The receiver, e.g. `x`.
1335 pub receiver: P<Expr>,
1336 /// The arguments, e.g. `a, b, c`.
1337 pub args: Vec<P<Expr>>,
1338 /// The span of the function, without the dot and receiver e.g. `foo::<Bar,
1343 #[derive(Clone, Encodable, Decodable, Debug)]
1344 pub enum StructRest {
1349 /// No trailing `..` or expression.
1353 #[derive(Clone, Encodable, Decodable, Debug)]
1354 pub struct StructExpr {
1355 pub qself: Option<P<QSelf>>,
1357 pub fields: Vec<ExprField>,
1358 pub rest: StructRest,
1361 #[derive(Clone, Encodable, Decodable, Debug)]
1363 /// A `box x` expression.
1365 /// An array (`[a, b, c, d]`)
1366 Array(Vec<P<Expr>>),
1367 /// Allow anonymous constants from an inline `const` block
1368 ConstBlock(AnonConst),
1371 /// The first field resolves to the function itself,
1372 /// and the second field is the list of arguments.
1373 /// This also represents calling the constructor of
1374 /// tuple-like ADTs such as tuple structs and enum variants.
1375 Call(P<Expr>, Vec<P<Expr>>),
1376 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1377 MethodCall(Box<MethodCall>),
1378 /// A tuple (e.g., `(a, b, c, d)`).
1380 /// A binary operation (e.g., `a + b`, `a * b`).
1381 Binary(BinOp, P<Expr>, P<Expr>),
1382 /// A unary operation (e.g., `!x`, `*x`).
1383 Unary(UnOp, P<Expr>),
1384 /// A literal (e.g., `1`, `"foo"`).
1386 /// A cast (e.g., `foo as f64`).
1387 Cast(P<Expr>, P<Ty>),
1388 /// A type ascription (e.g., `42: usize`).
1389 Type(P<Expr>, P<Ty>),
1390 /// A `let pat = expr` expression that is only semantically allowed in the condition
1391 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1393 /// `Span` represents the whole `let pat = expr` statement.
1394 Let(P<Pat>, P<Expr>, Span),
1395 /// An `if` block, with an optional `else` block.
1397 /// `if expr { block } else { expr }`
1398 If(P<Expr>, P<Block>, Option<P<Expr>>),
1399 /// A while loop, with an optional label.
1401 /// `'label: while expr { block }`
1402 While(P<Expr>, P<Block>, Option<Label>),
1403 /// A `for` loop, with an optional label.
1405 /// `'label: for pat in expr { block }`
1407 /// This is desugared to a combination of `loop` and `match` expressions.
1408 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1409 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1411 /// `'label: loop { block }`
1412 Loop(P<Block>, Option<Label>, Span),
1413 /// A `match` block.
1414 Match(P<Expr>, Vec<Arm>),
1415 /// A closure (e.g., `move |a, b, c| a + b + c`).
1416 Closure(Box<Closure>),
1417 /// A block (`'label: { ... }`).
1418 Block(P<Block>, Option<Label>),
1419 /// An async block (`async move { ... }`).
1421 /// The `NodeId` is the `NodeId` for the closure that results from
1422 /// desugaring an async block, just like the NodeId field in the
1423 /// `Async::Yes` variant. This is necessary in order to create a def for the
1424 /// closure which can be used as a parent of any child defs. Defs
1425 /// created during lowering cannot be made the parent of any other
1426 /// preexisting defs.
1427 Async(CaptureBy, NodeId, P<Block>),
1428 /// An await expression (`my_future.await`).
1431 /// A try block (`try { ... }`).
1434 /// An assignment (`a = foo()`).
1435 /// The `Span` argument is the span of the `=` token.
1436 Assign(P<Expr>, P<Expr>, Span),
1437 /// An assignment with an operator.
1440 AssignOp(BinOp, P<Expr>, P<Expr>),
1441 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1442 Field(P<Expr>, Ident),
1443 /// An indexing operation (e.g., `foo[2]`).
1444 Index(P<Expr>, P<Expr>),
1445 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1446 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1447 /// An underscore, used in destructuring assignment to ignore a value.
1450 /// Variable reference, possibly containing `::` and/or type
1451 /// parameters (e.g., `foo::bar::<baz>`).
1453 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1454 Path(Option<P<QSelf>>, Path),
1456 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1457 AddrOf(BorrowKind, Mutability, P<Expr>),
1458 /// A `break`, with an optional label to break, and an optional expression.
1459 Break(Option<Label>, Option<P<Expr>>),
1460 /// A `continue`, with an optional label.
1461 Continue(Option<Label>),
1462 /// A `return`, with an optional value to be returned.
1463 Ret(Option<P<Expr>>),
1465 /// Output of the `asm!()` macro.
1466 InlineAsm(P<InlineAsm>),
1468 /// A macro invocation; pre-expansion.
1469 MacCall(P<MacCall>),
1471 /// A struct literal expression.
1473 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1474 Struct(P<StructExpr>),
1476 /// An array literal constructed from one repeated element.
1478 /// E.g., `[1; 5]`. The expression is the element to be
1479 /// repeated; the constant is the number of times to repeat it.
1480 Repeat(P<Expr>, AnonConst),
1482 /// No-op: used solely so we can pretty-print faithfully.
1485 /// A try expression (`expr?`).
1488 /// A `yield`, with an optional value to be yielded.
1489 Yield(Option<P<Expr>>),
1491 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1492 /// with an optional value to be returned.
1493 Yeet(Option<P<Expr>>),
1495 /// Bytes included via `include_bytes!`
1496 /// Added for optimization purposes to avoid the need to escape
1497 /// large binary blobs - should always behave like [`ExprKind::Lit`]
1498 /// with a `ByteStr` literal.
1499 IncludedBytes(Lrc<[u8]>),
1501 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1505 /// The explicit `Self` type in a "qualified path". The actual
1506 /// path, including the trait and the associated item, is stored
1507 /// separately. `position` represents the index of the associated
1508 /// item qualified with this `Self` type.
1510 /// ```ignore (only-for-syntax-highlight)
1511 /// <Vec<T> as a::b::Trait>::AssociatedItem
1512 /// ^~~~~ ~~~~~~~~~~~~~~^
1515 /// <Vec<T>>::AssociatedItem
1519 #[derive(Clone, Encodable, Decodable, Debug)]
1523 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1524 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1525 /// 0`, this is an empty span.
1526 pub path_span: Span,
1527 pub position: usize,
1530 /// A capture clause used in closures and `async` blocks.
1531 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1532 pub enum CaptureBy {
1533 /// `move |x| y + x`.
1535 /// `move` keyword was not specified.
1539 /// The movability of a generator / closure literal:
1540 /// whether a generator contains self-references, causing it to be `!Unpin`.
1541 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1542 #[derive(HashStable_Generic)]
1543 pub enum Movability {
1544 /// May contain self-references, `!Unpin`.
1546 /// Must not contain self-references, `Unpin`.
1550 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1551 #[derive(Clone, Encodable, Decodable, Debug)]
1552 pub enum ClosureBinder {
1553 /// The binder is not present, all closure lifetimes are inferred.
1555 /// The binder is present.
1557 /// Span of the whole `for<>` clause
1560 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1561 /// ^^^^^^^^^^^ -- this
1565 /// Lifetimes in the `for<>` closure
1568 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1571 generic_params: P<[GenericParam]>,
1575 /// Represents a macro invocation. The `path` indicates which macro
1576 /// is being invoked, and the `args` are arguments passed to it.
1577 #[derive(Clone, Encodable, Decodable, Debug)]
1578 pub struct MacCall {
1580 pub args: P<DelimArgs>,
1581 pub prior_type_ascription: Option<(Span, bool)>,
1585 pub fn span(&self) -> Span {
1586 self.path.span.to(self.args.dspan.entire())
1590 /// Arguments passed to an attribute macro.
1591 #[derive(Clone, Encodable, Decodable, Debug)]
1593 /// No arguments: `#[attr]`.
1595 /// Delimited arguments: `#[attr()/[]/{}]`.
1596 Delimited(DelimArgs),
1597 /// Arguments of a key-value attribute: `#[attr = "value"]`.
1599 /// Span of the `=` token.
1606 // The RHS of an `AttrArgs::Eq` starts out as an expression. Once macro
1607 // expansion is completed, all cases end up either as a meta item literal,
1608 // which is the form used after lowering to HIR, or as an error.
1609 #[derive(Clone, Encodable, Decodable, Debug)]
1610 pub enum AttrArgsEq {
1616 pub fn span(&self) -> Option<Span> {
1618 AttrArgs::Empty => None,
1619 AttrArgs::Delimited(args) => Some(args.dspan.entire()),
1620 AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1621 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
1622 unreachable!("in literal form when getting span: {:?}", lit);
1627 /// Tokens inside the delimiters or after `=`.
1628 /// Proc macros see these tokens, for example.
1629 pub fn inner_tokens(&self) -> TokenStream {
1631 AttrArgs::Empty => TokenStream::default(),
1632 AttrArgs::Delimited(args) => args.tokens.clone(),
1633 AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => TokenStream::from_ast(expr),
1634 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
1635 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1641 impl<CTX> HashStable<CTX> for AttrArgs
1643 CTX: crate::HashStableContext,
1645 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1646 mem::discriminant(self).hash_stable(ctx, hasher);
1648 AttrArgs::Empty => {}
1649 AttrArgs::Delimited(args) => args.hash_stable(ctx, hasher),
1650 AttrArgs::Eq(_eq_span, AttrArgsEq::Ast(expr)) => {
1651 unreachable!("hash_stable {:?}", expr);
1653 AttrArgs::Eq(eq_span, AttrArgsEq::Hir(lit)) => {
1654 eq_span.hash_stable(ctx, hasher);
1655 lit.hash_stable(ctx, hasher);
1661 /// Delimited arguments, as used in `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1662 #[derive(Clone, Encodable, Decodable, Debug)]
1663 pub struct DelimArgs {
1664 pub dspan: DelimSpan,
1665 pub delim: MacDelimiter,
1666 pub tokens: TokenStream,
1670 /// Whether a macro with these arguments needs a semicolon
1671 /// when used as a standalone item or statement.
1672 pub fn need_semicolon(&self) -> bool {
1673 !matches!(self, DelimArgs { delim: MacDelimiter::Brace, .. })
1677 impl<CTX> HashStable<CTX> for DelimArgs
1679 CTX: crate::HashStableContext,
1681 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1682 let DelimArgs { dspan, delim, tokens } = self;
1683 dspan.hash_stable(ctx, hasher);
1684 delim.hash_stable(ctx, hasher);
1685 tokens.hash_stable(ctx, hasher);
1689 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1690 pub enum MacDelimiter {
1697 pub fn to_token(self) -> Delimiter {
1699 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1700 MacDelimiter::Bracket => Delimiter::Bracket,
1701 MacDelimiter::Brace => Delimiter::Brace,
1705 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1707 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1708 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1709 Delimiter::Brace => Some(MacDelimiter::Brace),
1710 Delimiter::Invisible => None,
1715 /// Represents a macro definition.
1716 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1717 pub struct MacroDef {
1718 pub body: P<DelimArgs>,
1719 /// `true` if macro was defined with `macro_rules`.
1720 pub macro_rules: bool,
1723 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1724 #[derive(HashStable_Generic)]
1726 /// A regular string, like `"foo"`.
1728 /// A raw string, like `r##"foo"##`.
1730 /// The value is the number of `#` symbols used.
1734 /// A literal in a meta item.
1735 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1736 pub struct MetaItemLit {
1737 /// The original literal as written in the source code.
1739 /// The original suffix as written in the source code.
1740 pub suffix: Option<Symbol>,
1741 /// The "semantic" representation of the literal lowered from the original tokens.
1742 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1747 /// Similar to `MetaItemLit`, but restricted to string literals.
1748 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1750 /// The original literal as written in source code.
1752 /// The original suffix as written in source code.
1753 pub suffix: Option<Symbol>,
1754 /// The semantic (unescaped) representation of the literal.
1755 pub symbol_unescaped: Symbol,
1756 pub style: StrStyle,
1761 pub fn as_token_lit(&self) -> token::Lit {
1762 let token_kind = match self.style {
1763 StrStyle::Cooked => token::Str,
1764 StrStyle::Raw(n) => token::StrRaw(n),
1766 token::Lit::new(token_kind, self.symbol, self.suffix)
1770 /// Type of the integer literal based on provided suffix.
1771 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1772 #[derive(HashStable_Generic)]
1773 pub enum LitIntType {
1782 /// Type of the float literal based on provided suffix.
1783 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1784 #[derive(HashStable_Generic)]
1785 pub enum LitFloatType {
1786 /// A float literal with a suffix (`1f32` or `1E10f32`).
1788 /// A float literal without a suffix (`1.0 or 1.0E10`).
1792 /// This type is used within both `ast::MetaItemLit` and `hir::Lit`.
1794 /// Note that the entire literal (including the suffix) is considered when
1795 /// deciding the `LitKind`. This means that float literals like `1f32` are
1796 /// classified by this type as `Float`. This is different to `token::LitKind`
1797 /// which does *not* consider the suffix.
1798 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1800 /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
1801 /// from the original token's symbol.
1802 Str(Symbol, StrStyle),
1803 /// A byte string (`b"foo"`). Not stored as a symbol because it might be
1804 /// non-utf8, and symbols only allow utf8 strings.
1805 ByteStr(Lrc<[u8]>, StrStyle),
1806 /// A byte char (`b'f'`).
1808 /// A character literal (`'a'`).
1810 /// An integer literal (`1`).
1811 Int(u128, LitIntType),
1812 /// A float literal (`1.0`, `1f64` or `1E10f64`). The pre-suffix part is
1813 /// stored as a symbol rather than `f64` so that `LitKind` can impl `Eq`
1815 Float(Symbol, LitFloatType),
1816 /// A boolean literal (`true`, `false`).
1818 /// Placeholder for a literal that wasn't well-formed in some way.
1823 /// Returns `true` if this literal is a string.
1824 pub fn is_str(&self) -> bool {
1825 matches!(self, LitKind::Str(..))
1828 /// Returns `true` if this literal is byte literal string.
1829 pub fn is_bytestr(&self) -> bool {
1830 matches!(self, LitKind::ByteStr(..))
1833 /// Returns `true` if this is a numeric literal.
1834 pub fn is_numeric(&self) -> bool {
1835 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1838 /// Returns `true` if this literal has no suffix.
1839 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1840 pub fn is_unsuffixed(&self) -> bool {
1844 /// Returns `true` if this literal has a suffix.
1845 pub fn is_suffixed(&self) -> bool {
1847 // suffixed variants
1848 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1849 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1850 // unsuffixed variants
1852 | LitKind::ByteStr(..)
1855 | LitKind::Int(_, LitIntType::Unsuffixed)
1856 | LitKind::Float(_, LitFloatType::Unsuffixed)
1858 | LitKind::Err => false,
1863 // N.B., If you change this, you'll probably want to change the corresponding
1864 // type structure in `middle/ty.rs` as well.
1865 #[derive(Clone, Encodable, Decodable, Debug)]
1868 pub mutbl: Mutability,
1871 /// Represents a function's signature in a trait declaration,
1872 /// trait implementation, or free function.
1873 #[derive(Clone, Encodable, Decodable, Debug)]
1875 pub header: FnHeader,
1876 pub decl: P<FnDecl>,
1880 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1881 #[derive(Encodable, Decodable, HashStable_Generic)]
1888 pub fn name_str(self) -> &'static str {
1890 FloatTy::F32 => "f32",
1891 FloatTy::F64 => "f64",
1895 pub fn name(self) -> Symbol {
1897 FloatTy::F32 => sym::f32,
1898 FloatTy::F64 => sym::f64,
1903 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1904 #[derive(Encodable, Decodable, HashStable_Generic)]
1915 pub fn name_str(&self) -> &'static str {
1917 IntTy::Isize => "isize",
1919 IntTy::I16 => "i16",
1920 IntTy::I32 => "i32",
1921 IntTy::I64 => "i64",
1922 IntTy::I128 => "i128",
1926 pub fn name(&self) -> Symbol {
1928 IntTy::Isize => sym::isize,
1929 IntTy::I8 => sym::i8,
1930 IntTy::I16 => sym::i16,
1931 IntTy::I32 => sym::i32,
1932 IntTy::I64 => sym::i64,
1933 IntTy::I128 => sym::i128,
1938 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1939 #[derive(Encodable, Decodable, HashStable_Generic)]
1950 pub fn name_str(&self) -> &'static str {
1952 UintTy::Usize => "usize",
1954 UintTy::U16 => "u16",
1955 UintTy::U32 => "u32",
1956 UintTy::U64 => "u64",
1957 UintTy::U128 => "u128",
1961 pub fn name(&self) -> Symbol {
1963 UintTy::Usize => sym::usize,
1964 UintTy::U8 => sym::u8,
1965 UintTy::U16 => sym::u16,
1966 UintTy::U32 => sym::u32,
1967 UintTy::U64 => sym::u64,
1968 UintTy::U128 => sym::u128,
1973 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1974 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1975 #[derive(Clone, Encodable, Decodable, Debug)]
1976 pub struct AssocConstraint {
1979 pub gen_args: Option<GenericArgs>,
1980 pub kind: AssocConstraintKind,
1984 /// The kinds of an `AssocConstraint`.
1985 #[derive(Clone, Encodable, Decodable, Debug)]
1991 impl From<P<Ty>> for Term {
1992 fn from(v: P<Ty>) -> Self {
1997 impl From<AnonConst> for Term {
1998 fn from(v: AnonConst) -> Self {
2003 /// The kinds of an `AssocConstraint`.
2004 #[derive(Clone, Encodable, Decodable, Debug)]
2005 pub enum AssocConstraintKind {
2006 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
2007 Equality { term: Term },
2008 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
2009 Bound { bounds: GenericBounds },
2012 #[derive(Encodable, Decodable, Debug)]
2017 pub tokens: Option<LazyAttrTokenStream>,
2021 fn clone(&self) -> Self {
2022 ensure_sufficient_stack(|| Self {
2024 kind: self.kind.clone(),
2026 tokens: self.tokens.clone(),
2032 pub fn peel_refs(&self) -> &Self {
2033 let mut final_ty = self;
2034 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
2041 #[derive(Clone, Encodable, Decodable, Debug)]
2042 pub struct BareFnTy {
2043 pub unsafety: Unsafe,
2045 pub generic_params: Vec<GenericParam>,
2046 pub decl: P<FnDecl>,
2047 /// Span of the `fn(...) -> ...` part.
2048 pub decl_span: Span,
2051 /// The various kinds of type recognized by the compiler.
2052 #[derive(Clone, Encodable, Decodable, Debug)]
2054 /// A variable-length slice (`[T]`).
2056 /// A fixed length array (`[T; n]`).
2057 Array(P<Ty>, AnonConst),
2058 /// A raw pointer (`*const T` or `*mut T`).
2060 /// A reference (`&'a T` or `&'a mut T`).
2061 Rptr(Option<Lifetime>, MutTy),
2062 /// A bare function (e.g., `fn(usize) -> bool`).
2063 BareFn(P<BareFnTy>),
2064 /// The never type (`!`).
2066 /// A tuple (`(A, B, C, D,...)`).
2068 /// A path (`module::module::...::Type`), optionally
2069 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2071 /// Type parameters are stored in the `Path` itself.
2072 Path(Option<P<QSelf>>, Path),
2073 /// A trait object type `Bound1 + Bound2 + Bound3`
2074 /// where `Bound` is a trait or a lifetime.
2075 TraitObject(GenericBounds, TraitObjectSyntax),
2076 /// An `impl Bound1 + Bound2 + Bound3` type
2077 /// where `Bound` is a trait or a lifetime.
2079 /// The `NodeId` exists to prevent lowering from having to
2080 /// generate `NodeId`s on the fly, which would complicate
2081 /// the generation of opaque `type Foo = impl Trait` items significantly.
2082 ImplTrait(NodeId, GenericBounds),
2083 /// No-op; kept solely so that we can pretty-print faithfully.
2087 /// This means the type should be inferred instead of it having been
2088 /// specified. This can appear anywhere in a type.
2090 /// Inferred type of a `self` or `&self` argument in a method.
2092 /// A macro in the type position.
2093 MacCall(P<MacCall>),
2094 /// Placeholder for a kind that has failed to be defined.
2096 /// Placeholder for a `va_list`.
2101 pub fn is_implicit_self(&self) -> bool {
2102 matches!(self, TyKind::ImplicitSelf)
2105 pub fn is_unit(&self) -> bool {
2106 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2109 pub fn is_simple_path(&self) -> Option<Symbol> {
2110 if let TyKind::Path(None, Path { segments, .. }) = &self
2111 && let [segment] = &segments[..]
2112 && segment.args.is_none()
2114 Some(segment.ident.name)
2121 /// Syntax used to declare a trait object.
2122 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2123 pub enum TraitObjectSyntax {
2129 /// Inline assembly operand explicit register or register class.
2131 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2132 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2133 pub enum InlineAsmRegOrRegClass {
2138 bitflags::bitflags! {
2139 #[derive(Encodable, Decodable, HashStable_Generic)]
2140 pub struct InlineAsmOptions: u16 {
2141 const PURE = 1 << 0;
2142 const NOMEM = 1 << 1;
2143 const READONLY = 1 << 2;
2144 const PRESERVES_FLAGS = 1 << 3;
2145 const NORETURN = 1 << 4;
2146 const NOSTACK = 1 << 5;
2147 const ATT_SYNTAX = 1 << 6;
2149 const MAY_UNWIND = 1 << 8;
2153 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2154 pub enum InlineAsmTemplatePiece {
2156 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2159 impl fmt::Display for InlineAsmTemplatePiece {
2160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2162 Self::String(s) => {
2163 for c in s.chars() {
2165 '{' => f.write_str("{{")?,
2166 '}' => f.write_str("}}")?,
2172 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2173 write!(f, "{{{}:{}}}", operand_idx, modifier)
2175 Self::Placeholder { operand_idx, modifier: None, .. } => {
2176 write!(f, "{{{}}}", operand_idx)
2182 impl InlineAsmTemplatePiece {
2183 /// Rebuilds the asm template string from its pieces.
2184 pub fn to_string(s: &[Self]) -> String {
2186 let mut out = String::new();
2188 let _ = write!(out, "{}", p);
2194 /// Inline assembly symbol operands get their own AST node that is somewhat
2195 /// similar to `AnonConst`.
2197 /// The main difference is that we specifically don't assign it `DefId` in
2198 /// `DefCollector`. Instead this is deferred until AST lowering where we
2199 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2200 /// depending on what the path resolves to.
2201 #[derive(Clone, Encodable, Decodable, Debug)]
2202 pub struct InlineAsmSym {
2204 pub qself: Option<P<QSelf>>,
2208 /// Inline assembly operand.
2210 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2211 #[derive(Clone, Encodable, Decodable, Debug)]
2212 pub enum InlineAsmOperand {
2214 reg: InlineAsmRegOrRegClass,
2218 reg: InlineAsmRegOrRegClass,
2220 expr: Option<P<Expr>>,
2223 reg: InlineAsmRegOrRegClass,
2228 reg: InlineAsmRegOrRegClass,
2231 out_expr: Option<P<Expr>>,
2234 anon_const: AnonConst,
2241 /// Inline assembly.
2243 /// E.g., `asm!("NOP");`.
2244 #[derive(Clone, Encodable, Decodable, Debug)]
2245 pub struct InlineAsm {
2246 pub template: Vec<InlineAsmTemplatePiece>,
2247 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2248 pub operands: Vec<(InlineAsmOperand, Span)>,
2249 pub clobber_abis: Vec<(Symbol, Span)>,
2250 pub options: InlineAsmOptions,
2251 pub line_spans: Vec<Span>,
2254 /// A parameter in a function header.
2256 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2257 #[derive(Clone, Encodable, Decodable, Debug)]
2264 pub is_placeholder: bool,
2267 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2269 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2270 #[derive(Clone, Encodable, Decodable, Debug)]
2272 /// `self`, `mut self`
2274 /// `&'lt self`, `&'lt mut self`
2275 Region(Option<Lifetime>, Mutability),
2276 /// `self: TYPE`, `mut self: TYPE`
2277 Explicit(P<Ty>, Mutability),
2280 pub type ExplicitSelf = Spanned<SelfKind>;
2283 /// Attempts to cast parameter to `ExplicitSelf`.
2284 pub fn to_self(&self) -> Option<ExplicitSelf> {
2285 if let PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), ident, _) = self.pat.kind {
2286 if ident.name == kw::SelfLower {
2287 return match self.ty.kind {
2288 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2289 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2290 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2293 self.pat.span.to(self.ty.span),
2294 SelfKind::Explicit(self.ty.clone(), mutbl),
2302 /// Returns `true` if parameter is `self`.
2303 pub fn is_self(&self) -> bool {
2304 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2305 ident.name == kw::SelfLower
2311 /// Builds a `Param` object from `ExplicitSelf`.
2312 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2313 let span = eself.span.to(eself_ident.span);
2314 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2315 let (mutbl, ty) = match eself.node {
2316 SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2317 SelfKind::Value(mutbl) => (mutbl, infer_ty),
2318 SelfKind::Region(lt, mutbl) => (
2322 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2332 kind: PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), eself_ident, None),
2339 is_placeholder: false,
2344 /// A signature (not the body) of a function declaration.
2346 /// E.g., `fn foo(bar: baz)`.
2348 /// Please note that it's different from `FnHeader` structure
2349 /// which contains metadata about function safety, asyncness, constness and ABI.
2350 #[derive(Clone, Encodable, Decodable, Debug)]
2352 pub inputs: Vec<Param>,
2353 pub output: FnRetTy,
2357 pub fn has_self(&self) -> bool {
2358 self.inputs.get(0).map_or(false, Param::is_self)
2360 pub fn c_variadic(&self) -> bool {
2361 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2365 /// Is the trait definition an auto trait?
2366 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2372 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2373 #[derive(HashStable_Generic)]
2379 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2381 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2386 pub fn is_async(self) -> bool {
2387 matches!(self, Async::Yes { .. })
2390 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2391 pub fn opt_return_id(self) -> Option<(NodeId, Span)> {
2393 Async::Yes { return_impl_trait_id, span, .. } => Some((return_impl_trait_id, span)),
2399 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2400 #[derive(HashStable_Generic)]
2406 /// Item defaultness.
2407 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2408 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2409 pub enum Defaultness {
2414 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2415 pub enum ImplPolarity {
2416 /// `impl Trait for Type`
2418 /// `impl !Trait for Type`
2422 impl fmt::Debug for ImplPolarity {
2423 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2425 ImplPolarity::Positive => "positive".fmt(f),
2426 ImplPolarity::Negative(_) => "negative".fmt(f),
2431 #[derive(Clone, Encodable, Decodable, Debug)]
2433 /// Returns type is not specified.
2435 /// Functions default to `()` and closures default to inference.
2436 /// Span points to where return type would be inserted.
2438 /// Everything else.
2443 pub fn span(&self) -> Span {
2445 &FnRetTy::Default(span) => span,
2446 FnRetTy::Ty(ty) => ty.span,
2451 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2457 /// Module item kind.
2458 #[derive(Clone, Encodable, Decodable, Debug)]
2460 /// Module with inlined definition `mod foo { ... }`,
2461 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2462 /// The inner span is from the first token past `{` to the last token until `}`,
2463 /// or from the first to the last token in the loaded file.
2464 Loaded(Vec<P<Item>>, Inline, ModSpans),
2465 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2469 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2470 pub struct ModSpans {
2471 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2472 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2473 pub inner_span: Span,
2474 pub inject_use_span: Span,
2477 /// Foreign module declaration.
2479 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2480 #[derive(Clone, Encodable, Decodable, Debug)]
2481 pub struct ForeignMod {
2482 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2483 /// semantically by Rust.
2484 pub unsafety: Unsafe,
2485 pub abi: Option<StrLit>,
2486 pub items: Vec<P<ForeignItem>>,
2489 #[derive(Clone, Encodable, Decodable, Debug)]
2490 pub struct EnumDef {
2491 pub variants: Vec<Variant>,
2494 #[derive(Clone, Encodable, Decodable, Debug)]
2495 pub struct Variant {
2496 /// Attributes of the variant.
2498 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2502 /// The visibility of the variant. Syntactically accepted but not semantically.
2503 pub vis: Visibility,
2504 /// Name of the variant.
2507 /// Fields and constructor id of the variant.
2508 pub data: VariantData,
2509 /// Explicit discriminant, e.g., `Foo = 1`.
2510 pub disr_expr: Option<AnonConst>,
2511 /// Is a macro placeholder
2512 pub is_placeholder: bool,
2515 /// Part of `use` item to the right of its prefix.
2516 #[derive(Clone, Encodable, Decodable, Debug)]
2517 pub enum UseTreeKind {
2518 /// `use prefix` or `use prefix as rename`
2519 Simple(Option<Ident>),
2520 /// `use prefix::{...}`
2521 Nested(Vec<(UseTree, NodeId)>),
2526 /// A tree of paths sharing common prefixes.
2527 /// Used in `use` items both at top-level and inside of braces in import groups.
2528 #[derive(Clone, Encodable, Decodable, Debug)]
2529 pub struct UseTree {
2531 pub kind: UseTreeKind,
2536 pub fn ident(&self) -> Ident {
2538 UseTreeKind::Simple(Some(rename)) => rename,
2539 UseTreeKind::Simple(None) => {
2540 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2542 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2547 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2548 /// are contained as statements within items. These two cases need to be
2549 /// distinguished for pretty-printing.
2550 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2551 pub enum AttrStyle {
2556 rustc_index::newtype_index! {
2559 DEBUG_FORMAT = "AttrId({})"
2563 impl<S: Encoder> Encodable<S> for AttrId {
2564 fn encode(&self, _s: &mut S) {}
2567 impl<D: Decoder> Decodable<D> for AttrId {
2568 default fn decode(_: &mut D) -> AttrId {
2569 panic!("cannot decode `AttrId` with `{}`", std::any::type_name::<D>());
2573 /// A list of attributes.
2574 pub type AttrVec = ThinVec<Attribute>;
2576 /// A syntax-level representation of an attribute.
2577 #[derive(Clone, Encodable, Decodable, Debug)]
2578 pub struct Attribute {
2581 /// Denotes if the attribute decorates the following construct (outer)
2582 /// or the construct this attribute is contained within (inner).
2583 pub style: AttrStyle,
2587 #[derive(Clone, Encodable, Decodable, Debug)]
2589 /// A normal attribute.
2590 Normal(P<NormalAttr>),
2592 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2593 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2594 /// variant (which is much less compact and thus more expensive).
2595 DocComment(CommentKind, Symbol),
2598 #[derive(Clone, Encodable, Decodable, Debug)]
2599 pub struct NormalAttr {
2601 pub tokens: Option<LazyAttrTokenStream>,
2604 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2605 pub struct AttrItem {
2608 pub tokens: Option<LazyAttrTokenStream>,
2611 /// `TraitRef`s appear in impls.
2613 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2614 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2615 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2616 /// same as the impl's `NodeId`).
2617 #[derive(Clone, Encodable, Decodable, Debug)]
2618 pub struct TraitRef {
2623 #[derive(Clone, Encodable, Decodable, Debug)]
2624 pub struct PolyTraitRef {
2625 /// The `'a` in `for<'a> Foo<&'a T>`.
2626 pub bound_generic_params: Vec<GenericParam>,
2628 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2629 pub trait_ref: TraitRef,
2635 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2637 bound_generic_params: generic_params,
2638 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2644 #[derive(Clone, Encodable, Decodable, Debug)]
2645 pub struct Visibility {
2646 pub kind: VisibilityKind,
2648 pub tokens: Option<LazyAttrTokenStream>,
2651 #[derive(Clone, Encodable, Decodable, Debug)]
2652 pub enum VisibilityKind {
2654 Restricted { path: P<Path>, id: NodeId, shorthand: bool },
2658 impl VisibilityKind {
2659 pub fn is_pub(&self) -> bool {
2660 matches!(self, VisibilityKind::Public)
2664 /// Field definition in a struct, variant or union.
2666 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2667 #[derive(Clone, Encodable, Decodable, Debug)]
2668 pub struct FieldDef {
2672 pub vis: Visibility,
2673 pub ident: Option<Ident>,
2676 pub is_placeholder: bool,
2679 /// Fields and constructor ids of enum variants and structs.
2680 #[derive(Clone, Encodable, Decodable, Debug)]
2681 pub enum VariantData {
2684 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2685 Struct(Vec<FieldDef>, bool),
2688 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2689 Tuple(Vec<FieldDef>, NodeId),
2692 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2697 /// Return the fields of this variant.
2698 pub fn fields(&self) -> &[FieldDef] {
2700 VariantData::Struct(fields, ..) | VariantData::Tuple(fields, _) => fields,
2705 /// Return the `NodeId` of this variant's constructor, if it has one.
2706 pub fn ctor_node_id(&self) -> Option<NodeId> {
2708 VariantData::Struct(..) => None,
2709 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2714 /// An item definition.
2715 #[derive(Clone, Encodable, Decodable, Debug)]
2716 pub struct Item<K = ItemKind> {
2720 pub vis: Visibility,
2721 /// The name of the item.
2722 /// It might be a dummy name in case of anonymous items.
2727 /// Original tokens this item was parsed from. This isn't necessarily
2728 /// available for all items, although over time more and more items should
2729 /// have this be `Some`. Right now this is primarily used for procedural
2730 /// macros, notably custom attributes.
2732 /// Note that the tokens here do not include the outer attributes, but will
2733 /// include inner attributes.
2734 pub tokens: Option<LazyAttrTokenStream>,
2738 /// Return the span that encompasses the attributes.
2739 pub fn span_with_attributes(&self) -> Span {
2740 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2744 /// `extern` qualifier on a function item or function type.
2745 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2749 Explicit(StrLit, Span),
2753 pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2755 Some(name) => Extern::Explicit(name, span),
2756 None => Extern::Implicit(span),
2761 /// A function header.
2763 /// All the information between the visibility and the name of the function is
2764 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2765 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2766 pub struct FnHeader {
2767 pub unsafety: Unsafe,
2768 pub asyncness: Async,
2769 pub constness: Const,
2774 /// Does this function header have any qualifiers or is it empty?
2775 pub fn has_qualifiers(&self) -> bool {
2776 let Self { unsafety, asyncness, constness, ext } = self;
2777 matches!(unsafety, Unsafe::Yes(_))
2778 || asyncness.is_async()
2779 || matches!(constness, Const::Yes(_))
2780 || !matches!(ext, Extern::None)
2784 impl Default for FnHeader {
2785 fn default() -> FnHeader {
2787 unsafety: Unsafe::No,
2788 asyncness: Async::No,
2789 constness: Const::No,
2795 #[derive(Clone, Encodable, Decodable, Debug)]
2797 pub unsafety: Unsafe,
2798 pub is_auto: IsAuto,
2799 pub generics: Generics,
2800 pub bounds: GenericBounds,
2801 pub items: Vec<P<AssocItem>>,
2804 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2805 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2806 /// are two locations for where clause on type aliases, but their predicates
2807 /// are concatenated together.
2809 /// Take this example:
2810 /// ```ignore (only-for-syntax-highlight)
2812 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2814 /// impl Foo for () {
2815 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2816 /// // ^^^^^^^^^^^^^^ first where clause
2817 /// // ^^^^^^^^^^^^^^ second where clause
2821 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2822 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2823 pub struct TyAliasWhereClause(pub bool, pub Span);
2825 #[derive(Clone, Encodable, Decodable, Debug)]
2826 pub struct TyAlias {
2827 pub defaultness: Defaultness,
2828 pub generics: Generics,
2829 /// The span information for the two where clauses (before equals, after equals)
2830 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2831 /// The index in `generics.where_clause.predicates` that would split into
2832 /// predicates from the where clause before the equals and the predicates
2833 /// from the where clause after the equals
2834 pub where_predicates_split: usize,
2835 pub bounds: GenericBounds,
2836 pub ty: Option<P<Ty>>,
2839 #[derive(Clone, Encodable, Decodable, Debug)]
2841 pub defaultness: Defaultness,
2842 pub unsafety: Unsafe,
2843 pub generics: Generics,
2844 pub constness: Const,
2845 pub polarity: ImplPolarity,
2846 /// The trait being implemented, if any.
2847 pub of_trait: Option<TraitRef>,
2849 pub items: Vec<P<AssocItem>>,
2852 #[derive(Clone, Encodable, Decodable, Debug)]
2854 pub defaultness: Defaultness,
2855 pub generics: Generics,
2857 pub body: Option<P<Block>>,
2860 #[derive(Clone, Encodable, Decodable, Debug)]
2862 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2864 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2865 ExternCrate(Option<Symbol>),
2866 /// A use declaration item (`use`).
2868 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2870 /// A static item (`static`).
2872 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2873 Static(P<Ty>, Mutability, Option<P<Expr>>),
2874 /// A constant item (`const`).
2876 /// E.g., `const FOO: i32 = 42;`.
2877 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2878 /// A function declaration (`fn`).
2880 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2882 /// A module declaration (`mod`).
2884 /// E.g., `mod foo;` or `mod foo { .. }`.
2885 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2886 /// semantically by Rust.
2887 Mod(Unsafe, ModKind),
2888 /// An external module (`extern`).
2890 /// E.g., `extern {}` or `extern "C" {}`.
2891 ForeignMod(ForeignMod),
2892 /// Module-level inline assembly (from `global_asm!()`).
2893 GlobalAsm(Box<InlineAsm>),
2894 /// A type alias (`type`).
2896 /// E.g., `type Foo = Bar<u8>;`.
2897 TyAlias(Box<TyAlias>),
2898 /// An enum definition (`enum`).
2900 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2901 Enum(EnumDef, Generics),
2902 /// A struct definition (`struct`).
2904 /// E.g., `struct Foo<A> { x: A }`.
2905 Struct(VariantData, Generics),
2906 /// A union definition (`union`).
2908 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2909 Union(VariantData, Generics),
2910 /// A trait declaration (`trait`).
2912 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2916 /// E.g., `trait Foo = Bar + Quux;`.
2917 TraitAlias(Generics, GenericBounds),
2918 /// An implementation.
2920 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2922 /// A macro invocation.
2924 /// E.g., `foo!(..)`.
2925 MacCall(P<MacCall>),
2927 /// A macro definition.
2932 pub fn article(&self) -> &str {
2935 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2936 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2937 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2941 pub fn descr(&self) -> &str {
2943 ItemKind::ExternCrate(..) => "extern crate",
2944 ItemKind::Use(..) => "`use` import",
2945 ItemKind::Static(..) => "static item",
2946 ItemKind::Const(..) => "constant item",
2947 ItemKind::Fn(..) => "function",
2948 ItemKind::Mod(..) => "module",
2949 ItemKind::ForeignMod(..) => "extern block",
2950 ItemKind::GlobalAsm(..) => "global asm item",
2951 ItemKind::TyAlias(..) => "type alias",
2952 ItemKind::Enum(..) => "enum",
2953 ItemKind::Struct(..) => "struct",
2954 ItemKind::Union(..) => "union",
2955 ItemKind::Trait(..) => "trait",
2956 ItemKind::TraitAlias(..) => "trait alias",
2957 ItemKind::MacCall(..) => "item macro invocation",
2958 ItemKind::MacroDef(..) => "macro definition",
2959 ItemKind::Impl { .. } => "implementation",
2963 pub fn generics(&self) -> Option<&Generics> {
2965 Self::Fn(box Fn { generics, .. })
2966 | Self::TyAlias(box TyAlias { generics, .. })
2967 | Self::Enum(_, generics)
2968 | Self::Struct(_, generics)
2969 | Self::Union(_, generics)
2970 | Self::Trait(box Trait { generics, .. })
2971 | Self::TraitAlias(generics, _)
2972 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2978 /// Represents associated items.
2979 /// These include items in `impl` and `trait` definitions.
2980 pub type AssocItem = Item<AssocItemKind>;
2982 /// Represents associated item kinds.
2984 /// The term "provided" in the variants below refers to the item having a default
2985 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2986 /// In an implementation, all items must be provided.
2987 /// The `Option`s below denote the bodies, where `Some(_)`
2988 /// means "provided" and conversely `None` means "required".
2989 #[derive(Clone, Encodable, Decodable, Debug)]
2990 pub enum AssocItemKind {
2991 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2992 /// If `def` is parsed, then the constant is provided, and otherwise required.
2993 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2994 /// An associated function.
2996 /// An associated type.
2998 /// A macro expanding to associated items.
2999 MacCall(P<MacCall>),
3002 impl AssocItemKind {
3003 pub fn defaultness(&self) -> Defaultness {
3005 Self::Const(defaultness, ..)
3006 | Self::Fn(box Fn { defaultness, .. })
3007 | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
3008 Self::MacCall(..) => Defaultness::Final,
3013 impl From<AssocItemKind> for ItemKind {
3014 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
3015 match assoc_item_kind {
3016 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
3017 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3018 AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3019 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
3024 impl TryFrom<ItemKind> for AssocItemKind {
3025 type Error = ItemKind;
3027 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
3028 Ok(match item_kind {
3029 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
3030 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
3031 ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
3032 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
3033 _ => return Err(item_kind),
3038 /// An item in `extern` block.
3039 #[derive(Clone, Encodable, Decodable, Debug)]
3040 pub enum ForeignItemKind {
3041 /// A foreign static item (`static FOO: u8`).
3042 Static(P<Ty>, Mutability, Option<P<Expr>>),
3043 /// An foreign function.
3045 /// An foreign type.
3046 TyAlias(Box<TyAlias>),
3047 /// A macro expanding to foreign items.
3048 MacCall(P<MacCall>),
3051 impl From<ForeignItemKind> for ItemKind {
3052 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3053 match foreign_item_kind {
3054 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3055 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3056 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3057 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3062 impl TryFrom<ItemKind> for ForeignItemKind {
3063 type Error = ItemKind;
3065 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3066 Ok(match item_kind {
3067 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3068 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3069 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3070 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3071 _ => return Err(item_kind),
3076 pub type ForeignItem = Item<ForeignItemKind>;
3078 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3079 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3082 use rustc_data_structures::static_assert_size;
3083 // tidy-alphabetical-start
3084 static_assert_size!(AssocItem, 104);
3085 static_assert_size!(AssocItemKind, 32);
3086 static_assert_size!(Attribute, 32);
3087 static_assert_size!(Block, 48);
3088 static_assert_size!(Expr, 72);
3089 static_assert_size!(ExprKind, 40);
3090 static_assert_size!(Fn, 184);
3091 static_assert_size!(ForeignItem, 96);
3092 static_assert_size!(ForeignItemKind, 24);
3093 static_assert_size!(GenericArg, 24);
3094 static_assert_size!(GenericBound, 72);
3095 static_assert_size!(Generics, 72);
3096 static_assert_size!(Impl, 184);
3097 static_assert_size!(Item, 184);
3098 static_assert_size!(ItemKind, 112);
3099 static_assert_size!(LitKind, 24);
3100 static_assert_size!(Local, 72);
3101 static_assert_size!(MetaItemLit, 40);
3102 static_assert_size!(Param, 40);
3103 static_assert_size!(Pat, 88);
3104 static_assert_size!(Path, 24);
3105 static_assert_size!(PathSegment, 24);
3106 static_assert_size!(PatKind, 64);
3107 static_assert_size!(Stmt, 32);
3108 static_assert_size!(StmtKind, 16);
3109 static_assert_size!(Ty, 64);
3110 static_assert_size!(TyKind, 40);
3111 // tidy-alphabetical-end