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, LazyAttrTokenStream, TokenStream};
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_data_structures::stack::ensure_sufficient_stack;
30 use rustc_data_structures::sync::Lrc;
31 use rustc_macros::HashStable_Generic;
32 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
33 use rustc_span::source_map::{respan, Spanned};
34 use rustc_span::symbol::{kw, sym, Ident, Symbol};
35 use rustc_span::{Span, DUMMY_SP};
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<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
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 {
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 /// Possible values inside of compile-time attribute lists.
484 /// E.g., the '..' in `#[name(..)]`.
485 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
486 pub enum NestedMetaItem {
487 /// A full MetaItem, for recursive meta items.
491 /// E.g., `"foo"`, `64`, `true`.
495 /// A spanned compile-time attribute item.
497 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
498 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
499 pub struct MetaItem {
501 pub kind: MetaItemKind,
505 /// A compile-time attribute item.
507 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
508 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
509 pub enum MetaItemKind {
512 /// E.g., `test` as in `#[test]`.
516 /// E.g., `derive(..)` as in `#[derive(..)]`.
517 List(Vec<NestedMetaItem>),
518 /// Name value meta item.
520 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
524 /// A block (`{ .. }`).
526 /// E.g., `{ .. }` as in `fn foo() { .. }`.
527 #[derive(Clone, Encodable, Decodable, Debug)]
529 /// The statements in the block.
530 pub stmts: Vec<Stmt>,
532 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
533 pub rules: BlockCheckMode,
535 pub tokens: Option<LazyAttrTokenStream>,
536 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
543 pub could_be_bare_literal: bool,
548 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
549 #[derive(Clone, Encodable, Decodable, Debug)]
554 pub tokens: Option<LazyAttrTokenStream>,
558 /// Attempt reparsing the pattern as a type.
559 /// This is intended for use by diagnostics.
560 pub fn to_ty(&self) -> Option<P<Ty>> {
561 let kind = match &self.kind {
562 // In a type expression `_` is an inference variable.
563 PatKind::Wild => TyKind::Infer,
564 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
565 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
566 TyKind::Path(None, Path::from_ident(*ident))
568 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
569 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
570 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
571 PatKind::Ref(pat, mutbl) => {
572 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
574 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
575 // when `P` can be reparsed as a type `T`.
576 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
577 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
578 // assuming `T0` to `Tn` are all syntactically valid as types.
579 PatKind::Tuple(pats) => {
580 let mut tys = Vec::with_capacity(pats.len());
581 // FIXME(#48994) - could just be collected into an Option<Vec>
583 tys.push(pat.to_ty()?);
590 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
593 /// Walk top-down and call `it` in each place where a pattern occurs
594 /// starting with the root pattern `walk` is called on. If `it` returns
595 /// false then we will descend no further but siblings will be processed.
596 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
602 // Walk into the pattern associated with `Ident` (if any).
603 PatKind::Ident(_, _, Some(p)) => p.walk(it),
605 // Walk into each field of struct.
606 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
608 // Sequence of patterns.
609 PatKind::TupleStruct(_, _, s)
612 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
614 // Trivial wrappers over inner patterns.
615 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
617 // These patterns do not contain subpatterns, skip.
624 | PatKind::MacCall(_) => {}
628 /// Is this a `..` pattern?
629 pub fn is_rest(&self) -> bool {
630 matches!(self.kind, PatKind::Rest)
634 /// A single field in a struct pattern.
636 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
637 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
638 /// except when `is_shorthand` is true.
639 #[derive(Clone, Encodable, Decodable, Debug)]
640 pub struct PatField {
641 /// The identifier for the field.
643 /// The pattern the field is destructured to.
645 pub is_shorthand: bool,
649 pub is_placeholder: bool,
652 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
653 #[derive(Encodable, Decodable, HashStable_Generic)]
659 impl From<bool> for ByRef {
660 fn from(b: bool) -> ByRef {
668 /// Explicit binding annotations given in the HIR for a binding. Note
669 /// that this is not the final binding *mode* that we infer after type
671 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
672 #[derive(Encodable, Decodable, HashStable_Generic)]
673 pub struct BindingAnnotation(pub ByRef, pub Mutability);
675 impl BindingAnnotation {
676 pub const NONE: Self = Self(ByRef::No, Mutability::Not);
677 pub const REF: Self = Self(ByRef::Yes, Mutability::Not);
678 pub const MUT: Self = Self(ByRef::No, Mutability::Mut);
679 pub const REF_MUT: Self = Self(ByRef::Yes, Mutability::Mut);
681 pub fn prefix_str(self) -> &'static str {
686 Self::REF_MUT => "ref mut ",
691 #[derive(Clone, Encodable, Decodable, Debug)]
694 Included(RangeSyntax),
699 #[derive(Clone, Encodable, Decodable, Debug)]
700 pub enum RangeSyntax {
707 /// All the different flavors of pattern that Rust recognizes.
708 #[derive(Clone, Encodable, Decodable, Debug)]
710 /// Represents a wildcard pattern (`_`).
713 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
714 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
715 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
716 /// during name resolution.
717 Ident(BindingAnnotation, Ident, Option<P<Pat>>),
719 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
720 /// The `bool` is `true` in the presence of a `..`.
721 Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool),
723 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
724 TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>),
726 /// An or-pattern `A | B | C`.
727 /// Invariant: `pats.len() >= 2`.
730 /// A possibly qualified path pattern.
731 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
732 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
733 /// only legally refer to associated constants.
734 Path(Option<QSelf>, Path),
736 /// A tuple pattern (`(a, b)`).
742 /// A reference pattern (e.g., `&mut (a, b)`).
743 Ref(P<Pat>, Mutability),
748 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
749 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
751 /// A slice pattern `[a, b, c]`.
754 /// A rest pattern `..`.
756 /// Syntactically it is valid anywhere.
758 /// Semantically however, it only has meaning immediately inside:
759 /// - a slice pattern: `[a, .., b]`,
760 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
761 /// - a tuple pattern: `(a, .., b)`,
762 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
764 /// In all of these cases, an additional restriction applies,
765 /// only one rest pattern may occur in the pattern sequences.
768 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
771 /// A macro pattern; pre-expansion.
775 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
776 #[derive(HashStable_Generic, Encodable, Decodable)]
777 pub enum Mutability {
783 pub fn invert(self) -> Self {
785 Mutability::Mut => Mutability::Not,
786 Mutability::Not => Mutability::Mut,
790 pub fn prefix_str(&self) -> &'static str {
792 Mutability::Mut => "mut ",
793 Mutability::Not => "",
798 /// The kind of borrow in an `AddrOf` expression,
799 /// e.g., `&place` or `&raw const place`.
800 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
801 #[derive(Encodable, Decodable, HashStable_Generic)]
802 pub enum BorrowKind {
803 /// A normal borrow, `&$expr` or `&mut $expr`.
804 /// The resulting type is either `&'a T` or `&'a mut T`
805 /// where `T = typeof($expr)` and `'a` is some lifetime.
807 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
808 /// The resulting type is either `*const T` or `*mut T`
809 /// where `T = typeof($expr)`.
813 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
815 /// The `+` operator (addition)
817 /// The `-` operator (subtraction)
819 /// The `*` operator (multiplication)
821 /// The `/` operator (division)
823 /// The `%` operator (modulus)
825 /// The `&&` operator (logical and)
827 /// The `||` operator (logical or)
829 /// The `^` operator (bitwise xor)
831 /// The `&` operator (bitwise and)
833 /// The `|` operator (bitwise or)
835 /// The `<<` operator (shift left)
837 /// The `>>` operator (shift right)
839 /// The `==` operator (equality)
841 /// The `<` operator (less than)
843 /// The `<=` operator (less than or equal to)
845 /// The `!=` operator (not equal to)
847 /// The `>=` operator (greater than or equal to)
849 /// The `>` operator (greater than)
854 pub fn to_string(&self) -> &'static str {
877 pub fn lazy(&self) -> bool {
878 matches!(self, BinOpKind::And | BinOpKind::Or)
881 pub fn is_comparison(&self) -> bool {
883 // Note for developers: please keep this as is;
884 // we want compilation to fail if another variant is added.
886 Eq | Lt | Le | Ne | Gt | Ge => true,
887 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
892 pub type BinOp = Spanned<BinOpKind>;
896 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
897 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
899 /// The `*` operator for dereferencing
901 /// The `!` operator for logical inversion
903 /// The `-` operator for negation
908 pub fn to_string(op: UnOp) -> &'static str {
918 #[derive(Clone, Encodable, Decodable, Debug)]
926 pub fn has_trailing_semicolon(&self) -> bool {
928 StmtKind::Semi(_) => true,
929 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
934 /// Converts a parsed `Stmt` to a `Stmt` with
935 /// a trailing semicolon.
937 /// This only modifies the parsed AST struct, not the attached
938 /// `LazyAttrTokenStream`. The parser is responsible for calling
939 /// `ToAttrTokenStream::add_trailing_semi` when there is actually
940 /// a semicolon in the tokenstream.
941 pub fn add_trailing_semicolon(mut self) -> Self {
942 self.kind = match self.kind {
943 StmtKind::Expr(expr) => StmtKind::Semi(expr),
944 StmtKind::MacCall(mac) => {
945 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
946 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
955 pub fn is_item(&self) -> bool {
956 matches!(self.kind, StmtKind::Item(_))
959 pub fn is_expr(&self) -> bool {
960 matches!(self.kind, StmtKind::Expr(_))
964 #[derive(Clone, Encodable, Decodable, Debug)]
966 /// A local (let) binding.
968 /// An item definition.
970 /// Expr without trailing semi-colon.
972 /// Expr with a trailing semi-colon.
974 /// Just a trailing semi-colon.
977 MacCall(P<MacCallStmt>),
980 #[derive(Clone, Encodable, Decodable, Debug)]
981 pub struct MacCallStmt {
983 pub style: MacStmtStyle,
985 pub tokens: Option<LazyAttrTokenStream>,
988 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
989 pub enum MacStmtStyle {
990 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
991 /// `foo!(...);`, `foo![...];`).
993 /// The macro statement had braces (e.g., `foo! { ... }`).
995 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
996 /// `foo!(...)`). All of these will end up being converted into macro
1001 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1002 #[derive(Clone, Encodable, Decodable, Debug)]
1006 pub ty: Option<P<Ty>>,
1007 pub kind: LocalKind,
1010 pub tokens: Option<LazyAttrTokenStream>,
1013 #[derive(Clone, Encodable, Decodable, Debug)]
1014 pub enum LocalKind {
1015 /// Local declaration.
1016 /// Example: `let x;`
1018 /// Local declaration with an initializer.
1019 /// Example: `let x = y;`
1021 /// Local declaration with an initializer and an `else` clause.
1022 /// Example: `let Some(x) = y else { return };`
1023 InitElse(P<Expr>, P<Block>),
1027 pub fn init(&self) -> Option<&Expr> {
1030 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1034 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1037 Self::Init(init) => Some((init, None)),
1038 Self::InitElse(init, els) => Some((init, Some(els))),
1043 /// An arm of a 'match'.
1045 /// E.g., `0..=10 => { println!("match!") }` as in
1049 /// 0..=10 => { println!("match!") },
1050 /// _ => { println!("no match!") },
1053 #[derive(Clone, Encodable, Decodable, Debug)]
1056 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1058 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1059 pub guard: Option<P<Expr>>,
1064 pub is_placeholder: bool,
1067 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1068 #[derive(Clone, Encodable, Decodable, Debug)]
1069 pub struct ExprField {
1075 pub is_shorthand: bool,
1076 pub is_placeholder: bool,
1079 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1080 pub enum BlockCheckMode {
1082 Unsafe(UnsafeSource),
1085 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1086 pub enum UnsafeSource {
1091 /// A constant (expression) that's not an item or associated item,
1092 /// but needs its own `DefId` for type-checking, const-eval, etc.
1093 /// These are usually found nested inside types (e.g., array lengths)
1094 /// or expressions (e.g., repeat counts), and also used to define
1095 /// explicit discriminant values for enum variants.
1096 #[derive(Clone, Encodable, Decodable, Debug)]
1097 pub struct AnonConst {
1103 #[derive(Clone, Encodable, Decodable, Debug)]
1109 pub tokens: Option<LazyAttrTokenStream>,
1113 /// Is this expr either `N`, or `{ N }`.
1115 /// If this is not the case, name resolution does not resolve `N` when using
1116 /// `min_const_generics` as more complex expressions are not supported.
1117 pub fn is_potential_trivial_const_param(&self) -> bool {
1118 let this = if let ExprKind::Block(ref block, None) = self.kind {
1119 if block.stmts.len() == 1 {
1120 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1128 if let ExprKind::Path(None, ref path) = this.kind {
1129 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1137 pub fn to_bound(&self) -> Option<GenericBound> {
1139 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1140 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1141 TraitBoundModifier::None,
1147 pub fn peel_parens(&self) -> &Expr {
1148 let mut expr = self;
1149 while let ExprKind::Paren(inner) = &expr.kind {
1155 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1156 pub fn to_ty(&self) -> Option<P<Ty>> {
1157 let kind = match &self.kind {
1158 // Trivial conversions.
1159 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1160 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1162 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1164 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1165 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1168 ExprKind::Repeat(expr, expr_len) => {
1169 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1172 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1174 ExprKind::Tup(exprs) => {
1175 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1179 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1180 // then type of result is trait object.
1181 // Otherwise we don't assume the result type.
1182 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1183 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1184 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1190 ExprKind::Underscore => TyKind::Infer,
1192 // This expression doesn't look like a type syntactically.
1196 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1199 pub fn precedence(&self) -> ExprPrecedence {
1201 ExprKind::Box(_) => ExprPrecedence::Box,
1202 ExprKind::Array(_) => ExprPrecedence::Array,
1203 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1204 ExprKind::Call(..) => ExprPrecedence::Call,
1205 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1206 ExprKind::Tup(_) => ExprPrecedence::Tup,
1207 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1208 ExprKind::Unary(..) => ExprPrecedence::Unary,
1209 ExprKind::Lit(_) | ExprKind::IncludedBytes(..) => ExprPrecedence::Lit,
1210 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1211 ExprKind::Let(..) => ExprPrecedence::Let,
1212 ExprKind::If(..) => ExprPrecedence::If,
1213 ExprKind::While(..) => ExprPrecedence::While,
1214 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1215 ExprKind::Loop(..) => ExprPrecedence::Loop,
1216 ExprKind::Match(..) => ExprPrecedence::Match,
1217 ExprKind::Closure(..) => ExprPrecedence::Closure,
1218 ExprKind::Block(..) => ExprPrecedence::Block,
1219 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1220 ExprKind::Async(..) => ExprPrecedence::Async,
1221 ExprKind::Await(..) => ExprPrecedence::Await,
1222 ExprKind::Assign(..) => ExprPrecedence::Assign,
1223 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1224 ExprKind::Field(..) => ExprPrecedence::Field,
1225 ExprKind::Index(..) => ExprPrecedence::Index,
1226 ExprKind::Range(..) => ExprPrecedence::Range,
1227 ExprKind::Underscore => ExprPrecedence::Path,
1228 ExprKind::Path(..) => ExprPrecedence::Path,
1229 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1230 ExprKind::Break(..) => ExprPrecedence::Break,
1231 ExprKind::Continue(..) => ExprPrecedence::Continue,
1232 ExprKind::Ret(..) => ExprPrecedence::Ret,
1233 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1234 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1235 ExprKind::Struct(..) => ExprPrecedence::Struct,
1236 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1237 ExprKind::Paren(..) => ExprPrecedence::Paren,
1238 ExprKind::Try(..) => ExprPrecedence::Try,
1239 ExprKind::Yield(..) => ExprPrecedence::Yield,
1240 ExprKind::Yeet(..) => ExprPrecedence::Yeet,
1241 ExprKind::Err => ExprPrecedence::Err,
1245 pub fn take(&mut self) -> Self {
1250 kind: ExprKind::Err,
1252 attrs: AttrVec::new(),
1258 // To a first-order approximation, is this a pattern
1259 pub fn is_approximately_pattern(&self) -> bool {
1260 match &self.peel_parens().kind {
1262 | ExprKind::Array(_)
1263 | ExprKind::Call(_, _)
1266 | ExprKind::Range(_, _, _)
1267 | ExprKind::Underscore
1268 | ExprKind::Path(_, _)
1269 | ExprKind::Struct(_) => true,
1275 /// Limit types of a range (inclusive or exclusive)
1276 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1277 pub enum RangeLimits {
1278 /// Inclusive at the beginning, exclusive at the end
1280 /// Inclusive at the beginning and end
1284 #[derive(Clone, Encodable, Decodable, Debug)]
1285 pub enum StructRest {
1290 /// No trailing `..` or expression.
1294 #[derive(Clone, Encodable, Decodable, Debug)]
1295 pub struct StructExpr {
1296 pub qself: Option<QSelf>,
1298 pub fields: Vec<ExprField>,
1299 pub rest: StructRest,
1302 #[derive(Clone, Encodable, Decodable, Debug)]
1304 /// A `box x` expression.
1306 /// An array (`[a, b, c, d]`)
1307 Array(Vec<P<Expr>>),
1308 /// Allow anonymous constants from an inline `const` block
1309 ConstBlock(AnonConst),
1312 /// The first field resolves to the function itself,
1313 /// and the second field is the list of arguments.
1314 /// This also represents calling the constructor of
1315 /// tuple-like ADTs such as tuple structs and enum variants.
1316 Call(P<Expr>, Vec<P<Expr>>),
1317 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1319 /// The `PathSegment` represents the method name and its generic arguments
1320 /// (within the angle brackets).
1321 /// The standalone `Expr` is the receiver expression.
1322 /// The vector of `Expr` is the arguments.
1323 /// `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1324 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d])`.
1325 /// This `Span` is the span of the function, without the dot and receiver
1326 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1327 MethodCall(PathSegment, P<Expr>, Vec<P<Expr>>, Span),
1328 /// A tuple (e.g., `(a, b, c, d)`).
1330 /// A binary operation (e.g., `a + b`, `a * b`).
1331 Binary(BinOp, P<Expr>, P<Expr>),
1332 /// A unary operation (e.g., `!x`, `*x`).
1333 Unary(UnOp, P<Expr>),
1334 /// A literal (e.g., `1`, `"foo"`).
1336 /// A cast (e.g., `foo as f64`).
1337 Cast(P<Expr>, P<Ty>),
1338 /// A type ascription (e.g., `42: usize`).
1339 Type(P<Expr>, P<Ty>),
1340 /// A `let pat = expr` expression that is only semantically allowed in the condition
1341 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1343 /// `Span` represents the whole `let pat = expr` statement.
1344 Let(P<Pat>, P<Expr>, Span),
1345 /// An `if` block, with an optional `else` block.
1347 /// `if expr { block } else { expr }`
1348 If(P<Expr>, P<Block>, Option<P<Expr>>),
1349 /// A while loop, with an optional label.
1351 /// `'label: while expr { block }`
1352 While(P<Expr>, P<Block>, Option<Label>),
1353 /// A `for` loop, with an optional label.
1355 /// `'label: for pat in expr { block }`
1357 /// This is desugared to a combination of `loop` and `match` expressions.
1358 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1359 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1361 /// `'label: loop { block }`
1362 Loop(P<Block>, Option<Label>),
1363 /// A `match` block.
1364 Match(P<Expr>, Vec<Arm>),
1365 /// A closure (e.g., `move |a, b, c| a + b + c`).
1367 /// The final span is the span of the argument block `|...|`.
1368 Closure(ClosureBinder, CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1369 /// A block (`'label: { ... }`).
1370 Block(P<Block>, Option<Label>),
1371 /// An async block (`async move { ... }`).
1373 /// The `NodeId` is the `NodeId` for the closure that results from
1374 /// desugaring an async block, just like the NodeId field in the
1375 /// `Async::Yes` variant. This is necessary in order to create a def for the
1376 /// closure which can be used as a parent of any child defs. Defs
1377 /// created during lowering cannot be made the parent of any other
1378 /// preexisting defs.
1379 Async(CaptureBy, NodeId, P<Block>),
1380 /// An await expression (`my_future.await`).
1383 /// A try block (`try { ... }`).
1386 /// An assignment (`a = foo()`).
1387 /// The `Span` argument is the span of the `=` token.
1388 Assign(P<Expr>, P<Expr>, Span),
1389 /// An assignment with an operator.
1392 AssignOp(BinOp, P<Expr>, P<Expr>),
1393 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1394 Field(P<Expr>, Ident),
1395 /// An indexing operation (e.g., `foo[2]`).
1396 Index(P<Expr>, P<Expr>),
1397 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1398 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1399 /// An underscore, used in destructuring assignment to ignore a value.
1402 /// Variable reference, possibly containing `::` and/or type
1403 /// parameters (e.g., `foo::bar::<baz>`).
1405 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1406 Path(Option<QSelf>, Path),
1408 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1409 AddrOf(BorrowKind, Mutability, P<Expr>),
1410 /// A `break`, with an optional label to break, and an optional expression.
1411 Break(Option<Label>, Option<P<Expr>>),
1412 /// A `continue`, with an optional label.
1413 Continue(Option<Label>),
1414 /// A `return`, with an optional value to be returned.
1415 Ret(Option<P<Expr>>),
1417 /// Output of the `asm!()` macro.
1418 InlineAsm(P<InlineAsm>),
1420 /// A macro invocation; pre-expansion.
1421 MacCall(P<MacCall>),
1423 /// A struct literal expression.
1425 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1426 Struct(P<StructExpr>),
1428 /// An array literal constructed from one repeated element.
1430 /// E.g., `[1; 5]`. The expression is the element to be
1431 /// repeated; the constant is the number of times to repeat it.
1432 Repeat(P<Expr>, AnonConst),
1434 /// No-op: used solely so we can pretty-print faithfully.
1437 /// A try expression (`expr?`).
1440 /// A `yield`, with an optional value to be yielded.
1441 Yield(Option<P<Expr>>),
1443 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1444 /// with an optional value to be returned.
1445 Yeet(Option<P<Expr>>),
1447 /// Bytes included via `include_bytes!`
1448 /// Added for optimization purposes to avoid the need to escape
1449 /// large binary blobs - should always behave like [`ExprKind::Lit`]
1450 /// with a `ByteStr` literal.
1451 IncludedBytes(Lrc<[u8]>),
1453 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1457 /// The explicit `Self` type in a "qualified path". The actual
1458 /// path, including the trait and the associated item, is stored
1459 /// separately. `position` represents the index of the associated
1460 /// item qualified with this `Self` type.
1462 /// ```ignore (only-for-syntax-highlight)
1463 /// <Vec<T> as a::b::Trait>::AssociatedItem
1464 /// ^~~~~ ~~~~~~~~~~~~~~^
1467 /// <Vec<T>>::AssociatedItem
1471 #[derive(Clone, Encodable, Decodable, Debug)]
1475 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1476 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1477 /// 0`, this is an empty span.
1478 pub path_span: Span,
1479 pub position: usize,
1482 /// A capture clause used in closures and `async` blocks.
1483 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1484 pub enum CaptureBy {
1485 /// `move |x| y + x`.
1487 /// `move` keyword was not specified.
1491 /// The movability of a generator / closure literal:
1492 /// whether a generator contains self-references, causing it to be `!Unpin`.
1493 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1494 #[derive(HashStable_Generic)]
1495 pub enum Movability {
1496 /// May contain self-references, `!Unpin`.
1498 /// Must not contain self-references, `Unpin`.
1502 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1503 #[derive(Clone, Encodable, Decodable, Debug)]
1504 pub enum ClosureBinder {
1505 /// The binder is not present, all closure lifetimes are inferred.
1507 /// The binder is present.
1509 /// Span of the whole `for<>` clause
1512 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1513 /// ^^^^^^^^^^^ -- this
1517 /// Lifetimes in the `for<>` closure
1520 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1523 generic_params: P<[GenericParam]>,
1527 /// Represents a macro invocation. The `path` indicates which macro
1528 /// is being invoked, and the `args` are arguments passed to it.
1529 #[derive(Clone, Encodable, Decodable, Debug)]
1530 pub struct MacCall {
1532 pub args: P<MacArgs>,
1533 pub prior_type_ascription: Option<(Span, bool)>,
1537 pub fn span(&self) -> Span {
1538 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1542 /// Arguments passed to an attribute or a function-like macro.
1543 #[derive(Clone, Encodable, Decodable, Debug)]
1545 /// No arguments - `#[attr]`.
1547 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1548 Delimited(DelimSpan, MacDelimiter, TokenStream),
1549 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1551 /// Span of the `=` token.
1558 // The RHS of a `MacArgs::Eq` starts out as an expression. Once macro expansion
1559 // is completed, all cases end up either as a literal, which is the form used
1560 // after lowering to HIR, or as an error.
1561 #[derive(Clone, Encodable, Decodable, Debug)]
1562 pub enum MacArgsEq {
1568 pub fn delim(&self) -> Option<Delimiter> {
1570 MacArgs::Delimited(_, delim, _) => Some(delim.to_token()),
1571 MacArgs::Empty | MacArgs::Eq(..) => None,
1575 pub fn span(&self) -> Option<Span> {
1577 MacArgs::Empty => None,
1578 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1579 MacArgs::Eq(eq_span, MacArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1580 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1581 unreachable!("in literal form when getting span: {:?}", lit);
1586 /// Tokens inside the delimiters or after `=`.
1587 /// Proc macros see these tokens, for example.
1588 pub fn inner_tokens(&self) -> TokenStream {
1590 MacArgs::Empty => TokenStream::default(),
1591 MacArgs::Delimited(.., tokens) => tokens.clone(),
1592 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => TokenStream::from_ast(expr),
1593 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1594 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1599 /// Whether a macro with these arguments needs a semicolon
1600 /// when used as a standalone item or statement.
1601 pub fn need_semicolon(&self) -> bool {
1602 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1606 impl<CTX> HashStable<CTX> for MacArgs
1608 CTX: crate::HashStableContext,
1610 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1611 mem::discriminant(self).hash_stable(ctx, hasher);
1613 MacArgs::Empty => {}
1614 MacArgs::Delimited(dspan, delim, tokens) => {
1615 dspan.hash_stable(ctx, hasher);
1616 delim.hash_stable(ctx, hasher);
1617 tokens.hash_stable(ctx, hasher);
1619 MacArgs::Eq(_eq_span, MacArgsEq::Ast(expr)) => {
1620 unreachable!("hash_stable {:?}", expr);
1622 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit)) => {
1623 eq_span.hash_stable(ctx, hasher);
1624 lit.hash_stable(ctx, hasher);
1630 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1631 pub enum MacDelimiter {
1638 pub fn to_token(self) -> Delimiter {
1640 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1641 MacDelimiter::Bracket => Delimiter::Bracket,
1642 MacDelimiter::Brace => Delimiter::Brace,
1646 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1648 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1649 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1650 Delimiter::Brace => Some(MacDelimiter::Brace),
1651 Delimiter::Invisible => None,
1656 /// Represents a macro definition.
1657 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1658 pub struct MacroDef {
1659 pub body: P<MacArgs>,
1660 /// `true` if macro was defined with `macro_rules`.
1661 pub macro_rules: bool,
1664 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1665 #[derive(HashStable_Generic)]
1667 /// A regular string, like `"foo"`.
1669 /// A raw string, like `r##"foo"##`.
1671 /// The value is the number of `#` symbols used.
1676 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1678 /// The original literal token as written in source code.
1679 pub token_lit: token::Lit,
1680 /// The "semantic" representation of the literal lowered from the original tokens.
1681 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1682 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1687 /// Same as `Lit`, but restricted to string literals.
1688 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1690 /// The original literal token as written in source code.
1691 pub style: StrStyle,
1693 pub suffix: Option<Symbol>,
1695 /// The unescaped "semantic" representation of the literal lowered from the original token.
1696 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1697 pub symbol_unescaped: Symbol,
1701 pub fn as_lit(&self) -> Lit {
1702 let token_kind = match self.style {
1703 StrStyle::Cooked => token::Str,
1704 StrStyle::Raw(n) => token::StrRaw(n),
1707 token_lit: token::Lit::new(token_kind, self.symbol, self.suffix),
1709 kind: LitKind::Str(self.symbol_unescaped, self.style),
1714 /// Type of the integer literal based on provided suffix.
1715 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1716 #[derive(HashStable_Generic)]
1717 pub enum LitIntType {
1726 /// Type of the float literal based on provided suffix.
1727 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1728 #[derive(HashStable_Generic)]
1729 pub enum LitFloatType {
1730 /// A float literal with a suffix (`1f32` or `1E10f32`).
1732 /// A float literal without a suffix (`1.0 or 1.0E10`).
1738 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1739 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1741 /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
1742 /// from the original token's symbol.
1743 Str(Symbol, StrStyle),
1744 /// A byte string (`b"foo"`).
1746 /// A byte char (`b'f'`).
1748 /// A character literal (`'a'`).
1750 /// An integer literal (`1`).
1751 Int(u128, LitIntType),
1752 /// A float literal (`1f64` or `1E10f64`). Stored as a symbol rather than
1753 /// `f64` so that `LitKind` can impl `Eq` and `Hash`.
1754 Float(Symbol, LitFloatType),
1755 /// A boolean literal.
1757 /// Placeholder for a literal that wasn't well-formed in some way.
1762 /// Returns `true` if this literal is a string.
1763 pub fn is_str(&self) -> bool {
1764 matches!(self, LitKind::Str(..))
1767 /// Returns `true` if this literal is byte literal string.
1768 pub fn is_bytestr(&self) -> bool {
1769 matches!(self, LitKind::ByteStr(_))
1772 /// Returns `true` if this is a numeric literal.
1773 pub fn is_numeric(&self) -> bool {
1774 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1777 /// Returns `true` if this literal has no suffix.
1778 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1779 pub fn is_unsuffixed(&self) -> bool {
1783 /// Returns `true` if this literal has a suffix.
1784 pub fn is_suffixed(&self) -> bool {
1786 // suffixed variants
1787 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1788 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1789 // unsuffixed variants
1791 | LitKind::ByteStr(..)
1794 | LitKind::Int(_, LitIntType::Unsuffixed)
1795 | LitKind::Float(_, LitFloatType::Unsuffixed)
1797 | LitKind::Err => false,
1802 // N.B., If you change this, you'll probably want to change the corresponding
1803 // type structure in `middle/ty.rs` as well.
1804 #[derive(Clone, Encodable, Decodable, Debug)]
1807 pub mutbl: Mutability,
1810 /// Represents a function's signature in a trait declaration,
1811 /// trait implementation, or free function.
1812 #[derive(Clone, Encodable, Decodable, Debug)]
1814 pub header: FnHeader,
1815 pub decl: P<FnDecl>,
1819 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1820 #[derive(Encodable, Decodable, HashStable_Generic)]
1827 pub fn name_str(self) -> &'static str {
1829 FloatTy::F32 => "f32",
1830 FloatTy::F64 => "f64",
1834 pub fn name(self) -> Symbol {
1836 FloatTy::F32 => sym::f32,
1837 FloatTy::F64 => sym::f64,
1842 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1843 #[derive(Encodable, Decodable, HashStable_Generic)]
1854 pub fn name_str(&self) -> &'static str {
1856 IntTy::Isize => "isize",
1858 IntTy::I16 => "i16",
1859 IntTy::I32 => "i32",
1860 IntTy::I64 => "i64",
1861 IntTy::I128 => "i128",
1865 pub fn name(&self) -> Symbol {
1867 IntTy::Isize => sym::isize,
1868 IntTy::I8 => sym::i8,
1869 IntTy::I16 => sym::i16,
1870 IntTy::I32 => sym::i32,
1871 IntTy::I64 => sym::i64,
1872 IntTy::I128 => sym::i128,
1877 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1878 #[derive(Encodable, Decodable, HashStable_Generic)]
1889 pub fn name_str(&self) -> &'static str {
1891 UintTy::Usize => "usize",
1893 UintTy::U16 => "u16",
1894 UintTy::U32 => "u32",
1895 UintTy::U64 => "u64",
1896 UintTy::U128 => "u128",
1900 pub fn name(&self) -> Symbol {
1902 UintTy::Usize => sym::usize,
1903 UintTy::U8 => sym::u8,
1904 UintTy::U16 => sym::u16,
1905 UintTy::U32 => sym::u32,
1906 UintTy::U64 => sym::u64,
1907 UintTy::U128 => sym::u128,
1912 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1913 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1914 #[derive(Clone, Encodable, Decodable, Debug)]
1915 pub struct AssocConstraint {
1918 pub gen_args: Option<GenericArgs>,
1919 pub kind: AssocConstraintKind,
1923 /// The kinds of an `AssocConstraint`.
1924 #[derive(Clone, Encodable, Decodable, Debug)]
1930 impl From<P<Ty>> for Term {
1931 fn from(v: P<Ty>) -> Self {
1936 impl From<AnonConst> for Term {
1937 fn from(v: AnonConst) -> Self {
1942 /// The kinds of an `AssocConstraint`.
1943 #[derive(Clone, Encodable, Decodable, Debug)]
1944 pub enum AssocConstraintKind {
1945 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1946 Equality { term: Term },
1947 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1948 Bound { bounds: GenericBounds },
1951 #[derive(Encodable, Decodable, Debug)]
1956 pub tokens: Option<LazyAttrTokenStream>,
1960 fn clone(&self) -> Self {
1961 ensure_sufficient_stack(|| Self {
1963 kind: self.kind.clone(),
1965 tokens: self.tokens.clone(),
1971 pub fn peel_refs(&self) -> &Self {
1972 let mut final_ty = self;
1973 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1980 #[derive(Clone, Encodable, Decodable, Debug)]
1981 pub struct BareFnTy {
1982 pub unsafety: Unsafe,
1984 pub generic_params: Vec<GenericParam>,
1985 pub decl: P<FnDecl>,
1986 /// Span of the `fn(...) -> ...` part.
1987 pub decl_span: Span,
1990 /// The various kinds of type recognized by the compiler.
1991 #[derive(Clone, Encodable, Decodable, Debug)]
1993 /// A variable-length slice (`[T]`).
1995 /// A fixed length array (`[T; n]`).
1996 Array(P<Ty>, AnonConst),
1997 /// A raw pointer (`*const T` or `*mut T`).
1999 /// A reference (`&'a T` or `&'a mut T`).
2000 Rptr(Option<Lifetime>, MutTy),
2001 /// A bare function (e.g., `fn(usize) -> bool`).
2002 BareFn(P<BareFnTy>),
2003 /// The never type (`!`).
2005 /// A tuple (`(A, B, C, D,...)`).
2007 /// A path (`module::module::...::Type`), optionally
2008 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2010 /// Type parameters are stored in the `Path` itself.
2011 Path(Option<QSelf>, Path),
2012 /// A trait object type `Bound1 + Bound2 + Bound3`
2013 /// where `Bound` is a trait or a lifetime.
2014 TraitObject(GenericBounds, TraitObjectSyntax),
2015 /// An `impl Bound1 + Bound2 + Bound3` type
2016 /// where `Bound` is a trait or a lifetime.
2018 /// The `NodeId` exists to prevent lowering from having to
2019 /// generate `NodeId`s on the fly, which would complicate
2020 /// the generation of opaque `type Foo = impl Trait` items significantly.
2021 ImplTrait(NodeId, GenericBounds),
2022 /// No-op; kept solely so that we can pretty-print faithfully.
2026 /// This means the type should be inferred instead of it having been
2027 /// specified. This can appear anywhere in a type.
2029 /// Inferred type of a `self` or `&self` argument in a method.
2031 /// A macro in the type position.
2032 MacCall(P<MacCall>),
2033 /// Placeholder for a kind that has failed to be defined.
2035 /// Placeholder for a `va_list`.
2040 pub fn is_implicit_self(&self) -> bool {
2041 matches!(self, TyKind::ImplicitSelf)
2044 pub fn is_unit(&self) -> bool {
2045 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2048 pub fn is_simple_path(&self) -> Option<Symbol> {
2049 if let TyKind::Path(None, Path { segments, .. }) = &self
2050 && let [segment] = &segments[..]
2051 && segment.args.is_none()
2053 Some(segment.ident.name)
2060 /// Syntax used to declare a trait object.
2061 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2062 pub enum TraitObjectSyntax {
2068 /// Inline assembly operand explicit register or register class.
2070 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2071 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2072 pub enum InlineAsmRegOrRegClass {
2077 bitflags::bitflags! {
2078 #[derive(Encodable, Decodable, HashStable_Generic)]
2079 pub struct InlineAsmOptions: u16 {
2080 const PURE = 1 << 0;
2081 const NOMEM = 1 << 1;
2082 const READONLY = 1 << 2;
2083 const PRESERVES_FLAGS = 1 << 3;
2084 const NORETURN = 1 << 4;
2085 const NOSTACK = 1 << 5;
2086 const ATT_SYNTAX = 1 << 6;
2088 const MAY_UNWIND = 1 << 8;
2092 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2093 pub enum InlineAsmTemplatePiece {
2095 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2098 impl fmt::Display for InlineAsmTemplatePiece {
2099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2101 Self::String(s) => {
2102 for c in s.chars() {
2104 '{' => f.write_str("{{")?,
2105 '}' => f.write_str("}}")?,
2111 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2112 write!(f, "{{{}:{}}}", operand_idx, modifier)
2114 Self::Placeholder { operand_idx, modifier: None, .. } => {
2115 write!(f, "{{{}}}", operand_idx)
2121 impl InlineAsmTemplatePiece {
2122 /// Rebuilds the asm template string from its pieces.
2123 pub fn to_string(s: &[Self]) -> String {
2125 let mut out = String::new();
2127 let _ = write!(out, "{}", p);
2133 /// Inline assembly symbol operands get their own AST node that is somewhat
2134 /// similar to `AnonConst`.
2136 /// The main difference is that we specifically don't assign it `DefId` in
2137 /// `DefCollector`. Instead this is deferred until AST lowering where we
2138 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2139 /// depending on what the path resolves to.
2140 #[derive(Clone, Encodable, Decodable, Debug)]
2141 pub struct InlineAsmSym {
2143 pub qself: Option<QSelf>,
2147 /// Inline assembly operand.
2149 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2150 #[derive(Clone, Encodable, Decodable, Debug)]
2151 pub enum InlineAsmOperand {
2153 reg: InlineAsmRegOrRegClass,
2157 reg: InlineAsmRegOrRegClass,
2159 expr: Option<P<Expr>>,
2162 reg: InlineAsmRegOrRegClass,
2167 reg: InlineAsmRegOrRegClass,
2170 out_expr: Option<P<Expr>>,
2173 anon_const: AnonConst,
2180 /// Inline assembly.
2182 /// E.g., `asm!("NOP");`.
2183 #[derive(Clone, Encodable, Decodable, Debug)]
2184 pub struct InlineAsm {
2185 pub template: Vec<InlineAsmTemplatePiece>,
2186 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2187 pub operands: Vec<(InlineAsmOperand, Span)>,
2188 pub clobber_abis: Vec<(Symbol, Span)>,
2189 pub options: InlineAsmOptions,
2190 pub line_spans: Vec<Span>,
2193 /// A parameter in a function header.
2195 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2196 #[derive(Clone, Encodable, Decodable, Debug)]
2203 pub is_placeholder: bool,
2206 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2208 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2209 #[derive(Clone, Encodable, Decodable, Debug)]
2211 /// `self`, `mut self`
2213 /// `&'lt self`, `&'lt mut self`
2214 Region(Option<Lifetime>, Mutability),
2215 /// `self: TYPE`, `mut self: TYPE`
2216 Explicit(P<Ty>, Mutability),
2219 pub type ExplicitSelf = Spanned<SelfKind>;
2222 /// Attempts to cast parameter to `ExplicitSelf`.
2223 pub fn to_self(&self) -> Option<ExplicitSelf> {
2224 if let PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), ident, _) = self.pat.kind {
2225 if ident.name == kw::SelfLower {
2226 return match self.ty.kind {
2227 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2228 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2229 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2232 self.pat.span.to(self.ty.span),
2233 SelfKind::Explicit(self.ty.clone(), mutbl),
2241 /// Returns `true` if parameter is `self`.
2242 pub fn is_self(&self) -> bool {
2243 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2244 ident.name == kw::SelfLower
2250 /// Builds a `Param` object from `ExplicitSelf`.
2251 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2252 let span = eself.span.to(eself_ident.span);
2253 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2254 let (mutbl, ty) = match eself.node {
2255 SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2256 SelfKind::Value(mutbl) => (mutbl, infer_ty),
2257 SelfKind::Region(lt, mutbl) => (
2261 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2271 kind: PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), eself_ident, None),
2278 is_placeholder: false,
2283 /// A signature (not the body) of a function declaration.
2285 /// E.g., `fn foo(bar: baz)`.
2287 /// Please note that it's different from `FnHeader` structure
2288 /// which contains metadata about function safety, asyncness, constness and ABI.
2289 #[derive(Clone, Encodable, Decodable, Debug)]
2291 pub inputs: Vec<Param>,
2292 pub output: FnRetTy,
2296 pub fn has_self(&self) -> bool {
2297 self.inputs.get(0).map_or(false, Param::is_self)
2299 pub fn c_variadic(&self) -> bool {
2300 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2304 /// Is the trait definition an auto trait?
2305 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2311 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2312 #[derive(HashStable_Generic)]
2318 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2320 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2325 pub fn is_async(self) -> bool {
2326 matches!(self, Async::Yes { .. })
2329 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2330 pub fn opt_return_id(self) -> Option<(NodeId, Span)> {
2332 Async::Yes { return_impl_trait_id, span, .. } => Some((return_impl_trait_id, span)),
2338 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2339 #[derive(HashStable_Generic)]
2345 /// Item defaultness.
2346 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2347 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2348 pub enum Defaultness {
2353 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2354 pub enum ImplPolarity {
2355 /// `impl Trait for Type`
2357 /// `impl !Trait for Type`
2361 impl fmt::Debug for ImplPolarity {
2362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2364 ImplPolarity::Positive => "positive".fmt(f),
2365 ImplPolarity::Negative(_) => "negative".fmt(f),
2370 #[derive(Clone, Encodable, Decodable, Debug)]
2372 /// Returns type is not specified.
2374 /// Functions default to `()` and closures default to inference.
2375 /// Span points to where return type would be inserted.
2377 /// Everything else.
2382 pub fn span(&self) -> Span {
2384 FnRetTy::Default(span) => span,
2385 FnRetTy::Ty(ref ty) => ty.span,
2390 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2396 /// Module item kind.
2397 #[derive(Clone, Encodable, Decodable, Debug)]
2399 /// Module with inlined definition `mod foo { ... }`,
2400 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2401 /// The inner span is from the first token past `{` to the last token until `}`,
2402 /// or from the first to the last token in the loaded file.
2403 Loaded(Vec<P<Item>>, Inline, ModSpans),
2404 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2408 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2409 pub struct ModSpans {
2410 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2411 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2412 pub inner_span: Span,
2413 pub inject_use_span: Span,
2416 impl Default for ModSpans {
2417 fn default() -> ModSpans {
2418 ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2422 /// Foreign module declaration.
2424 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2425 #[derive(Clone, Encodable, Decodable, Debug)]
2426 pub struct ForeignMod {
2427 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2428 /// semantically by Rust.
2429 pub unsafety: Unsafe,
2430 pub abi: Option<StrLit>,
2431 pub items: Vec<P<ForeignItem>>,
2434 #[derive(Clone, Encodable, Decodable, Debug)]
2435 pub struct EnumDef {
2436 pub variants: Vec<Variant>,
2439 #[derive(Clone, Encodable, Decodable, Debug)]
2440 pub struct Variant {
2441 /// Attributes of the variant.
2443 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2447 /// The visibility of the variant. Syntactically accepted but not semantically.
2448 pub vis: Visibility,
2449 /// Name of the variant.
2452 /// Fields and constructor id of the variant.
2453 pub data: VariantData,
2454 /// Explicit discriminant, e.g., `Foo = 1`.
2455 pub disr_expr: Option<AnonConst>,
2456 /// Is a macro placeholder
2457 pub is_placeholder: bool,
2460 /// Part of `use` item to the right of its prefix.
2461 #[derive(Clone, Encodable, Decodable, Debug)]
2462 pub enum UseTreeKind {
2463 /// `use prefix` or `use prefix as rename`
2465 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2467 Simple(Option<Ident>, NodeId, NodeId),
2468 /// `use prefix::{...}`
2469 Nested(Vec<(UseTree, NodeId)>),
2474 /// A tree of paths sharing common prefixes.
2475 /// Used in `use` items both at top-level and inside of braces in import groups.
2476 #[derive(Clone, Encodable, Decodable, Debug)]
2477 pub struct UseTree {
2479 pub kind: UseTreeKind,
2484 pub fn ident(&self) -> Ident {
2486 UseTreeKind::Simple(Some(rename), ..) => rename,
2487 UseTreeKind::Simple(None, ..) => {
2488 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2490 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2495 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2496 /// are contained as statements within items. These two cases need to be
2497 /// distinguished for pretty-printing.
2498 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2499 pub enum AttrStyle {
2504 rustc_index::newtype_index! {
2507 DEBUG_FORMAT = "AttrId({})"
2511 impl<S: Encoder> Encodable<S> for AttrId {
2512 fn encode(&self, _s: &mut S) {}
2515 impl<D: Decoder> Decodable<D> for AttrId {
2516 default fn decode(_: &mut D) -> AttrId {
2517 panic!("cannot decode `AttrId` with `{}`", std::any::type_name::<D>());
2521 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2522 pub struct AttrItem {
2525 pub tokens: Option<LazyAttrTokenStream>,
2528 /// A list of attributes.
2529 pub type AttrVec = ThinVec<Attribute>;
2531 /// Metadata associated with an item.
2532 #[derive(Clone, Encodable, Decodable, Debug)]
2533 pub struct Attribute {
2536 /// Denotes if the attribute decorates the following construct (outer)
2537 /// or the construct this attribute is contained within (inner).
2538 pub style: AttrStyle,
2542 #[derive(Clone, Encodable, Decodable, Debug)]
2543 pub struct NormalAttr {
2545 pub tokens: Option<LazyAttrTokenStream>,
2548 #[derive(Clone, Encodable, Decodable, Debug)]
2550 /// A normal attribute.
2551 Normal(P<NormalAttr>),
2553 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2554 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2555 /// variant (which is much less compact and thus more expensive).
2556 DocComment(CommentKind, Symbol),
2559 /// `TraitRef`s appear in impls.
2561 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2562 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2563 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2564 /// same as the impl's `NodeId`).
2565 #[derive(Clone, Encodable, Decodable, Debug)]
2566 pub struct TraitRef {
2571 #[derive(Clone, Encodable, Decodable, Debug)]
2572 pub struct PolyTraitRef {
2573 /// The `'a` in `for<'a> Foo<&'a T>`.
2574 pub bound_generic_params: Vec<GenericParam>,
2576 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2577 pub trait_ref: TraitRef,
2583 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2585 bound_generic_params: generic_params,
2586 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2592 #[derive(Clone, Encodable, Decodable, Debug)]
2593 pub struct Visibility {
2594 pub kind: VisibilityKind,
2596 pub tokens: Option<LazyAttrTokenStream>,
2599 #[derive(Clone, Encodable, Decodable, Debug)]
2600 pub enum VisibilityKind {
2602 Restricted { path: P<Path>, id: NodeId, shorthand: bool },
2606 impl VisibilityKind {
2607 pub fn is_pub(&self) -> bool {
2608 matches!(self, VisibilityKind::Public)
2612 /// Field definition in a struct, variant or union.
2614 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2615 #[derive(Clone, Encodable, Decodable, Debug)]
2616 pub struct FieldDef {
2620 pub vis: Visibility,
2621 pub ident: Option<Ident>,
2624 pub is_placeholder: bool,
2627 /// Fields and constructor ids of enum variants and structs.
2628 #[derive(Clone, Encodable, Decodable, Debug)]
2629 pub enum VariantData {
2632 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2633 Struct(Vec<FieldDef>, bool),
2636 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2637 Tuple(Vec<FieldDef>, NodeId),
2640 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2645 /// Return the fields of this variant.
2646 pub fn fields(&self) -> &[FieldDef] {
2648 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2653 /// Return the `NodeId` of this variant's constructor, if it has one.
2654 pub fn ctor_id(&self) -> Option<NodeId> {
2656 VariantData::Struct(..) => None,
2657 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2662 /// An item definition.
2663 #[derive(Clone, Encodable, Decodable, Debug)]
2664 pub struct Item<K = ItemKind> {
2668 pub vis: Visibility,
2669 /// The name of the item.
2670 /// It might be a dummy name in case of anonymous items.
2675 /// Original tokens this item was parsed from. This isn't necessarily
2676 /// available for all items, although over time more and more items should
2677 /// have this be `Some`. Right now this is primarily used for procedural
2678 /// macros, notably custom attributes.
2680 /// Note that the tokens here do not include the outer attributes, but will
2681 /// include inner attributes.
2682 pub tokens: Option<LazyAttrTokenStream>,
2686 /// Return the span that encompasses the attributes.
2687 pub fn span_with_attributes(&self) -> Span {
2688 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2692 /// `extern` qualifier on a function item or function type.
2693 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2697 Explicit(StrLit, Span),
2701 pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2703 Some(name) => Extern::Explicit(name, span),
2704 None => Extern::Implicit(span),
2709 /// A function header.
2711 /// All the information between the visibility and the name of the function is
2712 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2713 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2714 pub struct FnHeader {
2715 pub unsafety: Unsafe,
2716 pub asyncness: Async,
2717 pub constness: Const,
2722 /// Does this function header have any qualifiers or is it empty?
2723 pub fn has_qualifiers(&self) -> bool {
2724 let Self { unsafety, asyncness, constness, ext } = self;
2725 matches!(unsafety, Unsafe::Yes(_))
2726 || asyncness.is_async()
2727 || matches!(constness, Const::Yes(_))
2728 || !matches!(ext, Extern::None)
2732 impl Default for FnHeader {
2733 fn default() -> FnHeader {
2735 unsafety: Unsafe::No,
2736 asyncness: Async::No,
2737 constness: Const::No,
2743 #[derive(Clone, Encodable, Decodable, Debug)]
2745 pub unsafety: Unsafe,
2746 pub is_auto: IsAuto,
2747 pub generics: Generics,
2748 pub bounds: GenericBounds,
2749 pub items: Vec<P<AssocItem>>,
2752 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2753 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2754 /// are two locations for where clause on type aliases, but their predicates
2755 /// are concatenated together.
2757 /// Take this example:
2758 /// ```ignore (only-for-syntax-highlight)
2760 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2762 /// impl Foo for () {
2763 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2764 /// // ^^^^^^^^^^^^^^ first where clause
2765 /// // ^^^^^^^^^^^^^^ second where clause
2769 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2770 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2771 pub struct TyAliasWhereClause(pub bool, pub Span);
2773 #[derive(Clone, Encodable, Decodable, Debug)]
2774 pub struct TyAlias {
2775 pub defaultness: Defaultness,
2776 pub generics: Generics,
2777 /// The span information for the two where clauses (before equals, after equals)
2778 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2779 /// The index in `generics.where_clause.predicates` that would split into
2780 /// predicates from the where clause before the equals and the predicates
2781 /// from the where clause after the equals
2782 pub where_predicates_split: usize,
2783 pub bounds: GenericBounds,
2784 pub ty: Option<P<Ty>>,
2787 #[derive(Clone, Encodable, Decodable, Debug)]
2789 pub defaultness: Defaultness,
2790 pub unsafety: Unsafe,
2791 pub generics: Generics,
2792 pub constness: Const,
2793 pub polarity: ImplPolarity,
2794 /// The trait being implemented, if any.
2795 pub of_trait: Option<TraitRef>,
2797 pub items: Vec<P<AssocItem>>,
2800 #[derive(Clone, Encodable, Decodable, Debug)]
2802 pub defaultness: Defaultness,
2803 pub generics: Generics,
2805 pub body: Option<P<Block>>,
2808 #[derive(Clone, Encodable, Decodable, Debug)]
2810 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2812 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2813 ExternCrate(Option<Symbol>),
2814 /// A use declaration item (`use`).
2816 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2818 /// A static item (`static`).
2820 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2821 Static(P<Ty>, Mutability, Option<P<Expr>>),
2822 /// A constant item (`const`).
2824 /// E.g., `const FOO: i32 = 42;`.
2825 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2826 /// A function declaration (`fn`).
2828 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2830 /// A module declaration (`mod`).
2832 /// E.g., `mod foo;` or `mod foo { .. }`.
2833 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2834 /// semantically by Rust.
2835 Mod(Unsafe, ModKind),
2836 /// An external module (`extern`).
2838 /// E.g., `extern {}` or `extern "C" {}`.
2839 ForeignMod(ForeignMod),
2840 /// Module-level inline assembly (from `global_asm!()`).
2841 GlobalAsm(Box<InlineAsm>),
2842 /// A type alias (`type`).
2844 /// E.g., `type Foo = Bar<u8>;`.
2845 TyAlias(Box<TyAlias>),
2846 /// An enum definition (`enum`).
2848 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2849 Enum(EnumDef, Generics),
2850 /// A struct definition (`struct`).
2852 /// E.g., `struct Foo<A> { x: A }`.
2853 Struct(VariantData, Generics),
2854 /// A union definition (`union`).
2856 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2857 Union(VariantData, Generics),
2858 /// A trait declaration (`trait`).
2860 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2864 /// E.g., `trait Foo = Bar + Quux;`.
2865 TraitAlias(Generics, GenericBounds),
2866 /// An implementation.
2868 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2870 /// A macro invocation.
2872 /// E.g., `foo!(..)`.
2873 MacCall(P<MacCall>),
2875 /// A macro definition.
2880 pub fn article(&self) -> &str {
2883 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2884 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2885 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2889 pub fn descr(&self) -> &str {
2891 ItemKind::ExternCrate(..) => "extern crate",
2892 ItemKind::Use(..) => "`use` import",
2893 ItemKind::Static(..) => "static item",
2894 ItemKind::Const(..) => "constant item",
2895 ItemKind::Fn(..) => "function",
2896 ItemKind::Mod(..) => "module",
2897 ItemKind::ForeignMod(..) => "extern block",
2898 ItemKind::GlobalAsm(..) => "global asm item",
2899 ItemKind::TyAlias(..) => "type alias",
2900 ItemKind::Enum(..) => "enum",
2901 ItemKind::Struct(..) => "struct",
2902 ItemKind::Union(..) => "union",
2903 ItemKind::Trait(..) => "trait",
2904 ItemKind::TraitAlias(..) => "trait alias",
2905 ItemKind::MacCall(..) => "item macro invocation",
2906 ItemKind::MacroDef(..) => "macro definition",
2907 ItemKind::Impl { .. } => "implementation",
2911 pub fn generics(&self) -> Option<&Generics> {
2913 Self::Fn(box Fn { generics, .. })
2914 | Self::TyAlias(box TyAlias { generics, .. })
2915 | Self::Enum(_, generics)
2916 | Self::Struct(_, generics)
2917 | Self::Union(_, generics)
2918 | Self::Trait(box Trait { generics, .. })
2919 | Self::TraitAlias(generics, _)
2920 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2926 /// Represents associated items.
2927 /// These include items in `impl` and `trait` definitions.
2928 pub type AssocItem = Item<AssocItemKind>;
2930 /// Represents associated item kinds.
2932 /// The term "provided" in the variants below refers to the item having a default
2933 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2934 /// In an implementation, all items must be provided.
2935 /// The `Option`s below denote the bodies, where `Some(_)`
2936 /// means "provided" and conversely `None` means "required".
2937 #[derive(Clone, Encodable, Decodable, Debug)]
2938 pub enum AssocItemKind {
2939 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2940 /// If `def` is parsed, then the constant is provided, and otherwise required.
2941 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2942 /// An associated function.
2944 /// An associated type.
2946 /// A macro expanding to associated items.
2947 MacCall(P<MacCall>),
2950 impl AssocItemKind {
2951 pub fn defaultness(&self) -> Defaultness {
2953 Self::Const(defaultness, ..)
2954 | Self::Fn(box Fn { defaultness, .. })
2955 | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
2956 Self::MacCall(..) => Defaultness::Final,
2961 impl From<AssocItemKind> for ItemKind {
2962 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2963 match assoc_item_kind {
2964 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2965 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2966 AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2967 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2972 impl TryFrom<ItemKind> for AssocItemKind {
2973 type Error = ItemKind;
2975 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2976 Ok(match item_kind {
2977 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2978 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2979 ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
2980 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2981 _ => return Err(item_kind),
2986 /// An item in `extern` block.
2987 #[derive(Clone, Encodable, Decodable, Debug)]
2988 pub enum ForeignItemKind {
2989 /// A foreign static item (`static FOO: u8`).
2990 Static(P<Ty>, Mutability, Option<P<Expr>>),
2991 /// An foreign function.
2993 /// An foreign type.
2994 TyAlias(Box<TyAlias>),
2995 /// A macro expanding to foreign items.
2996 MacCall(P<MacCall>),
2999 impl From<ForeignItemKind> for ItemKind {
3000 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3001 match foreign_item_kind {
3002 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3003 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3004 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3005 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3010 impl TryFrom<ItemKind> for ForeignItemKind {
3011 type Error = ItemKind;
3013 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3014 Ok(match item_kind {
3015 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3016 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3017 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3018 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3019 _ => return Err(item_kind),
3024 pub type ForeignItem = Item<ForeignItemKind>;
3026 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3027 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3030 use rustc_data_structures::static_assert_size;
3031 // tidy-alphabetical-start
3032 static_assert_size!(AssocItem, 104);
3033 static_assert_size!(AssocItemKind, 32);
3034 static_assert_size!(Attribute, 32);
3035 static_assert_size!(Block, 48);
3036 static_assert_size!(Expr, 104);
3037 static_assert_size!(ExprKind, 72);
3038 static_assert_size!(Fn, 184);
3039 static_assert_size!(ForeignItem, 96);
3040 static_assert_size!(ForeignItemKind, 24);
3041 static_assert_size!(GenericArg, 24);
3042 static_assert_size!(GenericBound, 88);
3043 static_assert_size!(Generics, 72);
3044 static_assert_size!(Impl, 200);
3045 static_assert_size!(Item, 184);
3046 static_assert_size!(ItemKind, 112);
3047 static_assert_size!(Lit, 48);
3048 static_assert_size!(LitKind, 24);
3049 static_assert_size!(Local, 72);
3050 static_assert_size!(Param, 40);
3051 static_assert_size!(Pat, 120);
3052 static_assert_size!(Path, 40);
3053 static_assert_size!(PathSegment, 24);
3054 static_assert_size!(PatKind, 96);
3055 static_assert_size!(Stmt, 32);
3056 static_assert_size!(StmtKind, 16);
3057 static_assert_size!(Ty, 96);
3058 static_assert_size!(TyKind, 72);
3059 // tidy-alphabetical-end