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 //! - [`Lit`] 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, LazyTokenStream, 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};
36 use std::convert::TryFrom;
39 use 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: Vec<PathSegment>,
94 pub tokens: Option<LazyTokenStream>,
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
116 pub fn from_ident(ident: Ident) -> Path {
117 Path { segments: 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(ref data) => data.span,
180 Parenthesized(ref 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(ref t, ..) => t.span,
316 GenericBound::Outlives(ref 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 {
397 where_clause: WhereClause {
398 has_where_token: false,
399 predicates: Vec::new(),
407 /// A where-clause in a definition.
408 #[derive(Clone, Encodable, Decodable, Debug)]
409 pub struct WhereClause {
410 /// `true` if we ate a `where` token: this can happen
411 /// if we parsed no predicates (e.g. `struct Foo where {}`).
412 /// This allows us to pretty-print accurately.
413 pub has_where_token: bool,
414 pub predicates: Vec<WherePredicate>,
418 /// A single predicate in a where-clause.
419 #[derive(Clone, Encodable, Decodable, Debug)]
420 pub enum WherePredicate {
421 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
422 BoundPredicate(WhereBoundPredicate),
423 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
424 RegionPredicate(WhereRegionPredicate),
425 /// An equality predicate (unsupported).
426 EqPredicate(WhereEqPredicate),
429 impl WherePredicate {
430 pub fn span(&self) -> Span {
432 WherePredicate::BoundPredicate(p) => p.span,
433 WherePredicate::RegionPredicate(p) => p.span,
434 WherePredicate::EqPredicate(p) => p.span,
441 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
442 #[derive(Clone, Encodable, Decodable, Debug)]
443 pub struct WhereBoundPredicate {
445 /// Any generics from a `for` binding.
446 pub bound_generic_params: Vec<GenericParam>,
447 /// The type being bounded.
448 pub bounded_ty: P<Ty>,
449 /// Trait and lifetime bounds (`Clone + Send + 'static`).
450 pub bounds: GenericBounds,
453 /// A lifetime predicate.
455 /// E.g., `'a: 'b + 'c`.
456 #[derive(Clone, Encodable, Decodable, Debug)]
457 pub struct WhereRegionPredicate {
459 pub lifetime: Lifetime,
460 pub bounds: GenericBounds,
463 /// An equality predicate (unsupported).
466 #[derive(Clone, Encodable, Decodable, Debug)]
467 pub struct WhereEqPredicate {
473 #[derive(Clone, Encodable, Decodable, Debug)]
476 pub items: Vec<P<Item>>,
478 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
479 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
481 pub is_placeholder: bool,
484 /// Possible values inside of compile-time attribute lists.
486 /// E.g., the '..' in `#[name(..)]`.
487 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
488 pub enum NestedMetaItem {
489 /// A full MetaItem, for recursive meta items.
493 /// E.g., `"foo"`, `64`, `true`.
497 /// A spanned compile-time attribute item.
499 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
500 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
501 pub struct MetaItem {
503 pub kind: MetaItemKind,
507 /// A compile-time attribute item.
509 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
510 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
511 pub enum MetaItemKind {
514 /// E.g., `test` as in `#[test]`.
518 /// E.g., `derive(..)` as in `#[derive(..)]`.
519 List(Vec<NestedMetaItem>),
520 /// Name value meta item.
522 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
526 /// A block (`{ .. }`).
528 /// E.g., `{ .. }` as in `fn foo() { .. }`.
529 #[derive(Clone, Encodable, Decodable, Debug)]
531 /// The statements in the block.
532 pub stmts: Vec<Stmt>,
534 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
535 pub rules: BlockCheckMode,
537 pub tokens: Option<LazyTokenStream>,
538 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
545 pub could_be_bare_literal: bool,
550 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
551 #[derive(Clone, Encodable, Decodable, Debug)]
556 pub tokens: Option<LazyTokenStream>,
560 /// Attempt reparsing the pattern as a type.
561 /// This is intended for use by diagnostics.
562 pub fn to_ty(&self) -> Option<P<Ty>> {
563 let kind = match &self.kind {
564 // In a type expression `_` is an inference variable.
565 PatKind::Wild => TyKind::Infer,
566 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
567 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
568 TyKind::Path(None, Path::from_ident(*ident))
570 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
571 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
572 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
573 PatKind::Ref(pat, mutbl) => {
574 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
576 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
577 // when `P` can be reparsed as a type `T`.
578 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
579 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
580 // assuming `T0` to `Tn` are all syntactically valid as types.
581 PatKind::Tuple(pats) => {
582 let mut tys = Vec::with_capacity(pats.len());
583 // FIXME(#48994) - could just be collected into an Option<Vec>
585 tys.push(pat.to_ty()?);
592 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
595 /// Walk top-down and call `it` in each place where a pattern occurs
596 /// starting with the root pattern `walk` is called on. If `it` returns
597 /// false then we will descend no further but siblings will be processed.
598 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
604 // Walk into the pattern associated with `Ident` (if any).
605 PatKind::Ident(_, _, Some(p)) => p.walk(it),
607 // Walk into each field of struct.
608 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
610 // Sequence of patterns.
611 PatKind::TupleStruct(_, _, s)
614 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
616 // Trivial wrappers over inner patterns.
617 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
619 // These patterns do not contain subpatterns, skip.
626 | PatKind::MacCall(_) => {}
630 /// Is this a `..` pattern?
631 pub fn is_rest(&self) -> bool {
632 matches!(self.kind, PatKind::Rest)
636 /// A single field in a struct pattern.
638 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
639 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
640 /// except when `is_shorthand` is true.
641 #[derive(Clone, Encodable, Decodable, Debug)]
642 pub struct PatField {
643 /// The identifier for the field.
645 /// The pattern the field is destructured to.
647 pub is_shorthand: bool,
651 pub is_placeholder: bool,
654 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
655 #[derive(Encodable, Decodable, HashStable_Generic)]
661 impl From<bool> for ByRef {
662 fn from(b: bool) -> ByRef {
670 /// Explicit binding annotations given in the HIR for a binding. Note
671 /// that this is not the final binding *mode* that we infer after type
673 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
674 #[derive(Encodable, Decodable, HashStable_Generic)]
675 pub struct BindingAnnotation(pub ByRef, pub Mutability);
677 impl BindingAnnotation {
678 pub const NONE: Self = Self(ByRef::No, Mutability::Not);
679 pub const REF: Self = Self(ByRef::Yes, Mutability::Not);
680 pub const MUT: Self = Self(ByRef::No, Mutability::Mut);
681 pub const REF_MUT: Self = Self(ByRef::Yes, Mutability::Mut);
683 pub fn prefix_str(self) -> &'static str {
688 Self::REF_MUT => "ref mut ",
693 #[derive(Clone, Encodable, Decodable, Debug)]
696 Included(RangeSyntax),
701 #[derive(Clone, Encodable, Decodable, Debug)]
702 pub enum RangeSyntax {
709 /// All the different flavors of pattern that Rust recognizes.
710 #[derive(Clone, Encodable, Decodable, Debug)]
712 /// Represents a wildcard pattern (`_`).
715 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
716 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
717 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
718 /// during name resolution.
719 Ident(BindingAnnotation, Ident, Option<P<Pat>>),
721 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
722 /// The `bool` is `true` in the presence of a `..`.
723 Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool),
725 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
726 TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>),
728 /// An or-pattern `A | B | C`.
729 /// Invariant: `pats.len() >= 2`.
732 /// A possibly qualified path pattern.
733 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
734 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
735 /// only legally refer to associated constants.
736 Path(Option<QSelf>, Path),
738 /// A tuple pattern (`(a, b)`).
744 /// A reference pattern (e.g., `&mut (a, b)`).
745 Ref(P<Pat>, Mutability),
750 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
751 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
753 /// A slice pattern `[a, b, c]`.
756 /// A rest pattern `..`.
758 /// Syntactically it is valid anywhere.
760 /// Semantically however, it only has meaning immediately inside:
761 /// - a slice pattern: `[a, .., b]`,
762 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
763 /// - a tuple pattern: `(a, .., b)`,
764 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
766 /// In all of these cases, an additional restriction applies,
767 /// only one rest pattern may occur in the pattern sequences.
770 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
773 /// A macro pattern; pre-expansion.
777 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
778 #[derive(HashStable_Generic, Encodable, Decodable)]
779 pub enum Mutability {
785 pub fn invert(self) -> Self {
787 Mutability::Mut => Mutability::Not,
788 Mutability::Not => Mutability::Mut,
792 pub fn prefix_str(&self) -> &'static str {
794 Mutability::Mut => "mut ",
795 Mutability::Not => "",
800 /// The kind of borrow in an `AddrOf` expression,
801 /// e.g., `&place` or `&raw const place`.
802 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
803 #[derive(Encodable, Decodable, HashStable_Generic)]
804 pub enum BorrowKind {
805 /// A normal borrow, `&$expr` or `&mut $expr`.
806 /// The resulting type is either `&'a T` or `&'a mut T`
807 /// where `T = typeof($expr)` and `'a` is some lifetime.
809 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
810 /// The resulting type is either `*const T` or `*mut T`
811 /// where `T = typeof($expr)`.
815 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
817 /// The `+` operator (addition)
819 /// The `-` operator (subtraction)
821 /// The `*` operator (multiplication)
823 /// The `/` operator (division)
825 /// The `%` operator (modulus)
827 /// The `&&` operator (logical and)
829 /// The `||` operator (logical or)
831 /// The `^` operator (bitwise xor)
833 /// The `&` operator (bitwise and)
835 /// The `|` operator (bitwise or)
837 /// The `<<` operator (shift left)
839 /// The `>>` operator (shift right)
841 /// The `==` operator (equality)
843 /// The `<` operator (less than)
845 /// The `<=` operator (less than or equal to)
847 /// The `!=` operator (not equal to)
849 /// The `>=` operator (greater than or equal to)
851 /// The `>` operator (greater than)
856 pub fn to_string(&self) -> &'static str {
879 pub fn lazy(&self) -> bool {
880 matches!(self, BinOpKind::And | BinOpKind::Or)
883 pub fn is_comparison(&self) -> bool {
885 // Note for developers: please keep this as is;
886 // we want compilation to fail if another variant is added.
888 Eq | Lt | Le | Ne | Gt | Ge => true,
889 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
894 pub type BinOp = Spanned<BinOpKind>;
898 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
899 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
901 /// The `*` operator for dereferencing
903 /// The `!` operator for logical inversion
905 /// The `-` operator for negation
910 pub fn to_string(op: UnOp) -> &'static str {
920 #[derive(Clone, Encodable, Decodable, Debug)]
928 pub fn has_trailing_semicolon(&self) -> bool {
930 StmtKind::Semi(_) => true,
931 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
936 /// Converts a parsed `Stmt` to a `Stmt` with
937 /// a trailing semicolon.
939 /// This only modifies the parsed AST struct, not the attached
940 /// `LazyTokenStream`. The parser is responsible for calling
941 /// `CreateTokenStream::add_trailing_semi` when there is actually
942 /// a semicolon in the tokenstream.
943 pub fn add_trailing_semicolon(mut self) -> Self {
944 self.kind = match self.kind {
945 StmtKind::Expr(expr) => StmtKind::Semi(expr),
946 StmtKind::MacCall(mac) => {
947 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
948 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
957 pub fn is_item(&self) -> bool {
958 matches!(self.kind, StmtKind::Item(_))
961 pub fn is_expr(&self) -> bool {
962 matches!(self.kind, StmtKind::Expr(_))
966 #[derive(Clone, Encodable, Decodable, Debug)]
968 /// A local (let) binding.
970 /// An item definition.
972 /// Expr without trailing semi-colon.
974 /// Expr with a trailing semi-colon.
976 /// Just a trailing semi-colon.
979 MacCall(P<MacCallStmt>),
982 #[derive(Clone, Encodable, Decodable, Debug)]
983 pub struct MacCallStmt {
985 pub style: MacStmtStyle,
987 pub tokens: Option<LazyTokenStream>,
990 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
991 pub enum MacStmtStyle {
992 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
993 /// `foo!(...);`, `foo![...];`).
995 /// The macro statement had braces (e.g., `foo! { ... }`).
997 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
998 /// `foo!(...)`). All of these will end up being converted into macro
1003 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1004 #[derive(Clone, Encodable, Decodable, Debug)]
1008 pub ty: Option<P<Ty>>,
1009 pub kind: LocalKind,
1012 pub tokens: Option<LazyTokenStream>,
1015 #[derive(Clone, Encodable, Decodable, Debug)]
1016 pub enum LocalKind {
1017 /// Local declaration.
1018 /// Example: `let x;`
1020 /// Local declaration with an initializer.
1021 /// Example: `let x = y;`
1023 /// Local declaration with an initializer and an `else` clause.
1024 /// Example: `let Some(x) = y else { return };`
1025 InitElse(P<Expr>, P<Block>),
1029 pub fn init(&self) -> Option<&Expr> {
1032 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1036 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1039 Self::Init(init) => Some((init, None)),
1040 Self::InitElse(init, els) => Some((init, Some(els))),
1045 /// An arm of a 'match'.
1047 /// E.g., `0..=10 => { println!("match!") }` as in
1051 /// 0..=10 => { println!("match!") },
1052 /// _ => { println!("no match!") },
1055 #[derive(Clone, Encodable, Decodable, Debug)]
1058 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1060 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1061 pub guard: Option<P<Expr>>,
1066 pub is_placeholder: bool,
1069 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1070 #[derive(Clone, Encodable, Decodable, Debug)]
1071 pub struct ExprField {
1077 pub is_shorthand: bool,
1078 pub is_placeholder: bool,
1081 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1082 pub enum BlockCheckMode {
1084 Unsafe(UnsafeSource),
1087 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1088 pub enum UnsafeSource {
1093 /// A constant (expression) that's not an item or associated item,
1094 /// but needs its own `DefId` for type-checking, const-eval, etc.
1095 /// These are usually found nested inside types (e.g., array lengths)
1096 /// or expressions (e.g., repeat counts), and also used to define
1097 /// explicit discriminant values for enum variants.
1098 #[derive(Clone, Encodable, Decodable, Debug)]
1099 pub struct AnonConst {
1105 #[derive(Clone, Encodable, Decodable, Debug)]
1111 pub tokens: Option<LazyTokenStream>,
1115 /// Returns `true` if this expression would be valid somewhere that expects a value;
1116 /// for example, an `if` condition.
1117 pub fn returns(&self) -> bool {
1118 if let ExprKind::Block(ref block, _) = self.kind {
1119 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1121 Some(StmtKind::Expr(_)) => true,
1122 // Last statement is an explicit return?
1123 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1124 // This is a block that doesn't end in either an implicit or explicit return.
1128 // This is not a block, it is a value.
1133 /// Is this expr either `N`, or `{ N }`.
1135 /// If this is not the case, name resolution does not resolve `N` when using
1136 /// `min_const_generics` as more complex expressions are not supported.
1137 pub fn is_potential_trivial_const_param(&self) -> bool {
1138 let this = if let ExprKind::Block(ref block, None) = self.kind {
1139 if block.stmts.len() == 1 {
1140 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1148 if let ExprKind::Path(None, ref path) = this.kind {
1149 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1157 pub fn to_bound(&self) -> Option<GenericBound> {
1159 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1160 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1161 TraitBoundModifier::None,
1167 pub fn peel_parens(&self) -> &Expr {
1168 let mut expr = self;
1169 while let ExprKind::Paren(inner) = &expr.kind {
1175 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1176 pub fn to_ty(&self) -> Option<P<Ty>> {
1177 let kind = match &self.kind {
1178 // Trivial conversions.
1179 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1180 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1182 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1184 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1185 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1188 ExprKind::Repeat(expr, expr_len) => {
1189 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1192 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1194 ExprKind::Tup(exprs) => {
1195 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1199 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1200 // then type of result is trait object.
1201 // Otherwise we don't assume the result type.
1202 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1203 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1204 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1210 ExprKind::Underscore => TyKind::Infer,
1212 // This expression doesn't look like a type syntactically.
1216 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1219 pub fn precedence(&self) -> ExprPrecedence {
1221 ExprKind::Box(_) => ExprPrecedence::Box,
1222 ExprKind::Array(_) => ExprPrecedence::Array,
1223 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1224 ExprKind::Call(..) => ExprPrecedence::Call,
1225 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1226 ExprKind::Tup(_) => ExprPrecedence::Tup,
1227 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1228 ExprKind::Unary(..) => ExprPrecedence::Unary,
1229 ExprKind::Lit(_) => ExprPrecedence::Lit,
1230 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1231 ExprKind::Let(..) => ExprPrecedence::Let,
1232 ExprKind::If(..) => ExprPrecedence::If,
1233 ExprKind::While(..) => ExprPrecedence::While,
1234 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1235 ExprKind::Loop(..) => ExprPrecedence::Loop,
1236 ExprKind::Match(..) => ExprPrecedence::Match,
1237 ExprKind::Closure(..) => ExprPrecedence::Closure,
1238 ExprKind::Block(..) => ExprPrecedence::Block,
1239 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1240 ExprKind::Async(..) => ExprPrecedence::Async,
1241 ExprKind::Await(..) => ExprPrecedence::Await,
1242 ExprKind::Assign(..) => ExprPrecedence::Assign,
1243 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1244 ExprKind::Field(..) => ExprPrecedence::Field,
1245 ExprKind::Index(..) => ExprPrecedence::Index,
1246 ExprKind::Range(..) => ExprPrecedence::Range,
1247 ExprKind::Underscore => ExprPrecedence::Path,
1248 ExprKind::Path(..) => ExprPrecedence::Path,
1249 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1250 ExprKind::Break(..) => ExprPrecedence::Break,
1251 ExprKind::Continue(..) => ExprPrecedence::Continue,
1252 ExprKind::Ret(..) => ExprPrecedence::Ret,
1253 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1254 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1255 ExprKind::Struct(..) => ExprPrecedence::Struct,
1256 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1257 ExprKind::Paren(..) => ExprPrecedence::Paren,
1258 ExprKind::Try(..) => ExprPrecedence::Try,
1259 ExprKind::Yield(..) => ExprPrecedence::Yield,
1260 ExprKind::Yeet(..) => ExprPrecedence::Yeet,
1261 ExprKind::Err => ExprPrecedence::Err,
1265 pub fn take(&mut self) -> Self {
1270 kind: ExprKind::Err,
1272 attrs: AttrVec::new(),
1278 // To a first-order approximation, is this a pattern
1279 pub fn is_approximately_pattern(&self) -> bool {
1280 match &self.peel_parens().kind {
1282 | ExprKind::Array(_)
1283 | ExprKind::Call(_, _)
1286 | ExprKind::Range(_, _, _)
1287 | ExprKind::Underscore
1288 | ExprKind::Path(_, _)
1289 | ExprKind::Struct(_) => true,
1295 /// Limit types of a range (inclusive or exclusive)
1296 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1297 pub enum RangeLimits {
1298 /// Inclusive at the beginning, exclusive at the end
1300 /// Inclusive at the beginning and end
1304 #[derive(Clone, Encodable, Decodable, Debug)]
1305 pub enum StructRest {
1310 /// No trailing `..` or expression.
1314 #[derive(Clone, Encodable, Decodable, Debug)]
1315 pub struct StructExpr {
1316 pub qself: Option<QSelf>,
1318 pub fields: Vec<ExprField>,
1319 pub rest: StructRest,
1322 #[derive(Clone, Encodable, Decodable, Debug)]
1324 /// A `box x` expression.
1326 /// An array (`[a, b, c, d]`)
1327 Array(Vec<P<Expr>>),
1328 /// Allow anonymous constants from an inline `const` block
1329 ConstBlock(AnonConst),
1332 /// The first field resolves to the function itself,
1333 /// and the second field is the list of arguments.
1334 /// This also represents calling the constructor of
1335 /// tuple-like ADTs such as tuple structs and enum variants.
1336 Call(P<Expr>, Vec<P<Expr>>),
1337 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1339 /// The `PathSegment` represents the method name and its generic arguments
1340 /// (within the angle brackets).
1341 /// The standalone `Expr` is the receiver expression.
1342 /// The vector of `Expr` is the arguments.
1343 /// `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1344 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d])`.
1345 /// This `Span` is the span of the function, without the dot and receiver
1346 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1347 MethodCall(PathSegment, P<Expr>, Vec<P<Expr>>, Span),
1348 /// A tuple (e.g., `(a, b, c, d)`).
1350 /// A binary operation (e.g., `a + b`, `a * b`).
1351 Binary(BinOp, P<Expr>, P<Expr>),
1352 /// A unary operation (e.g., `!x`, `*x`).
1353 Unary(UnOp, P<Expr>),
1354 /// A literal (e.g., `1`, `"foo"`).
1356 /// A cast (e.g., `foo as f64`).
1357 Cast(P<Expr>, P<Ty>),
1358 /// A type ascription (e.g., `42: usize`).
1359 Type(P<Expr>, P<Ty>),
1360 /// A `let pat = expr` expression that is only semantically allowed in the condition
1361 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1363 /// `Span` represents the whole `let pat = expr` statement.
1364 Let(P<Pat>, P<Expr>, Span),
1365 /// An `if` block, with an optional `else` block.
1367 /// `if expr { block } else { expr }`
1368 If(P<Expr>, P<Block>, Option<P<Expr>>),
1369 /// A while loop, with an optional label.
1371 /// `'label: while expr { block }`
1372 While(P<Expr>, P<Block>, Option<Label>),
1373 /// A `for` loop, with an optional label.
1375 /// `'label: for pat in expr { block }`
1377 /// This is desugared to a combination of `loop` and `match` expressions.
1378 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1379 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1381 /// `'label: loop { block }`
1382 Loop(P<Block>, Option<Label>),
1383 /// A `match` block.
1384 Match(P<Expr>, Vec<Arm>),
1385 /// A closure (e.g., `move |a, b, c| a + b + c`).
1387 /// The final span is the span of the argument block `|...|`.
1388 Closure(ClosureBinder, CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1389 /// A block (`'label: { ... }`).
1390 Block(P<Block>, Option<Label>),
1391 /// An async block (`async move { ... }`).
1393 /// The `NodeId` is the `NodeId` for the closure that results from
1394 /// desugaring an async block, just like the NodeId field in the
1395 /// `Async::Yes` variant. This is necessary in order to create a def for the
1396 /// closure which can be used as a parent of any child defs. Defs
1397 /// created during lowering cannot be made the parent of any other
1398 /// preexisting defs.
1399 Async(CaptureBy, NodeId, P<Block>),
1400 /// An await expression (`my_future.await`).
1403 /// A try block (`try { ... }`).
1406 /// An assignment (`a = foo()`).
1407 /// The `Span` argument is the span of the `=` token.
1408 Assign(P<Expr>, P<Expr>, Span),
1409 /// An assignment with an operator.
1412 AssignOp(BinOp, P<Expr>, P<Expr>),
1413 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1414 Field(P<Expr>, Ident),
1415 /// An indexing operation (e.g., `foo[2]`).
1416 Index(P<Expr>, P<Expr>),
1417 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1418 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1419 /// An underscore, used in destructuring assignment to ignore a value.
1422 /// Variable reference, possibly containing `::` and/or type
1423 /// parameters (e.g., `foo::bar::<baz>`).
1425 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1426 Path(Option<QSelf>, Path),
1428 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1429 AddrOf(BorrowKind, Mutability, P<Expr>),
1430 /// A `break`, with an optional label to break, and an optional expression.
1431 Break(Option<Label>, Option<P<Expr>>),
1432 /// A `continue`, with an optional label.
1433 Continue(Option<Label>),
1434 /// A `return`, with an optional value to be returned.
1435 Ret(Option<P<Expr>>),
1437 /// Output of the `asm!()` macro.
1438 InlineAsm(P<InlineAsm>),
1440 /// A macro invocation; pre-expansion.
1441 MacCall(P<MacCall>),
1443 /// A struct literal expression.
1445 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1446 Struct(P<StructExpr>),
1448 /// An array literal constructed from one repeated element.
1450 /// E.g., `[1; 5]`. The expression is the element to be
1451 /// repeated; the constant is the number of times to repeat it.
1452 Repeat(P<Expr>, AnonConst),
1454 /// No-op: used solely so we can pretty-print faithfully.
1457 /// A try expression (`expr?`).
1460 /// A `yield`, with an optional value to be yielded.
1461 Yield(Option<P<Expr>>),
1463 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1464 /// with an optional value to be returned.
1465 Yeet(Option<P<Expr>>),
1467 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1471 /// The explicit `Self` type in a "qualified path". The actual
1472 /// path, including the trait and the associated item, is stored
1473 /// separately. `position` represents the index of the associated
1474 /// item qualified with this `Self` type.
1476 /// ```ignore (only-for-syntax-highlight)
1477 /// <Vec<T> as a::b::Trait>::AssociatedItem
1478 /// ^~~~~ ~~~~~~~~~~~~~~^
1481 /// <Vec<T>>::AssociatedItem
1485 #[derive(Clone, Encodable, Decodable, Debug)]
1489 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1490 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1491 /// 0`, this is an empty span.
1492 pub path_span: Span,
1493 pub position: usize,
1496 /// A capture clause used in closures and `async` blocks.
1497 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1498 pub enum CaptureBy {
1499 /// `move |x| y + x`.
1501 /// `move` keyword was not specified.
1505 /// The movability of a generator / closure literal:
1506 /// whether a generator contains self-references, causing it to be `!Unpin`.
1507 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1508 #[derive(HashStable_Generic)]
1509 pub enum Movability {
1510 /// May contain self-references, `!Unpin`.
1512 /// Must not contain self-references, `Unpin`.
1516 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1517 #[derive(Clone, Encodable, Decodable, Debug)]
1518 pub enum ClosureBinder {
1519 /// The binder is not present, all closure lifetimes are inferred.
1521 /// The binder is present.
1523 /// Span of the whole `for<>` clause
1526 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1527 /// ^^^^^^^^^^^ -- this
1531 /// Lifetimes in the `for<>` closure
1534 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1537 generic_params: P<[GenericParam]>,
1541 /// Represents a macro invocation. The `path` indicates which macro
1542 /// is being invoked, and the `args` are arguments passed to it.
1543 #[derive(Clone, Encodable, Decodable, Debug)]
1544 pub struct MacCall {
1546 pub args: P<MacArgs>,
1547 pub prior_type_ascription: Option<(Span, bool)>,
1551 pub fn span(&self) -> Span {
1552 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1556 /// Arguments passed to an attribute or a function-like macro.
1557 #[derive(Clone, Encodable, Decodable, Debug)]
1559 /// No arguments - `#[attr]`.
1561 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1562 Delimited(DelimSpan, MacDelimiter, TokenStream),
1563 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1565 /// Span of the `=` token.
1572 // The RHS of a `MacArgs::Eq` starts out as an expression. Once macro expansion
1573 // is completed, all cases end up either as a literal, which is the form used
1574 // after lowering to HIR, or as an error.
1575 #[derive(Clone, Encodable, Decodable, Debug)]
1576 pub enum MacArgsEq {
1582 pub fn delim(&self) -> Option<Delimiter> {
1584 MacArgs::Delimited(_, delim, _) => Some(delim.to_token()),
1585 MacArgs::Empty | MacArgs::Eq(..) => None,
1589 pub fn span(&self) -> Option<Span> {
1591 MacArgs::Empty => None,
1592 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1593 MacArgs::Eq(eq_span, MacArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1594 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1595 unreachable!("in literal form when getting span: {:?}", lit);
1600 /// Tokens inside the delimiters or after `=`.
1601 /// Proc macros see these tokens, for example.
1602 pub fn inner_tokens(&self) -> TokenStream {
1604 MacArgs::Empty => TokenStream::default(),
1605 MacArgs::Delimited(.., tokens) => tokens.clone(),
1606 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => TokenStream::from_ast(expr),
1607 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1608 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1613 /// Whether a macro with these arguments needs a semicolon
1614 /// when used as a standalone item or statement.
1615 pub fn need_semicolon(&self) -> bool {
1616 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1620 impl<CTX> HashStable<CTX> for MacArgs
1622 CTX: crate::HashStableContext,
1624 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1625 mem::discriminant(self).hash_stable(ctx, hasher);
1627 MacArgs::Empty => {}
1628 MacArgs::Delimited(dspan, delim, tokens) => {
1629 dspan.hash_stable(ctx, hasher);
1630 delim.hash_stable(ctx, hasher);
1631 tokens.hash_stable(ctx, hasher);
1633 MacArgs::Eq(_eq_span, MacArgsEq::Ast(expr)) => {
1634 unreachable!("hash_stable {:?}", expr);
1636 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit)) => {
1637 eq_span.hash_stable(ctx, hasher);
1638 lit.hash_stable(ctx, hasher);
1644 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1645 pub enum MacDelimiter {
1652 pub fn to_token(self) -> Delimiter {
1654 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1655 MacDelimiter::Bracket => Delimiter::Bracket,
1656 MacDelimiter::Brace => Delimiter::Brace,
1660 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1662 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1663 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1664 Delimiter::Brace => Some(MacDelimiter::Brace),
1665 Delimiter::Invisible => None,
1670 /// Represents a macro definition.
1671 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1672 pub struct MacroDef {
1673 pub body: P<MacArgs>,
1674 /// `true` if macro was defined with `macro_rules`.
1675 pub macro_rules: bool,
1678 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1679 #[derive(HashStable_Generic)]
1681 /// A regular string, like `"foo"`.
1683 /// A raw string, like `r##"foo"##`.
1685 /// The value is the number of `#` symbols used.
1690 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1692 /// The original literal token as written in source code.
1693 pub token_lit: token::Lit,
1694 /// The "semantic" representation of the literal lowered from the original tokens.
1695 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1696 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1701 /// Same as `Lit`, but restricted to string literals.
1702 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1704 /// The original literal token as written in source code.
1705 pub style: StrStyle,
1707 pub suffix: Option<Symbol>,
1709 /// The unescaped "semantic" representation of the literal lowered from the original token.
1710 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1711 pub symbol_unescaped: Symbol,
1715 pub fn as_lit(&self) -> Lit {
1716 let token_kind = match self.style {
1717 StrStyle::Cooked => token::Str,
1718 StrStyle::Raw(n) => token::StrRaw(n),
1721 token_lit: token::Lit::new(token_kind, self.symbol, self.suffix),
1723 kind: LitKind::Str(self.symbol_unescaped, self.style),
1728 /// Type of the integer literal based on provided suffix.
1729 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1730 #[derive(HashStable_Generic)]
1731 pub enum LitIntType {
1740 /// Type of the float literal based on provided suffix.
1741 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1742 #[derive(HashStable_Generic)]
1743 pub enum LitFloatType {
1744 /// A float literal with a suffix (`1f32` or `1E10f32`).
1746 /// A float literal without a suffix (`1.0 or 1.0E10`).
1752 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1753 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1755 /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
1756 /// from the original token's symbol.
1757 Str(Symbol, StrStyle),
1758 /// A byte string (`b"foo"`).
1760 /// A byte char (`b'f'`).
1762 /// A character literal (`'a'`).
1764 /// An integer literal (`1`).
1765 Int(u128, LitIntType),
1766 /// A float literal (`1f64` or `1E10f64`). Stored as a symbol rather than
1767 /// `f64` so that `LitKind` can impl `Eq` and `Hash`.
1768 Float(Symbol, LitFloatType),
1769 /// A boolean literal.
1771 /// Placeholder for a literal that wasn't well-formed in some way.
1776 /// Returns `true` if this literal is a string.
1777 pub fn is_str(&self) -> bool {
1778 matches!(self, LitKind::Str(..))
1781 /// Returns `true` if this literal is byte literal string.
1782 pub fn is_bytestr(&self) -> bool {
1783 matches!(self, LitKind::ByteStr(_))
1786 /// Returns `true` if this is a numeric literal.
1787 pub fn is_numeric(&self) -> bool {
1788 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1791 /// Returns `true` if this literal has no suffix.
1792 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1793 pub fn is_unsuffixed(&self) -> bool {
1797 /// Returns `true` if this literal has a suffix.
1798 pub fn is_suffixed(&self) -> bool {
1800 // suffixed variants
1801 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1802 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1803 // unsuffixed variants
1805 | LitKind::ByteStr(..)
1808 | LitKind::Int(_, LitIntType::Unsuffixed)
1809 | LitKind::Float(_, LitFloatType::Unsuffixed)
1811 | LitKind::Err => false,
1816 // N.B., If you change this, you'll probably want to change the corresponding
1817 // type structure in `middle/ty.rs` as well.
1818 #[derive(Clone, Encodable, Decodable, Debug)]
1821 pub mutbl: Mutability,
1824 /// Represents a function's signature in a trait declaration,
1825 /// trait implementation, or free function.
1826 #[derive(Clone, Encodable, Decodable, Debug)]
1828 pub header: FnHeader,
1829 pub decl: P<FnDecl>,
1833 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1834 #[derive(Encodable, Decodable, HashStable_Generic)]
1841 pub fn name_str(self) -> &'static str {
1843 FloatTy::F32 => "f32",
1844 FloatTy::F64 => "f64",
1848 pub fn name(self) -> Symbol {
1850 FloatTy::F32 => sym::f32,
1851 FloatTy::F64 => sym::f64,
1856 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1857 #[derive(Encodable, Decodable, HashStable_Generic)]
1868 pub fn name_str(&self) -> &'static str {
1870 IntTy::Isize => "isize",
1872 IntTy::I16 => "i16",
1873 IntTy::I32 => "i32",
1874 IntTy::I64 => "i64",
1875 IntTy::I128 => "i128",
1879 pub fn name(&self) -> Symbol {
1881 IntTy::Isize => sym::isize,
1882 IntTy::I8 => sym::i8,
1883 IntTy::I16 => sym::i16,
1884 IntTy::I32 => sym::i32,
1885 IntTy::I64 => sym::i64,
1886 IntTy::I128 => sym::i128,
1891 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1892 #[derive(Encodable, Decodable, HashStable_Generic)]
1903 pub fn name_str(&self) -> &'static str {
1905 UintTy::Usize => "usize",
1907 UintTy::U16 => "u16",
1908 UintTy::U32 => "u32",
1909 UintTy::U64 => "u64",
1910 UintTy::U128 => "u128",
1914 pub fn name(&self) -> Symbol {
1916 UintTy::Usize => sym::usize,
1917 UintTy::U8 => sym::u8,
1918 UintTy::U16 => sym::u16,
1919 UintTy::U32 => sym::u32,
1920 UintTy::U64 => sym::u64,
1921 UintTy::U128 => sym::u128,
1926 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1927 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1928 #[derive(Clone, Encodable, Decodable, Debug)]
1929 pub struct AssocConstraint {
1932 pub gen_args: Option<GenericArgs>,
1933 pub kind: AssocConstraintKind,
1937 /// The kinds of an `AssocConstraint`.
1938 #[derive(Clone, Encodable, Decodable, Debug)]
1944 impl From<P<Ty>> for Term {
1945 fn from(v: P<Ty>) -> Self {
1950 impl From<AnonConst> for Term {
1951 fn from(v: AnonConst) -> Self {
1956 /// The kinds of an `AssocConstraint`.
1957 #[derive(Clone, Encodable, Decodable, Debug)]
1958 pub enum AssocConstraintKind {
1959 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1960 Equality { term: Term },
1961 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1962 Bound { bounds: GenericBounds },
1965 #[derive(Encodable, Decodable, Debug)]
1970 pub tokens: Option<LazyTokenStream>,
1974 fn clone(&self) -> Self {
1975 ensure_sufficient_stack(|| Self {
1977 kind: self.kind.clone(),
1979 tokens: self.tokens.clone(),
1985 pub fn peel_refs(&self) -> &Self {
1986 let mut final_ty = self;
1987 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1994 #[derive(Clone, Encodable, Decodable, Debug)]
1995 pub struct BareFnTy {
1996 pub unsafety: Unsafe,
1998 pub generic_params: Vec<GenericParam>,
1999 pub decl: P<FnDecl>,
2000 /// Span of the `fn(...) -> ...` part.
2001 pub decl_span: Span,
2004 /// The various kinds of type recognized by the compiler.
2005 #[derive(Clone, Encodable, Decodable, Debug)]
2007 /// A variable-length slice (`[T]`).
2009 /// A fixed length array (`[T; n]`).
2010 Array(P<Ty>, AnonConst),
2011 /// A raw pointer (`*const T` or `*mut T`).
2013 /// A reference (`&'a T` or `&'a mut T`).
2014 Rptr(Option<Lifetime>, MutTy),
2015 /// A bare function (e.g., `fn(usize) -> bool`).
2016 BareFn(P<BareFnTy>),
2017 /// The never type (`!`).
2019 /// A tuple (`(A, B, C, D,...)`).
2021 /// A path (`module::module::...::Type`), optionally
2022 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2024 /// Type parameters are stored in the `Path` itself.
2025 Path(Option<QSelf>, Path),
2026 /// A trait object type `Bound1 + Bound2 + Bound3`
2027 /// where `Bound` is a trait or a lifetime.
2028 TraitObject(GenericBounds, TraitObjectSyntax),
2029 /// An `impl Bound1 + Bound2 + Bound3` type
2030 /// where `Bound` is a trait or a lifetime.
2032 /// The `NodeId` exists to prevent lowering from having to
2033 /// generate `NodeId`s on the fly, which would complicate
2034 /// the generation of opaque `type Foo = impl Trait` items significantly.
2035 ImplTrait(NodeId, GenericBounds),
2036 /// No-op; kept solely so that we can pretty-print faithfully.
2040 /// This means the type should be inferred instead of it having been
2041 /// specified. This can appear anywhere in a type.
2043 /// Inferred type of a `self` or `&self` argument in a method.
2045 /// A macro in the type position.
2046 MacCall(P<MacCall>),
2047 /// Placeholder for a kind that has failed to be defined.
2049 /// Placeholder for a `va_list`.
2054 pub fn is_implicit_self(&self) -> bool {
2055 matches!(self, TyKind::ImplicitSelf)
2058 pub fn is_unit(&self) -> bool {
2059 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2062 pub fn is_simple_path(&self) -> Option<Symbol> {
2063 if let TyKind::Path(None, Path { segments, .. }) = &self && segments.len() == 1 {
2064 Some(segments[0].ident.name)
2071 /// Syntax used to declare a trait object.
2072 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2073 pub enum TraitObjectSyntax {
2078 /// Inline assembly operand explicit register or register class.
2080 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2081 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2082 pub enum InlineAsmRegOrRegClass {
2087 bitflags::bitflags! {
2088 #[derive(Encodable, Decodable, HashStable_Generic)]
2089 pub struct InlineAsmOptions: u16 {
2090 const PURE = 1 << 0;
2091 const NOMEM = 1 << 1;
2092 const READONLY = 1 << 2;
2093 const PRESERVES_FLAGS = 1 << 3;
2094 const NORETURN = 1 << 4;
2095 const NOSTACK = 1 << 5;
2096 const ATT_SYNTAX = 1 << 6;
2098 const MAY_UNWIND = 1 << 8;
2102 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2103 pub enum InlineAsmTemplatePiece {
2105 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2108 impl fmt::Display for InlineAsmTemplatePiece {
2109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2111 Self::String(s) => {
2112 for c in s.chars() {
2114 '{' => f.write_str("{{")?,
2115 '}' => f.write_str("}}")?,
2121 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2122 write!(f, "{{{}:{}}}", operand_idx, modifier)
2124 Self::Placeholder { operand_idx, modifier: None, .. } => {
2125 write!(f, "{{{}}}", operand_idx)
2131 impl InlineAsmTemplatePiece {
2132 /// Rebuilds the asm template string from its pieces.
2133 pub fn to_string(s: &[Self]) -> String {
2135 let mut out = String::new();
2137 let _ = write!(out, "{}", p);
2143 /// Inline assembly symbol operands get their own AST node that is somewhat
2144 /// similar to `AnonConst`.
2146 /// The main difference is that we specifically don't assign it `DefId` in
2147 /// `DefCollector`. Instead this is deferred until AST lowering where we
2148 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2149 /// depending on what the path resolves to.
2150 #[derive(Clone, Encodable, Decodable, Debug)]
2151 pub struct InlineAsmSym {
2153 pub qself: Option<QSelf>,
2157 /// Inline assembly operand.
2159 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2160 #[derive(Clone, Encodable, Decodable, Debug)]
2161 pub enum InlineAsmOperand {
2163 reg: InlineAsmRegOrRegClass,
2167 reg: InlineAsmRegOrRegClass,
2169 expr: Option<P<Expr>>,
2172 reg: InlineAsmRegOrRegClass,
2177 reg: InlineAsmRegOrRegClass,
2180 out_expr: Option<P<Expr>>,
2183 anon_const: AnonConst,
2190 /// Inline assembly.
2192 /// E.g., `asm!("NOP");`.
2193 #[derive(Clone, Encodable, Decodable, Debug)]
2194 pub struct InlineAsm {
2195 pub template: Vec<InlineAsmTemplatePiece>,
2196 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2197 pub operands: Vec<(InlineAsmOperand, Span)>,
2198 pub clobber_abis: Vec<(Symbol, Span)>,
2199 pub options: InlineAsmOptions,
2200 pub line_spans: Vec<Span>,
2203 /// A parameter in a function header.
2205 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2206 #[derive(Clone, Encodable, Decodable, Debug)]
2213 pub is_placeholder: bool,
2216 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2218 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2219 #[derive(Clone, Encodable, Decodable, Debug)]
2221 /// `self`, `mut self`
2223 /// `&'lt self`, `&'lt mut self`
2224 Region(Option<Lifetime>, Mutability),
2225 /// `self: TYPE`, `mut self: TYPE`
2226 Explicit(P<Ty>, Mutability),
2229 pub type ExplicitSelf = Spanned<SelfKind>;
2232 /// Attempts to cast parameter to `ExplicitSelf`.
2233 pub fn to_self(&self) -> Option<ExplicitSelf> {
2234 if let PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), ident, _) = self.pat.kind {
2235 if ident.name == kw::SelfLower {
2236 return match self.ty.kind {
2237 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2238 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2239 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2242 self.pat.span.to(self.ty.span),
2243 SelfKind::Explicit(self.ty.clone(), mutbl),
2251 /// Returns `true` if parameter is `self`.
2252 pub fn is_self(&self) -> bool {
2253 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2254 ident.name == kw::SelfLower
2260 /// Builds a `Param` object from `ExplicitSelf`.
2261 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2262 let span = eself.span.to(eself_ident.span);
2263 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2264 let (mutbl, ty) = match eself.node {
2265 SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2266 SelfKind::Value(mutbl) => (mutbl, infer_ty),
2267 SelfKind::Region(lt, mutbl) => (
2271 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2281 kind: PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), eself_ident, None),
2288 is_placeholder: false,
2293 /// A signature (not the body) of a function declaration.
2295 /// E.g., `fn foo(bar: baz)`.
2297 /// Please note that it's different from `FnHeader` structure
2298 /// which contains metadata about function safety, asyncness, constness and ABI.
2299 #[derive(Clone, Encodable, Decodable, Debug)]
2301 pub inputs: Vec<Param>,
2302 pub output: FnRetTy,
2306 pub fn has_self(&self) -> bool {
2307 self.inputs.get(0).map_or(false, Param::is_self)
2309 pub fn c_variadic(&self) -> bool {
2310 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2314 /// Is the trait definition an auto trait?
2315 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2321 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2322 #[derive(HashStable_Generic)]
2328 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2330 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2335 pub fn is_async(self) -> bool {
2336 matches!(self, Async::Yes { .. })
2339 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2340 pub fn opt_return_id(self) -> Option<(NodeId, Span)> {
2342 Async::Yes { return_impl_trait_id, span, .. } => Some((return_impl_trait_id, span)),
2348 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2349 #[derive(HashStable_Generic)]
2355 /// Item defaultness.
2356 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2357 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2358 pub enum Defaultness {
2363 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2364 pub enum ImplPolarity {
2365 /// `impl Trait for Type`
2367 /// `impl !Trait for Type`
2371 impl fmt::Debug for ImplPolarity {
2372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2374 ImplPolarity::Positive => "positive".fmt(f),
2375 ImplPolarity::Negative(_) => "negative".fmt(f),
2380 #[derive(Clone, Encodable, Decodable, Debug)]
2382 /// Returns type is not specified.
2384 /// Functions default to `()` and closures default to inference.
2385 /// Span points to where return type would be inserted.
2387 /// Everything else.
2392 pub fn span(&self) -> Span {
2394 FnRetTy::Default(span) => span,
2395 FnRetTy::Ty(ref ty) => ty.span,
2400 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2406 /// Module item kind.
2407 #[derive(Clone, Encodable, Decodable, Debug)]
2409 /// Module with inlined definition `mod foo { ... }`,
2410 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2411 /// The inner span is from the first token past `{` to the last token until `}`,
2412 /// or from the first to the last token in the loaded file.
2413 Loaded(Vec<P<Item>>, Inline, ModSpans),
2414 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2418 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2419 pub struct ModSpans {
2420 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2421 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2422 pub inner_span: Span,
2423 pub inject_use_span: Span,
2426 impl Default for ModSpans {
2427 fn default() -> ModSpans {
2428 ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2432 /// Foreign module declaration.
2434 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2435 #[derive(Clone, Encodable, Decodable, Debug)]
2436 pub struct ForeignMod {
2437 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2438 /// semantically by Rust.
2439 pub unsafety: Unsafe,
2440 pub abi: Option<StrLit>,
2441 pub items: Vec<P<ForeignItem>>,
2444 #[derive(Clone, Encodable, Decodable, Debug)]
2445 pub struct EnumDef {
2446 pub variants: Vec<Variant>,
2449 #[derive(Clone, Encodable, Decodable, Debug)]
2450 pub struct Variant {
2451 /// Attributes of the variant.
2453 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2457 /// The visibility of the variant. Syntactically accepted but not semantically.
2458 pub vis: Visibility,
2459 /// Name of the variant.
2462 /// Fields and constructor id of the variant.
2463 pub data: VariantData,
2464 /// Explicit discriminant, e.g., `Foo = 1`.
2465 pub disr_expr: Option<AnonConst>,
2466 /// Is a macro placeholder
2467 pub is_placeholder: bool,
2470 /// Part of `use` item to the right of its prefix.
2471 #[derive(Clone, Encodable, Decodable, Debug)]
2472 pub enum UseTreeKind {
2473 /// `use prefix` or `use prefix as rename`
2475 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2477 Simple(Option<Ident>, NodeId, NodeId),
2478 /// `use prefix::{...}`
2479 Nested(Vec<(UseTree, NodeId)>),
2484 /// A tree of paths sharing common prefixes.
2485 /// Used in `use` items both at top-level and inside of braces in import groups.
2486 #[derive(Clone, Encodable, Decodable, Debug)]
2487 pub struct UseTree {
2489 pub kind: UseTreeKind,
2494 pub fn ident(&self) -> Ident {
2496 UseTreeKind::Simple(Some(rename), ..) => rename,
2497 UseTreeKind::Simple(None, ..) => {
2498 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2500 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2505 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2506 /// are contained as statements within items. These two cases need to be
2507 /// distinguished for pretty-printing.
2508 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2509 pub enum AttrStyle {
2514 rustc_index::newtype_index! {
2517 DEBUG_FORMAT = "AttrId({})"
2521 impl<S: Encoder> Encodable<S> for AttrId {
2522 fn encode(&self, _s: &mut S) {}
2525 impl<D: Decoder> Decodable<D> for AttrId {
2526 fn decode(_: &mut D) -> AttrId {
2527 crate::attr::mk_attr_id()
2531 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2532 pub struct AttrItem {
2535 pub tokens: Option<LazyTokenStream>,
2538 /// A list of attributes.
2539 pub type AttrVec = ThinVec<Attribute>;
2541 /// Metadata associated with an item.
2542 #[derive(Clone, Encodable, Decodable, Debug)]
2543 pub struct Attribute {
2546 /// Denotes if the attribute decorates the following construct (outer)
2547 /// or the construct this attribute is contained within (inner).
2548 pub style: AttrStyle,
2552 #[derive(Clone, Encodable, Decodable, Debug)]
2553 pub struct NormalAttr {
2555 pub tokens: Option<LazyTokenStream>,
2558 #[derive(Clone, Encodable, Decodable, Debug)]
2560 /// A normal attribute.
2561 Normal(P<NormalAttr>),
2563 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2564 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2565 /// variant (which is much less compact and thus more expensive).
2566 DocComment(CommentKind, Symbol),
2569 /// `TraitRef`s appear in impls.
2571 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2572 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2573 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2574 /// same as the impl's `NodeId`).
2575 #[derive(Clone, Encodable, Decodable, Debug)]
2576 pub struct TraitRef {
2581 #[derive(Clone, Encodable, Decodable, Debug)]
2582 pub struct PolyTraitRef {
2583 /// The `'a` in `for<'a> Foo<&'a T>`.
2584 pub bound_generic_params: Vec<GenericParam>,
2586 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2587 pub trait_ref: TraitRef,
2593 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2595 bound_generic_params: generic_params,
2596 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2602 #[derive(Clone, Encodable, Decodable, Debug)]
2603 pub struct Visibility {
2604 pub kind: VisibilityKind,
2606 pub tokens: Option<LazyTokenStream>,
2609 #[derive(Clone, Encodable, Decodable, Debug)]
2610 pub enum VisibilityKind {
2612 Restricted { path: P<Path>, id: NodeId, shorthand: bool },
2616 impl VisibilityKind {
2617 pub fn is_pub(&self) -> bool {
2618 matches!(self, VisibilityKind::Public)
2622 /// Field definition in a struct, variant or union.
2624 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2625 #[derive(Clone, Encodable, Decodable, Debug)]
2626 pub struct FieldDef {
2630 pub vis: Visibility,
2631 pub ident: Option<Ident>,
2634 pub is_placeholder: bool,
2637 /// Fields and constructor ids of enum variants and structs.
2638 #[derive(Clone, Encodable, Decodable, Debug)]
2639 pub enum VariantData {
2642 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2643 Struct(Vec<FieldDef>, bool),
2646 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2647 Tuple(Vec<FieldDef>, NodeId),
2650 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2655 /// Return the fields of this variant.
2656 pub fn fields(&self) -> &[FieldDef] {
2658 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2663 /// Return the `NodeId` of this variant's constructor, if it has one.
2664 pub fn ctor_id(&self) -> Option<NodeId> {
2666 VariantData::Struct(..) => None,
2667 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2672 /// An item definition.
2673 #[derive(Clone, Encodable, Decodable, Debug)]
2674 pub struct Item<K = ItemKind> {
2678 pub vis: Visibility,
2679 /// The name of the item.
2680 /// It might be a dummy name in case of anonymous items.
2685 /// Original tokens this item was parsed from. This isn't necessarily
2686 /// available for all items, although over time more and more items should
2687 /// have this be `Some`. Right now this is primarily used for procedural
2688 /// macros, notably custom attributes.
2690 /// Note that the tokens here do not include the outer attributes, but will
2691 /// include inner attributes.
2692 pub tokens: Option<LazyTokenStream>,
2696 /// Return the span that encompasses the attributes.
2697 pub fn span_with_attributes(&self) -> Span {
2698 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2702 /// `extern` qualifier on a function item or function type.
2703 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2707 Explicit(StrLit, Span),
2711 pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2713 Some(name) => Extern::Explicit(name, span),
2714 None => Extern::Implicit(span),
2719 /// A function header.
2721 /// All the information between the visibility and the name of the function is
2722 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2723 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2724 pub struct FnHeader {
2725 pub unsafety: Unsafe,
2726 pub asyncness: Async,
2727 pub constness: Const,
2732 /// Does this function header have any qualifiers or is it empty?
2733 pub fn has_qualifiers(&self) -> bool {
2734 let Self { unsafety, asyncness, constness, ext } = self;
2735 matches!(unsafety, Unsafe::Yes(_))
2736 || asyncness.is_async()
2737 || matches!(constness, Const::Yes(_))
2738 || !matches!(ext, Extern::None)
2742 impl Default for FnHeader {
2743 fn default() -> FnHeader {
2745 unsafety: Unsafe::No,
2746 asyncness: Async::No,
2747 constness: Const::No,
2753 #[derive(Clone, Encodable, Decodable, Debug)]
2755 pub unsafety: Unsafe,
2756 pub is_auto: IsAuto,
2757 pub generics: Generics,
2758 pub bounds: GenericBounds,
2759 pub items: Vec<P<AssocItem>>,
2762 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2763 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2764 /// are two locations for where clause on type aliases, but their predicates
2765 /// are concatenated together.
2767 /// Take this example:
2768 /// ```ignore (only-for-syntax-highlight)
2770 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2772 /// impl Foo for () {
2773 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2774 /// // ^^^^^^^^^^^^^^ first where clause
2775 /// // ^^^^^^^^^^^^^^ second where clause
2779 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2780 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2781 pub struct TyAliasWhereClause(pub bool, pub Span);
2783 #[derive(Clone, Encodable, Decodable, Debug)]
2784 pub struct TyAlias {
2785 pub defaultness: Defaultness,
2786 pub generics: Generics,
2787 /// The span information for the two where clauses (before equals, after equals)
2788 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2789 /// The index in `generics.where_clause.predicates` that would split into
2790 /// predicates from the where clause before the equals and the predicates
2791 /// from the where clause after the equals
2792 pub where_predicates_split: usize,
2793 pub bounds: GenericBounds,
2794 pub ty: Option<P<Ty>>,
2797 #[derive(Clone, Encodable, Decodable, Debug)]
2799 pub defaultness: Defaultness,
2800 pub unsafety: Unsafe,
2801 pub generics: Generics,
2802 pub constness: Const,
2803 pub polarity: ImplPolarity,
2804 /// The trait being implemented, if any.
2805 pub of_trait: Option<TraitRef>,
2807 pub items: Vec<P<AssocItem>>,
2810 #[derive(Clone, Encodable, Decodable, Debug)]
2812 pub defaultness: Defaultness,
2813 pub generics: Generics,
2815 pub body: Option<P<Block>>,
2818 #[derive(Clone, Encodable, Decodable, Debug)]
2820 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2822 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2823 ExternCrate(Option<Symbol>),
2824 /// A use declaration item (`use`).
2826 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2828 /// A static item (`static`).
2830 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2831 Static(P<Ty>, Mutability, Option<P<Expr>>),
2832 /// A constant item (`const`).
2834 /// E.g., `const FOO: i32 = 42;`.
2835 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2836 /// A function declaration (`fn`).
2838 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2840 /// A module declaration (`mod`).
2842 /// E.g., `mod foo;` or `mod foo { .. }`.
2843 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2844 /// semantically by Rust.
2845 Mod(Unsafe, ModKind),
2846 /// An external module (`extern`).
2848 /// E.g., `extern {}` or `extern "C" {}`.
2849 ForeignMod(ForeignMod),
2850 /// Module-level inline assembly (from `global_asm!()`).
2851 GlobalAsm(Box<InlineAsm>),
2852 /// A type alias (`type`).
2854 /// E.g., `type Foo = Bar<u8>;`.
2855 TyAlias(Box<TyAlias>),
2856 /// An enum definition (`enum`).
2858 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2859 Enum(EnumDef, Generics),
2860 /// A struct definition (`struct`).
2862 /// E.g., `struct Foo<A> { x: A }`.
2863 Struct(VariantData, Generics),
2864 /// A union definition (`union`).
2866 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2867 Union(VariantData, Generics),
2868 /// A trait declaration (`trait`).
2870 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2874 /// E.g., `trait Foo = Bar + Quux;`.
2875 TraitAlias(Generics, GenericBounds),
2876 /// An implementation.
2878 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2880 /// A macro invocation.
2882 /// E.g., `foo!(..)`.
2883 MacCall(P<MacCall>),
2885 /// A macro definition.
2890 pub fn article(&self) -> &str {
2893 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2894 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2895 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2899 pub fn descr(&self) -> &str {
2901 ItemKind::ExternCrate(..) => "extern crate",
2902 ItemKind::Use(..) => "`use` import",
2903 ItemKind::Static(..) => "static item",
2904 ItemKind::Const(..) => "constant item",
2905 ItemKind::Fn(..) => "function",
2906 ItemKind::Mod(..) => "module",
2907 ItemKind::ForeignMod(..) => "extern block",
2908 ItemKind::GlobalAsm(..) => "global asm item",
2909 ItemKind::TyAlias(..) => "type alias",
2910 ItemKind::Enum(..) => "enum",
2911 ItemKind::Struct(..) => "struct",
2912 ItemKind::Union(..) => "union",
2913 ItemKind::Trait(..) => "trait",
2914 ItemKind::TraitAlias(..) => "trait alias",
2915 ItemKind::MacCall(..) => "item macro invocation",
2916 ItemKind::MacroDef(..) => "macro definition",
2917 ItemKind::Impl { .. } => "implementation",
2921 pub fn generics(&self) -> Option<&Generics> {
2923 Self::Fn(box Fn { generics, .. })
2924 | Self::TyAlias(box TyAlias { generics, .. })
2925 | Self::Enum(_, generics)
2926 | Self::Struct(_, generics)
2927 | Self::Union(_, generics)
2928 | Self::Trait(box Trait { generics, .. })
2929 | Self::TraitAlias(generics, _)
2930 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2936 /// Represents associated items.
2937 /// These include items in `impl` and `trait` definitions.
2938 pub type AssocItem = Item<AssocItemKind>;
2940 /// Represents associated item kinds.
2942 /// The term "provided" in the variants below refers to the item having a default
2943 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2944 /// In an implementation, all items must be provided.
2945 /// The `Option`s below denote the bodies, where `Some(_)`
2946 /// means "provided" and conversely `None` means "required".
2947 #[derive(Clone, Encodable, Decodable, Debug)]
2948 pub enum AssocItemKind {
2949 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2950 /// If `def` is parsed, then the constant is provided, and otherwise required.
2951 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2952 /// An associated function.
2954 /// An associated type.
2955 TyAlias(Box<TyAlias>),
2956 /// A macro expanding to associated items.
2957 MacCall(P<MacCall>),
2960 impl AssocItemKind {
2961 pub fn defaultness(&self) -> Defaultness {
2963 Self::Const(defaultness, ..)
2964 | Self::Fn(box Fn { defaultness, .. })
2965 | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness,
2966 Self::MacCall(..) => Defaultness::Final,
2971 impl From<AssocItemKind> for ItemKind {
2972 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2973 match assoc_item_kind {
2974 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2975 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2976 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2977 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2982 impl TryFrom<ItemKind> for AssocItemKind {
2983 type Error = ItemKind;
2985 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2986 Ok(match item_kind {
2987 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2988 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2989 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2990 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2991 _ => return Err(item_kind),
2996 /// An item in `extern` block.
2997 #[derive(Clone, Encodable, Decodable, Debug)]
2998 pub enum ForeignItemKind {
2999 /// A foreign static item (`static FOO: u8`).
3000 Static(P<Ty>, Mutability, Option<P<Expr>>),
3001 /// An foreign function.
3003 /// An foreign type.
3004 TyAlias(Box<TyAlias>),
3005 /// A macro expanding to foreign items.
3006 MacCall(P<MacCall>),
3009 impl From<ForeignItemKind> for ItemKind {
3010 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3011 match foreign_item_kind {
3012 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3013 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3014 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3015 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3020 impl TryFrom<ItemKind> for ForeignItemKind {
3021 type Error = ItemKind;
3023 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3024 Ok(match item_kind {
3025 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3026 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3027 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3028 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3029 _ => return Err(item_kind),
3034 pub type ForeignItem = Item<ForeignItemKind>;
3036 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3037 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3040 use rustc_data_structures::static_assert_size;
3041 // These are in alphabetical order, which is easy to maintain.
3042 static_assert_size!(AssocItem, 104);
3043 static_assert_size!(AssocItemKind, 32);
3044 static_assert_size!(Attribute, 32);
3045 static_assert_size!(Block, 48);
3046 static_assert_size!(Expr, 104);
3047 static_assert_size!(ExprKind, 72);
3048 #[cfg(not(bootstrap))]
3049 static_assert_size!(Fn, 184);
3050 static_assert_size!(ForeignItem, 96);
3051 static_assert_size!(ForeignItemKind, 24);
3052 static_assert_size!(GenericArg, 24);
3053 static_assert_size!(GenericBound, 88);
3054 static_assert_size!(Generics, 72);
3055 static_assert_size!(Impl, 200);
3056 static_assert_size!(Item, 184);
3057 static_assert_size!(ItemKind, 112);
3058 static_assert_size!(Lit, 48);
3059 static_assert_size!(LitKind, 24);
3060 static_assert_size!(Local, 72);
3061 static_assert_size!(Param, 40);
3062 static_assert_size!(Pat, 120);
3063 static_assert_size!(PatKind, 96);
3064 static_assert_size!(Path, 40);
3065 static_assert_size!(PathSegment, 24);
3066 static_assert_size!(Stmt, 32);
3067 static_assert_size!(StmtKind, 16);
3068 static_assert_size!(Ty, 96);
3069 static_assert_size!(TyKind, 72);