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::format::*;
22 pub use crate::util::parser::ExprPrecedence;
23 pub use GenericArgs::*;
24 pub use UnsafeSource::*;
27 use crate::token::{self, CommentKind, Delimiter};
28 use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream};
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_macros::HashStable_Generic;
33 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
34 use rustc_span::source_map::{respan, Spanned};
35 use rustc_span::symbol::{kw, sym, Ident, Symbol};
36 use rustc_span::{Span, DUMMY_SP};
39 use thin_vec::{thin_vec, ThinVec};
41 /// A "Label" is an identifier of some point in sources,
42 /// e.g. in the following code:
50 /// `'outer` is a label.
51 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
56 impl fmt::Debug for Label {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 write!(f, "label({:?})", self.ident)
62 /// A "Lifetime" is an annotation of the scope in which variable
63 /// can be used, e.g. `'a` in `&'a i32`.
64 #[derive(Clone, Encodable, Decodable, Copy, PartialEq, Eq)]
70 impl fmt::Debug for Lifetime {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 write!(f, "lifetime({}: {})", self.id, self)
76 impl fmt::Display for Lifetime {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "{}", self.ident.name)
82 /// A "Path" is essentially Rust's notion of a name.
84 /// It's represented as a sequence of identifiers,
85 /// along with a bunch of supporting information.
87 /// E.g., `std::cmp::PartialEq`.
88 #[derive(Clone, Encodable, Decodable, Debug)]
91 /// The segments in the path: the things separated by `::`.
92 /// Global paths begin with `kw::PathRoot`.
93 pub segments: ThinVec<PathSegment>,
94 pub tokens: Option<LazyAttrTokenStream>,
97 impl PartialEq<Symbol> for Path {
99 fn eq(&self, symbol: &Symbol) -> bool {
100 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
104 impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
105 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
106 self.segments.len().hash_stable(hcx, hasher);
107 for segment in &self.segments {
108 segment.ident.hash_stable(hcx, hasher);
114 /// Convert a span and an identifier to the corresponding
115 /// one-segment path.
116 pub fn from_ident(ident: Ident) -> Path {
117 Path { segments: thin_vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
120 pub fn is_global(&self) -> bool {
121 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
125 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
127 /// E.g., `std`, `String` or `Box<T>`.
128 #[derive(Clone, Encodable, Decodable, Debug)]
129 pub struct PathSegment {
130 /// The identifier portion of this path segment.
135 /// Type/lifetime parameters attached to this path. They come in
136 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
137 /// `None` means that no parameter list is supplied (`Path`),
138 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
139 /// but it can be empty (`Path<>`).
140 /// `P` is used as a size optimization for the common case with no parameters.
141 pub args: Option<P<GenericArgs>>,
145 pub fn from_ident(ident: Ident) -> Self {
146 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
149 pub fn path_root(span: Span) -> Self {
150 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
153 pub fn span(&self) -> Span {
155 Some(args) => self.ident.span.to(args.span()),
156 None => self.ident.span,
161 /// The arguments of a path segment.
163 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
164 #[derive(Clone, Encodable, Decodable, Debug)]
165 pub enum GenericArgs {
166 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
167 AngleBracketed(AngleBracketedArgs),
168 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
169 Parenthesized(ParenthesizedArgs),
173 pub fn is_angle_bracketed(&self) -> bool {
174 matches!(self, AngleBracketed(..))
177 pub fn span(&self) -> Span {
179 AngleBracketed(data) => data.span,
180 Parenthesized(data) => data.span,
185 /// Concrete argument in the sequence of generic args.
186 #[derive(Clone, Encodable, Decodable, Debug)]
187 pub enum GenericArg {
188 /// `'a` in `Foo<'a>`
190 /// `Bar` in `Foo<Bar>`
197 pub fn span(&self) -> Span {
199 GenericArg::Lifetime(lt) => lt.ident.span,
200 GenericArg::Type(ty) => ty.span,
201 GenericArg::Const(ct) => ct.value.span,
206 /// A path like `Foo<'a, T>`.
207 #[derive(Clone, Encodable, Decodable, Debug, Default)]
208 pub struct AngleBracketedArgs {
209 /// The overall span.
211 /// The comma separated parts in the `<...>`.
212 pub args: Vec<AngleBracketedArg>,
215 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
216 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
217 #[derive(Clone, Encodable, Decodable, Debug)]
218 pub enum AngleBracketedArg {
219 /// Argument for a generic parameter.
221 /// Constraint for an associated item.
222 Constraint(AssocConstraint),
225 impl AngleBracketedArg {
226 pub fn span(&self) -> Span {
228 AngleBracketedArg::Arg(arg) => arg.span(),
229 AngleBracketedArg::Constraint(constraint) => constraint.span,
234 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
235 fn into(self) -> Option<P<GenericArgs>> {
236 Some(P(GenericArgs::AngleBracketed(self)))
240 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
241 fn into(self) -> Option<P<GenericArgs>> {
242 Some(P(GenericArgs::Parenthesized(self)))
246 /// A path like `Foo(A, B) -> C`.
247 #[derive(Clone, Encodable, Decodable, Debug)]
248 pub struct ParenthesizedArgs {
256 pub inputs: Vec<P<Ty>>,
262 pub inputs_span: Span,
268 impl ParenthesizedArgs {
269 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
274 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
276 AngleBracketedArgs { span: self.inputs_span, args }
280 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
282 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
284 /// Negative bounds should also be handled here.
285 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
286 pub enum TraitBoundModifier {
298 // This parses but will be rejected during AST validation.
302 /// The AST represents all type param bounds as types.
303 /// `typeck::collect::compute_bounds` matches these against
304 /// the "special" built-in traits (see `middle::lang_items`) and
305 /// detects `Copy`, `Send` and `Sync`.
306 #[derive(Clone, Encodable, Decodable, Debug)]
307 pub enum GenericBound {
308 Trait(PolyTraitRef, TraitBoundModifier),
313 pub fn span(&self) -> Span {
315 GenericBound::Trait(t, ..) => t.span,
316 GenericBound::Outlives(l) => l.ident.span,
321 pub type GenericBounds = Vec<GenericBound>;
323 /// Specifies the enforced ordering for generic parameters. In the future,
324 /// if we wanted to relax this order, we could override `PartialEq` and
325 /// `PartialOrd`, to allow the kinds to be unordered.
326 #[derive(Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
327 pub enum ParamKindOrd {
332 impl fmt::Display for ParamKindOrd {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 ParamKindOrd::Lifetime => "lifetime".fmt(f),
336 ParamKindOrd::TypeOrConst => "type and const".fmt(f),
341 #[derive(Clone, Encodable, Decodable, Debug)]
342 pub enum GenericParamKind {
343 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
346 default: Option<P<Ty>>,
350 /// Span of the `const` keyword.
352 /// Optional default value for the const generic param
353 default: Option<AnonConst>,
357 #[derive(Clone, Encodable, Decodable, Debug)]
358 pub struct GenericParam {
362 pub bounds: GenericBounds,
363 pub is_placeholder: bool,
364 pub kind: GenericParamKind,
365 pub colon_span: Option<Span>,
369 pub fn span(&self) -> Span {
371 GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
374 GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
375 GenericParamKind::Const { kw_span, default: Some(default), .. } => {
376 kw_span.to(default.value.span)
378 GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
383 /// Represents lifetime, type and const parameters attached to a declaration of
384 /// a function, enum, trait, etc.
385 #[derive(Clone, Encodable, Decodable, Debug)]
386 pub struct Generics {
387 pub params: Vec<GenericParam>,
388 pub where_clause: WhereClause,
392 impl Default for Generics {
393 /// Creates an instance of `Generics`.
394 fn default() -> Generics {
395 Generics { params: Vec::new(), where_clause: Default::default(), span: DUMMY_SP }
399 /// A where-clause in a definition.
400 #[derive(Clone, Encodable, Decodable, Debug)]
401 pub struct WhereClause {
402 /// `true` if we ate a `where` token: this can happen
403 /// if we parsed no predicates (e.g. `struct Foo where {}`).
404 /// This allows us to pretty-print accurately.
405 pub has_where_token: bool,
406 pub predicates: Vec<WherePredicate>,
410 impl Default for WhereClause {
411 fn default() -> WhereClause {
412 WhereClause { has_where_token: false, predicates: Vec::new(), span: DUMMY_SP }
416 /// A single predicate in a where-clause.
417 #[derive(Clone, Encodable, Decodable, Debug)]
418 pub enum WherePredicate {
419 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
420 BoundPredicate(WhereBoundPredicate),
421 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
422 RegionPredicate(WhereRegionPredicate),
423 /// An equality predicate (unsupported).
424 EqPredicate(WhereEqPredicate),
427 impl WherePredicate {
428 pub fn span(&self) -> Span {
430 WherePredicate::BoundPredicate(p) => p.span,
431 WherePredicate::RegionPredicate(p) => p.span,
432 WherePredicate::EqPredicate(p) => p.span,
439 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
440 #[derive(Clone, Encodable, Decodable, Debug)]
441 pub struct WhereBoundPredicate {
443 /// Any generics from a `for` binding.
444 pub bound_generic_params: Vec<GenericParam>,
445 /// The type being bounded.
446 pub bounded_ty: P<Ty>,
447 /// Trait and lifetime bounds (`Clone + Send + 'static`).
448 pub bounds: GenericBounds,
451 /// A lifetime predicate.
453 /// E.g., `'a: 'b + 'c`.
454 #[derive(Clone, Encodable, Decodable, Debug)]
455 pub struct WhereRegionPredicate {
457 pub lifetime: Lifetime,
458 pub bounds: GenericBounds,
461 /// An equality predicate (unsupported).
464 #[derive(Clone, Encodable, Decodable, Debug)]
465 pub struct WhereEqPredicate {
471 #[derive(Clone, Encodable, Decodable, Debug)]
474 pub items: Vec<P<Item>>,
476 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
477 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
479 pub is_placeholder: bool,
482 /// A semantic representation of a meta item. A meta item is a slightly
483 /// restricted form of an attribute -- it can only contain expressions in
484 /// certain leaf positions, rather than arbitrary token streams -- that is used
485 /// for most built-in attributes.
487 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
488 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
489 pub struct MetaItem {
491 pub kind: MetaItemKind,
495 /// The meta item kind, containing the data after the initial path.
496 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
497 pub enum MetaItemKind {
500 /// E.g., `#[test]`, which lacks any arguments after `test`.
505 /// E.g., `#[derive(..)]`, where the field represents the `..`.
506 List(Vec<NestedMetaItem>),
508 /// Name value meta item.
510 /// E.g., `#[feature = "foo"]`, where the field represents the `"foo"`.
511 NameValue(MetaItemLit),
514 /// Values inside meta item lists.
516 /// E.g., each of `Clone`, `Copy` in `#[derive(Clone, Copy)]`.
517 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
518 pub enum NestedMetaItem {
519 /// A full MetaItem, for recursive meta items.
524 /// E.g., `"foo"`, `64`, `true`.
528 /// A block (`{ .. }`).
530 /// E.g., `{ .. }` as in `fn foo() { .. }`.
531 #[derive(Clone, Encodable, Decodable, Debug)]
533 /// The statements in the block.
534 pub stmts: Vec<Stmt>,
536 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
537 pub rules: BlockCheckMode,
539 pub tokens: Option<LazyAttrTokenStream>,
540 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
547 pub could_be_bare_literal: bool,
552 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
553 #[derive(Clone, Encodable, Decodable, Debug)]
558 pub tokens: Option<LazyAttrTokenStream>,
562 /// Attempt reparsing the pattern as a type.
563 /// This is intended for use by diagnostics.
564 pub fn to_ty(&self) -> Option<P<Ty>> {
565 let kind = match &self.kind {
566 // In a type expression `_` is an inference variable.
567 PatKind::Wild => TyKind::Infer,
568 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
569 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
570 TyKind::Path(None, Path::from_ident(*ident))
572 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
573 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
574 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
575 PatKind::Ref(pat, mutbl) => {
576 pat.to_ty().map(|ty| TyKind::Ref(None, MutTy { ty, mutbl: *mutbl }))?
578 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
579 // when `P` can be reparsed as a type `T`.
580 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
581 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
582 // assuming `T0` to `Tn` are all syntactically valid as types.
583 PatKind::Tuple(pats) => {
584 let mut tys = Vec::with_capacity(pats.len());
585 // FIXME(#48994) - could just be collected into an Option<Vec>
587 tys.push(pat.to_ty()?);
594 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
597 /// Walk top-down and call `it` in each place where a pattern occurs
598 /// starting with the root pattern `walk` is called on. If `it` returns
599 /// false then we will descend no further but siblings will be processed.
600 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
606 // Walk into the pattern associated with `Ident` (if any).
607 PatKind::Ident(_, _, Some(p)) => p.walk(it),
609 // Walk into each field of struct.
610 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
612 // Sequence of patterns.
613 PatKind::TupleStruct(_, _, s)
616 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
618 // Trivial wrappers over inner patterns.
619 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
621 // These patterns do not contain subpatterns, skip.
628 | PatKind::MacCall(_) => {}
632 /// Is this a `..` pattern?
633 pub fn is_rest(&self) -> bool {
634 matches!(self.kind, PatKind::Rest)
638 /// A single field in a struct pattern.
640 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
641 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
642 /// except when `is_shorthand` is true.
643 #[derive(Clone, Encodable, Decodable, Debug)]
644 pub struct PatField {
645 /// The identifier for the field.
647 /// The pattern the field is destructured to.
649 pub is_shorthand: bool,
653 pub is_placeholder: bool,
656 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
657 #[derive(Encodable, Decodable, HashStable_Generic)]
663 impl From<bool> for ByRef {
664 fn from(b: bool) -> ByRef {
672 /// Explicit binding annotations given in the HIR for a binding. Note
673 /// that this is not the final binding *mode* that we infer after type
675 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
676 #[derive(Encodable, Decodable, HashStable_Generic)]
677 pub struct BindingAnnotation(pub ByRef, pub Mutability);
679 impl BindingAnnotation {
680 pub const NONE: Self = Self(ByRef::No, Mutability::Not);
681 pub const REF: Self = Self(ByRef::Yes, Mutability::Not);
682 pub const MUT: Self = Self(ByRef::No, Mutability::Mut);
683 pub const REF_MUT: Self = Self(ByRef::Yes, Mutability::Mut);
685 pub fn prefix_str(self) -> &'static str {
690 Self::REF_MUT => "ref mut ",
695 #[derive(Clone, Encodable, Decodable, Debug)]
698 Included(RangeSyntax),
703 #[derive(Clone, Encodable, Decodable, Debug)]
704 pub enum RangeSyntax {
711 /// All the different flavors of pattern that Rust recognizes.
712 #[derive(Clone, Encodable, Decodable, Debug)]
714 /// Represents a wildcard pattern (`_`).
717 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
718 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
719 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
720 /// during name resolution.
721 Ident(BindingAnnotation, Ident, Option<P<Pat>>),
723 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
724 /// The `bool` is `true` in the presence of a `..`.
725 Struct(Option<P<QSelf>>, Path, Vec<PatField>, /* recovered */ bool),
727 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
728 TupleStruct(Option<P<QSelf>>, Path, Vec<P<Pat>>),
730 /// An or-pattern `A | B | C`.
731 /// Invariant: `pats.len() >= 2`.
734 /// A possibly qualified path pattern.
735 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
736 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
737 /// only legally refer to associated constants.
738 Path(Option<P<QSelf>>, Path),
740 /// A tuple pattern (`(a, b)`).
746 /// A reference pattern (e.g., `&mut (a, b)`).
747 Ref(P<Pat>, Mutability),
752 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
753 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
755 /// A slice pattern `[a, b, c]`.
758 /// A rest pattern `..`.
760 /// Syntactically it is valid anywhere.
762 /// Semantically however, it only has meaning immediately inside:
763 /// - a slice pattern: `[a, .., b]`,
764 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
765 /// - a tuple pattern: `(a, .., b)`,
766 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
768 /// In all of these cases, an additional restriction applies,
769 /// only one rest pattern may occur in the pattern sequences.
772 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
775 /// A macro pattern; pre-expansion.
779 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
780 #[derive(HashStable_Generic, Encodable, Decodable)]
781 pub enum Mutability {
782 // N.B. Order is deliberate, so that Not < Mut
788 pub fn invert(self) -> Self {
790 Mutability::Mut => Mutability::Not,
791 Mutability::Not => Mutability::Mut,
795 /// Returns `""` (empty string) or `"mut "` depending on the mutability.
796 pub fn prefix_str(self) -> &'static str {
798 Mutability::Mut => "mut ",
799 Mutability::Not => "",
803 /// Returns `"&"` or `"&mut "` depending on the mutability.
804 pub fn ref_prefix_str(self) -> &'static str {
806 Mutability::Not => "&",
807 Mutability::Mut => "&mut ",
811 /// Returns `""` (empty string) or `"mutably "` depending on the mutability.
812 pub fn mutably_str(self) -> &'static str {
814 Mutability::Not => "",
815 Mutability::Mut => "mutably ",
819 /// Return `true` if self is mutable
820 pub fn is_mut(self) -> bool {
821 matches!(self, Self::Mut)
824 /// Return `true` if self is **not** mutable
825 pub fn is_not(self) -> bool {
826 matches!(self, Self::Not)
830 /// The kind of borrow in an `AddrOf` expression,
831 /// e.g., `&place` or `&raw const place`.
832 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
833 #[derive(Encodable, Decodable, HashStable_Generic)]
834 pub enum BorrowKind {
835 /// A normal borrow, `&$expr` or `&mut $expr`.
836 /// The resulting type is either `&'a T` or `&'a mut T`
837 /// where `T = typeof($expr)` and `'a` is some lifetime.
839 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
840 /// The resulting type is either `*const T` or `*mut T`
841 /// where `T = typeof($expr)`.
845 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
847 /// The `+` operator (addition)
849 /// The `-` operator (subtraction)
851 /// The `*` operator (multiplication)
853 /// The `/` operator (division)
855 /// The `%` operator (modulus)
857 /// The `&&` operator (logical and)
859 /// The `||` operator (logical or)
861 /// The `^` operator (bitwise xor)
863 /// The `&` operator (bitwise and)
865 /// The `|` operator (bitwise or)
867 /// The `<<` operator (shift left)
869 /// The `>>` operator (shift right)
871 /// The `==` operator (equality)
873 /// The `<` operator (less than)
875 /// The `<=` operator (less than or equal to)
877 /// The `!=` operator (not equal to)
879 /// The `>=` operator (greater than or equal to)
881 /// The `>` operator (greater than)
886 pub fn to_string(&self) -> &'static str {
909 pub fn lazy(&self) -> bool {
910 matches!(self, BinOpKind::And | BinOpKind::Or)
913 pub fn is_comparison(&self) -> bool {
915 // Note for developers: please keep this as is;
916 // we want compilation to fail if another variant is added.
918 Eq | Lt | Le | Ne | Gt | Ge => true,
919 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
924 pub type BinOp = Spanned<BinOpKind>;
928 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
929 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
931 /// The `*` operator for dereferencing
933 /// The `!` operator for logical inversion
935 /// The `-` operator for negation
940 pub fn to_string(op: UnOp) -> &'static str {
950 #[derive(Clone, Encodable, Decodable, Debug)]
958 pub fn has_trailing_semicolon(&self) -> bool {
960 StmtKind::Semi(_) => true,
961 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
966 /// Converts a parsed `Stmt` to a `Stmt` with
967 /// a trailing semicolon.
969 /// This only modifies the parsed AST struct, not the attached
970 /// `LazyAttrTokenStream`. The parser is responsible for calling
971 /// `ToAttrTokenStream::add_trailing_semi` when there is actually
972 /// a semicolon in the tokenstream.
973 pub fn add_trailing_semicolon(mut self) -> Self {
974 self.kind = match self.kind {
975 StmtKind::Expr(expr) => StmtKind::Semi(expr),
976 StmtKind::MacCall(mac) => {
977 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
978 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
987 pub fn is_item(&self) -> bool {
988 matches!(self.kind, StmtKind::Item(_))
991 pub fn is_expr(&self) -> bool {
992 matches!(self.kind, StmtKind::Expr(_))
996 #[derive(Clone, Encodable, Decodable, Debug)]
998 /// A local (let) binding.
1000 /// An item definition.
1002 /// Expr without trailing semi-colon.
1004 /// Expr with a trailing semi-colon.
1006 /// Just a trailing semi-colon.
1009 MacCall(P<MacCallStmt>),
1012 #[derive(Clone, Encodable, Decodable, Debug)]
1013 pub struct MacCallStmt {
1014 pub mac: P<MacCall>,
1015 pub style: MacStmtStyle,
1017 pub tokens: Option<LazyAttrTokenStream>,
1020 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1021 pub enum MacStmtStyle {
1022 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1023 /// `foo!(...);`, `foo![...];`).
1025 /// The macro statement had braces (e.g., `foo! { ... }`).
1027 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1028 /// `foo!(...)`). All of these will end up being converted into macro
1033 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1034 #[derive(Clone, Encodable, Decodable, Debug)]
1038 pub ty: Option<P<Ty>>,
1039 pub kind: LocalKind,
1042 pub tokens: Option<LazyAttrTokenStream>,
1045 #[derive(Clone, Encodable, Decodable, Debug)]
1046 pub enum LocalKind {
1047 /// Local declaration.
1048 /// Example: `let x;`
1050 /// Local declaration with an initializer.
1051 /// Example: `let x = y;`
1053 /// Local declaration with an initializer and an `else` clause.
1054 /// Example: `let Some(x) = y else { return };`
1055 InitElse(P<Expr>, P<Block>),
1059 pub fn init(&self) -> Option<&Expr> {
1062 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1066 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1069 Self::Init(init) => Some((init, None)),
1070 Self::InitElse(init, els) => Some((init, Some(els))),
1075 /// An arm of a 'match'.
1077 /// E.g., `0..=10 => { println!("match!") }` as in
1081 /// 0..=10 => { println!("match!") },
1082 /// _ => { println!("no match!") },
1085 #[derive(Clone, Encodable, Decodable, Debug)]
1088 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1090 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1091 pub guard: Option<P<Expr>>,
1096 pub is_placeholder: bool,
1099 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1100 #[derive(Clone, Encodable, Decodable, Debug)]
1101 pub struct ExprField {
1107 pub is_shorthand: bool,
1108 pub is_placeholder: bool,
1111 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1112 pub enum BlockCheckMode {
1114 Unsafe(UnsafeSource),
1117 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1118 pub enum UnsafeSource {
1123 /// A constant (expression) that's not an item or associated item,
1124 /// but needs its own `DefId` for type-checking, const-eval, etc.
1125 /// These are usually found nested inside types (e.g., array lengths)
1126 /// or expressions (e.g., repeat counts), and also used to define
1127 /// explicit discriminant values for enum variants.
1128 #[derive(Clone, Encodable, Decodable, Debug)]
1129 pub struct AnonConst {
1135 #[derive(Clone, Encodable, Decodable, Debug)]
1141 pub tokens: Option<LazyAttrTokenStream>,
1145 /// Is this expr either `N`, or `{ N }`.
1147 /// If this is not the case, name resolution does not resolve `N` when using
1148 /// `min_const_generics` as more complex expressions are not supported.
1149 pub fn is_potential_trivial_const_param(&self) -> bool {
1150 let this = if let ExprKind::Block(block, None) = &self.kind
1151 && block.stmts.len() == 1
1152 && let StmtKind::Expr(expr) = &block.stmts[0].kind
1159 if let ExprKind::Path(None, path) = &this.kind
1160 && path.segments.len() == 1
1161 && path.segments[0].args.is_none()
1169 pub fn to_bound(&self) -> Option<GenericBound> {
1171 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1172 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1173 TraitBoundModifier::None,
1179 pub fn peel_parens(&self) -> &Expr {
1180 let mut expr = self;
1181 while let ExprKind::Paren(inner) = &expr.kind {
1187 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1188 pub fn to_ty(&self) -> Option<P<Ty>> {
1189 let kind = match &self.kind {
1190 // Trivial conversions.
1191 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1192 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1194 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1196 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1197 expr.to_ty().map(|ty| TyKind::Ref(None, MutTy { ty, mutbl: *mutbl }))?
1200 ExprKind::Repeat(expr, expr_len) => {
1201 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1204 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1206 ExprKind::Tup(exprs) => {
1207 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1211 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1212 // then type of result is trait object.
1213 // Otherwise we don't assume the result type.
1214 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1215 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1216 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1222 ExprKind::Underscore => TyKind::Infer,
1224 // This expression doesn't look like a type syntactically.
1228 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1231 pub fn precedence(&self) -> ExprPrecedence {
1233 ExprKind::Box(_) => ExprPrecedence::Box,
1234 ExprKind::Array(_) => ExprPrecedence::Array,
1235 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1236 ExprKind::Call(..) => ExprPrecedence::Call,
1237 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1238 ExprKind::Tup(_) => ExprPrecedence::Tup,
1239 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1240 ExprKind::Unary(..) => ExprPrecedence::Unary,
1241 ExprKind::Lit(_) | ExprKind::IncludedBytes(..) => ExprPrecedence::Lit,
1242 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1243 ExprKind::Let(..) => ExprPrecedence::Let,
1244 ExprKind::If(..) => ExprPrecedence::If,
1245 ExprKind::While(..) => ExprPrecedence::While,
1246 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1247 ExprKind::Loop(..) => ExprPrecedence::Loop,
1248 ExprKind::Match(..) => ExprPrecedence::Match,
1249 ExprKind::Closure(..) => ExprPrecedence::Closure,
1250 ExprKind::Block(..) => ExprPrecedence::Block,
1251 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1252 ExprKind::Async(..) => ExprPrecedence::Async,
1253 ExprKind::Await(..) => ExprPrecedence::Await,
1254 ExprKind::Assign(..) => ExprPrecedence::Assign,
1255 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1256 ExprKind::Field(..) => ExprPrecedence::Field,
1257 ExprKind::Index(..) => ExprPrecedence::Index,
1258 ExprKind::Range(..) => ExprPrecedence::Range,
1259 ExprKind::Underscore => ExprPrecedence::Path,
1260 ExprKind::Path(..) => ExprPrecedence::Path,
1261 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1262 ExprKind::Break(..) => ExprPrecedence::Break,
1263 ExprKind::Continue(..) => ExprPrecedence::Continue,
1264 ExprKind::Ret(..) => ExprPrecedence::Ret,
1265 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1266 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1267 ExprKind::Struct(..) => ExprPrecedence::Struct,
1268 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1269 ExprKind::Paren(..) => ExprPrecedence::Paren,
1270 ExprKind::Try(..) => ExprPrecedence::Try,
1271 ExprKind::Yield(..) => ExprPrecedence::Yield,
1272 ExprKind::Yeet(..) => ExprPrecedence::Yeet,
1273 ExprKind::FormatArgs(..) => ExprPrecedence::FormatArgs,
1274 ExprKind::Err => ExprPrecedence::Err,
1278 pub fn take(&mut self) -> Self {
1283 kind: ExprKind::Err,
1285 attrs: AttrVec::new(),
1291 /// To a first-order approximation, is this a pattern?
1292 pub fn is_approximately_pattern(&self) -> bool {
1293 match &self.peel_parens().kind {
1295 | ExprKind::Array(_)
1296 | ExprKind::Call(_, _)
1299 | ExprKind::Range(_, _, _)
1300 | ExprKind::Underscore
1301 | ExprKind::Path(_, _)
1302 | ExprKind::Struct(_) => true,
1308 #[derive(Clone, Encodable, Decodable, Debug)]
1309 pub struct Closure {
1310 pub binder: ClosureBinder,
1311 pub capture_clause: CaptureBy,
1312 pub constness: Const,
1313 pub asyncness: Async,
1314 pub movability: Movability,
1315 pub fn_decl: P<FnDecl>,
1317 /// The span of the declaration block: 'move |...| -> ...'
1318 pub fn_decl_span: Span,
1319 /// The span of the argument block `|...|`
1320 pub fn_arg_span: Span,
1323 /// Limit types of a range (inclusive or exclusive)
1324 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1325 pub enum RangeLimits {
1326 /// Inclusive at the beginning, exclusive at the end
1328 /// Inclusive at the beginning and end
1332 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1333 #[derive(Clone, Encodable, Decodable, Debug)]
1334 pub struct MethodCall {
1335 /// The method name and its generic arguments, e.g. `foo::<Bar, Baz>`.
1336 pub seg: PathSegment,
1337 /// The receiver, e.g. `x`.
1338 pub receiver: P<Expr>,
1339 /// The arguments, e.g. `a, b, c`.
1340 pub args: Vec<P<Expr>>,
1341 /// The span of the function, without the dot and receiver e.g. `foo::<Bar,
1346 #[derive(Clone, Encodable, Decodable, Debug)]
1347 pub enum StructRest {
1352 /// No trailing `..` or expression.
1356 #[derive(Clone, Encodable, Decodable, Debug)]
1357 pub struct StructExpr {
1358 pub qself: Option<P<QSelf>>,
1360 pub fields: Vec<ExprField>,
1361 pub rest: StructRest,
1364 #[derive(Clone, Encodable, Decodable, Debug)]
1366 /// A `box x` expression.
1368 /// An array (`[a, b, c, d]`)
1369 Array(Vec<P<Expr>>),
1370 /// Allow anonymous constants from an inline `const` block
1371 ConstBlock(AnonConst),
1374 /// The first field resolves to the function itself,
1375 /// and the second field is the list of arguments.
1376 /// This also represents calling the constructor of
1377 /// tuple-like ADTs such as tuple structs and enum variants.
1378 Call(P<Expr>, Vec<P<Expr>>),
1379 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1380 MethodCall(Box<MethodCall>),
1381 /// A tuple (e.g., `(a, b, c, d)`).
1383 /// A binary operation (e.g., `a + b`, `a * b`).
1384 Binary(BinOp, P<Expr>, P<Expr>),
1385 /// A unary operation (e.g., `!x`, `*x`).
1386 Unary(UnOp, P<Expr>),
1387 /// A literal (e.g., `1`, `"foo"`).
1389 /// A cast (e.g., `foo as f64`).
1390 Cast(P<Expr>, P<Ty>),
1391 /// A type ascription (e.g., `42: usize`).
1392 Type(P<Expr>, P<Ty>),
1393 /// A `let pat = expr` expression that is only semantically allowed in the condition
1394 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1396 /// `Span` represents the whole `let pat = expr` statement.
1397 Let(P<Pat>, P<Expr>, Span),
1398 /// An `if` block, with an optional `else` block.
1400 /// `if expr { block } else { expr }`
1401 If(P<Expr>, P<Block>, Option<P<Expr>>),
1402 /// A while loop, with an optional label.
1404 /// `'label: while expr { block }`
1405 While(P<Expr>, P<Block>, Option<Label>),
1406 /// A `for` loop, with an optional label.
1408 /// `'label: for pat in expr { block }`
1410 /// This is desugared to a combination of `loop` and `match` expressions.
1411 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1412 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1414 /// `'label: loop { block }`
1415 Loop(P<Block>, Option<Label>, Span),
1416 /// A `match` block.
1417 Match(P<Expr>, Vec<Arm>),
1418 /// A closure (e.g., `move |a, b, c| a + b + c`).
1419 Closure(Box<Closure>),
1420 /// A block (`'label: { ... }`).
1421 Block(P<Block>, Option<Label>),
1422 /// An async block (`async move { ... }`).
1424 /// The `NodeId` is the `NodeId` for the closure that results from
1425 /// desugaring an async block, just like the NodeId field in the
1426 /// `Async::Yes` variant. This is necessary in order to create a def for the
1427 /// closure which can be used as a parent of any child defs. Defs
1428 /// created during lowering cannot be made the parent of any other
1429 /// preexisting defs.
1430 Async(CaptureBy, NodeId, P<Block>),
1431 /// An await expression (`my_future.await`).
1434 /// A try block (`try { ... }`).
1437 /// An assignment (`a = foo()`).
1438 /// The `Span` argument is the span of the `=` token.
1439 Assign(P<Expr>, P<Expr>, Span),
1440 /// An assignment with an operator.
1443 AssignOp(BinOp, P<Expr>, P<Expr>),
1444 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1445 Field(P<Expr>, Ident),
1446 /// An indexing operation (e.g., `foo[2]`).
1447 Index(P<Expr>, P<Expr>),
1448 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1449 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1450 /// An underscore, used in destructuring assignment to ignore a value.
1453 /// Variable reference, possibly containing `::` and/or type
1454 /// parameters (e.g., `foo::bar::<baz>`).
1456 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1457 Path(Option<P<QSelf>>, Path),
1459 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1460 AddrOf(BorrowKind, Mutability, P<Expr>),
1461 /// A `break`, with an optional label to break, and an optional expression.
1462 Break(Option<Label>, Option<P<Expr>>),
1463 /// A `continue`, with an optional label.
1464 Continue(Option<Label>),
1465 /// A `return`, with an optional value to be returned.
1466 Ret(Option<P<Expr>>),
1468 /// Output of the `asm!()` macro.
1469 InlineAsm(P<InlineAsm>),
1471 /// A macro invocation; pre-expansion.
1472 MacCall(P<MacCall>),
1474 /// A struct literal expression.
1476 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1477 Struct(P<StructExpr>),
1479 /// An array literal constructed from one repeated element.
1481 /// E.g., `[1; 5]`. The expression is the element to be
1482 /// repeated; the constant is the number of times to repeat it.
1483 Repeat(P<Expr>, AnonConst),
1485 /// No-op: used solely so we can pretty-print faithfully.
1488 /// A try expression (`expr?`).
1491 /// A `yield`, with an optional value to be yielded.
1492 Yield(Option<P<Expr>>),
1494 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1495 /// with an optional value to be returned.
1496 Yeet(Option<P<Expr>>),
1498 /// Bytes included via `include_bytes!`
1499 /// Added for optimization purposes to avoid the need to escape
1500 /// large binary blobs - should always behave like [`ExprKind::Lit`]
1501 /// with a `ByteStr` literal.
1502 IncludedBytes(Lrc<[u8]>),
1504 /// A `format_args!()` expression.
1505 FormatArgs(P<FormatArgs>),
1507 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1511 /// The explicit `Self` type in a "qualified path". The actual
1512 /// path, including the trait and the associated item, is stored
1513 /// separately. `position` represents the index of the associated
1514 /// item qualified with this `Self` type.
1516 /// ```ignore (only-for-syntax-highlight)
1517 /// <Vec<T> as a::b::Trait>::AssociatedItem
1518 /// ^~~~~ ~~~~~~~~~~~~~~^
1521 /// <Vec<T>>::AssociatedItem
1525 #[derive(Clone, Encodable, Decodable, Debug)]
1529 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1530 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1531 /// 0`, this is an empty span.
1532 pub path_span: Span,
1533 pub position: usize,
1536 /// A capture clause used in closures and `async` blocks.
1537 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1538 pub enum CaptureBy {
1539 /// `move |x| y + x`.
1541 /// `move` keyword was not specified.
1545 /// The movability of a generator / closure literal:
1546 /// whether a generator contains self-references, causing it to be `!Unpin`.
1547 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1548 #[derive(HashStable_Generic)]
1549 pub enum Movability {
1550 /// May contain self-references, `!Unpin`.
1552 /// Must not contain self-references, `Unpin`.
1556 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1557 #[derive(Clone, Encodable, Decodable, Debug)]
1558 pub enum ClosureBinder {
1559 /// The binder is not present, all closure lifetimes are inferred.
1561 /// The binder is present.
1563 /// Span of the whole `for<>` clause
1566 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1567 /// ^^^^^^^^^^^ -- this
1571 /// Lifetimes in the `for<>` closure
1574 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1577 generic_params: P<[GenericParam]>,
1581 /// Represents a macro invocation. The `path` indicates which macro
1582 /// is being invoked, and the `args` are arguments passed to it.
1583 #[derive(Clone, Encodable, Decodable, Debug)]
1584 pub struct MacCall {
1586 pub args: P<DelimArgs>,
1587 pub prior_type_ascription: Option<(Span, bool)>,
1591 pub fn span(&self) -> Span {
1592 self.path.span.to(self.args.dspan.entire())
1596 /// Arguments passed to an attribute macro.
1597 #[derive(Clone, Encodable, Decodable, Debug)]
1599 /// No arguments: `#[attr]`.
1601 /// Delimited arguments: `#[attr()/[]/{}]`.
1602 Delimited(DelimArgs),
1603 /// Arguments of a key-value attribute: `#[attr = "value"]`.
1605 /// Span of the `=` token.
1612 // The RHS of an `AttrArgs::Eq` starts out as an expression. Once macro
1613 // expansion is completed, all cases end up either as a meta item literal,
1614 // which is the form used after lowering to HIR, or as an error.
1615 #[derive(Clone, Encodable, Decodable, Debug)]
1616 pub enum AttrArgsEq {
1622 pub fn span(&self) -> Option<Span> {
1624 AttrArgs::Empty => None,
1625 AttrArgs::Delimited(args) => Some(args.dspan.entire()),
1626 AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1627 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
1628 unreachable!("in literal form when getting span: {:?}", lit);
1633 /// Tokens inside the delimiters or after `=`.
1634 /// Proc macros see these tokens, for example.
1635 pub fn inner_tokens(&self) -> TokenStream {
1637 AttrArgs::Empty => TokenStream::default(),
1638 AttrArgs::Delimited(args) => args.tokens.clone(),
1639 AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => TokenStream::from_ast(expr),
1640 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
1641 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1647 impl<CTX> HashStable<CTX> for AttrArgs
1649 CTX: crate::HashStableContext,
1651 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1652 mem::discriminant(self).hash_stable(ctx, hasher);
1654 AttrArgs::Empty => {}
1655 AttrArgs::Delimited(args) => args.hash_stable(ctx, hasher),
1656 AttrArgs::Eq(_eq_span, AttrArgsEq::Ast(expr)) => {
1657 unreachable!("hash_stable {:?}", expr);
1659 AttrArgs::Eq(eq_span, AttrArgsEq::Hir(lit)) => {
1660 eq_span.hash_stable(ctx, hasher);
1661 lit.hash_stable(ctx, hasher);
1667 /// Delimited arguments, as used in `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1668 #[derive(Clone, Encodable, Decodable, Debug)]
1669 pub struct DelimArgs {
1670 pub dspan: DelimSpan,
1671 pub delim: MacDelimiter,
1672 pub tokens: TokenStream,
1676 /// Whether a macro with these arguments needs a semicolon
1677 /// when used as a standalone item or statement.
1678 pub fn need_semicolon(&self) -> bool {
1679 !matches!(self, DelimArgs { delim: MacDelimiter::Brace, .. })
1683 impl<CTX> HashStable<CTX> for DelimArgs
1685 CTX: crate::HashStableContext,
1687 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1688 let DelimArgs { dspan, delim, tokens } = self;
1689 dspan.hash_stable(ctx, hasher);
1690 delim.hash_stable(ctx, hasher);
1691 tokens.hash_stable(ctx, hasher);
1695 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1696 pub enum MacDelimiter {
1703 pub fn to_token(self) -> Delimiter {
1705 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1706 MacDelimiter::Bracket => Delimiter::Bracket,
1707 MacDelimiter::Brace => Delimiter::Brace,
1711 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1713 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1714 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1715 Delimiter::Brace => Some(MacDelimiter::Brace),
1716 Delimiter::Invisible => None,
1721 /// Represents a macro definition.
1722 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1723 pub struct MacroDef {
1724 pub body: P<DelimArgs>,
1725 /// `true` if macro was defined with `macro_rules`.
1726 pub macro_rules: bool,
1729 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1730 #[derive(HashStable_Generic)]
1732 /// A regular string, like `"foo"`.
1734 /// A raw string, like `r##"foo"##`.
1736 /// The value is the number of `#` symbols used.
1740 /// A literal in a meta item.
1741 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1742 pub struct MetaItemLit {
1743 /// The original literal as written in the source code.
1745 /// The original suffix as written in the source code.
1746 pub suffix: Option<Symbol>,
1747 /// The "semantic" representation of the literal lowered from the original tokens.
1748 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1753 /// Similar to `MetaItemLit`, but restricted to string literals.
1754 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1756 /// The original literal as written in source code.
1758 /// The original suffix as written in source code.
1759 pub suffix: Option<Symbol>,
1760 /// The semantic (unescaped) representation of the literal.
1761 pub symbol_unescaped: Symbol,
1762 pub style: StrStyle,
1767 pub fn as_token_lit(&self) -> token::Lit {
1768 let token_kind = match self.style {
1769 StrStyle::Cooked => token::Str,
1770 StrStyle::Raw(n) => token::StrRaw(n),
1772 token::Lit::new(token_kind, self.symbol, self.suffix)
1776 /// Type of the integer literal based on provided suffix.
1777 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1778 #[derive(HashStable_Generic)]
1779 pub enum LitIntType {
1788 /// Type of the float literal based on provided suffix.
1789 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1790 #[derive(HashStable_Generic)]
1791 pub enum LitFloatType {
1792 /// A float literal with a suffix (`1f32` or `1E10f32`).
1794 /// A float literal without a suffix (`1.0 or 1.0E10`).
1798 /// This type is used within both `ast::MetaItemLit` and `hir::Lit`.
1800 /// Note that the entire literal (including the suffix) is considered when
1801 /// deciding the `LitKind`. This means that float literals like `1f32` are
1802 /// classified by this type as `Float`. This is different to `token::LitKind`
1803 /// which does *not* consider the suffix.
1804 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1806 /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
1807 /// from the original token's symbol.
1808 Str(Symbol, StrStyle),
1809 /// A byte string (`b"foo"`). Not stored as a symbol because it might be
1810 /// non-utf8, and symbols only allow utf8 strings.
1811 ByteStr(Lrc<[u8]>, StrStyle),
1812 /// A byte char (`b'f'`).
1814 /// A character literal (`'a'`).
1816 /// An integer literal (`1`).
1817 Int(u128, LitIntType),
1818 /// A float literal (`1.0`, `1f64` or `1E10f64`). The pre-suffix part is
1819 /// stored as a symbol rather than `f64` so that `LitKind` can impl `Eq`
1821 Float(Symbol, LitFloatType),
1822 /// A boolean literal (`true`, `false`).
1824 /// Placeholder for a literal that wasn't well-formed in some way.
1829 pub fn str(&self) -> Option<Symbol> {
1831 LitKind::Str(s, _) => Some(s),
1836 /// Returns `true` if this literal is a string.
1837 pub fn is_str(&self) -> bool {
1838 matches!(self, LitKind::Str(..))
1841 /// Returns `true` if this literal is byte literal string.
1842 pub fn is_bytestr(&self) -> bool {
1843 matches!(self, LitKind::ByteStr(..))
1846 /// Returns `true` if this is a numeric literal.
1847 pub fn is_numeric(&self) -> bool {
1848 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1851 /// Returns `true` if this literal has no suffix.
1852 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1853 pub fn is_unsuffixed(&self) -> bool {
1857 /// Returns `true` if this literal has a suffix.
1858 pub fn is_suffixed(&self) -> bool {
1860 // suffixed variants
1861 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1862 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1863 // unsuffixed variants
1865 | LitKind::ByteStr(..)
1868 | LitKind::Int(_, LitIntType::Unsuffixed)
1869 | LitKind::Float(_, LitFloatType::Unsuffixed)
1871 | LitKind::Err => false,
1876 // N.B., If you change this, you'll probably want to change the corresponding
1877 // type structure in `middle/ty.rs` as well.
1878 #[derive(Clone, Encodable, Decodable, Debug)]
1881 pub mutbl: Mutability,
1884 /// Represents a function's signature in a trait declaration,
1885 /// trait implementation, or free function.
1886 #[derive(Clone, Encodable, Decodable, Debug)]
1888 pub header: FnHeader,
1889 pub decl: P<FnDecl>,
1893 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1894 #[derive(Encodable, Decodable, HashStable_Generic)]
1901 pub fn name_str(self) -> &'static str {
1903 FloatTy::F32 => "f32",
1904 FloatTy::F64 => "f64",
1908 pub fn name(self) -> Symbol {
1910 FloatTy::F32 => sym::f32,
1911 FloatTy::F64 => sym::f64,
1916 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1917 #[derive(Encodable, Decodable, HashStable_Generic)]
1928 pub fn name_str(&self) -> &'static str {
1930 IntTy::Isize => "isize",
1932 IntTy::I16 => "i16",
1933 IntTy::I32 => "i32",
1934 IntTy::I64 => "i64",
1935 IntTy::I128 => "i128",
1939 pub fn name(&self) -> Symbol {
1941 IntTy::Isize => sym::isize,
1942 IntTy::I8 => sym::i8,
1943 IntTy::I16 => sym::i16,
1944 IntTy::I32 => sym::i32,
1945 IntTy::I64 => sym::i64,
1946 IntTy::I128 => sym::i128,
1951 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1952 #[derive(Encodable, Decodable, HashStable_Generic)]
1963 pub fn name_str(&self) -> &'static str {
1965 UintTy::Usize => "usize",
1967 UintTy::U16 => "u16",
1968 UintTy::U32 => "u32",
1969 UintTy::U64 => "u64",
1970 UintTy::U128 => "u128",
1974 pub fn name(&self) -> Symbol {
1976 UintTy::Usize => sym::usize,
1977 UintTy::U8 => sym::u8,
1978 UintTy::U16 => sym::u16,
1979 UintTy::U32 => sym::u32,
1980 UintTy::U64 => sym::u64,
1981 UintTy::U128 => sym::u128,
1986 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1987 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1988 #[derive(Clone, Encodable, Decodable, Debug)]
1989 pub struct AssocConstraint {
1992 pub gen_args: Option<GenericArgs>,
1993 pub kind: AssocConstraintKind,
1997 /// The kinds of an `AssocConstraint`.
1998 #[derive(Clone, Encodable, Decodable, Debug)]
2004 impl From<P<Ty>> for Term {
2005 fn from(v: P<Ty>) -> Self {
2010 impl From<AnonConst> for Term {
2011 fn from(v: AnonConst) -> Self {
2016 /// The kinds of an `AssocConstraint`.
2017 #[derive(Clone, Encodable, Decodable, Debug)]
2018 pub enum AssocConstraintKind {
2019 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
2020 Equality { term: Term },
2021 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
2022 Bound { bounds: GenericBounds },
2025 #[derive(Encodable, Decodable, Debug)]
2030 pub tokens: Option<LazyAttrTokenStream>,
2034 fn clone(&self) -> Self {
2035 ensure_sufficient_stack(|| Self {
2037 kind: self.kind.clone(),
2039 tokens: self.tokens.clone(),
2045 pub fn peel_refs(&self) -> &Self {
2046 let mut final_ty = self;
2047 while let TyKind::Ref(_, MutTy { ty, .. }) | TyKind::Ptr(MutTy { ty, .. }) = &final_ty.kind
2055 #[derive(Clone, Encodable, Decodable, Debug)]
2056 pub struct BareFnTy {
2057 pub unsafety: Unsafe,
2059 pub generic_params: Vec<GenericParam>,
2060 pub decl: P<FnDecl>,
2061 /// Span of the `fn(...) -> ...` part.
2062 pub decl_span: Span,
2065 /// The various kinds of type recognized by the compiler.
2066 #[derive(Clone, Encodable, Decodable, Debug)]
2068 /// A variable-length slice (`[T]`).
2070 /// A fixed length array (`[T; n]`).
2071 Array(P<Ty>, AnonConst),
2072 /// A raw pointer (`*const T` or `*mut T`).
2074 /// A reference (`&'a T` or `&'a mut T`).
2075 Ref(Option<Lifetime>, MutTy),
2076 /// A bare function (e.g., `fn(usize) -> bool`).
2077 BareFn(P<BareFnTy>),
2078 /// The never type (`!`).
2080 /// A tuple (`(A, B, C, D,...)`).
2082 /// A path (`module::module::...::Type`), optionally
2083 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2085 /// Type parameters are stored in the `Path` itself.
2086 Path(Option<P<QSelf>>, Path),
2087 /// A trait object type `Bound1 + Bound2 + Bound3`
2088 /// where `Bound` is a trait or a lifetime.
2089 TraitObject(GenericBounds, TraitObjectSyntax),
2090 /// An `impl Bound1 + Bound2 + Bound3` type
2091 /// where `Bound` is a trait or a lifetime.
2093 /// The `NodeId` exists to prevent lowering from having to
2094 /// generate `NodeId`s on the fly, which would complicate
2095 /// the generation of opaque `type Foo = impl Trait` items significantly.
2096 ImplTrait(NodeId, GenericBounds),
2097 /// No-op; kept solely so that we can pretty-print faithfully.
2101 /// This means the type should be inferred instead of it having been
2102 /// specified. This can appear anywhere in a type.
2104 /// Inferred type of a `self` or `&self` argument in a method.
2106 /// A macro in the type position.
2107 MacCall(P<MacCall>),
2108 /// Placeholder for a kind that has failed to be defined.
2110 /// Placeholder for a `va_list`.
2115 pub fn is_implicit_self(&self) -> bool {
2116 matches!(self, TyKind::ImplicitSelf)
2119 pub fn is_unit(&self) -> bool {
2120 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2123 pub fn is_simple_path(&self) -> Option<Symbol> {
2124 if let TyKind::Path(None, Path { segments, .. }) = &self
2125 && let [segment] = &segments[..]
2126 && segment.args.is_none()
2128 Some(segment.ident.name)
2135 /// Syntax used to declare a trait object.
2136 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2137 pub enum TraitObjectSyntax {
2143 /// Inline assembly operand explicit register or register class.
2145 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2146 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2147 pub enum InlineAsmRegOrRegClass {
2152 bitflags::bitflags! {
2153 #[derive(Encodable, Decodable, HashStable_Generic)]
2154 pub struct InlineAsmOptions: u16 {
2155 const PURE = 1 << 0;
2156 const NOMEM = 1 << 1;
2157 const READONLY = 1 << 2;
2158 const PRESERVES_FLAGS = 1 << 3;
2159 const NORETURN = 1 << 4;
2160 const NOSTACK = 1 << 5;
2161 const ATT_SYNTAX = 1 << 6;
2163 const MAY_UNWIND = 1 << 8;
2167 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2168 pub enum InlineAsmTemplatePiece {
2170 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2173 impl fmt::Display for InlineAsmTemplatePiece {
2174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2176 Self::String(s) => {
2177 for c in s.chars() {
2179 '{' => f.write_str("{{")?,
2180 '}' => f.write_str("}}")?,
2186 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2187 write!(f, "{{{operand_idx}:{modifier}}}")
2189 Self::Placeholder { operand_idx, modifier: None, .. } => {
2190 write!(f, "{{{operand_idx}}}")
2196 impl InlineAsmTemplatePiece {
2197 /// Rebuilds the asm template string from its pieces.
2198 pub fn to_string(s: &[Self]) -> String {
2200 let mut out = String::new();
2202 let _ = write!(out, "{p}");
2208 /// Inline assembly symbol operands get their own AST node that is somewhat
2209 /// similar to `AnonConst`.
2211 /// The main difference is that we specifically don't assign it `DefId` in
2212 /// `DefCollector`. Instead this is deferred until AST lowering where we
2213 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2214 /// depending on what the path resolves to.
2215 #[derive(Clone, Encodable, Decodable, Debug)]
2216 pub struct InlineAsmSym {
2218 pub qself: Option<P<QSelf>>,
2222 /// Inline assembly operand.
2224 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2225 #[derive(Clone, Encodable, Decodable, Debug)]
2226 pub enum InlineAsmOperand {
2228 reg: InlineAsmRegOrRegClass,
2232 reg: InlineAsmRegOrRegClass,
2234 expr: Option<P<Expr>>,
2237 reg: InlineAsmRegOrRegClass,
2242 reg: InlineAsmRegOrRegClass,
2245 out_expr: Option<P<Expr>>,
2248 anon_const: AnonConst,
2255 /// Inline assembly.
2257 /// E.g., `asm!("NOP");`.
2258 #[derive(Clone, Encodable, Decodable, Debug)]
2259 pub struct InlineAsm {
2260 pub template: Vec<InlineAsmTemplatePiece>,
2261 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2262 pub operands: Vec<(InlineAsmOperand, Span)>,
2263 pub clobber_abis: Vec<(Symbol, Span)>,
2264 pub options: InlineAsmOptions,
2265 pub line_spans: Vec<Span>,
2268 /// A parameter in a function header.
2270 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2271 #[derive(Clone, Encodable, Decodable, Debug)]
2278 pub is_placeholder: bool,
2281 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2283 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2284 #[derive(Clone, Encodable, Decodable, Debug)]
2286 /// `self`, `mut self`
2288 /// `&'lt self`, `&'lt mut self`
2289 Region(Option<Lifetime>, Mutability),
2290 /// `self: TYPE`, `mut self: TYPE`
2291 Explicit(P<Ty>, Mutability),
2294 pub type ExplicitSelf = Spanned<SelfKind>;
2297 /// Attempts to cast parameter to `ExplicitSelf`.
2298 pub fn to_self(&self) -> Option<ExplicitSelf> {
2299 if let PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), ident, _) = self.pat.kind {
2300 if ident.name == kw::SelfLower {
2301 return match self.ty.kind {
2302 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2303 TyKind::Ref(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2304 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2307 self.pat.span.to(self.ty.span),
2308 SelfKind::Explicit(self.ty.clone(), mutbl),
2316 /// Returns `true` if parameter is `self`.
2317 pub fn is_self(&self) -> bool {
2318 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2319 ident.name == kw::SelfLower
2325 /// Builds a `Param` object from `ExplicitSelf`.
2326 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2327 let span = eself.span.to(eself_ident.span);
2328 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2329 let (mutbl, ty) = match eself.node {
2330 SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2331 SelfKind::Value(mutbl) => (mutbl, infer_ty),
2332 SelfKind::Region(lt, mutbl) => (
2336 kind: TyKind::Ref(lt, MutTy { ty: infer_ty, mutbl }),
2346 kind: PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), eself_ident, None),
2353 is_placeholder: false,
2358 /// A signature (not the body) of a function declaration.
2360 /// E.g., `fn foo(bar: baz)`.
2362 /// Please note that it's different from `FnHeader` structure
2363 /// which contains metadata about function safety, asyncness, constness and ABI.
2364 #[derive(Clone, Encodable, Decodable, Debug)]
2366 pub inputs: Vec<Param>,
2367 pub output: FnRetTy,
2371 pub fn has_self(&self) -> bool {
2372 self.inputs.get(0).map_or(false, Param::is_self)
2374 pub fn c_variadic(&self) -> bool {
2375 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2379 /// Is the trait definition an auto trait?
2380 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2386 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2387 #[derive(HashStable_Generic)]
2393 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2395 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2400 pub fn is_async(self) -> bool {
2401 matches!(self, Async::Yes { .. })
2404 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2405 pub fn opt_return_id(self) -> Option<(NodeId, Span)> {
2407 Async::Yes { return_impl_trait_id, span, .. } => Some((return_impl_trait_id, span)),
2413 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2414 #[derive(HashStable_Generic)]
2420 /// Item defaultness.
2421 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2422 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2423 pub enum Defaultness {
2428 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2429 pub enum ImplPolarity {
2430 /// `impl Trait for Type`
2432 /// `impl !Trait for Type`
2436 impl fmt::Debug for ImplPolarity {
2437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2439 ImplPolarity::Positive => "positive".fmt(f),
2440 ImplPolarity::Negative(_) => "negative".fmt(f),
2445 #[derive(Clone, Encodable, Decodable, Debug)]
2447 /// Returns type is not specified.
2449 /// Functions default to `()` and closures default to inference.
2450 /// Span points to where return type would be inserted.
2452 /// Everything else.
2457 pub fn span(&self) -> Span {
2459 &FnRetTy::Default(span) => span,
2460 FnRetTy::Ty(ty) => ty.span,
2465 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2471 /// Module item kind.
2472 #[derive(Clone, Encodable, Decodable, Debug)]
2474 /// Module with inlined definition `mod foo { ... }`,
2475 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2476 /// The inner span is from the first token past `{` to the last token until `}`,
2477 /// or from the first to the last token in the loaded file.
2478 Loaded(Vec<P<Item>>, Inline, ModSpans),
2479 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2483 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2484 pub struct ModSpans {
2485 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2486 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2487 pub inner_span: Span,
2488 pub inject_use_span: Span,
2491 /// Foreign module declaration.
2493 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2494 #[derive(Clone, Encodable, Decodable, Debug)]
2495 pub struct ForeignMod {
2496 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2497 /// semantically by Rust.
2498 pub unsafety: Unsafe,
2499 pub abi: Option<StrLit>,
2500 pub items: Vec<P<ForeignItem>>,
2503 #[derive(Clone, Encodable, Decodable, Debug)]
2504 pub struct EnumDef {
2505 pub variants: Vec<Variant>,
2508 #[derive(Clone, Encodable, Decodable, Debug)]
2509 pub struct Variant {
2510 /// Attributes of the variant.
2512 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2516 /// The visibility of the variant. Syntactically accepted but not semantically.
2517 pub vis: Visibility,
2518 /// Name of the variant.
2521 /// Fields and constructor id of the variant.
2522 pub data: VariantData,
2523 /// Explicit discriminant, e.g., `Foo = 1`.
2524 pub disr_expr: Option<AnonConst>,
2525 /// Is a macro placeholder
2526 pub is_placeholder: bool,
2529 /// Part of `use` item to the right of its prefix.
2530 #[derive(Clone, Encodable, Decodable, Debug)]
2531 pub enum UseTreeKind {
2532 /// `use prefix` or `use prefix as rename`
2533 Simple(Option<Ident>),
2534 /// `use prefix::{...}`
2535 Nested(Vec<(UseTree, NodeId)>),
2540 /// A tree of paths sharing common prefixes.
2541 /// Used in `use` items both at top-level and inside of braces in import groups.
2542 #[derive(Clone, Encodable, Decodable, Debug)]
2543 pub struct UseTree {
2545 pub kind: UseTreeKind,
2550 pub fn ident(&self) -> Ident {
2552 UseTreeKind::Simple(Some(rename)) => rename,
2553 UseTreeKind::Simple(None) => {
2554 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2556 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2561 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2562 /// are contained as statements within items. These two cases need to be
2563 /// distinguished for pretty-printing.
2564 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2565 pub enum AttrStyle {
2570 rustc_index::newtype_index! {
2572 #[debug_format = "AttrId({})]"]
2573 pub struct AttrId {}
2576 impl<S: Encoder> Encodable<S> for AttrId {
2577 fn encode(&self, _s: &mut S) {}
2580 impl<D: Decoder> Decodable<D> for AttrId {
2581 default fn decode(_: &mut D) -> AttrId {
2582 panic!("cannot decode `AttrId` with `{}`", std::any::type_name::<D>());
2586 /// A list of attributes.
2587 pub type AttrVec = ThinVec<Attribute>;
2589 /// A syntax-level representation of an attribute.
2590 #[derive(Clone, Encodable, Decodable, Debug)]
2591 pub struct Attribute {
2594 /// Denotes if the attribute decorates the following construct (outer)
2595 /// or the construct this attribute is contained within (inner).
2596 pub style: AttrStyle,
2600 #[derive(Clone, Encodable, Decodable, Debug)]
2602 /// A normal attribute.
2603 Normal(P<NormalAttr>),
2605 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2606 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2607 /// variant (which is much less compact and thus more expensive).
2608 DocComment(CommentKind, Symbol),
2611 #[derive(Clone, Encodable, Decodable, Debug)]
2612 pub struct NormalAttr {
2614 pub tokens: Option<LazyAttrTokenStream>,
2617 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2618 pub struct AttrItem {
2621 pub tokens: Option<LazyAttrTokenStream>,
2624 /// `TraitRef`s appear in impls.
2626 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2627 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2628 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2629 /// same as the impl's `NodeId`).
2630 #[derive(Clone, Encodable, Decodable, Debug)]
2631 pub struct TraitRef {
2636 #[derive(Clone, Encodable, Decodable, Debug)]
2637 pub struct PolyTraitRef {
2638 /// The `'a` in `for<'a> Foo<&'a T>`.
2639 pub bound_generic_params: Vec<GenericParam>,
2641 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2642 pub trait_ref: TraitRef,
2648 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2650 bound_generic_params: generic_params,
2651 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2657 #[derive(Clone, Encodable, Decodable, Debug)]
2658 pub struct Visibility {
2659 pub kind: VisibilityKind,
2661 pub tokens: Option<LazyAttrTokenStream>,
2664 #[derive(Clone, Encodable, Decodable, Debug)]
2665 pub enum VisibilityKind {
2667 Restricted { path: P<Path>, id: NodeId, shorthand: bool },
2671 impl VisibilityKind {
2672 pub fn is_pub(&self) -> bool {
2673 matches!(self, VisibilityKind::Public)
2677 /// Field definition in a struct, variant or union.
2679 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2680 #[derive(Clone, Encodable, Decodable, Debug)]
2681 pub struct FieldDef {
2685 pub vis: Visibility,
2686 pub ident: Option<Ident>,
2689 pub is_placeholder: bool,
2692 /// Fields and constructor ids of enum variants and structs.
2693 #[derive(Clone, Encodable, Decodable, Debug)]
2694 pub enum VariantData {
2697 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2698 Struct(Vec<FieldDef>, bool),
2701 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2702 Tuple(Vec<FieldDef>, NodeId),
2705 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2710 /// Return the fields of this variant.
2711 pub fn fields(&self) -> &[FieldDef] {
2713 VariantData::Struct(fields, ..) | VariantData::Tuple(fields, _) => fields,
2718 /// Return the `NodeId` of this variant's constructor, if it has one.
2719 pub fn ctor_node_id(&self) -> Option<NodeId> {
2721 VariantData::Struct(..) => None,
2722 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2727 /// An item definition.
2728 #[derive(Clone, Encodable, Decodable, Debug)]
2729 pub struct Item<K = ItemKind> {
2733 pub vis: Visibility,
2734 /// The name of the item.
2735 /// It might be a dummy name in case of anonymous items.
2740 /// Original tokens this item was parsed from. This isn't necessarily
2741 /// available for all items, although over time more and more items should
2742 /// have this be `Some`. Right now this is primarily used for procedural
2743 /// macros, notably custom attributes.
2745 /// Note that the tokens here do not include the outer attributes, but will
2746 /// include inner attributes.
2747 pub tokens: Option<LazyAttrTokenStream>,
2751 /// Return the span that encompasses the attributes.
2752 pub fn span_with_attributes(&self) -> Span {
2753 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2757 /// `extern` qualifier on a function item or function type.
2758 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2760 /// No explicit extern keyword was used
2762 /// E.g. `fn foo() {}`
2764 /// An explicit extern keyword was used, but with implicit ABI
2766 /// E.g. `extern fn foo() {}`
2768 /// This is just `extern "C"` (see `rustc_target::spec::abi::Abi::FALLBACK`)
2770 /// An explicit extern keyword was used with an explicit ABI
2772 /// E.g. `extern "C" fn foo() {}`
2773 Explicit(StrLit, Span),
2777 pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2779 Some(name) => Extern::Explicit(name, span),
2780 None => Extern::Implicit(span),
2785 /// A function header.
2787 /// All the information between the visibility and the name of the function is
2788 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2789 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2790 pub struct FnHeader {
2791 /// The `unsafe` keyword, if any
2792 pub unsafety: Unsafe,
2793 /// The `async` keyword, if any
2794 pub asyncness: Async,
2795 /// The `const` keyword, if any
2796 pub constness: Const,
2797 /// The `extern` keyword and corresponding ABI string, if any
2802 /// Does this function header have any qualifiers or is it empty?
2803 pub fn has_qualifiers(&self) -> bool {
2804 let Self { unsafety, asyncness, constness, ext } = self;
2805 matches!(unsafety, Unsafe::Yes(_))
2806 || asyncness.is_async()
2807 || matches!(constness, Const::Yes(_))
2808 || !matches!(ext, Extern::None)
2812 impl Default for FnHeader {
2813 fn default() -> FnHeader {
2815 unsafety: Unsafe::No,
2816 asyncness: Async::No,
2817 constness: Const::No,
2823 #[derive(Clone, Encodable, Decodable, Debug)]
2825 pub unsafety: Unsafe,
2826 pub is_auto: IsAuto,
2827 pub generics: Generics,
2828 pub bounds: GenericBounds,
2829 pub items: Vec<P<AssocItem>>,
2832 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2833 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2834 /// are two locations for where clause on type aliases, but their predicates
2835 /// are concatenated together.
2837 /// Take this example:
2838 /// ```ignore (only-for-syntax-highlight)
2840 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2842 /// impl Foo for () {
2843 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2844 /// // ^^^^^^^^^^^^^^ first where clause
2845 /// // ^^^^^^^^^^^^^^ second where clause
2849 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2850 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2851 pub struct TyAliasWhereClause(pub bool, pub Span);
2853 #[derive(Clone, Encodable, Decodable, Debug)]
2854 pub struct TyAlias {
2855 pub defaultness: Defaultness,
2856 pub generics: Generics,
2857 /// The span information for the two where clauses (before equals, after equals)
2858 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2859 /// The index in `generics.where_clause.predicates` that would split into
2860 /// predicates from the where clause before the equals and the predicates
2861 /// from the where clause after the equals
2862 pub where_predicates_split: usize,
2863 pub bounds: GenericBounds,
2864 pub ty: Option<P<Ty>>,
2867 #[derive(Clone, Encodable, Decodable, Debug)]
2869 pub defaultness: Defaultness,
2870 pub unsafety: Unsafe,
2871 pub generics: Generics,
2872 pub constness: Const,
2873 pub polarity: ImplPolarity,
2874 /// The trait being implemented, if any.
2875 pub of_trait: Option<TraitRef>,
2877 pub items: Vec<P<AssocItem>>,
2880 #[derive(Clone, Encodable, Decodable, Debug)]
2882 pub defaultness: Defaultness,
2883 pub generics: Generics,
2885 pub body: Option<P<Block>>,
2888 #[derive(Clone, Encodable, Decodable, Debug)]
2890 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2892 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2893 ExternCrate(Option<Symbol>),
2894 /// A use declaration item (`use`).
2896 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2898 /// A static item (`static`).
2900 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2901 Static(P<Ty>, Mutability, Option<P<Expr>>),
2902 /// A constant item (`const`).
2904 /// E.g., `const FOO: i32 = 42;`.
2905 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2906 /// A function declaration (`fn`).
2908 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2910 /// A module declaration (`mod`).
2912 /// E.g., `mod foo;` or `mod foo { .. }`.
2913 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2914 /// semantically by Rust.
2915 Mod(Unsafe, ModKind),
2916 /// An external module (`extern`).
2918 /// E.g., `extern {}` or `extern "C" {}`.
2919 ForeignMod(ForeignMod),
2920 /// Module-level inline assembly (from `global_asm!()`).
2921 GlobalAsm(Box<InlineAsm>),
2922 /// A type alias (`type`).
2924 /// E.g., `type Foo = Bar<u8>;`.
2925 TyAlias(Box<TyAlias>),
2926 /// An enum definition (`enum`).
2928 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2929 Enum(EnumDef, Generics),
2930 /// A struct definition (`struct`).
2932 /// E.g., `struct Foo<A> { x: A }`.
2933 Struct(VariantData, Generics),
2934 /// A union definition (`union`).
2936 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2937 Union(VariantData, Generics),
2938 /// A trait declaration (`trait`).
2940 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2944 /// E.g., `trait Foo = Bar + Quux;`.
2945 TraitAlias(Generics, GenericBounds),
2946 /// An implementation.
2948 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2950 /// A macro invocation.
2952 /// E.g., `foo!(..)`.
2953 MacCall(P<MacCall>),
2955 /// A macro definition.
2960 pub fn article(&self) -> &str {
2963 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2964 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2965 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2969 pub fn descr(&self) -> &str {
2971 ItemKind::ExternCrate(..) => "extern crate",
2972 ItemKind::Use(..) => "`use` import",
2973 ItemKind::Static(..) => "static item",
2974 ItemKind::Const(..) => "constant item",
2975 ItemKind::Fn(..) => "function",
2976 ItemKind::Mod(..) => "module",
2977 ItemKind::ForeignMod(..) => "extern block",
2978 ItemKind::GlobalAsm(..) => "global asm item",
2979 ItemKind::TyAlias(..) => "type alias",
2980 ItemKind::Enum(..) => "enum",
2981 ItemKind::Struct(..) => "struct",
2982 ItemKind::Union(..) => "union",
2983 ItemKind::Trait(..) => "trait",
2984 ItemKind::TraitAlias(..) => "trait alias",
2985 ItemKind::MacCall(..) => "item macro invocation",
2986 ItemKind::MacroDef(..) => "macro definition",
2987 ItemKind::Impl { .. } => "implementation",
2991 pub fn generics(&self) -> Option<&Generics> {
2993 Self::Fn(box Fn { generics, .. })
2994 | Self::TyAlias(box TyAlias { generics, .. })
2995 | Self::Enum(_, generics)
2996 | Self::Struct(_, generics)
2997 | Self::Union(_, generics)
2998 | Self::Trait(box Trait { generics, .. })
2999 | Self::TraitAlias(generics, _)
3000 | Self::Impl(box Impl { generics, .. }) => Some(generics),
3006 /// Represents associated items.
3007 /// These include items in `impl` and `trait` definitions.
3008 pub type AssocItem = Item<AssocItemKind>;
3010 /// Represents associated item kinds.
3012 /// The term "provided" in the variants below refers to the item having a default
3013 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
3014 /// In an implementation, all items must be provided.
3015 /// The `Option`s below denote the bodies, where `Some(_)`
3016 /// means "provided" and conversely `None` means "required".
3017 #[derive(Clone, Encodable, Decodable, Debug)]
3018 pub enum AssocItemKind {
3019 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
3020 /// If `def` is parsed, then the constant is provided, and otherwise required.
3021 Const(Defaultness, P<Ty>, Option<P<Expr>>),
3022 /// An associated function.
3024 /// An associated type.
3026 /// A macro expanding to associated items.
3027 MacCall(P<MacCall>),
3030 impl AssocItemKind {
3031 pub fn defaultness(&self) -> Defaultness {
3033 Self::Const(defaultness, ..)
3034 | Self::Fn(box Fn { defaultness, .. })
3035 | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
3036 Self::MacCall(..) => Defaultness::Final,
3041 impl From<AssocItemKind> for ItemKind {
3042 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
3043 match assoc_item_kind {
3044 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
3045 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3046 AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3047 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
3052 impl TryFrom<ItemKind> for AssocItemKind {
3053 type Error = ItemKind;
3055 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
3056 Ok(match item_kind {
3057 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
3058 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
3059 ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
3060 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
3061 _ => return Err(item_kind),
3066 /// An item in `extern` block.
3067 #[derive(Clone, Encodable, Decodable, Debug)]
3068 pub enum ForeignItemKind {
3069 /// A foreign static item (`static FOO: u8`).
3070 Static(P<Ty>, Mutability, Option<P<Expr>>),
3071 /// An foreign function.
3073 /// An foreign type.
3074 TyAlias(Box<TyAlias>),
3075 /// A macro expanding to foreign items.
3076 MacCall(P<MacCall>),
3079 impl From<ForeignItemKind> for ItemKind {
3080 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3081 match foreign_item_kind {
3082 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3083 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3084 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3085 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3090 impl TryFrom<ItemKind> for ForeignItemKind {
3091 type Error = ItemKind;
3093 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3094 Ok(match item_kind {
3095 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3096 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3097 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3098 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3099 _ => return Err(item_kind),
3104 pub type ForeignItem = Item<ForeignItemKind>;
3106 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3107 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3110 use rustc_data_structures::static_assert_size;
3111 // tidy-alphabetical-start
3112 static_assert_size!(AssocItem, 104);
3113 static_assert_size!(AssocItemKind, 32);
3114 static_assert_size!(Attribute, 32);
3115 static_assert_size!(Block, 48);
3116 static_assert_size!(Expr, 72);
3117 static_assert_size!(ExprKind, 40);
3118 static_assert_size!(Fn, 184);
3119 static_assert_size!(ForeignItem, 96);
3120 static_assert_size!(ForeignItemKind, 24);
3121 static_assert_size!(GenericArg, 24);
3122 static_assert_size!(GenericBound, 72);
3123 static_assert_size!(Generics, 72);
3124 static_assert_size!(Impl, 184);
3125 static_assert_size!(Item, 184);
3126 static_assert_size!(ItemKind, 112);
3127 static_assert_size!(LitKind, 24);
3128 static_assert_size!(Local, 72);
3129 static_assert_size!(MetaItemLit, 40);
3130 static_assert_size!(Param, 40);
3131 static_assert_size!(Pat, 88);
3132 static_assert_size!(Path, 24);
3133 static_assert_size!(PathSegment, 24);
3134 static_assert_size!(PatKind, 64);
3135 static_assert_size!(Stmt, 32);
3136 static_assert_size!(StmtKind, 16);
3137 static_assert_size!(Ty, 64);
3138 static_assert_size!(TyKind, 40);
3139 // tidy-alphabetical-end