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, DelimToken, 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;
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
55 /// `'outer` is a label.
56 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
61 impl fmt::Debug for Label {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "label({:?})", self.ident)
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, Encodable, Decodable, Copy)]
75 impl fmt::Debug for Lifetime {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "lifetime({}: {})", self.id, self)
81 impl fmt::Display for Lifetime {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "{}", self.ident.name)
87 /// A "Path" is essentially Rust's notion of a name.
89 /// It's represented as a sequence of identifiers,
90 /// along with a bunch of supporting information.
92 /// E.g., `std::cmp::PartialEq`.
93 #[derive(Clone, Encodable, Decodable, Debug)]
96 /// The segments in the path: the things separated by `::`.
97 /// Global paths begin with `kw::PathRoot`.
98 pub segments: Vec<PathSegment>,
99 pub tokens: Option<LazyTokenStream>,
102 impl PartialEq<Symbol> for Path {
104 fn eq(&self, symbol: &Symbol) -> bool {
105 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
109 impl<CTX> HashStable<CTX> for Path {
110 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
111 self.segments.len().hash_stable(hcx, hasher);
112 for segment in &self.segments {
113 segment.ident.name.hash_stable(hcx, hasher);
119 // Convert a span and an identifier to the corresponding
121 pub fn from_ident(ident: Ident) -> Path {
122 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
125 pub fn is_global(&self) -> bool {
126 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
130 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
132 /// E.g., `std`, `String` or `Box<T>`.
133 #[derive(Clone, Encodable, Decodable, Debug)]
134 pub struct PathSegment {
135 /// The identifier portion of this path segment.
140 /// Type/lifetime parameters attached to this path. They come in
141 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
142 /// `None` means that no parameter list is supplied (`Path`),
143 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
144 /// but it can be empty (`Path<>`).
145 /// `P` is used as a size optimization for the common case with no parameters.
146 pub args: Option<P<GenericArgs>>,
150 pub fn from_ident(ident: Ident) -> Self {
151 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
154 pub fn path_root(span: Span) -> Self {
155 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
158 pub fn span(&self) -> Span {
160 Some(args) => self.ident.span.to(args.span()),
161 None => self.ident.span,
166 /// The arguments of a path segment.
168 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
169 #[derive(Clone, Encodable, Decodable, Debug)]
170 pub enum GenericArgs {
171 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
172 AngleBracketed(AngleBracketedArgs),
173 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
174 Parenthesized(ParenthesizedArgs),
178 pub fn is_angle_bracketed(&self) -> bool {
179 matches!(self, AngleBracketed(..))
182 pub fn span(&self) -> Span {
184 AngleBracketed(ref data) => data.span,
185 Parenthesized(ref data) => data.span,
190 /// Concrete argument in the sequence of generic args.
191 #[derive(Clone, Encodable, Decodable, Debug)]
192 pub enum GenericArg {
193 /// `'a` in `Foo<'a>`
195 /// `Bar` in `Foo<Bar>`
202 pub fn span(&self) -> Span {
204 GenericArg::Lifetime(lt) => lt.ident.span,
205 GenericArg::Type(ty) => ty.span,
206 GenericArg::Const(ct) => ct.value.span,
211 /// A path like `Foo<'a, T>`.
212 #[derive(Clone, Encodable, Decodable, Debug, Default)]
213 pub struct AngleBracketedArgs {
214 /// The overall span.
216 /// The comma separated parts in the `<...>`.
217 pub args: Vec<AngleBracketedArg>,
220 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
221 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
222 #[derive(Clone, Encodable, Decodable, Debug)]
223 pub enum AngleBracketedArg {
224 /// Argument for a generic parameter.
226 /// Constraint for an associated item.
227 Constraint(AssocTyConstraint),
230 impl AngleBracketedArg {
231 pub fn span(&self) -> Span {
233 AngleBracketedArg::Arg(arg) => arg.span(),
234 AngleBracketedArg::Constraint(constraint) => constraint.span,
239 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
240 fn into(self) -> Option<P<GenericArgs>> {
241 Some(P(GenericArgs::AngleBracketed(self)))
245 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
246 fn into(self) -> Option<P<GenericArgs>> {
247 Some(P(GenericArgs::Parenthesized(self)))
251 /// A path like `Foo(A, B) -> C`.
252 #[derive(Clone, Encodable, Decodable, Debug)]
253 pub struct ParenthesizedArgs {
261 pub inputs: Vec<P<Ty>>,
267 pub inputs_span: Span,
273 impl ParenthesizedArgs {
274 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
279 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
281 AngleBracketedArgs { span: self.inputs_span, args }
285 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
287 /// A modifier on a bound, e.g., `?Sized` or `~const Trait`.
289 /// Negative bounds should also be handled here.
290 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
291 pub enum TraitBoundModifier {
303 // This parses but will be rejected during AST validation.
307 /// The AST represents all type param bounds as types.
308 /// `typeck::collect::compute_bounds` matches these against
309 /// the "special" built-in traits (see `middle::lang_items`) and
310 /// detects `Copy`, `Send` and `Sync`.
311 #[derive(Clone, Encodable, Decodable, Debug)]
312 pub enum GenericBound {
313 Trait(PolyTraitRef, TraitBoundModifier),
318 pub fn span(&self) -> Span {
320 GenericBound::Trait(ref t, ..) => t.span,
321 GenericBound::Outlives(ref l) => l.ident.span,
326 pub type GenericBounds = Vec<GenericBound>;
328 /// Specifies the enforced ordering for generic parameters. In the future,
329 /// if we wanted to relax this order, we could override `PartialEq` and
330 /// `PartialOrd`, to allow the kinds to be unordered.
331 #[derive(Hash, Clone, Copy)]
332 pub enum ParamKindOrd {
336 // `Infer` is not actually constructed directly from the AST, but is implicitly constructed
337 // during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last.
341 impl Ord for ParamKindOrd {
342 fn cmp(&self, other: &Self) -> Ordering {
344 let to_int = |v| match v {
346 Infer | Type | Const => 1,
349 to_int(*self).cmp(&to_int(*other))
352 impl PartialOrd for ParamKindOrd {
353 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
354 Some(self.cmp(other))
357 impl PartialEq for ParamKindOrd {
358 fn eq(&self, other: &Self) -> bool {
359 self.cmp(other) == Ordering::Equal
362 impl Eq for ParamKindOrd {}
364 impl fmt::Display for ParamKindOrd {
365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367 ParamKindOrd::Lifetime => "lifetime".fmt(f),
368 ParamKindOrd::Type => "type".fmt(f),
369 ParamKindOrd::Const { .. } => "const".fmt(f),
370 ParamKindOrd::Infer => "infer".fmt(f),
375 #[derive(Clone, Encodable, Decodable, Debug)]
376 pub enum GenericParamKind {
377 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
380 default: Option<P<Ty>>,
384 /// Span of the `const` keyword.
386 /// Optional default value for the const generic param
387 default: Option<AnonConst>,
391 #[derive(Clone, Encodable, Decodable, Debug)]
392 pub struct GenericParam {
396 pub bounds: GenericBounds,
397 pub is_placeholder: bool,
398 pub kind: GenericParamKind,
402 pub fn span(&self) -> Span {
404 GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
407 GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
408 GenericParamKind::Const { kw_span, default: Some(default), .. } => {
409 kw_span.to(default.value.span)
411 GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
416 /// Represents lifetime, type and const parameters attached to a declaration of
417 /// a function, enum, trait, etc.
418 #[derive(Clone, Encodable, Decodable, Debug)]
419 pub struct Generics {
420 pub params: Vec<GenericParam>,
421 pub where_clause: WhereClause,
425 impl Default for Generics {
426 /// Creates an instance of `Generics`.
427 fn default() -> Generics {
430 where_clause: WhereClause {
431 has_where_token: false,
432 predicates: Vec::new(),
440 /// A where-clause in a definition.
441 #[derive(Clone, Encodable, Decodable, Debug)]
442 pub struct WhereClause {
443 /// `true` if we ate a `where` token: this can happen
444 /// if we parsed no predicates (e.g. `struct Foo where {}`).
445 /// This allows us to accurately pretty-print
446 /// in `nt_to_tokenstream`
447 pub has_where_token: bool,
448 pub predicates: Vec<WherePredicate>,
452 /// A single predicate in a where-clause.
453 #[derive(Clone, Encodable, Decodable, Debug)]
454 pub enum WherePredicate {
455 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
456 BoundPredicate(WhereBoundPredicate),
457 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
458 RegionPredicate(WhereRegionPredicate),
459 /// An equality predicate (unsupported).
460 EqPredicate(WhereEqPredicate),
463 impl WherePredicate {
464 pub fn span(&self) -> Span {
466 WherePredicate::BoundPredicate(p) => p.span,
467 WherePredicate::RegionPredicate(p) => p.span,
468 WherePredicate::EqPredicate(p) => p.span,
475 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
476 #[derive(Clone, Encodable, Decodable, Debug)]
477 pub struct WhereBoundPredicate {
479 /// Any generics from a `for` binding.
480 pub bound_generic_params: Vec<GenericParam>,
481 /// The type being bounded.
482 pub bounded_ty: P<Ty>,
483 /// Trait and lifetime bounds (`Clone + Send + 'static`).
484 pub bounds: GenericBounds,
487 /// A lifetime predicate.
489 /// E.g., `'a: 'b + 'c`.
490 #[derive(Clone, Encodable, Decodable, Debug)]
491 pub struct WhereRegionPredicate {
493 pub lifetime: Lifetime,
494 pub bounds: GenericBounds,
497 /// An equality predicate (unsupported).
500 #[derive(Clone, Encodable, Decodable, Debug)]
501 pub struct WhereEqPredicate {
508 #[derive(Clone, Encodable, Decodable, Debug)]
510 pub attrs: Vec<Attribute>,
511 pub items: Vec<P<Item>>,
513 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
514 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
516 pub is_placeholder: bool,
519 /// Possible values inside of compile-time attribute lists.
521 /// E.g., the '..' in `#[name(..)]`.
522 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
523 pub enum NestedMetaItem {
524 /// A full MetaItem, for recursive meta items.
528 /// E.g., `"foo"`, `64`, `true`.
532 /// A spanned compile-time attribute item.
534 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
535 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
536 pub struct MetaItem {
538 pub kind: MetaItemKind,
542 /// A compile-time attribute item.
544 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
545 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
546 pub enum MetaItemKind {
549 /// E.g., `test` as in `#[test]`.
553 /// E.g., `derive(..)` as in `#[derive(..)]`.
554 List(Vec<NestedMetaItem>),
555 /// Name value meta item.
557 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
561 /// A block (`{ .. }`).
563 /// E.g., `{ .. }` as in `fn foo() { .. }`.
564 #[derive(Clone, Encodable, Decodable, Debug)]
566 /// The statements in the block.
567 pub stmts: Vec<Stmt>,
569 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
570 pub rules: BlockCheckMode,
572 pub tokens: Option<LazyTokenStream>,
573 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
580 pub could_be_bare_literal: bool,
585 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
586 #[derive(Clone, Encodable, Decodable, Debug)]
591 pub tokens: Option<LazyTokenStream>,
595 /// Attempt reparsing the pattern as a type.
596 /// This is intended for use by diagnostics.
597 pub fn to_ty(&self) -> Option<P<Ty>> {
598 let kind = match &self.kind {
599 // In a type expression `_` is an inference variable.
600 PatKind::Wild => TyKind::Infer,
601 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
602 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
603 TyKind::Path(None, Path::from_ident(*ident))
605 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
606 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
607 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
608 PatKind::Ref(pat, mutbl) => {
609 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
611 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
612 // when `P` can be reparsed as a type `T`.
613 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
614 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
615 // assuming `T0` to `Tn` are all syntactically valid as types.
616 PatKind::Tuple(pats) => {
617 let mut tys = Vec::with_capacity(pats.len());
618 // FIXME(#48994) - could just be collected into an Option<Vec>
620 tys.push(pat.to_ty()?);
627 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
630 /// Walk top-down and call `it` in each place where a pattern occurs
631 /// starting with the root pattern `walk` is called on. If `it` returns
632 /// false then we will descend no further but siblings will be processed.
633 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
639 // Walk into the pattern associated with `Ident` (if any).
640 PatKind::Ident(_, _, Some(p)) => p.walk(it),
642 // Walk into each field of struct.
643 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
645 // Sequence of patterns.
646 PatKind::TupleStruct(_, _, s)
649 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
651 // Trivial wrappers over inner patterns.
652 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
654 // These patterns do not contain subpatterns, skip.
661 | PatKind::MacCall(_) => {}
665 /// Is this a `..` pattern?
666 pub fn is_rest(&self) -> bool {
667 matches!(self.kind, PatKind::Rest)
671 /// A single field in a struct pattern.
673 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
674 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
675 /// except when `is_shorthand` is true.
676 #[derive(Clone, Encodable, Decodable, Debug)]
677 pub struct PatField {
678 /// The identifier for the field.
680 /// The pattern the field is destructured to.
682 pub is_shorthand: bool,
686 pub is_placeholder: bool,
689 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
690 pub enum BindingMode {
695 #[derive(Clone, Encodable, Decodable, Debug)]
698 Included(RangeSyntax),
703 #[derive(Clone, Encodable, Decodable, Debug)]
704 pub enum RangeSyntax {
711 /// All the different flavors of pattern that Rust recognizes.
712 #[derive(Clone, Encodable, Decodable, Debug)]
714 /// Represents a wildcard pattern (`_`).
717 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
718 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
719 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
720 /// during name resolution.
721 Ident(BindingMode, Ident, Option<P<Pat>>),
723 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
724 /// The `bool` is `true` in the presence of a `..`.
725 Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool),
727 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
728 TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>),
730 /// An or-pattern `A | B | C`.
731 /// Invariant: `pats.len() >= 2`.
734 /// A possibly qualified path pattern.
735 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
736 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
737 /// only legally refer to associated constants.
738 Path(Option<QSelf>, Path),
740 /// A tuple pattern (`(a, b)`).
746 /// A reference pattern (e.g., `&mut (a, b)`).
747 Ref(P<Pat>, Mutability),
752 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
753 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
755 /// A slice pattern `[a, b, c]`.
758 /// A rest pattern `..`.
760 /// Syntactically it is valid anywhere.
762 /// Semantically however, it only has meaning immediately inside:
763 /// - a slice pattern: `[a, .., b]`,
764 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
765 /// - a tuple pattern: `(a, .., b)`,
766 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
768 /// In all of these cases, an additional restriction applies,
769 /// only one rest pattern may occur in the pattern sequences.
772 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
775 /// A macro pattern; pre-expansion.
779 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
780 #[derive(HashStable_Generic, Encodable, Decodable)]
781 pub enum Mutability {
787 pub fn invert(self) -> Self {
789 Mutability::Mut => Mutability::Not,
790 Mutability::Not => Mutability::Mut,
794 pub fn prefix_str(&self) -> &'static str {
796 Mutability::Mut => "mut ",
797 Mutability::Not => "",
802 /// The kind of borrow in an `AddrOf` expression,
803 /// e.g., `&place` or `&raw const place`.
804 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
805 #[derive(Encodable, Decodable, HashStable_Generic)]
806 pub enum BorrowKind {
807 /// A normal borrow, `&$expr` or `&mut $expr`.
808 /// The resulting type is either `&'a T` or `&'a mut T`
809 /// where `T = typeof($expr)` and `'a` is some lifetime.
811 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
812 /// The resulting type is either `*const T` or `*mut T`
813 /// where `T = typeof($expr)`.
817 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
819 /// The `+` operator (addition)
821 /// The `-` operator (subtraction)
823 /// The `*` operator (multiplication)
825 /// The `/` operator (division)
827 /// The `%` operator (modulus)
829 /// The `&&` operator (logical and)
831 /// The `||` operator (logical or)
833 /// The `^` operator (bitwise xor)
835 /// The `&` operator (bitwise and)
837 /// The `|` operator (bitwise or)
839 /// The `<<` operator (shift left)
841 /// The `>>` operator (shift right)
843 /// The `==` operator (equality)
845 /// The `<` operator (less than)
847 /// The `<=` operator (less than or equal to)
849 /// The `!=` operator (not equal to)
851 /// The `>=` operator (greater than or equal to)
853 /// The `>` operator (greater than)
858 pub fn to_string(&self) -> &'static str {
881 pub fn lazy(&self) -> bool {
882 matches!(self, BinOpKind::And | BinOpKind::Or)
885 pub fn is_comparison(&self) -> bool {
887 // Note for developers: please keep this as is;
888 // we want compilation to fail if another variant is added.
890 Eq | Lt | Le | Ne | Gt | Ge => true,
891 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
896 pub type BinOp = Spanned<BinOpKind>;
900 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
901 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
903 /// The `*` operator for dereferencing
905 /// The `!` operator for logical inversion
907 /// The `-` operator for negation
912 pub fn to_string(op: UnOp) -> &'static str {
922 #[derive(Clone, Encodable, Decodable, Debug)]
930 pub fn tokens(&self) -> Option<&LazyTokenStream> {
932 StmtKind::Local(ref local) => local.tokens.as_ref(),
933 StmtKind::Item(ref item) => item.tokens.as_ref(),
934 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(),
935 StmtKind::Empty => None,
936 StmtKind::MacCall(ref mac) => mac.tokens.as_ref(),
940 pub fn has_trailing_semicolon(&self) -> bool {
942 StmtKind::Semi(_) => true,
943 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
948 /// Converts a parsed `Stmt` to a `Stmt` with
949 /// a trailing semicolon.
951 /// This only modifies the parsed AST struct, not the attached
952 /// `LazyTokenStream`. The parser is responsible for calling
953 /// `CreateTokenStream::add_trailing_semi` when there is actually
954 /// a semicolon in the tokenstream.
955 pub fn add_trailing_semicolon(mut self) -> Self {
956 self.kind = match self.kind {
957 StmtKind::Expr(expr) => StmtKind::Semi(expr),
958 StmtKind::MacCall(mac) => {
959 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
960 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
969 pub fn is_item(&self) -> bool {
970 matches!(self.kind, StmtKind::Item(_))
973 pub fn is_expr(&self) -> bool {
974 matches!(self.kind, StmtKind::Expr(_))
978 #[derive(Clone, Encodable, Decodable, Debug)]
980 /// A local (let) binding.
982 /// An item definition.
984 /// Expr without trailing semi-colon.
986 /// Expr with a trailing semi-colon.
988 /// Just a trailing semi-colon.
991 MacCall(P<MacCallStmt>),
994 #[derive(Clone, Encodable, Decodable, Debug)]
995 pub struct MacCallStmt {
997 pub style: MacStmtStyle,
999 pub tokens: Option<LazyTokenStream>,
1002 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1003 pub enum MacStmtStyle {
1004 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1005 /// `foo!(...);`, `foo![...];`).
1007 /// The macro statement had braces (e.g., `foo! { ... }`).
1009 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1010 /// `foo!(...)`). All of these will end up being converted into macro
1015 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1016 #[derive(Clone, Encodable, Decodable, Debug)]
1020 pub ty: Option<P<Ty>>,
1021 pub kind: LocalKind,
1024 pub tokens: Option<LazyTokenStream>,
1027 #[derive(Clone, Encodable, Decodable, Debug)]
1028 pub enum LocalKind {
1029 /// Local declaration.
1030 /// Example: `let x;`
1032 /// Local declaration with an initializer.
1033 /// Example: `let x = y;`
1035 /// Local declaration with an initializer and an `else` clause.
1036 /// Example: `let Some(x) = y else { return };`
1037 InitElse(P<Expr>, P<Block>),
1041 pub fn init(&self) -> Option<&Expr> {
1044 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1048 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1051 Self::Init(init) => Some((init, None)),
1052 Self::InitElse(init, els) => Some((init, Some(els))),
1057 /// An arm of a 'match'.
1059 /// E.g., `0..=10 => { println!("match!") }` as in
1063 /// 0..=10 => { println!("match!") },
1064 /// _ => { println!("no match!") },
1067 #[derive(Clone, Encodable, Decodable, Debug)]
1070 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1072 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1073 pub guard: Option<P<Expr>>,
1078 pub is_placeholder: bool,
1081 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1082 #[derive(Clone, Encodable, Decodable, Debug)]
1083 pub struct ExprField {
1089 pub is_shorthand: bool,
1090 pub is_placeholder: bool,
1093 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1094 pub enum BlockCheckMode {
1096 Unsafe(UnsafeSource),
1099 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1100 pub enum UnsafeSource {
1105 /// A constant (expression) that's not an item or associated item,
1106 /// but needs its own `DefId` for type-checking, const-eval, etc.
1107 /// These are usually found nested inside types (e.g., array lengths)
1108 /// or expressions (e.g., repeat counts), and also used to define
1109 /// explicit discriminant values for enum variants.
1110 #[derive(Clone, Encodable, Decodable, Debug)]
1111 pub struct AnonConst {
1117 #[derive(Clone, Encodable, Decodable, Debug)]
1123 pub tokens: Option<LazyTokenStream>,
1126 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1127 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1128 rustc_data_structures::static_assert_size!(Expr, 104);
1131 /// Returns `true` if this expression would be valid somewhere that expects a value;
1132 /// for example, an `if` condition.
1133 pub fn returns(&self) -> bool {
1134 if let ExprKind::Block(ref block, _) = self.kind {
1135 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1137 Some(StmtKind::Expr(_)) => true,
1138 // Last statement is an explicit return?
1139 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1140 // This is a block that doesn't end in either an implicit or explicit return.
1144 // This is not a block, it is a value.
1149 /// Is this expr either `N`, or `{ N }`.
1151 /// If this is not the case, name resolution does not resolve `N` when using
1152 /// `min_const_generics` as more complex expressions are not supported.
1153 pub fn is_potential_trivial_const_param(&self) -> bool {
1154 let this = if let ExprKind::Block(ref block, None) = self.kind {
1155 if block.stmts.len() == 1 {
1156 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1164 if let ExprKind::Path(None, ref path) = this.kind {
1165 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1173 pub fn to_bound(&self) -> Option<GenericBound> {
1175 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1176 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1177 TraitBoundModifier::None,
1183 pub fn peel_parens(&self) -> &Expr {
1184 let mut expr = self;
1185 while let ExprKind::Paren(inner) = &expr.kind {
1191 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1192 pub fn to_ty(&self) -> Option<P<Ty>> {
1193 let kind = match &self.kind {
1194 // Trivial conversions.
1195 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1196 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1198 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1200 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1201 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1204 ExprKind::Repeat(expr, expr_len) => {
1205 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1208 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1210 ExprKind::Tup(exprs) => {
1211 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1215 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1216 // then type of result is trait object.
1217 // Otherwise we don't assume the result type.
1218 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1219 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1220 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1226 ExprKind::Underscore => TyKind::Infer,
1228 // This expression doesn't look like a type syntactically.
1232 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1235 pub fn precedence(&self) -> ExprPrecedence {
1237 ExprKind::Box(_) => ExprPrecedence::Box,
1238 ExprKind::Array(_) => ExprPrecedence::Array,
1239 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1240 ExprKind::Call(..) => ExprPrecedence::Call,
1241 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1242 ExprKind::Tup(_) => ExprPrecedence::Tup,
1243 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1244 ExprKind::Unary(..) => ExprPrecedence::Unary,
1245 ExprKind::Lit(_) => ExprPrecedence::Lit,
1246 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1247 ExprKind::Let(..) => ExprPrecedence::Let,
1248 ExprKind::If(..) => ExprPrecedence::If,
1249 ExprKind::While(..) => ExprPrecedence::While,
1250 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1251 ExprKind::Loop(..) => ExprPrecedence::Loop,
1252 ExprKind::Match(..) => ExprPrecedence::Match,
1253 ExprKind::Closure(..) => ExprPrecedence::Closure,
1254 ExprKind::Block(..) => ExprPrecedence::Block,
1255 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1256 ExprKind::Async(..) => ExprPrecedence::Async,
1257 ExprKind::Await(..) => ExprPrecedence::Await,
1258 ExprKind::Assign(..) => ExprPrecedence::Assign,
1259 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1260 ExprKind::Field(..) => ExprPrecedence::Field,
1261 ExprKind::Index(..) => ExprPrecedence::Index,
1262 ExprKind::Range(..) => ExprPrecedence::Range,
1263 ExprKind::Underscore => ExprPrecedence::Path,
1264 ExprKind::Path(..) => ExprPrecedence::Path,
1265 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1266 ExprKind::Break(..) => ExprPrecedence::Break,
1267 ExprKind::Continue(..) => ExprPrecedence::Continue,
1268 ExprKind::Ret(..) => ExprPrecedence::Ret,
1269 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1270 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1271 ExprKind::Struct(..) => ExprPrecedence::Struct,
1272 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1273 ExprKind::Paren(..) => ExprPrecedence::Paren,
1274 ExprKind::Try(..) => ExprPrecedence::Try,
1275 ExprKind::Yield(..) => ExprPrecedence::Yield,
1276 ExprKind::Err => ExprPrecedence::Err,
1281 /// Limit types of a range (inclusive or exclusive)
1282 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1283 pub enum RangeLimits {
1284 /// Inclusive at the beginning, exclusive at the end
1286 /// Inclusive at the beginning and end
1290 #[derive(Clone, Encodable, Decodable, Debug)]
1291 pub enum StructRest {
1296 /// No trailing `..` or expression.
1300 #[derive(Clone, Encodable, Decodable, Debug)]
1301 pub struct StructExpr {
1302 pub qself: Option<QSelf>,
1304 pub fields: Vec<ExprField>,
1305 pub rest: StructRest,
1308 #[derive(Clone, Encodable, Decodable, Debug)]
1310 /// A `box x` expression.
1312 /// An array (`[a, b, c, d]`)
1313 Array(Vec<P<Expr>>),
1314 /// Allow anonymous constants from an inline `const` block
1315 ConstBlock(AnonConst),
1318 /// The first field resolves to the function itself,
1319 /// and the second field is the list of arguments.
1320 /// This also represents calling the constructor of
1321 /// tuple-like ADTs such as tuple structs and enum variants.
1322 Call(P<Expr>, Vec<P<Expr>>),
1323 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1325 /// The `PathSegment` represents the method name and its generic arguments
1326 /// (within the angle brackets).
1327 /// The first element of the vector of an `Expr` is the expression that evaluates
1328 /// to the object on which the method is being called on (the receiver),
1329 /// and the remaining elements are the rest of the arguments.
1330 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1331 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1332 /// This `Span` is the span of the function, without the dot and receiver
1333 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1334 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1335 /// A tuple (e.g., `(a, b, c, d)`).
1337 /// A binary operation (e.g., `a + b`, `a * b`).
1338 Binary(BinOp, P<Expr>, P<Expr>),
1339 /// A unary operation (e.g., `!x`, `*x`).
1340 Unary(UnOp, P<Expr>),
1341 /// A literal (e.g., `1`, `"foo"`).
1343 /// A cast (e.g., `foo as f64`).
1344 Cast(P<Expr>, P<Ty>),
1345 /// A type ascription (e.g., `42: usize`).
1346 Type(P<Expr>, P<Ty>),
1347 /// A `let pat = expr` expression that is only semantically allowed in the condition
1348 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1350 /// `Span` represents the whole `let pat = expr` statement.
1351 Let(P<Pat>, P<Expr>, Span),
1352 /// An `if` block, with an optional `else` block.
1354 /// `if expr { block } else { expr }`
1355 If(P<Expr>, P<Block>, Option<P<Expr>>),
1356 /// A while loop, with an optional label.
1358 /// `'label: while expr { block }`
1359 While(P<Expr>, P<Block>, Option<Label>),
1360 /// A `for` loop, with an optional label.
1362 /// `'label: for pat in expr { block }`
1364 /// This is desugared to a combination of `loop` and `match` expressions.
1365 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1366 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1368 /// `'label: loop { block }`
1369 Loop(P<Block>, Option<Label>),
1370 /// A `match` block.
1371 Match(P<Expr>, Vec<Arm>),
1372 /// A closure (e.g., `move |a, b, c| a + b + c`).
1374 /// The final span is the span of the argument block `|...|`.
1375 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1376 /// A block (`'label: { ... }`).
1377 Block(P<Block>, Option<Label>),
1378 /// An async block (`async move { ... }`).
1380 /// The `NodeId` is the `NodeId` for the closure that results from
1381 /// desugaring an async block, just like the NodeId field in the
1382 /// `Async::Yes` variant. This is necessary in order to create a def for the
1383 /// closure which can be used as a parent of any child defs. Defs
1384 /// created during lowering cannot be made the parent of any other
1385 /// preexisting defs.
1386 Async(CaptureBy, NodeId, P<Block>),
1387 /// An await expression (`my_future.await`).
1390 /// A try block (`try { ... }`).
1393 /// An assignment (`a = foo()`).
1394 /// The `Span` argument is the span of the `=` token.
1395 Assign(P<Expr>, P<Expr>, Span),
1396 /// An assignment with an operator.
1399 AssignOp(BinOp, P<Expr>, P<Expr>),
1400 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1401 Field(P<Expr>, Ident),
1402 /// An indexing operation (e.g., `foo[2]`).
1403 Index(P<Expr>, P<Expr>),
1404 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1405 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1406 /// An underscore, used in destructuring assignment to ignore a value.
1409 /// Variable reference, possibly containing `::` and/or type
1410 /// parameters (e.g., `foo::bar::<baz>`).
1412 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1413 Path(Option<QSelf>, Path),
1415 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1416 AddrOf(BorrowKind, Mutability, P<Expr>),
1417 /// A `break`, with an optional label to break, and an optional expression.
1418 Break(Option<Label>, Option<P<Expr>>),
1419 /// A `continue`, with an optional label.
1420 Continue(Option<Label>),
1421 /// A `return`, with an optional value to be returned.
1422 Ret(Option<P<Expr>>),
1424 /// Output of the `asm!()` macro.
1425 InlineAsm(P<InlineAsm>),
1426 /// Output of the `llvm_asm!()` macro.
1427 LlvmInlineAsm(P<LlvmInlineAsm>),
1429 /// A macro invocation; pre-expansion.
1432 /// A struct literal expression.
1434 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1435 Struct(P<StructExpr>),
1437 /// An array literal constructed from one repeated element.
1439 /// E.g., `[1; 5]`. The expression is the element to be
1440 /// repeated; the constant is the number of times to repeat it.
1441 Repeat(P<Expr>, AnonConst),
1443 /// No-op: used solely so we can pretty-print faithfully.
1446 /// A try expression (`expr?`).
1449 /// A `yield`, with an optional value to be yielded.
1450 Yield(Option<P<Expr>>),
1452 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1456 /// The explicit `Self` type in a "qualified path". The actual
1457 /// path, including the trait and the associated item, is stored
1458 /// separately. `position` represents the index of the associated
1459 /// item qualified with this `Self` type.
1461 /// ```ignore (only-for-syntax-highlight)
1462 /// <Vec<T> as a::b::Trait>::AssociatedItem
1463 /// ^~~~~ ~~~~~~~~~~~~~~^
1466 /// <Vec<T>>::AssociatedItem
1470 #[derive(Clone, Encodable, Decodable, Debug)]
1474 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1475 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1476 /// 0`, this is an empty span.
1477 pub path_span: Span,
1478 pub position: usize,
1481 /// A capture clause used in closures and `async` blocks.
1482 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1483 pub enum CaptureBy {
1484 /// `move |x| y + x`.
1486 /// `move` keyword was not specified.
1490 /// The movability of a generator / closure literal:
1491 /// whether a generator contains self-references, causing it to be `!Unpin`.
1492 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1493 #[derive(HashStable_Generic)]
1494 pub enum Movability {
1495 /// May contain self-references, `!Unpin`.
1497 /// Must not contain self-references, `Unpin`.
1501 /// Represents a macro invocation. The `path` indicates which macro
1502 /// is being invoked, and the `args` are arguments passed to it.
1503 #[derive(Clone, Encodable, Decodable, Debug)]
1504 pub struct MacCall {
1506 pub args: P<MacArgs>,
1507 pub prior_type_ascription: Option<(Span, bool)>,
1511 pub fn span(&self) -> Span {
1512 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1516 /// Arguments passed to an attribute or a function-like macro.
1517 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1519 /// No arguments - `#[attr]`.
1521 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1522 Delimited(DelimSpan, MacDelimiter, TokenStream),
1523 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1525 /// Span of the `=` token.
1527 /// "value" as a nonterminal token.
1533 pub fn delim(&self) -> DelimToken {
1535 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1536 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1540 pub fn span(&self) -> Option<Span> {
1542 MacArgs::Empty => None,
1543 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1544 MacArgs::Eq(eq_span, token) => Some(eq_span.to(token.span)),
1548 /// Tokens inside the delimiters or after `=`.
1549 /// Proc macros see these tokens, for example.
1550 pub fn inner_tokens(&self) -> TokenStream {
1552 MacArgs::Empty => TokenStream::default(),
1553 MacArgs::Delimited(.., tokens) => tokens.clone(),
1554 MacArgs::Eq(.., token) => TokenTree::Token(token.clone()).into(),
1558 /// Whether a macro with these arguments needs a semicolon
1559 /// when used as a standalone item or statement.
1560 pub fn need_semicolon(&self) -> bool {
1561 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1565 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1566 pub enum MacDelimiter {
1573 pub fn to_token(self) -> DelimToken {
1575 MacDelimiter::Parenthesis => DelimToken::Paren,
1576 MacDelimiter::Bracket => DelimToken::Bracket,
1577 MacDelimiter::Brace => DelimToken::Brace,
1581 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1583 token::Paren => Some(MacDelimiter::Parenthesis),
1584 token::Bracket => Some(MacDelimiter::Bracket),
1585 token::Brace => Some(MacDelimiter::Brace),
1586 token::NoDelim => None,
1591 /// Represents a macro definition.
1592 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1593 pub struct MacroDef {
1594 pub body: P<MacArgs>,
1595 /// `true` if macro was defined with `macro_rules`.
1596 pub macro_rules: bool,
1599 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1600 #[derive(HashStable_Generic)]
1602 /// A regular string, like `"foo"`.
1604 /// A raw string, like `r##"foo"##`.
1606 /// The value is the number of `#` symbols used.
1611 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1613 /// The original literal token as written in source code.
1614 pub token: token::Lit,
1615 /// The "semantic" representation of the literal lowered from the original tokens.
1616 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1617 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1622 /// Same as `Lit`, but restricted to string literals.
1623 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1625 /// The original literal token as written in source code.
1626 pub style: StrStyle,
1628 pub suffix: Option<Symbol>,
1630 /// The unescaped "semantic" representation of the literal lowered from the original token.
1631 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1632 pub symbol_unescaped: Symbol,
1636 pub fn as_lit(&self) -> Lit {
1637 let token_kind = match self.style {
1638 StrStyle::Cooked => token::Str,
1639 StrStyle::Raw(n) => token::StrRaw(n),
1642 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1644 kind: LitKind::Str(self.symbol_unescaped, self.style),
1649 /// Type of the integer literal based on provided suffix.
1650 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1651 #[derive(HashStable_Generic)]
1652 pub enum LitIntType {
1661 /// Type of the float literal based on provided suffix.
1662 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1663 #[derive(HashStable_Generic)]
1664 pub enum LitFloatType {
1665 /// A float literal with a suffix (`1f32` or `1E10f32`).
1667 /// A float literal without a suffix (`1.0 or 1.0E10`).
1673 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1674 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1676 /// A string literal (`"foo"`).
1677 Str(Symbol, StrStyle),
1678 /// A byte string (`b"foo"`).
1680 /// A byte char (`b'f'`).
1682 /// A character literal (`'a'`).
1684 /// An integer literal (`1`).
1685 Int(u128, LitIntType),
1686 /// A float literal (`1f64` or `1E10f64`).
1687 Float(Symbol, LitFloatType),
1688 /// A boolean literal.
1690 /// Placeholder for a literal that wasn't well-formed in some way.
1695 /// Returns `true` if this literal is a string.
1696 pub fn is_str(&self) -> bool {
1697 matches!(self, LitKind::Str(..))
1700 /// Returns `true` if this literal is byte literal string.
1701 pub fn is_bytestr(&self) -> bool {
1702 matches!(self, LitKind::ByteStr(_))
1705 /// Returns `true` if this is a numeric literal.
1706 pub fn is_numeric(&self) -> bool {
1707 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1710 /// Returns `true` if this literal has no suffix.
1711 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1712 pub fn is_unsuffixed(&self) -> bool {
1716 /// Returns `true` if this literal has a suffix.
1717 pub fn is_suffixed(&self) -> bool {
1719 // suffixed variants
1720 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1721 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1722 // unsuffixed variants
1724 | LitKind::ByteStr(..)
1727 | LitKind::Int(_, LitIntType::Unsuffixed)
1728 | LitKind::Float(_, LitFloatType::Unsuffixed)
1730 | LitKind::Err(..) => false,
1735 // N.B., If you change this, you'll probably want to change the corresponding
1736 // type structure in `middle/ty.rs` as well.
1737 #[derive(Clone, Encodable, Decodable, Debug)]
1740 pub mutbl: Mutability,
1743 /// Represents a function's signature in a trait declaration,
1744 /// trait implementation, or free function.
1745 #[derive(Clone, Encodable, Decodable, Debug)]
1747 pub header: FnHeader,
1748 pub decl: P<FnDecl>,
1752 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1753 #[derive(Encodable, Decodable, HashStable_Generic)]
1760 pub fn name_str(self) -> &'static str {
1762 FloatTy::F32 => "f32",
1763 FloatTy::F64 => "f64",
1767 pub fn name(self) -> Symbol {
1769 FloatTy::F32 => sym::f32,
1770 FloatTy::F64 => sym::f64,
1775 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1776 #[derive(Encodable, Decodable, HashStable_Generic)]
1787 pub fn name_str(&self) -> &'static str {
1789 IntTy::Isize => "isize",
1791 IntTy::I16 => "i16",
1792 IntTy::I32 => "i32",
1793 IntTy::I64 => "i64",
1794 IntTy::I128 => "i128",
1798 pub fn name(&self) -> Symbol {
1800 IntTy::Isize => sym::isize,
1801 IntTy::I8 => sym::i8,
1802 IntTy::I16 => sym::i16,
1803 IntTy::I32 => sym::i32,
1804 IntTy::I64 => sym::i64,
1805 IntTy::I128 => sym::i128,
1810 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1811 #[derive(Encodable, Decodable, HashStable_Generic)]
1822 pub fn name_str(&self) -> &'static str {
1824 UintTy::Usize => "usize",
1826 UintTy::U16 => "u16",
1827 UintTy::U32 => "u32",
1828 UintTy::U64 => "u64",
1829 UintTy::U128 => "u128",
1833 pub fn name(&self) -> Symbol {
1835 UintTy::Usize => sym::usize,
1836 UintTy::U8 => sym::u8,
1837 UintTy::U16 => sym::u16,
1838 UintTy::U32 => sym::u32,
1839 UintTy::U64 => sym::u64,
1840 UintTy::U128 => sym::u128,
1845 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1846 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1847 #[derive(Clone, Encodable, Decodable, Debug)]
1848 pub struct AssocTyConstraint {
1851 pub gen_args: Option<GenericArgs>,
1852 pub kind: AssocTyConstraintKind,
1856 /// The kinds of an `AssocTyConstraint`.
1857 #[derive(Clone, Encodable, Decodable, Debug)]
1858 pub enum AssocTyConstraintKind {
1859 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1860 Equality { ty: P<Ty> },
1861 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1862 Bound { bounds: GenericBounds },
1865 #[derive(Encodable, Decodable, Debug)]
1870 pub tokens: Option<LazyTokenStream>,
1874 fn clone(&self) -> Self {
1875 ensure_sufficient_stack(|| Self {
1877 kind: self.kind.clone(),
1879 tokens: self.tokens.clone(),
1885 pub fn peel_refs(&self) -> &Self {
1886 let mut final_ty = self;
1887 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1894 #[derive(Clone, Encodable, Decodable, Debug)]
1895 pub struct BareFnTy {
1896 pub unsafety: Unsafe,
1898 pub generic_params: Vec<GenericParam>,
1899 pub decl: P<FnDecl>,
1902 /// The various kinds of type recognized by the compiler.
1903 #[derive(Clone, Encodable, Decodable, Debug)]
1905 /// A variable-length slice (`[T]`).
1907 /// A fixed length array (`[T; n]`).
1908 Array(P<Ty>, AnonConst),
1909 /// A raw pointer (`*const T` or `*mut T`).
1911 /// A reference (`&'a T` or `&'a mut T`).
1912 Rptr(Option<Lifetime>, MutTy),
1913 /// A bare function (e.g., `fn(usize) -> bool`).
1914 BareFn(P<BareFnTy>),
1915 /// The never type (`!`).
1917 /// A tuple (`(A, B, C, D,...)`).
1919 /// A path (`module::module::...::Type`), optionally
1920 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1922 /// Type parameters are stored in the `Path` itself.
1923 Path(Option<QSelf>, Path),
1924 /// A trait object type `Bound1 + Bound2 + Bound3`
1925 /// where `Bound` is a trait or a lifetime.
1926 TraitObject(GenericBounds, TraitObjectSyntax),
1927 /// An `impl Bound1 + Bound2 + Bound3` type
1928 /// where `Bound` is a trait or a lifetime.
1930 /// The `NodeId` exists to prevent lowering from having to
1931 /// generate `NodeId`s on the fly, which would complicate
1932 /// the generation of opaque `type Foo = impl Trait` items significantly.
1933 ImplTrait(NodeId, GenericBounds),
1934 /// No-op; kept solely so that we can pretty-print faithfully.
1938 /// This means the type should be inferred instead of it having been
1939 /// specified. This can appear anywhere in a type.
1941 /// Inferred type of a `self` or `&self` argument in a method.
1943 /// A macro in the type position.
1945 /// Placeholder for a kind that has failed to be defined.
1947 /// Placeholder for a `va_list`.
1952 pub fn is_implicit_self(&self) -> bool {
1953 matches!(self, TyKind::ImplicitSelf)
1956 pub fn is_unit(&self) -> bool {
1957 matches!(self, TyKind::Tup(tys) if tys.is_empty())
1961 /// Syntax used to declare a trait object.
1962 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1963 pub enum TraitObjectSyntax {
1968 /// Inline assembly operand explicit register or register class.
1970 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1971 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1972 pub enum InlineAsmRegOrRegClass {
1977 bitflags::bitflags! {
1978 #[derive(Encodable, Decodable, HashStable_Generic)]
1979 pub struct InlineAsmOptions: u16 {
1980 const PURE = 1 << 0;
1981 const NOMEM = 1 << 1;
1982 const READONLY = 1 << 2;
1983 const PRESERVES_FLAGS = 1 << 3;
1984 const NORETURN = 1 << 4;
1985 const NOSTACK = 1 << 5;
1986 const ATT_SYNTAX = 1 << 6;
1988 const MAY_UNWIND = 1 << 8;
1992 #[derive(Clone, PartialEq, PartialOrd, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
1993 pub enum InlineAsmTemplatePiece {
1995 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1998 impl fmt::Display for InlineAsmTemplatePiece {
1999 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2001 Self::String(s) => {
2002 for c in s.chars() {
2004 '{' => f.write_str("{{")?,
2005 '}' => f.write_str("}}")?,
2011 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2012 write!(f, "{{{}:{}}}", operand_idx, modifier)
2014 Self::Placeholder { operand_idx, modifier: None, .. } => {
2015 write!(f, "{{{}}}", operand_idx)
2021 impl InlineAsmTemplatePiece {
2022 /// Rebuilds the asm template string from its pieces.
2023 pub fn to_string(s: &[Self]) -> String {
2025 let mut out = String::new();
2027 let _ = write!(out, "{}", p);
2033 /// Inline assembly operand.
2035 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2036 #[derive(Clone, Encodable, Decodable, Debug)]
2037 pub enum InlineAsmOperand {
2039 reg: InlineAsmRegOrRegClass,
2043 reg: InlineAsmRegOrRegClass,
2045 expr: Option<P<Expr>>,
2048 reg: InlineAsmRegOrRegClass,
2053 reg: InlineAsmRegOrRegClass,
2056 out_expr: Option<P<Expr>>,
2059 anon_const: AnonConst,
2066 /// Inline assembly.
2068 /// E.g., `asm!("NOP");`.
2069 #[derive(Clone, Encodable, Decodable, Debug)]
2070 pub struct InlineAsm {
2071 pub template: Vec<InlineAsmTemplatePiece>,
2072 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2073 pub operands: Vec<(InlineAsmOperand, Span)>,
2074 pub clobber_abis: Vec<(Symbol, Span)>,
2075 pub options: InlineAsmOptions,
2076 pub line_spans: Vec<Span>,
2079 /// Inline assembly dialect.
2081 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2082 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Hash, HashStable_Generic)]
2083 pub enum LlvmAsmDialect {
2088 /// LLVM-style inline assembly.
2090 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2091 #[derive(Clone, Encodable, Decodable, Debug)]
2092 pub struct LlvmInlineAsmOutput {
2093 pub constraint: Symbol,
2096 pub is_indirect: bool,
2099 /// LLVM-style inline assembly.
2101 /// E.g., `llvm_asm!("NOP");`.
2102 #[derive(Clone, Encodable, Decodable, Debug)]
2103 pub struct LlvmInlineAsm {
2105 pub asm_str_style: StrStyle,
2106 pub outputs: Vec<LlvmInlineAsmOutput>,
2107 pub inputs: Vec<(Symbol, P<Expr>)>,
2108 pub clobbers: Vec<Symbol>,
2110 pub alignstack: bool,
2111 pub dialect: LlvmAsmDialect,
2114 /// A parameter in a function header.
2116 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2117 #[derive(Clone, Encodable, Decodable, Debug)]
2124 pub is_placeholder: bool,
2127 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2129 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2130 #[derive(Clone, Encodable, Decodable, Debug)]
2132 /// `self`, `mut self`
2134 /// `&'lt self`, `&'lt mut self`
2135 Region(Option<Lifetime>, Mutability),
2136 /// `self: TYPE`, `mut self: TYPE`
2137 Explicit(P<Ty>, Mutability),
2140 pub type ExplicitSelf = Spanned<SelfKind>;
2143 /// Attempts to cast parameter to `ExplicitSelf`.
2144 pub fn to_self(&self) -> Option<ExplicitSelf> {
2145 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2146 if ident.name == kw::SelfLower {
2147 return match self.ty.kind {
2148 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2149 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2150 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2153 self.pat.span.to(self.ty.span),
2154 SelfKind::Explicit(self.ty.clone(), mutbl),
2162 /// Returns `true` if parameter is `self`.
2163 pub fn is_self(&self) -> bool {
2164 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2165 ident.name == kw::SelfLower
2171 /// Builds a `Param` object from `ExplicitSelf`.
2172 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2173 let span = eself.span.to(eself_ident.span);
2174 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2175 let param = |mutbl, ty| Param {
2179 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2186 is_placeholder: false,
2189 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2190 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2191 SelfKind::Region(lt, mutbl) => param(
2195 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2204 /// A signature (not the body) of a function declaration.
2206 /// E.g., `fn foo(bar: baz)`.
2208 /// Please note that it's different from `FnHeader` structure
2209 /// which contains metadata about function safety, asyncness, constness and ABI.
2210 #[derive(Clone, Encodable, Decodable, Debug)]
2212 pub inputs: Vec<Param>,
2213 pub output: FnRetTy,
2217 pub fn has_self(&self) -> bool {
2218 self.inputs.get(0).map_or(false, Param::is_self)
2220 pub fn c_variadic(&self) -> bool {
2221 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2225 /// Is the trait definition an auto trait?
2226 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2232 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2233 #[derive(HashStable_Generic)]
2239 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2241 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2246 pub fn is_async(self) -> bool {
2247 matches!(self, Async::Yes { .. })
2250 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2251 pub fn opt_return_id(self) -> Option<NodeId> {
2253 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2259 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2260 #[derive(HashStable_Generic)]
2266 /// Item defaultness.
2267 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2268 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2269 pub enum Defaultness {
2274 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2275 pub enum ImplPolarity {
2276 /// `impl Trait for Type`
2278 /// `impl !Trait for Type`
2282 impl fmt::Debug for ImplPolarity {
2283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2285 ImplPolarity::Positive => "positive".fmt(f),
2286 ImplPolarity::Negative(_) => "negative".fmt(f),
2291 #[derive(Clone, Encodable, Decodable, Debug)]
2293 /// Returns type is not specified.
2295 /// Functions default to `()` and closures default to inference.
2296 /// Span points to where return type would be inserted.
2298 /// Everything else.
2303 pub fn span(&self) -> Span {
2305 FnRetTy::Default(span) => span,
2306 FnRetTy::Ty(ref ty) => ty.span,
2311 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2317 /// Module item kind.
2318 #[derive(Clone, Encodable, Decodable, Debug)]
2320 /// Module with inlined definition `mod foo { ... }`,
2321 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2322 /// The inner span is from the first token past `{` to the last token until `}`,
2323 /// or from the first to the last token in the loaded file.
2324 Loaded(Vec<P<Item>>, Inline, Span),
2325 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2329 /// Foreign module declaration.
2331 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2332 #[derive(Clone, Encodable, Decodable, Debug)]
2333 pub struct ForeignMod {
2334 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2335 /// semantically by Rust.
2336 pub unsafety: Unsafe,
2337 pub abi: Option<StrLit>,
2338 pub items: Vec<P<ForeignItem>>,
2341 #[derive(Clone, Encodable, Decodable, Debug)]
2342 pub struct EnumDef {
2343 pub variants: Vec<Variant>,
2346 #[derive(Clone, Encodable, Decodable, Debug)]
2347 pub struct Variant {
2348 /// Attributes of the variant.
2350 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2354 /// The visibility of the variant. Syntactically accepted but not semantically.
2355 pub vis: Visibility,
2356 /// Name of the variant.
2359 /// Fields and constructor id of the variant.
2360 pub data: VariantData,
2361 /// Explicit discriminant, e.g., `Foo = 1`.
2362 pub disr_expr: Option<AnonConst>,
2363 /// Is a macro placeholder
2364 pub is_placeholder: bool,
2367 /// Part of `use` item to the right of its prefix.
2368 #[derive(Clone, Encodable, Decodable, Debug)]
2369 pub enum UseTreeKind {
2370 /// `use prefix` or `use prefix as rename`
2372 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2374 Simple(Option<Ident>, NodeId, NodeId),
2375 /// `use prefix::{...}`
2376 Nested(Vec<(UseTree, NodeId)>),
2381 /// A tree of paths sharing common prefixes.
2382 /// Used in `use` items both at top-level and inside of braces in import groups.
2383 #[derive(Clone, Encodable, Decodable, Debug)]
2384 pub struct UseTree {
2386 pub kind: UseTreeKind,
2391 pub fn ident(&self) -> Ident {
2393 UseTreeKind::Simple(Some(rename), ..) => rename,
2394 UseTreeKind::Simple(None, ..) => {
2395 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2397 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2402 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2403 /// are contained as statements within items. These two cases need to be
2404 /// distinguished for pretty-printing.
2405 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2406 pub enum AttrStyle {
2411 rustc_index::newtype_index! {
2414 DEBUG_FORMAT = "AttrId({})"
2418 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2419 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2424 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2425 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2426 d.read_nil().map(|_| crate::attr::mk_attr_id())
2430 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2431 pub struct AttrItem {
2434 pub tokens: Option<LazyTokenStream>,
2437 /// A list of attributes.
2438 pub type AttrVec = ThinVec<Attribute>;
2440 /// Metadata associated with an item.
2441 #[derive(Clone, Encodable, Decodable, Debug)]
2442 pub struct Attribute {
2445 /// Denotes if the attribute decorates the following construct (outer)
2446 /// or the construct this attribute is contained within (inner).
2447 pub style: AttrStyle,
2451 #[derive(Clone, Encodable, Decodable, Debug)]
2453 /// A normal attribute.
2454 Normal(AttrItem, Option<LazyTokenStream>),
2456 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2457 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2458 /// variant (which is much less compact and thus more expensive).
2459 DocComment(CommentKind, Symbol),
2462 /// `TraitRef`s appear in impls.
2464 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2465 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2466 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2467 /// same as the impl's `NodeId`).
2468 #[derive(Clone, Encodable, Decodable, Debug)]
2469 pub struct TraitRef {
2474 #[derive(Clone, Encodable, Decodable, Debug)]
2475 pub struct PolyTraitRef {
2476 /// The `'a` in `<'a> Foo<&'a T>`.
2477 pub bound_generic_params: Vec<GenericParam>,
2479 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2480 pub trait_ref: TraitRef,
2486 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2488 bound_generic_params: generic_params,
2489 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2495 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2496 pub enum CrateSugar {
2497 /// Source is `pub(crate)`.
2500 /// Source is (just) `crate`.
2504 #[derive(Clone, Encodable, Decodable, Debug)]
2505 pub struct Visibility {
2506 pub kind: VisibilityKind,
2508 pub tokens: Option<LazyTokenStream>,
2511 #[derive(Clone, Encodable, Decodable, Debug)]
2512 pub enum VisibilityKind {
2515 Restricted { path: P<Path>, id: NodeId },
2519 impl VisibilityKind {
2520 pub fn is_pub(&self) -> bool {
2521 matches!(self, VisibilityKind::Public)
2525 /// Field definition in a struct, variant or union.
2527 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2528 #[derive(Clone, Encodable, Decodable, Debug)]
2529 pub struct FieldDef {
2533 pub vis: Visibility,
2534 pub ident: Option<Ident>,
2537 pub is_placeholder: bool,
2540 /// Fields and constructor ids of enum variants and structs.
2541 #[derive(Clone, Encodable, Decodable, Debug)]
2542 pub enum VariantData {
2545 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2546 Struct(Vec<FieldDef>, bool),
2549 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2550 Tuple(Vec<FieldDef>, NodeId),
2553 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2558 /// Return the fields of this variant.
2559 pub fn fields(&self) -> &[FieldDef] {
2561 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2566 /// Return the `NodeId` of this variant's constructor, if it has one.
2567 pub fn ctor_id(&self) -> Option<NodeId> {
2569 VariantData::Struct(..) => None,
2570 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2575 /// An item definition.
2576 #[derive(Clone, Encodable, Decodable, Debug)]
2577 pub struct Item<K = ItemKind> {
2578 pub attrs: Vec<Attribute>,
2581 pub vis: Visibility,
2582 /// The name of the item.
2583 /// It might be a dummy name in case of anonymous items.
2588 /// Original tokens this item was parsed from. This isn't necessarily
2589 /// available for all items, although over time more and more items should
2590 /// have this be `Some`. Right now this is primarily used for procedural
2591 /// macros, notably custom attributes.
2593 /// Note that the tokens here do not include the outer attributes, but will
2594 /// include inner attributes.
2595 pub tokens: Option<LazyTokenStream>,
2599 /// Return the span that encompasses the attributes.
2600 pub fn span_with_attributes(&self) -> Span {
2601 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2605 impl<K: Into<ItemKind>> Item<K> {
2606 pub fn into_item(self) -> Item {
2607 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2608 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2612 /// `extern` qualifier on a function item or function type.
2613 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2621 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2622 abi.map_or(Extern::Implicit, Extern::Explicit)
2626 /// A function header.
2628 /// All the information between the visibility and the name of the function is
2629 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2630 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2631 pub struct FnHeader {
2632 pub unsafety: Unsafe,
2633 pub asyncness: Async,
2634 pub constness: Const,
2639 /// Does this function header have any qualifiers or is it empty?
2640 pub fn has_qualifiers(&self) -> bool {
2641 let Self { unsafety, asyncness, constness, ext } = self;
2642 matches!(unsafety, Unsafe::Yes(_))
2643 || asyncness.is_async()
2644 || matches!(constness, Const::Yes(_))
2645 || !matches!(ext, Extern::None)
2649 impl Default for FnHeader {
2650 fn default() -> FnHeader {
2652 unsafety: Unsafe::No,
2653 asyncness: Async::No,
2654 constness: Const::No,
2660 #[derive(Clone, Encodable, Decodable, Debug)]
2662 pub unsafety: Unsafe,
2663 pub is_auto: IsAuto,
2664 pub generics: Generics,
2665 pub bounds: GenericBounds,
2666 pub items: Vec<P<AssocItem>>,
2669 #[derive(Clone, Encodable, Decodable, Debug)]
2670 pub struct TyAlias {
2671 pub defaultness: Defaultness,
2672 pub generics: Generics,
2673 pub bounds: GenericBounds,
2674 pub ty: Option<P<Ty>>,
2677 #[derive(Clone, Encodable, Decodable, Debug)]
2679 pub defaultness: Defaultness,
2680 pub unsafety: Unsafe,
2681 pub generics: Generics,
2682 pub constness: Const,
2683 pub polarity: ImplPolarity,
2684 /// The trait being implemented, if any.
2685 pub of_trait: Option<TraitRef>,
2687 pub items: Vec<P<AssocItem>>,
2690 #[derive(Clone, Encodable, Decodable, Debug)]
2692 pub defaultness: Defaultness,
2693 pub generics: Generics,
2695 pub body: Option<P<Block>>,
2698 #[derive(Clone, Encodable, Decodable, Debug)]
2700 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2702 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2703 ExternCrate(Option<Symbol>),
2704 /// A use declaration item (`use`).
2706 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2708 /// A static item (`static`).
2710 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2711 Static(P<Ty>, Mutability, Option<P<Expr>>),
2712 /// A constant item (`const`).
2714 /// E.g., `const FOO: i32 = 42;`.
2715 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2716 /// A function declaration (`fn`).
2718 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2720 /// A module declaration (`mod`).
2722 /// E.g., `mod foo;` or `mod foo { .. }`.
2723 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2724 /// semantically by Rust.
2725 Mod(Unsafe, ModKind),
2726 /// An external module (`extern`).
2728 /// E.g., `extern {}` or `extern "C" {}`.
2729 ForeignMod(ForeignMod),
2730 /// Module-level inline assembly (from `global_asm!()`).
2731 GlobalAsm(Box<InlineAsm>),
2732 /// A type alias (`type`).
2734 /// E.g., `type Foo = Bar<u8>;`.
2735 TyAlias(Box<TyAlias>),
2736 /// An enum definition (`enum`).
2738 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2739 Enum(EnumDef, Generics),
2740 /// A struct definition (`struct`).
2742 /// E.g., `struct Foo<A> { x: A }`.
2743 Struct(VariantData, Generics),
2744 /// A union definition (`union`).
2746 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2747 Union(VariantData, Generics),
2748 /// A trait declaration (`trait`).
2750 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2754 /// E.g., `trait Foo = Bar + Quux;`.
2755 TraitAlias(Generics, GenericBounds),
2756 /// An implementation.
2758 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2760 /// A macro invocation.
2762 /// E.g., `foo!(..)`.
2765 /// A macro definition.
2769 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2770 rustc_data_structures::static_assert_size!(ItemKind, 112);
2773 pub fn article(&self) -> &str {
2776 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2777 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2778 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2782 pub fn descr(&self) -> &str {
2784 ItemKind::ExternCrate(..) => "extern crate",
2785 ItemKind::Use(..) => "`use` import",
2786 ItemKind::Static(..) => "static item",
2787 ItemKind::Const(..) => "constant item",
2788 ItemKind::Fn(..) => "function",
2789 ItemKind::Mod(..) => "module",
2790 ItemKind::ForeignMod(..) => "extern block",
2791 ItemKind::GlobalAsm(..) => "global asm item",
2792 ItemKind::TyAlias(..) => "type alias",
2793 ItemKind::Enum(..) => "enum",
2794 ItemKind::Struct(..) => "struct",
2795 ItemKind::Union(..) => "union",
2796 ItemKind::Trait(..) => "trait",
2797 ItemKind::TraitAlias(..) => "trait alias",
2798 ItemKind::MacCall(..) => "item macro invocation",
2799 ItemKind::MacroDef(..) => "macro definition",
2800 ItemKind::Impl { .. } => "implementation",
2804 pub fn generics(&self) -> Option<&Generics> {
2806 Self::Fn(box Fn { generics, .. })
2807 | Self::TyAlias(box TyAlias { generics, .. })
2808 | Self::Enum(_, generics)
2809 | Self::Struct(_, generics)
2810 | Self::Union(_, generics)
2811 | Self::Trait(box Trait { generics, .. })
2812 | Self::TraitAlias(generics, _)
2813 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2819 /// Represents associated items.
2820 /// These include items in `impl` and `trait` definitions.
2821 pub type AssocItem = Item<AssocItemKind>;
2823 /// Represents associated item kinds.
2825 /// The term "provided" in the variants below refers to the item having a default
2826 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2827 /// In an implementation, all items must be provided.
2828 /// The `Option`s below denote the bodies, where `Some(_)`
2829 /// means "provided" and conversely `None` means "required".
2830 #[derive(Clone, Encodable, Decodable, Debug)]
2831 pub enum AssocItemKind {
2832 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2833 /// If `def` is parsed, then the constant is provided, and otherwise required.
2834 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2835 /// An associated function.
2837 /// An associated type.
2838 TyAlias(Box<TyAlias>),
2839 /// A macro expanding to associated items.
2843 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2844 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2846 impl AssocItemKind {
2847 pub fn defaultness(&self) -> Defaultness {
2849 Self::Const(defaultness, ..)
2850 | Self::Fn(box Fn { defaultness, .. })
2851 | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness,
2852 Self::MacCall(..) => Defaultness::Final,
2857 impl From<AssocItemKind> for ItemKind {
2858 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2859 match assoc_item_kind {
2860 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2861 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2862 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2863 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2868 impl TryFrom<ItemKind> for AssocItemKind {
2869 type Error = ItemKind;
2871 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2872 Ok(match item_kind {
2873 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2874 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2875 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2876 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2877 _ => return Err(item_kind),
2882 /// An item in `extern` block.
2883 #[derive(Clone, Encodable, Decodable, Debug)]
2884 pub enum ForeignItemKind {
2885 /// A foreign static item (`static FOO: u8`).
2886 Static(P<Ty>, Mutability, Option<P<Expr>>),
2887 /// An foreign function.
2889 /// An foreign type.
2890 TyAlias(Box<TyAlias>),
2891 /// A macro expanding to foreign items.
2895 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2896 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
2898 impl From<ForeignItemKind> for ItemKind {
2899 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2900 match foreign_item_kind {
2901 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2902 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2903 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2904 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2909 impl TryFrom<ItemKind> for ForeignItemKind {
2910 type Error = ItemKind;
2912 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2913 Ok(match item_kind {
2914 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2915 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
2916 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
2917 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2918 _ => return Err(item_kind),
2923 pub type ForeignItem = Item<ForeignItemKind>;