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, Token};
27 use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree};
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable_Generic;
34 use rustc_serialize::{self, Decoder, Encoder};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
39 use std::cmp::Ordering;
40 use std::convert::TryFrom;
47 /// A "Label" is an identifier of some point in sources,
48 /// e.g. in the following code:
56 /// `'outer` is a label.
57 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
62 impl fmt::Debug for Label {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "label({:?})", self.ident)
68 /// A "Lifetime" is an annotation of the scope in which variable
69 /// can be used, e.g. `'a` in `&'a i32`.
70 #[derive(Clone, Encodable, Decodable, Copy)]
76 impl fmt::Debug for Lifetime {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "lifetime({}: {})", self.id, self)
82 impl fmt::Display for Lifetime {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 write!(f, "{}", self.ident.name)
88 /// A "Path" is essentially Rust's notion of a name.
90 /// It's represented as a sequence of identifiers,
91 /// along with a bunch of supporting information.
93 /// E.g., `std::cmp::PartialEq`.
94 #[derive(Clone, Encodable, Decodable, Debug)]
97 /// The segments in the path: the things separated by `::`.
98 /// Global paths begin with `kw::PathRoot`.
99 pub segments: Vec<PathSegment>,
100 pub tokens: Option<LazyTokenStream>,
103 impl PartialEq<Symbol> for Path {
105 fn eq(&self, symbol: &Symbol) -> bool {
106 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
110 impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
111 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
112 self.segments.len().hash_stable(hcx, hasher);
113 for segment in &self.segments {
114 segment.ident.hash_stable(hcx, hasher);
120 // Convert a span and an identifier to the corresponding
122 pub fn from_ident(ident: Ident) -> Path {
123 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
126 pub fn is_global(&self) -> bool {
127 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
131 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
133 /// E.g., `std`, `String` or `Box<T>`.
134 #[derive(Clone, Encodable, Decodable, Debug)]
135 pub struct PathSegment {
136 /// The identifier portion of this path segment.
141 /// Type/lifetime parameters attached to this path. They come in
142 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
143 /// `None` means that no parameter list is supplied (`Path`),
144 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
145 /// but it can be empty (`Path<>`).
146 /// `P` is used as a size optimization for the common case with no parameters.
147 pub args: Option<P<GenericArgs>>,
151 pub fn from_ident(ident: Ident) -> Self {
152 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
155 pub fn path_root(span: Span) -> Self {
156 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
159 pub fn span(&self) -> Span {
161 Some(args) => self.ident.span.to(args.span()),
162 None => self.ident.span,
167 /// The arguments of a path segment.
169 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
170 #[derive(Clone, Encodable, Decodable, Debug)]
171 pub enum GenericArgs {
172 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
173 AngleBracketed(AngleBracketedArgs),
174 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
175 Parenthesized(ParenthesizedArgs),
179 pub fn is_angle_bracketed(&self) -> bool {
180 matches!(self, AngleBracketed(..))
183 pub fn span(&self) -> Span {
185 AngleBracketed(ref data) => data.span,
186 Parenthesized(ref data) => data.span,
191 /// Concrete argument in the sequence of generic args.
192 #[derive(Clone, Encodable, Decodable, Debug)]
193 pub enum GenericArg {
194 /// `'a` in `Foo<'a>`
196 /// `Bar` in `Foo<Bar>`
203 pub fn span(&self) -> Span {
205 GenericArg::Lifetime(lt) => lt.ident.span,
206 GenericArg::Type(ty) => ty.span,
207 GenericArg::Const(ct) => ct.value.span,
212 /// A path like `Foo<'a, T>`.
213 #[derive(Clone, Encodable, Decodable, Debug, Default)]
214 pub struct AngleBracketedArgs {
215 /// The overall span.
217 /// The comma separated parts in the `<...>`.
218 pub args: Vec<AngleBracketedArg>,
221 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
222 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
223 #[derive(Clone, Encodable, Decodable, Debug)]
224 pub enum AngleBracketedArg {
225 /// Argument for a generic parameter.
227 /// Constraint for an associated item.
228 Constraint(AssocConstraint),
231 impl AngleBracketedArg {
232 pub fn span(&self) -> Span {
234 AngleBracketedArg::Arg(arg) => arg.span(),
235 AngleBracketedArg::Constraint(constraint) => constraint.span,
240 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
241 fn into(self) -> Option<P<GenericArgs>> {
242 Some(P(GenericArgs::AngleBracketed(self)))
246 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
247 fn into(self) -> Option<P<GenericArgs>> {
248 Some(P(GenericArgs::Parenthesized(self)))
252 /// A path like `Foo(A, B) -> C`.
253 #[derive(Clone, Encodable, Decodable, Debug)]
254 pub struct ParenthesizedArgs {
262 pub inputs: Vec<P<Ty>>,
268 pub inputs_span: Span,
274 impl ParenthesizedArgs {
275 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
280 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
282 AngleBracketedArgs { span: self.inputs_span, args }
286 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
288 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
290 /// Negative bounds should also be handled here.
291 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
292 pub enum TraitBoundModifier {
304 // This parses but will be rejected during AST validation.
308 /// The AST represents all type param bounds as types.
309 /// `typeck::collect::compute_bounds` matches these against
310 /// the "special" built-in traits (see `middle::lang_items`) and
311 /// detects `Copy`, `Send` and `Sync`.
312 #[derive(Clone, Encodable, Decodable, Debug)]
313 pub enum GenericBound {
314 Trait(PolyTraitRef, TraitBoundModifier),
319 pub fn span(&self) -> Span {
321 GenericBound::Trait(ref t, ..) => t.span,
322 GenericBound::Outlives(ref l) => l.ident.span,
327 pub type GenericBounds = Vec<GenericBound>;
329 /// Specifies the enforced ordering for generic parameters. In the future,
330 /// if we wanted to relax this order, we could override `PartialEq` and
331 /// `PartialOrd`, to allow the kinds to be unordered.
332 #[derive(Hash, Clone, Copy)]
333 pub enum ParamKindOrd {
337 // `Infer` is not actually constructed directly from the AST, but is implicitly constructed
338 // during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last.
342 impl Ord for ParamKindOrd {
343 fn cmp(&self, other: &Self) -> Ordering {
345 let to_int = |v| match v {
347 Infer | Type | Const => 1,
350 to_int(*self).cmp(&to_int(*other))
353 impl PartialOrd for ParamKindOrd {
354 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
355 Some(self.cmp(other))
358 impl PartialEq for ParamKindOrd {
359 fn eq(&self, other: &Self) -> bool {
360 self.cmp(other) == Ordering::Equal
363 impl Eq for ParamKindOrd {}
365 impl fmt::Display for ParamKindOrd {
366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 ParamKindOrd::Lifetime => "lifetime".fmt(f),
369 ParamKindOrd::Type => "type".fmt(f),
370 ParamKindOrd::Const { .. } => "const".fmt(f),
371 ParamKindOrd::Infer => "infer".fmt(f),
376 #[derive(Clone, Encodable, Decodable, Debug)]
377 pub enum GenericParamKind {
378 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
381 default: Option<P<Ty>>,
385 /// Span of the `const` keyword.
387 /// Optional default value for the const generic param
388 default: Option<AnonConst>,
392 #[derive(Clone, Encodable, Decodable, Debug)]
393 pub struct GenericParam {
397 pub bounds: GenericBounds,
398 pub is_placeholder: bool,
399 pub kind: GenericParamKind,
400 pub colon_span: Option<Span>,
404 pub fn span(&self) -> Span {
406 GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
409 GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
410 GenericParamKind::Const { kw_span, default: Some(default), .. } => {
411 kw_span.to(default.value.span)
413 GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
418 /// Represents lifetime, type and const parameters attached to a declaration of
419 /// a function, enum, trait, etc.
420 #[derive(Clone, Encodable, Decodable, Debug)]
421 pub struct Generics {
422 pub params: Vec<GenericParam>,
423 pub where_clause: WhereClause,
427 impl Default for Generics {
428 /// Creates an instance of `Generics`.
429 fn default() -> Generics {
432 where_clause: WhereClause {
433 has_where_token: false,
434 predicates: Vec::new(),
442 /// A where-clause in a definition.
443 #[derive(Clone, Encodable, Decodable, Debug)]
444 pub struct WhereClause {
445 /// `true` if we ate a `where` token: this can happen
446 /// if we parsed no predicates (e.g. `struct Foo where {}`).
447 /// This allows us to accurately pretty-print
448 /// in `nt_to_tokenstream`
449 pub has_where_token: bool,
450 pub predicates: Vec<WherePredicate>,
454 /// A single predicate in a where-clause.
455 #[derive(Clone, Encodable, Decodable, Debug)]
456 pub enum WherePredicate {
457 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
458 BoundPredicate(WhereBoundPredicate),
459 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
460 RegionPredicate(WhereRegionPredicate),
461 /// An equality predicate (unsupported).
462 EqPredicate(WhereEqPredicate),
465 impl WherePredicate {
466 pub fn span(&self) -> Span {
468 WherePredicate::BoundPredicate(p) => p.span,
469 WherePredicate::RegionPredicate(p) => p.span,
470 WherePredicate::EqPredicate(p) => p.span,
477 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
478 #[derive(Clone, Encodable, Decodable, Debug)]
479 pub struct WhereBoundPredicate {
481 /// Any generics from a `for` binding.
482 pub bound_generic_params: Vec<GenericParam>,
483 /// The type being bounded.
484 pub bounded_ty: P<Ty>,
485 /// Trait and lifetime bounds (`Clone + Send + 'static`).
486 pub bounds: GenericBounds,
489 /// A lifetime predicate.
491 /// E.g., `'a: 'b + 'c`.
492 #[derive(Clone, Encodable, Decodable, Debug)]
493 pub struct WhereRegionPredicate {
495 pub lifetime: Lifetime,
496 pub bounds: GenericBounds,
499 /// An equality predicate (unsupported).
502 #[derive(Clone, Encodable, Decodable, Debug)]
503 pub struct WhereEqPredicate {
510 #[derive(Clone, Encodable, Decodable, Debug)]
512 pub attrs: Vec<Attribute>,
513 pub items: Vec<P<Item>>,
515 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
516 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
518 pub is_placeholder: bool,
521 /// Possible values inside of compile-time attribute lists.
523 /// E.g., the '..' in `#[name(..)]`.
524 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
525 pub enum NestedMetaItem {
526 /// A full MetaItem, for recursive meta items.
530 /// E.g., `"foo"`, `64`, `true`.
534 /// A spanned compile-time attribute item.
536 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
537 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
538 pub struct MetaItem {
540 pub kind: MetaItemKind,
544 /// A compile-time attribute item.
546 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
547 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
548 pub enum MetaItemKind {
551 /// E.g., `test` as in `#[test]`.
555 /// E.g., `derive(..)` as in `#[derive(..)]`.
556 List(Vec<NestedMetaItem>),
557 /// Name value meta item.
559 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
563 /// A block (`{ .. }`).
565 /// E.g., `{ .. }` as in `fn foo() { .. }`.
566 #[derive(Clone, Encodable, Decodable, Debug)]
568 /// The statements in the block.
569 pub stmts: Vec<Stmt>,
571 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
572 pub rules: BlockCheckMode,
574 pub tokens: Option<LazyTokenStream>,
575 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
582 pub could_be_bare_literal: bool,
587 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
588 #[derive(Clone, Encodable, Decodable, Debug)]
593 pub tokens: Option<LazyTokenStream>,
597 /// Attempt reparsing the pattern as a type.
598 /// This is intended for use by diagnostics.
599 pub fn to_ty(&self) -> Option<P<Ty>> {
600 let kind = match &self.kind {
601 // In a type expression `_` is an inference variable.
602 PatKind::Wild => TyKind::Infer,
603 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
604 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
605 TyKind::Path(None, Path::from_ident(*ident))
607 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
608 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
609 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
610 PatKind::Ref(pat, mutbl) => {
611 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
613 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
614 // when `P` can be reparsed as a type `T`.
615 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
616 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
617 // assuming `T0` to `Tn` are all syntactically valid as types.
618 PatKind::Tuple(pats) => {
619 let mut tys = Vec::with_capacity(pats.len());
620 // FIXME(#48994) - could just be collected into an Option<Vec>
622 tys.push(pat.to_ty()?);
629 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
632 /// Walk top-down and call `it` in each place where a pattern occurs
633 /// starting with the root pattern `walk` is called on. If `it` returns
634 /// false then we will descend no further but siblings will be processed.
635 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
641 // Walk into the pattern associated with `Ident` (if any).
642 PatKind::Ident(_, _, Some(p)) => p.walk(it),
644 // Walk into each field of struct.
645 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
647 // Sequence of patterns.
648 PatKind::TupleStruct(_, _, s)
651 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
653 // Trivial wrappers over inner patterns.
654 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
656 // These patterns do not contain subpatterns, skip.
663 | PatKind::MacCall(_) => {}
667 /// Is this a `..` pattern?
668 pub fn is_rest(&self) -> bool {
669 matches!(self.kind, PatKind::Rest)
673 /// A single field in a struct pattern.
675 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
676 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
677 /// except when `is_shorthand` is true.
678 #[derive(Clone, Encodable, Decodable, Debug)]
679 pub struct PatField {
680 /// The identifier for the field.
682 /// The pattern the field is destructured to.
684 pub is_shorthand: bool,
688 pub is_placeholder: bool,
691 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
692 pub enum BindingMode {
697 #[derive(Clone, Encodable, Decodable, Debug)]
700 Included(RangeSyntax),
705 #[derive(Clone, Encodable, Decodable, Debug)]
706 pub enum RangeSyntax {
713 /// All the different flavors of pattern that Rust recognizes.
714 #[derive(Clone, Encodable, Decodable, Debug)]
716 /// Represents a wildcard pattern (`_`).
719 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
720 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
721 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
722 /// during name resolution.
723 Ident(BindingMode, Ident, Option<P<Pat>>),
725 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
726 /// The `bool` is `true` in the presence of a `..`.
727 Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool),
729 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
730 TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>),
732 /// An or-pattern `A | B | C`.
733 /// Invariant: `pats.len() >= 2`.
736 /// A possibly qualified path pattern.
737 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
738 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
739 /// only legally refer to associated constants.
740 Path(Option<QSelf>, Path),
742 /// A tuple pattern (`(a, b)`).
748 /// A reference pattern (e.g., `&mut (a, b)`).
749 Ref(P<Pat>, Mutability),
754 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
755 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
757 /// A slice pattern `[a, b, c]`.
760 /// A rest pattern `..`.
762 /// Syntactically it is valid anywhere.
764 /// Semantically however, it only has meaning immediately inside:
765 /// - a slice pattern: `[a, .., b]`,
766 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
767 /// - a tuple pattern: `(a, .., b)`,
768 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
770 /// In all of these cases, an additional restriction applies,
771 /// only one rest pattern may occur in the pattern sequences.
774 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
777 /// A macro pattern; pre-expansion.
781 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
782 #[derive(HashStable_Generic, Encodable, Decodable)]
783 pub enum Mutability {
789 pub fn invert(self) -> Self {
791 Mutability::Mut => Mutability::Not,
792 Mutability::Not => Mutability::Mut,
796 pub fn prefix_str(&self) -> &'static str {
798 Mutability::Mut => "mut ",
799 Mutability::Not => "",
804 /// The kind of borrow in an `AddrOf` expression,
805 /// e.g., `&place` or `&raw const place`.
806 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
807 #[derive(Encodable, Decodable, HashStable_Generic)]
808 pub enum BorrowKind {
809 /// A normal borrow, `&$expr` or `&mut $expr`.
810 /// The resulting type is either `&'a T` or `&'a mut T`
811 /// where `T = typeof($expr)` and `'a` is some lifetime.
813 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
814 /// The resulting type is either `*const T` or `*mut T`
815 /// where `T = typeof($expr)`.
819 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
821 /// The `+` operator (addition)
823 /// The `-` operator (subtraction)
825 /// The `*` operator (multiplication)
827 /// The `/` operator (division)
829 /// The `%` operator (modulus)
831 /// The `&&` operator (logical and)
833 /// The `||` operator (logical or)
835 /// The `^` operator (bitwise xor)
837 /// The `&` operator (bitwise and)
839 /// The `|` operator (bitwise or)
841 /// The `<<` operator (shift left)
843 /// The `>>` operator (shift right)
845 /// The `==` operator (equality)
847 /// The `<` operator (less than)
849 /// The `<=` operator (less than or equal to)
851 /// The `!=` operator (not equal to)
853 /// The `>=` operator (greater than or equal to)
855 /// The `>` operator (greater than)
860 pub fn to_string(&self) -> &'static str {
883 pub fn lazy(&self) -> bool {
884 matches!(self, BinOpKind::And | BinOpKind::Or)
887 pub fn is_comparison(&self) -> bool {
889 // Note for developers: please keep this as is;
890 // we want compilation to fail if another variant is added.
892 Eq | Lt | Le | Ne | Gt | Ge => true,
893 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
898 pub type BinOp = Spanned<BinOpKind>;
902 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
903 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
905 /// The `*` operator for dereferencing
907 /// The `!` operator for logical inversion
909 /// The `-` operator for negation
914 pub fn to_string(op: UnOp) -> &'static str {
924 #[derive(Clone, Encodable, Decodable, Debug)]
932 pub fn tokens(&self) -> Option<&LazyTokenStream> {
934 StmtKind::Local(ref local) => local.tokens.as_ref(),
935 StmtKind::Item(ref item) => item.tokens.as_ref(),
936 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(),
937 StmtKind::Empty => None,
938 StmtKind::MacCall(ref mac) => mac.tokens.as_ref(),
942 pub fn has_trailing_semicolon(&self) -> bool {
944 StmtKind::Semi(_) => true,
945 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
950 /// Converts a parsed `Stmt` to a `Stmt` with
951 /// a trailing semicolon.
953 /// This only modifies the parsed AST struct, not the attached
954 /// `LazyTokenStream`. The parser is responsible for calling
955 /// `CreateTokenStream::add_trailing_semi` when there is actually
956 /// a semicolon in the tokenstream.
957 pub fn add_trailing_semicolon(mut self) -> Self {
958 self.kind = match self.kind {
959 StmtKind::Expr(expr) => StmtKind::Semi(expr),
960 StmtKind::MacCall(mac) => {
961 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
962 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
971 pub fn is_item(&self) -> bool {
972 matches!(self.kind, StmtKind::Item(_))
975 pub fn is_expr(&self) -> bool {
976 matches!(self.kind, StmtKind::Expr(_))
980 #[derive(Clone, Encodable, Decodable, Debug)]
982 /// A local (let) binding.
984 /// An item definition.
986 /// Expr without trailing semi-colon.
988 /// Expr with a trailing semi-colon.
990 /// Just a trailing semi-colon.
993 MacCall(P<MacCallStmt>),
996 #[derive(Clone, Encodable, Decodable, Debug)]
997 pub struct MacCallStmt {
999 pub style: MacStmtStyle,
1001 pub tokens: Option<LazyTokenStream>,
1004 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1005 pub enum MacStmtStyle {
1006 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1007 /// `foo!(...);`, `foo![...];`).
1009 /// The macro statement had braces (e.g., `foo! { ... }`).
1011 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1012 /// `foo!(...)`). All of these will end up being converted into macro
1017 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1018 #[derive(Clone, Encodable, Decodable, Debug)]
1022 pub ty: Option<P<Ty>>,
1023 pub kind: LocalKind,
1026 pub tokens: Option<LazyTokenStream>,
1029 #[derive(Clone, Encodable, Decodable, Debug)]
1030 pub enum LocalKind {
1031 /// Local declaration.
1032 /// Example: `let x;`
1034 /// Local declaration with an initializer.
1035 /// Example: `let x = y;`
1037 /// Local declaration with an initializer and an `else` clause.
1038 /// Example: `let Some(x) = y else { return };`
1039 InitElse(P<Expr>, P<Block>),
1043 pub fn init(&self) -> Option<&Expr> {
1046 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1050 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1053 Self::Init(init) => Some((init, None)),
1054 Self::InitElse(init, els) => Some((init, Some(els))),
1059 /// An arm of a 'match'.
1061 /// E.g., `0..=10 => { println!("match!") }` as in
1065 /// 0..=10 => { println!("match!") },
1066 /// _ => { println!("no match!") },
1069 #[derive(Clone, Encodable, Decodable, Debug)]
1072 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1074 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1075 pub guard: Option<P<Expr>>,
1080 pub is_placeholder: bool,
1083 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1084 #[derive(Clone, Encodable, Decodable, Debug)]
1085 pub struct ExprField {
1091 pub is_shorthand: bool,
1092 pub is_placeholder: bool,
1095 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1096 pub enum BlockCheckMode {
1098 Unsafe(UnsafeSource),
1101 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1102 pub enum UnsafeSource {
1107 /// A constant (expression) that's not an item or associated item,
1108 /// but needs its own `DefId` for type-checking, const-eval, etc.
1109 /// These are usually found nested inside types (e.g., array lengths)
1110 /// or expressions (e.g., repeat counts), and also used to define
1111 /// explicit discriminant values for enum variants.
1112 #[derive(Clone, Encodable, Decodable, Debug)]
1113 pub struct AnonConst {
1119 #[derive(Clone, Encodable, Decodable, Debug)]
1125 pub tokens: Option<LazyTokenStream>,
1128 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1129 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1130 rustc_data_structures::static_assert_size!(Expr, 104);
1133 /// Returns `true` if this expression would be valid somewhere that expects a value;
1134 /// for example, an `if` condition.
1135 pub fn returns(&self) -> bool {
1136 if let ExprKind::Block(ref block, _) = self.kind {
1137 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1139 Some(StmtKind::Expr(_)) => true,
1140 // Last statement is an explicit return?
1141 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1142 // This is a block that doesn't end in either an implicit or explicit return.
1146 // This is not a block, it is a value.
1151 /// Is this expr either `N`, or `{ N }`.
1153 /// If this is not the case, name resolution does not resolve `N` when using
1154 /// `min_const_generics` as more complex expressions are not supported.
1155 pub fn is_potential_trivial_const_param(&self) -> bool {
1156 let this = if let ExprKind::Block(ref block, None) = self.kind {
1157 if block.stmts.len() == 1 {
1158 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1166 if let ExprKind::Path(None, ref path) = this.kind {
1167 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1175 pub fn to_bound(&self) -> Option<GenericBound> {
1177 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1178 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1179 TraitBoundModifier::None,
1185 pub fn peel_parens(&self) -> &Expr {
1186 let mut expr = self;
1187 while let ExprKind::Paren(inner) = &expr.kind {
1193 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1194 pub fn to_ty(&self) -> Option<P<Ty>> {
1195 let kind = match &self.kind {
1196 // Trivial conversions.
1197 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1198 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1200 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1202 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1203 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1206 ExprKind::Repeat(expr, expr_len) => {
1207 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1210 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1212 ExprKind::Tup(exprs) => {
1213 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1217 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1218 // then type of result is trait object.
1219 // Otherwise we don't assume the result type.
1220 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1221 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1222 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1228 ExprKind::Underscore => TyKind::Infer,
1230 // This expression doesn't look like a type syntactically.
1234 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1237 pub fn precedence(&self) -> ExprPrecedence {
1239 ExprKind::Box(_) => ExprPrecedence::Box,
1240 ExprKind::Array(_) => ExprPrecedence::Array,
1241 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1242 ExprKind::Call(..) => ExprPrecedence::Call,
1243 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1244 ExprKind::Tup(_) => ExprPrecedence::Tup,
1245 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1246 ExprKind::Unary(..) => ExprPrecedence::Unary,
1247 ExprKind::Lit(_) => ExprPrecedence::Lit,
1248 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1249 ExprKind::Let(..) => ExprPrecedence::Let,
1250 ExprKind::If(..) => ExprPrecedence::If,
1251 ExprKind::While(..) => ExprPrecedence::While,
1252 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1253 ExprKind::Loop(..) => ExprPrecedence::Loop,
1254 ExprKind::Match(..) => ExprPrecedence::Match,
1255 ExprKind::Closure(..) => ExprPrecedence::Closure,
1256 ExprKind::Block(..) => ExprPrecedence::Block,
1257 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1258 ExprKind::Async(..) => ExprPrecedence::Async,
1259 ExprKind::Await(..) => ExprPrecedence::Await,
1260 ExprKind::Assign(..) => ExprPrecedence::Assign,
1261 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1262 ExprKind::Field(..) => ExprPrecedence::Field,
1263 ExprKind::Index(..) => ExprPrecedence::Index,
1264 ExprKind::Range(..) => ExprPrecedence::Range,
1265 ExprKind::Underscore => ExprPrecedence::Path,
1266 ExprKind::Path(..) => ExprPrecedence::Path,
1267 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1268 ExprKind::Break(..) => ExprPrecedence::Break,
1269 ExprKind::Continue(..) => ExprPrecedence::Continue,
1270 ExprKind::Ret(..) => ExprPrecedence::Ret,
1271 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1272 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1273 ExprKind::Struct(..) => ExprPrecedence::Struct,
1274 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1275 ExprKind::Paren(..) => ExprPrecedence::Paren,
1276 ExprKind::Try(..) => ExprPrecedence::Try,
1277 ExprKind::Yield(..) => ExprPrecedence::Yield,
1278 ExprKind::Yeet(..) => ExprPrecedence::Yeet,
1279 ExprKind::Err => ExprPrecedence::Err,
1283 pub fn take(&mut self) -> Self {
1288 kind: ExprKind::Err,
1290 attrs: ThinVec::new(),
1297 /// Limit types of a range (inclusive or exclusive)
1298 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1299 pub enum RangeLimits {
1300 /// Inclusive at the beginning, exclusive at the end
1302 /// Inclusive at the beginning and end
1306 #[derive(Clone, Encodable, Decodable, Debug)]
1307 pub enum StructRest {
1312 /// No trailing `..` or expression.
1316 #[derive(Clone, Encodable, Decodable, Debug)]
1317 pub struct StructExpr {
1318 pub qself: Option<QSelf>,
1320 pub fields: Vec<ExprField>,
1321 pub rest: StructRest,
1324 #[derive(Clone, Encodable, Decodable, Debug)]
1326 /// A `box x` expression.
1328 /// An array (`[a, b, c, d]`)
1329 Array(Vec<P<Expr>>),
1330 /// Allow anonymous constants from an inline `const` block
1331 ConstBlock(AnonConst),
1334 /// The first field resolves to the function itself,
1335 /// and the second field is the list of arguments.
1336 /// This also represents calling the constructor of
1337 /// tuple-like ADTs such as tuple structs and enum variants.
1338 Call(P<Expr>, Vec<P<Expr>>),
1339 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1341 /// The `PathSegment` represents the method name and its generic arguments
1342 /// (within the angle brackets).
1343 /// The first element of the vector of an `Expr` is the expression that evaluates
1344 /// to the object on which the method is being called on (the receiver),
1345 /// and the remaining elements are the rest of the arguments.
1346 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1347 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1348 /// This `Span` is the span of the function, without the dot and receiver
1349 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1350 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1351 /// A tuple (e.g., `(a, b, c, d)`).
1353 /// A binary operation (e.g., `a + b`, `a * b`).
1354 Binary(BinOp, P<Expr>, P<Expr>),
1355 /// A unary operation (e.g., `!x`, `*x`).
1356 Unary(UnOp, P<Expr>),
1357 /// A literal (e.g., `1`, `"foo"`).
1359 /// A cast (e.g., `foo as f64`).
1360 Cast(P<Expr>, P<Ty>),
1361 /// A type ascription (e.g., `42: usize`).
1362 Type(P<Expr>, P<Ty>),
1363 /// A `let pat = expr` expression that is only semantically allowed in the condition
1364 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1366 /// `Span` represents the whole `let pat = expr` statement.
1367 Let(P<Pat>, P<Expr>, Span),
1368 /// An `if` block, with an optional `else` block.
1370 /// `if expr { block } else { expr }`
1371 If(P<Expr>, P<Block>, Option<P<Expr>>),
1372 /// A while loop, with an optional label.
1374 /// `'label: while expr { block }`
1375 While(P<Expr>, P<Block>, Option<Label>),
1376 /// A `for` loop, with an optional label.
1378 /// `'label: for pat in expr { block }`
1380 /// This is desugared to a combination of `loop` and `match` expressions.
1381 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1382 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1384 /// `'label: loop { block }`
1385 Loop(P<Block>, Option<Label>),
1386 /// A `match` block.
1387 Match(P<Expr>, Vec<Arm>),
1388 /// A closure (e.g., `move |a, b, c| a + b + c`).
1390 /// The final span is the span of the argument block `|...|`.
1391 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1392 /// A block (`'label: { ... }`).
1393 Block(P<Block>, Option<Label>),
1394 /// An async block (`async move { ... }`).
1396 /// The `NodeId` is the `NodeId` for the closure that results from
1397 /// desugaring an async block, just like the NodeId field in the
1398 /// `Async::Yes` variant. This is necessary in order to create a def for the
1399 /// closure which can be used as a parent of any child defs. Defs
1400 /// created during lowering cannot be made the parent of any other
1401 /// preexisting defs.
1402 Async(CaptureBy, NodeId, P<Block>),
1403 /// An await expression (`my_future.await`).
1406 /// A try block (`try { ... }`).
1409 /// An assignment (`a = foo()`).
1410 /// The `Span` argument is the span of the `=` token.
1411 Assign(P<Expr>, P<Expr>, Span),
1412 /// An assignment with an operator.
1415 AssignOp(BinOp, P<Expr>, P<Expr>),
1416 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1417 Field(P<Expr>, Ident),
1418 /// An indexing operation (e.g., `foo[2]`).
1419 Index(P<Expr>, P<Expr>),
1420 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1421 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1422 /// An underscore, used in destructuring assignment to ignore a value.
1425 /// Variable reference, possibly containing `::` and/or type
1426 /// parameters (e.g., `foo::bar::<baz>`).
1428 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1429 Path(Option<QSelf>, Path),
1431 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1432 AddrOf(BorrowKind, Mutability, P<Expr>),
1433 /// A `break`, with an optional label to break, and an optional expression.
1434 Break(Option<Label>, Option<P<Expr>>),
1435 /// A `continue`, with an optional label.
1436 Continue(Option<Label>),
1437 /// A `return`, with an optional value to be returned.
1438 Ret(Option<P<Expr>>),
1440 /// Output of the `asm!()` macro.
1441 InlineAsm(P<InlineAsm>),
1443 /// A macro invocation; pre-expansion.
1446 /// A struct literal expression.
1448 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1449 Struct(P<StructExpr>),
1451 /// An array literal constructed from one repeated element.
1453 /// E.g., `[1; 5]`. The expression is the element to be
1454 /// repeated; the constant is the number of times to repeat it.
1455 Repeat(P<Expr>, AnonConst),
1457 /// No-op: used solely so we can pretty-print faithfully.
1460 /// A try expression (`expr?`).
1463 /// A `yield`, with an optional value to be yielded.
1464 Yield(Option<P<Expr>>),
1466 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1467 /// with an optional value to be returned.
1468 Yeet(Option<P<Expr>>),
1470 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1474 /// The explicit `Self` type in a "qualified path". The actual
1475 /// path, including the trait and the associated item, is stored
1476 /// separately. `position` represents the index of the associated
1477 /// item qualified with this `Self` type.
1479 /// ```ignore (only-for-syntax-highlight)
1480 /// <Vec<T> as a::b::Trait>::AssociatedItem
1481 /// ^~~~~ ~~~~~~~~~~~~~~^
1484 /// <Vec<T>>::AssociatedItem
1488 #[derive(Clone, Encodable, Decodable, Debug)]
1492 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1493 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1494 /// 0`, this is an empty span.
1495 pub path_span: Span,
1496 pub position: usize,
1499 /// A capture clause used in closures and `async` blocks.
1500 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1501 pub enum CaptureBy {
1502 /// `move |x| y + x`.
1504 /// `move` keyword was not specified.
1508 /// The movability of a generator / closure literal:
1509 /// whether a generator contains self-references, causing it to be `!Unpin`.
1510 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1511 #[derive(HashStable_Generic)]
1512 pub enum Movability {
1513 /// May contain self-references, `!Unpin`.
1515 /// Must not contain self-references, `Unpin`.
1519 /// Represents a macro invocation. The `path` indicates which macro
1520 /// is being invoked, and the `args` are arguments passed to it.
1521 #[derive(Clone, Encodable, Decodable, Debug)]
1522 pub struct MacCall {
1524 pub args: P<MacArgs>,
1525 pub prior_type_ascription: Option<(Span, bool)>,
1529 pub fn span(&self) -> Span {
1530 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1534 /// Arguments passed to an attribute or a function-like macro.
1535 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1537 /// No arguments - `#[attr]`.
1539 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1540 Delimited(DelimSpan, MacDelimiter, TokenStream),
1541 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1543 /// Span of the `=` token.
1545 /// "value" as a nonterminal token.
1551 pub fn delim(&self) -> Option<Delimiter> {
1553 MacArgs::Delimited(_, delim, _) => Some(delim.to_token()),
1554 MacArgs::Empty | MacArgs::Eq(..) => None,
1558 pub fn span(&self) -> Option<Span> {
1560 MacArgs::Empty => None,
1561 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1562 MacArgs::Eq(eq_span, token) => Some(eq_span.to(token.span)),
1566 /// Tokens inside the delimiters or after `=`.
1567 /// Proc macros see these tokens, for example.
1568 pub fn inner_tokens(&self) -> TokenStream {
1570 MacArgs::Empty => TokenStream::default(),
1571 MacArgs::Delimited(.., tokens) => tokens.clone(),
1572 MacArgs::Eq(.., token) => TokenTree::Token(token.clone()).into(),
1576 /// Whether a macro with these arguments needs a semicolon
1577 /// when used as a standalone item or statement.
1578 pub fn need_semicolon(&self) -> bool {
1579 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1583 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1584 pub enum MacDelimiter {
1591 pub fn to_token(self) -> Delimiter {
1593 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1594 MacDelimiter::Bracket => Delimiter::Bracket,
1595 MacDelimiter::Brace => Delimiter::Brace,
1599 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1601 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1602 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1603 Delimiter::Brace => Some(MacDelimiter::Brace),
1604 Delimiter::Invisible => None,
1609 /// Represents a macro definition.
1610 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1611 pub struct MacroDef {
1612 pub body: P<MacArgs>,
1613 /// `true` if macro was defined with `macro_rules`.
1614 pub macro_rules: bool,
1617 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1618 #[derive(HashStable_Generic)]
1620 /// A regular string, like `"foo"`.
1622 /// A raw string, like `r##"foo"##`.
1624 /// The value is the number of `#` symbols used.
1629 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1631 /// The original literal token as written in source code.
1632 pub token: token::Lit,
1633 /// The "semantic" representation of the literal lowered from the original tokens.
1634 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1635 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1640 /// Same as `Lit`, but restricted to string literals.
1641 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1643 /// The original literal token as written in source code.
1644 pub style: StrStyle,
1646 pub suffix: Option<Symbol>,
1648 /// The unescaped "semantic" representation of the literal lowered from the original token.
1649 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1650 pub symbol_unescaped: Symbol,
1654 pub fn as_lit(&self) -> Lit {
1655 let token_kind = match self.style {
1656 StrStyle::Cooked => token::Str,
1657 StrStyle::Raw(n) => token::StrRaw(n),
1660 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1662 kind: LitKind::Str(self.symbol_unescaped, self.style),
1667 /// Type of the integer literal based on provided suffix.
1668 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1669 #[derive(HashStable_Generic)]
1670 pub enum LitIntType {
1679 /// Type of the float literal based on provided suffix.
1680 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1681 #[derive(HashStable_Generic)]
1682 pub enum LitFloatType {
1683 /// A float literal with a suffix (`1f32` or `1E10f32`).
1685 /// A float literal without a suffix (`1.0 or 1.0E10`).
1691 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1692 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1694 /// A string literal (`"foo"`).
1695 Str(Symbol, StrStyle),
1696 /// A byte string (`b"foo"`).
1698 /// A byte char (`b'f'`).
1700 /// A character literal (`'a'`).
1702 /// An integer literal (`1`).
1703 Int(u128, LitIntType),
1704 /// A float literal (`1f64` or `1E10f64`).
1705 Float(Symbol, LitFloatType),
1706 /// A boolean literal.
1708 /// Placeholder for a literal that wasn't well-formed in some way.
1713 /// Returns `true` if this literal is a string.
1714 pub fn is_str(&self) -> bool {
1715 matches!(self, LitKind::Str(..))
1718 /// Returns `true` if this literal is byte literal string.
1719 pub fn is_bytestr(&self) -> bool {
1720 matches!(self, LitKind::ByteStr(_))
1723 /// Returns `true` if this is a numeric literal.
1724 pub fn is_numeric(&self) -> bool {
1725 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1728 /// Returns `true` if this literal has no suffix.
1729 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1730 pub fn is_unsuffixed(&self) -> bool {
1734 /// Returns `true` if this literal has a suffix.
1735 pub fn is_suffixed(&self) -> bool {
1737 // suffixed variants
1738 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1739 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1740 // unsuffixed variants
1742 | LitKind::ByteStr(..)
1745 | LitKind::Int(_, LitIntType::Unsuffixed)
1746 | LitKind::Float(_, LitFloatType::Unsuffixed)
1748 | LitKind::Err(..) => false,
1753 // N.B., If you change this, you'll probably want to change the corresponding
1754 // type structure in `middle/ty.rs` as well.
1755 #[derive(Clone, Encodable, Decodable, Debug)]
1758 pub mutbl: Mutability,
1761 /// Represents a function's signature in a trait declaration,
1762 /// trait implementation, or free function.
1763 #[derive(Clone, Encodable, Decodable, Debug)]
1765 pub header: FnHeader,
1766 pub decl: P<FnDecl>,
1770 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1771 #[derive(Encodable, Decodable, HashStable_Generic)]
1778 pub fn name_str(self) -> &'static str {
1780 FloatTy::F32 => "f32",
1781 FloatTy::F64 => "f64",
1785 pub fn name(self) -> Symbol {
1787 FloatTy::F32 => sym::f32,
1788 FloatTy::F64 => sym::f64,
1793 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1794 #[derive(Encodable, Decodable, HashStable_Generic)]
1805 pub fn name_str(&self) -> &'static str {
1807 IntTy::Isize => "isize",
1809 IntTy::I16 => "i16",
1810 IntTy::I32 => "i32",
1811 IntTy::I64 => "i64",
1812 IntTy::I128 => "i128",
1816 pub fn name(&self) -> Symbol {
1818 IntTy::Isize => sym::isize,
1819 IntTy::I8 => sym::i8,
1820 IntTy::I16 => sym::i16,
1821 IntTy::I32 => sym::i32,
1822 IntTy::I64 => sym::i64,
1823 IntTy::I128 => sym::i128,
1828 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1829 #[derive(Encodable, Decodable, HashStable_Generic)]
1840 pub fn name_str(&self) -> &'static str {
1842 UintTy::Usize => "usize",
1844 UintTy::U16 => "u16",
1845 UintTy::U32 => "u32",
1846 UintTy::U64 => "u64",
1847 UintTy::U128 => "u128",
1851 pub fn name(&self) -> Symbol {
1853 UintTy::Usize => sym::usize,
1854 UintTy::U8 => sym::u8,
1855 UintTy::U16 => sym::u16,
1856 UintTy::U32 => sym::u32,
1857 UintTy::U64 => sym::u64,
1858 UintTy::U128 => sym::u128,
1863 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1864 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1865 #[derive(Clone, Encodable, Decodable, Debug)]
1866 pub struct AssocConstraint {
1869 pub gen_args: Option<GenericArgs>,
1870 pub kind: AssocConstraintKind,
1874 /// The kinds of an `AssocConstraint`.
1875 #[derive(Clone, Encodable, Decodable, Debug)]
1881 impl From<P<Ty>> for Term {
1882 fn from(v: P<Ty>) -> Self {
1887 impl From<AnonConst> for Term {
1888 fn from(v: AnonConst) -> Self {
1893 /// The kinds of an `AssocConstraint`.
1894 #[derive(Clone, Encodable, Decodable, Debug)]
1895 pub enum AssocConstraintKind {
1896 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1897 Equality { term: Term },
1898 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1899 Bound { bounds: GenericBounds },
1902 #[derive(Encodable, Decodable, Debug)]
1907 pub tokens: Option<LazyTokenStream>,
1911 fn clone(&self) -> Self {
1912 ensure_sufficient_stack(|| Self {
1914 kind: self.kind.clone(),
1916 tokens: self.tokens.clone(),
1922 pub fn peel_refs(&self) -> &Self {
1923 let mut final_ty = self;
1924 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1931 #[derive(Clone, Encodable, Decodable, Debug)]
1932 pub struct BareFnTy {
1933 pub unsafety: Unsafe,
1935 pub generic_params: Vec<GenericParam>,
1936 pub decl: P<FnDecl>,
1939 /// The various kinds of type recognized by the compiler.
1940 #[derive(Clone, Encodable, Decodable, Debug)]
1942 /// A variable-length slice (`[T]`).
1944 /// A fixed length array (`[T; n]`).
1945 Array(P<Ty>, AnonConst),
1946 /// A raw pointer (`*const T` or `*mut T`).
1948 /// A reference (`&'a T` or `&'a mut T`).
1949 Rptr(Option<Lifetime>, MutTy),
1950 /// A bare function (e.g., `fn(usize) -> bool`).
1951 BareFn(P<BareFnTy>),
1952 /// The never type (`!`).
1954 /// A tuple (`(A, B, C, D,...)`).
1956 /// A path (`module::module::...::Type`), optionally
1957 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1959 /// Type parameters are stored in the `Path` itself.
1960 Path(Option<QSelf>, Path),
1961 /// A trait object type `Bound1 + Bound2 + Bound3`
1962 /// where `Bound` is a trait or a lifetime.
1963 TraitObject(GenericBounds, TraitObjectSyntax),
1964 /// An `impl Bound1 + Bound2 + Bound3` type
1965 /// where `Bound` is a trait or a lifetime.
1967 /// The `NodeId` exists to prevent lowering from having to
1968 /// generate `NodeId`s on the fly, which would complicate
1969 /// the generation of opaque `type Foo = impl Trait` items significantly.
1970 ImplTrait(NodeId, GenericBounds),
1971 /// No-op; kept solely so that we can pretty-print faithfully.
1975 /// This means the type should be inferred instead of it having been
1976 /// specified. This can appear anywhere in a type.
1978 /// Inferred type of a `self` or `&self` argument in a method.
1980 /// A macro in the type position.
1982 /// Placeholder for a kind that has failed to be defined.
1984 /// Placeholder for a `va_list`.
1989 pub fn is_implicit_self(&self) -> bool {
1990 matches!(self, TyKind::ImplicitSelf)
1993 pub fn is_unit(&self) -> bool {
1994 matches!(self, TyKind::Tup(tys) if tys.is_empty())
1998 /// Syntax used to declare a trait object.
1999 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2000 pub enum TraitObjectSyntax {
2005 /// Inline assembly operand explicit register or register class.
2007 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2008 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2009 pub enum InlineAsmRegOrRegClass {
2014 bitflags::bitflags! {
2015 #[derive(Encodable, Decodable, HashStable_Generic)]
2016 pub struct InlineAsmOptions: u16 {
2017 const PURE = 1 << 0;
2018 const NOMEM = 1 << 1;
2019 const READONLY = 1 << 2;
2020 const PRESERVES_FLAGS = 1 << 3;
2021 const NORETURN = 1 << 4;
2022 const NOSTACK = 1 << 5;
2023 const ATT_SYNTAX = 1 << 6;
2025 const MAY_UNWIND = 1 << 8;
2029 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2030 pub enum InlineAsmTemplatePiece {
2032 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2035 impl fmt::Display for InlineAsmTemplatePiece {
2036 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2038 Self::String(s) => {
2039 for c in s.chars() {
2041 '{' => f.write_str("{{")?,
2042 '}' => f.write_str("}}")?,
2048 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2049 write!(f, "{{{}:{}}}", operand_idx, modifier)
2051 Self::Placeholder { operand_idx, modifier: None, .. } => {
2052 write!(f, "{{{}}}", operand_idx)
2058 impl InlineAsmTemplatePiece {
2059 /// Rebuilds the asm template string from its pieces.
2060 pub fn to_string(s: &[Self]) -> String {
2062 let mut out = String::new();
2064 let _ = write!(out, "{}", p);
2070 /// Inline assembly symbol operands get their own AST node that is somewhat
2071 /// similar to `AnonConst`.
2073 /// The main difference is that we specifically don't assign it `DefId` in
2074 /// `DefCollector`. Instead this is deferred until AST lowering where we
2075 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2076 /// depending on what the path resolves to.
2077 #[derive(Clone, Encodable, Decodable, Debug)]
2078 pub struct InlineAsmSym {
2080 pub qself: Option<QSelf>,
2084 /// Inline assembly operand.
2086 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2087 #[derive(Clone, Encodable, Decodable, Debug)]
2088 pub enum InlineAsmOperand {
2090 reg: InlineAsmRegOrRegClass,
2094 reg: InlineAsmRegOrRegClass,
2096 expr: Option<P<Expr>>,
2099 reg: InlineAsmRegOrRegClass,
2104 reg: InlineAsmRegOrRegClass,
2107 out_expr: Option<P<Expr>>,
2110 anon_const: AnonConst,
2117 /// Inline assembly.
2119 /// E.g., `asm!("NOP");`.
2120 #[derive(Clone, Encodable, Decodable, Debug)]
2121 pub struct InlineAsm {
2122 pub template: Vec<InlineAsmTemplatePiece>,
2123 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2124 pub operands: Vec<(InlineAsmOperand, Span)>,
2125 pub clobber_abis: Vec<(Symbol, Span)>,
2126 pub options: InlineAsmOptions,
2127 pub line_spans: Vec<Span>,
2130 /// A parameter in a function header.
2132 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2133 #[derive(Clone, Encodable, Decodable, Debug)]
2140 pub is_placeholder: bool,
2143 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2145 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2146 #[derive(Clone, Encodable, Decodable, Debug)]
2148 /// `self`, `mut self`
2150 /// `&'lt self`, `&'lt mut self`
2151 Region(Option<Lifetime>, Mutability),
2152 /// `self: TYPE`, `mut self: TYPE`
2153 Explicit(P<Ty>, Mutability),
2156 pub type ExplicitSelf = Spanned<SelfKind>;
2159 /// Attempts to cast parameter to `ExplicitSelf`.
2160 pub fn to_self(&self) -> Option<ExplicitSelf> {
2161 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2162 if ident.name == kw::SelfLower {
2163 return match self.ty.kind {
2164 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2165 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2166 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2169 self.pat.span.to(self.ty.span),
2170 SelfKind::Explicit(self.ty.clone(), mutbl),
2178 /// Returns `true` if parameter is `self`.
2179 pub fn is_self(&self) -> bool {
2180 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2181 ident.name == kw::SelfLower
2187 /// Builds a `Param` object from `ExplicitSelf`.
2188 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2189 let span = eself.span.to(eself_ident.span);
2190 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2191 let param = |mutbl, ty| Param {
2195 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2202 is_placeholder: false,
2205 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2206 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2207 SelfKind::Region(lt, mutbl) => param(
2211 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2220 /// A signature (not the body) of a function declaration.
2222 /// E.g., `fn foo(bar: baz)`.
2224 /// Please note that it's different from `FnHeader` structure
2225 /// which contains metadata about function safety, asyncness, constness and ABI.
2226 #[derive(Clone, Encodable, Decodable, Debug)]
2228 pub inputs: Vec<Param>,
2229 pub output: FnRetTy,
2233 pub fn has_self(&self) -> bool {
2234 self.inputs.get(0).map_or(false, Param::is_self)
2236 pub fn c_variadic(&self) -> bool {
2237 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2241 /// Is the trait definition an auto trait?
2242 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2248 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2249 #[derive(HashStable_Generic)]
2255 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2257 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2262 pub fn is_async(self) -> bool {
2263 matches!(self, Async::Yes { .. })
2266 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2267 pub fn opt_return_id(self) -> Option<NodeId> {
2269 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2275 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2276 #[derive(HashStable_Generic)]
2282 /// Item defaultness.
2283 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2284 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2285 pub enum Defaultness {
2290 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2291 pub enum ImplPolarity {
2292 /// `impl Trait for Type`
2294 /// `impl !Trait for Type`
2298 impl fmt::Debug for ImplPolarity {
2299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2301 ImplPolarity::Positive => "positive".fmt(f),
2302 ImplPolarity::Negative(_) => "negative".fmt(f),
2307 #[derive(Clone, Encodable, Decodable, Debug)]
2309 /// Returns type is not specified.
2311 /// Functions default to `()` and closures default to inference.
2312 /// Span points to where return type would be inserted.
2314 /// Everything else.
2319 pub fn span(&self) -> Span {
2321 FnRetTy::Default(span) => span,
2322 FnRetTy::Ty(ref ty) => ty.span,
2327 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2333 /// Module item kind.
2334 #[derive(Clone, Encodable, Decodable, Debug)]
2336 /// Module with inlined definition `mod foo { ... }`,
2337 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2338 /// The inner span is from the first token past `{` to the last token until `}`,
2339 /// or from the first to the last token in the loaded file.
2340 Loaded(Vec<P<Item>>, Inline, ModSpans),
2341 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2345 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2346 pub struct ModSpans {
2347 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2348 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2349 pub inner_span: Span,
2350 pub inject_use_span: Span,
2353 impl Default for ModSpans {
2354 fn default() -> ModSpans {
2355 ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2359 /// Foreign module declaration.
2361 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2362 #[derive(Clone, Encodable, Decodable, Debug)]
2363 pub struct ForeignMod {
2364 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2365 /// semantically by Rust.
2366 pub unsafety: Unsafe,
2367 pub abi: Option<StrLit>,
2368 pub items: Vec<P<ForeignItem>>,
2371 #[derive(Clone, Encodable, Decodable, Debug)]
2372 pub struct EnumDef {
2373 pub variants: Vec<Variant>,
2376 #[derive(Clone, Encodable, Decodable, Debug)]
2377 pub struct Variant {
2378 /// Attributes of the variant.
2380 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2384 /// The visibility of the variant. Syntactically accepted but not semantically.
2385 pub vis: Visibility,
2386 /// Name of the variant.
2389 /// Fields and constructor id of the variant.
2390 pub data: VariantData,
2391 /// Explicit discriminant, e.g., `Foo = 1`.
2392 pub disr_expr: Option<AnonConst>,
2393 /// Is a macro placeholder
2394 pub is_placeholder: bool,
2397 /// Part of `use` item to the right of its prefix.
2398 #[derive(Clone, Encodable, Decodable, Debug)]
2399 pub enum UseTreeKind {
2400 /// `use prefix` or `use prefix as rename`
2402 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2404 Simple(Option<Ident>, NodeId, NodeId),
2405 /// `use prefix::{...}`
2406 Nested(Vec<(UseTree, NodeId)>),
2411 /// A tree of paths sharing common prefixes.
2412 /// Used in `use` items both at top-level and inside of braces in import groups.
2413 #[derive(Clone, Encodable, Decodable, Debug)]
2414 pub struct UseTree {
2416 pub kind: UseTreeKind,
2421 pub fn ident(&self) -> Ident {
2423 UseTreeKind::Simple(Some(rename), ..) => rename,
2424 UseTreeKind::Simple(None, ..) => {
2425 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2427 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2432 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2433 /// are contained as statements within items. These two cases need to be
2434 /// distinguished for pretty-printing.
2435 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2436 pub enum AttrStyle {
2441 rustc_index::newtype_index! {
2444 DEBUG_FORMAT = "AttrId({})"
2448 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2449 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2454 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2455 fn decode(_: &mut D) -> AttrId {
2456 crate::attr::mk_attr_id()
2460 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2461 pub struct AttrItem {
2464 pub tokens: Option<LazyTokenStream>,
2467 /// A list of attributes.
2468 pub type AttrVec = ThinVec<Attribute>;
2470 /// Metadata associated with an item.
2471 #[derive(Clone, Encodable, Decodable, Debug)]
2472 pub struct Attribute {
2475 /// Denotes if the attribute decorates the following construct (outer)
2476 /// or the construct this attribute is contained within (inner).
2477 pub style: AttrStyle,
2481 #[derive(Clone, Encodable, Decodable, Debug)]
2483 /// A normal attribute.
2484 Normal(AttrItem, Option<LazyTokenStream>),
2486 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2487 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2488 /// variant (which is much less compact and thus more expensive).
2489 DocComment(CommentKind, Symbol),
2492 /// `TraitRef`s appear in impls.
2494 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2495 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2496 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2497 /// same as the impl's `NodeId`).
2498 #[derive(Clone, Encodable, Decodable, Debug)]
2499 pub struct TraitRef {
2504 #[derive(Clone, Encodable, Decodable, Debug)]
2505 pub struct PolyTraitRef {
2506 /// The `'a` in `for<'a> Foo<&'a T>`.
2507 pub bound_generic_params: Vec<GenericParam>,
2509 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2510 pub trait_ref: TraitRef,
2516 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2518 bound_generic_params: generic_params,
2519 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2525 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2526 pub enum CrateSugar {
2527 /// Source is `pub(crate)`.
2530 /// Source is (just) `crate`.
2534 #[derive(Clone, Encodable, Decodable, Debug)]
2535 pub struct Visibility {
2536 pub kind: VisibilityKind,
2538 pub tokens: Option<LazyTokenStream>,
2541 #[derive(Clone, Encodable, Decodable, Debug)]
2542 pub enum VisibilityKind {
2545 Restricted { path: P<Path>, id: NodeId },
2549 impl VisibilityKind {
2550 pub fn is_pub(&self) -> bool {
2551 matches!(self, VisibilityKind::Public)
2555 /// Field definition in a struct, variant or union.
2557 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2558 #[derive(Clone, Encodable, Decodable, Debug)]
2559 pub struct FieldDef {
2563 pub vis: Visibility,
2564 pub ident: Option<Ident>,
2567 pub is_placeholder: bool,
2570 /// Fields and constructor ids of enum variants and structs.
2571 #[derive(Clone, Encodable, Decodable, Debug)]
2572 pub enum VariantData {
2575 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2576 Struct(Vec<FieldDef>, bool),
2579 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2580 Tuple(Vec<FieldDef>, NodeId),
2583 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2588 /// Return the fields of this variant.
2589 pub fn fields(&self) -> &[FieldDef] {
2591 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2596 /// Return the `NodeId` of this variant's constructor, if it has one.
2597 pub fn ctor_id(&self) -> Option<NodeId> {
2599 VariantData::Struct(..) => None,
2600 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2605 /// An item definition.
2606 #[derive(Clone, Encodable, Decodable, Debug)]
2607 pub struct Item<K = ItemKind> {
2608 pub attrs: Vec<Attribute>,
2611 pub vis: Visibility,
2612 /// The name of the item.
2613 /// It might be a dummy name in case of anonymous items.
2618 /// Original tokens this item was parsed from. This isn't necessarily
2619 /// available for all items, although over time more and more items should
2620 /// have this be `Some`. Right now this is primarily used for procedural
2621 /// macros, notably custom attributes.
2623 /// Note that the tokens here do not include the outer attributes, but will
2624 /// include inner attributes.
2625 pub tokens: Option<LazyTokenStream>,
2629 /// Return the span that encompasses the attributes.
2630 pub fn span_with_attributes(&self) -> Span {
2631 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2635 impl<K: Into<ItemKind>> Item<K> {
2636 pub fn into_item(self) -> Item {
2637 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2638 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2642 /// `extern` qualifier on a function item or function type.
2643 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2651 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2652 abi.map_or(Extern::Implicit, Extern::Explicit)
2656 /// A function header.
2658 /// All the information between the visibility and the name of the function is
2659 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2660 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2661 pub struct FnHeader {
2662 pub unsafety: Unsafe,
2663 pub asyncness: Async,
2664 pub constness: Const,
2669 /// Does this function header have any qualifiers or is it empty?
2670 pub fn has_qualifiers(&self) -> bool {
2671 let Self { unsafety, asyncness, constness, ext } = self;
2672 matches!(unsafety, Unsafe::Yes(_))
2673 || asyncness.is_async()
2674 || matches!(constness, Const::Yes(_))
2675 || !matches!(ext, Extern::None)
2679 impl Default for FnHeader {
2680 fn default() -> FnHeader {
2682 unsafety: Unsafe::No,
2683 asyncness: Async::No,
2684 constness: Const::No,
2690 #[derive(Clone, Encodable, Decodable, Debug)]
2692 pub unsafety: Unsafe,
2693 pub is_auto: IsAuto,
2694 pub generics: Generics,
2695 pub bounds: GenericBounds,
2696 pub items: Vec<P<AssocItem>>,
2699 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2700 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2701 /// are two locations for where clause on type aliases, but their predicates
2702 /// are concatenated together.
2704 /// Take this example:
2705 /// ```ignore (only-for-syntax-highlight)
2707 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2709 /// impl Foo for () {
2710 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2711 /// // ^^^^^^^^^^^^^^ first where clause
2712 /// // ^^^^^^^^^^^^^^ second where clause
2716 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2717 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2718 pub struct TyAliasWhereClause(pub bool, pub Span);
2720 #[derive(Clone, Encodable, Decodable, Debug)]
2721 pub struct TyAlias {
2722 pub defaultness: Defaultness,
2723 pub generics: Generics,
2724 /// The span information for the two where clauses (before equals, after equals)
2725 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2726 /// The index in `generics.where_clause.predicates` that would split into
2727 /// predicates from the where clause before the equals and the predicates
2728 /// from the where clause after the equals
2729 pub where_predicates_split: usize,
2730 pub bounds: GenericBounds,
2731 pub ty: Option<P<Ty>>,
2734 #[derive(Clone, Encodable, Decodable, Debug)]
2736 pub defaultness: Defaultness,
2737 pub unsafety: Unsafe,
2738 pub generics: Generics,
2739 pub constness: Const,
2740 pub polarity: ImplPolarity,
2741 /// The trait being implemented, if any.
2742 pub of_trait: Option<TraitRef>,
2744 pub items: Vec<P<AssocItem>>,
2747 #[derive(Clone, Encodable, Decodable, Debug)]
2749 pub defaultness: Defaultness,
2750 pub generics: Generics,
2752 pub body: Option<P<Block>>,
2755 #[derive(Clone, Encodable, Decodable, Debug)]
2757 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2759 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2760 ExternCrate(Option<Symbol>),
2761 /// A use declaration item (`use`).
2763 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2765 /// A static item (`static`).
2767 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2768 Static(P<Ty>, Mutability, Option<P<Expr>>),
2769 /// A constant item (`const`).
2771 /// E.g., `const FOO: i32 = 42;`.
2772 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2773 /// A function declaration (`fn`).
2775 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2777 /// A module declaration (`mod`).
2779 /// E.g., `mod foo;` or `mod foo { .. }`.
2780 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2781 /// semantically by Rust.
2782 Mod(Unsafe, ModKind),
2783 /// An external module (`extern`).
2785 /// E.g., `extern {}` or `extern "C" {}`.
2786 ForeignMod(ForeignMod),
2787 /// Module-level inline assembly (from `global_asm!()`).
2788 GlobalAsm(Box<InlineAsm>),
2789 /// A type alias (`type`).
2791 /// E.g., `type Foo = Bar<u8>;`.
2792 TyAlias(Box<TyAlias>),
2793 /// An enum definition (`enum`).
2795 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2796 Enum(EnumDef, Generics),
2797 /// A struct definition (`struct`).
2799 /// E.g., `struct Foo<A> { x: A }`.
2800 Struct(VariantData, Generics),
2801 /// A union definition (`union`).
2803 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2804 Union(VariantData, Generics),
2805 /// A trait declaration (`trait`).
2807 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2811 /// E.g., `trait Foo = Bar + Quux;`.
2812 TraitAlias(Generics, GenericBounds),
2813 /// An implementation.
2815 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2817 /// A macro invocation.
2819 /// E.g., `foo!(..)`.
2822 /// A macro definition.
2826 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2827 rustc_data_structures::static_assert_size!(ItemKind, 112);
2830 pub fn article(&self) -> &str {
2833 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2834 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2835 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2839 pub fn descr(&self) -> &str {
2841 ItemKind::ExternCrate(..) => "extern crate",
2842 ItemKind::Use(..) => "`use` import",
2843 ItemKind::Static(..) => "static item",
2844 ItemKind::Const(..) => "constant item",
2845 ItemKind::Fn(..) => "function",
2846 ItemKind::Mod(..) => "module",
2847 ItemKind::ForeignMod(..) => "extern block",
2848 ItemKind::GlobalAsm(..) => "global asm item",
2849 ItemKind::TyAlias(..) => "type alias",
2850 ItemKind::Enum(..) => "enum",
2851 ItemKind::Struct(..) => "struct",
2852 ItemKind::Union(..) => "union",
2853 ItemKind::Trait(..) => "trait",
2854 ItemKind::TraitAlias(..) => "trait alias",
2855 ItemKind::MacCall(..) => "item macro invocation",
2856 ItemKind::MacroDef(..) => "macro definition",
2857 ItemKind::Impl { .. } => "implementation",
2861 pub fn generics(&self) -> Option<&Generics> {
2863 Self::Fn(box Fn { generics, .. })
2864 | Self::TyAlias(box TyAlias { generics, .. })
2865 | Self::Enum(_, generics)
2866 | Self::Struct(_, generics)
2867 | Self::Union(_, generics)
2868 | Self::Trait(box Trait { generics, .. })
2869 | Self::TraitAlias(generics, _)
2870 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2876 /// Represents associated items.
2877 /// These include items in `impl` and `trait` definitions.
2878 pub type AssocItem = Item<AssocItemKind>;
2880 /// Represents associated item kinds.
2882 /// The term "provided" in the variants below refers to the item having a default
2883 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2884 /// In an implementation, all items must be provided.
2885 /// The `Option`s below denote the bodies, where `Some(_)`
2886 /// means "provided" and conversely `None` means "required".
2887 #[derive(Clone, Encodable, Decodable, Debug)]
2888 pub enum AssocItemKind {
2889 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2890 /// If `def` is parsed, then the constant is provided, and otherwise required.
2891 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2892 /// An associated function.
2894 /// An associated type.
2895 TyAlias(Box<TyAlias>),
2896 /// A macro expanding to associated items.
2900 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2901 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2903 impl AssocItemKind {
2904 pub fn defaultness(&self) -> Defaultness {
2906 Self::Const(defaultness, ..)
2907 | Self::Fn(box Fn { defaultness, .. })
2908 | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness,
2909 Self::MacCall(..) => Defaultness::Final,
2914 impl From<AssocItemKind> for ItemKind {
2915 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2916 match assoc_item_kind {
2917 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2918 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2919 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2920 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2925 impl TryFrom<ItemKind> for AssocItemKind {
2926 type Error = ItemKind;
2928 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2929 Ok(match item_kind {
2930 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2931 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2932 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2933 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2934 _ => return Err(item_kind),
2939 /// An item in `extern` block.
2940 #[derive(Clone, Encodable, Decodable, Debug)]
2941 pub enum ForeignItemKind {
2942 /// A foreign static item (`static FOO: u8`).
2943 Static(P<Ty>, Mutability, Option<P<Expr>>),
2944 /// An foreign function.
2946 /// An foreign type.
2947 TyAlias(Box<TyAlias>),
2948 /// A macro expanding to foreign items.
2952 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2953 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
2955 impl From<ForeignItemKind> for ItemKind {
2956 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2957 match foreign_item_kind {
2958 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2959 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2960 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2961 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2966 impl TryFrom<ItemKind> for ForeignItemKind {
2967 type Error = ItemKind;
2969 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2970 Ok(match item_kind {
2971 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2972 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
2973 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
2974 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2975 _ => return Err(item_kind),
2980 pub type ForeignItem = Item<ForeignItemKind>;