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, TokenKind};
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,
403 pub fn span(&self) -> Span {
405 GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
408 GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
409 GenericParamKind::Const { kw_span, default: Some(default), .. } => {
410 kw_span.to(default.value.span)
412 GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
417 /// Represents lifetime, type and const parameters attached to a declaration of
418 /// a function, enum, trait, etc.
419 #[derive(Clone, Encodable, Decodable, Debug)]
420 pub struct Generics {
421 pub params: Vec<GenericParam>,
422 pub where_clause: WhereClause,
426 impl Default for Generics {
427 /// Creates an instance of `Generics`.
428 fn default() -> Generics {
431 where_clause: WhereClause {
432 has_where_token: false,
433 predicates: Vec::new(),
441 /// A where-clause in a definition.
442 #[derive(Clone, Encodable, Decodable, Debug)]
443 pub struct WhereClause {
444 /// `true` if we ate a `where` token: this can happen
445 /// if we parsed no predicates (e.g. `struct Foo where {}`).
446 /// This allows us to accurately pretty-print
447 /// in `nt_to_tokenstream`
448 pub has_where_token: bool,
449 pub predicates: Vec<WherePredicate>,
453 /// A single predicate in a where-clause.
454 #[derive(Clone, Encodable, Decodable, Debug)]
455 pub enum WherePredicate {
456 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
457 BoundPredicate(WhereBoundPredicate),
458 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
459 RegionPredicate(WhereRegionPredicate),
460 /// An equality predicate (unsupported).
461 EqPredicate(WhereEqPredicate),
464 impl WherePredicate {
465 pub fn span(&self) -> Span {
467 WherePredicate::BoundPredicate(p) => p.span,
468 WherePredicate::RegionPredicate(p) => p.span,
469 WherePredicate::EqPredicate(p) => p.span,
476 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
477 #[derive(Clone, Encodable, Decodable, Debug)]
478 pub struct WhereBoundPredicate {
480 /// Any generics from a `for` binding.
481 pub bound_generic_params: Vec<GenericParam>,
482 /// The type being bounded.
483 pub bounded_ty: P<Ty>,
484 /// Trait and lifetime bounds (`Clone + Send + 'static`).
485 pub bounds: GenericBounds,
488 /// A lifetime predicate.
490 /// E.g., `'a: 'b + 'c`.
491 #[derive(Clone, Encodable, Decodable, Debug)]
492 pub struct WhereRegionPredicate {
494 pub lifetime: Lifetime,
495 pub bounds: GenericBounds,
498 /// An equality predicate (unsupported).
501 #[derive(Clone, Encodable, Decodable, Debug)]
502 pub struct WhereEqPredicate {
509 #[derive(Clone, Encodable, Decodable, Debug)]
511 pub attrs: Vec<Attribute>,
512 pub items: Vec<P<Item>>,
514 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
515 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
517 pub is_placeholder: bool,
520 /// Possible values inside of compile-time attribute lists.
522 /// E.g., the '..' in `#[name(..)]`.
523 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
524 pub enum NestedMetaItem {
525 /// A full MetaItem, for recursive meta items.
529 /// E.g., `"foo"`, `64`, `true`.
533 /// A spanned compile-time attribute item.
535 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
536 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
537 pub struct MetaItem {
539 pub kind: MetaItemKind,
543 /// A compile-time attribute item.
545 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
546 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
547 pub enum MetaItemKind {
550 /// E.g., `test` as in `#[test]`.
554 /// E.g., `derive(..)` as in `#[derive(..)]`.
555 List(Vec<NestedMetaItem>),
556 /// Name value meta item.
558 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
562 /// A block (`{ .. }`).
564 /// E.g., `{ .. }` as in `fn foo() { .. }`.
565 #[derive(Clone, Encodable, Decodable, Debug)]
567 /// The statements in the block.
568 pub stmts: Vec<Stmt>,
570 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
571 pub rules: BlockCheckMode,
573 pub tokens: Option<LazyTokenStream>,
574 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
581 pub could_be_bare_literal: bool,
586 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
587 #[derive(Clone, Encodable, Decodable, Debug)]
592 pub tokens: Option<LazyTokenStream>,
596 /// Attempt reparsing the pattern as a type.
597 /// This is intended for use by diagnostics.
598 pub fn to_ty(&self) -> Option<P<Ty>> {
599 let kind = match &self.kind {
600 // In a type expression `_` is an inference variable.
601 PatKind::Wild => TyKind::Infer,
602 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
603 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
604 TyKind::Path(None, Path::from_ident(*ident))
606 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
607 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
608 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
609 PatKind::Ref(pat, mutbl) => {
610 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
612 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
613 // when `P` can be reparsed as a type `T`.
614 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
615 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
616 // assuming `T0` to `Tn` are all syntactically valid as types.
617 PatKind::Tuple(pats) => {
618 let mut tys = Vec::with_capacity(pats.len());
619 // FIXME(#48994) - could just be collected into an Option<Vec>
621 tys.push(pat.to_ty()?);
628 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
631 /// Walk top-down and call `it` in each place where a pattern occurs
632 /// starting with the root pattern `walk` is called on. If `it` returns
633 /// false then we will descend no further but siblings will be processed.
634 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
640 // Walk into the pattern associated with `Ident` (if any).
641 PatKind::Ident(_, _, Some(p)) => p.walk(it),
643 // Walk into each field of struct.
644 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
646 // Sequence of patterns.
647 PatKind::TupleStruct(_, _, s)
650 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
652 // Trivial wrappers over inner patterns.
653 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
655 // These patterns do not contain subpatterns, skip.
662 | PatKind::MacCall(_) => {}
666 /// Is this a `..` pattern?
667 pub fn is_rest(&self) -> bool {
668 matches!(self.kind, PatKind::Rest)
672 /// A single field in a struct pattern.
674 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
675 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
676 /// except when `is_shorthand` is true.
677 #[derive(Clone, Encodable, Decodable, Debug)]
678 pub struct PatField {
679 /// The identifier for the field.
681 /// The pattern the field is destructured to.
683 pub is_shorthand: bool,
687 pub is_placeholder: bool,
690 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
691 pub enum BindingMode {
696 #[derive(Clone, Encodable, Decodable, Debug)]
699 Included(RangeSyntax),
704 #[derive(Clone, Encodable, Decodable, Debug)]
705 pub enum RangeSyntax {
712 /// All the different flavors of pattern that Rust recognizes.
713 #[derive(Clone, Encodable, Decodable, Debug)]
715 /// Represents a wildcard pattern (`_`).
718 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
719 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
720 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
721 /// during name resolution.
722 Ident(BindingMode, Ident, Option<P<Pat>>),
724 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
725 /// The `bool` is `true` in the presence of a `..`.
726 Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool),
728 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
729 TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>),
731 /// An or-pattern `A | B | C`.
732 /// Invariant: `pats.len() >= 2`.
735 /// A possibly qualified path pattern.
736 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
737 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
738 /// only legally refer to associated constants.
739 Path(Option<QSelf>, Path),
741 /// A tuple pattern (`(a, b)`).
747 /// A reference pattern (e.g., `&mut (a, b)`).
748 Ref(P<Pat>, Mutability),
753 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
754 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
756 /// A slice pattern `[a, b, c]`.
759 /// A rest pattern `..`.
761 /// Syntactically it is valid anywhere.
763 /// Semantically however, it only has meaning immediately inside:
764 /// - a slice pattern: `[a, .., b]`,
765 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
766 /// - a tuple pattern: `(a, .., b)`,
767 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
769 /// In all of these cases, an additional restriction applies,
770 /// only one rest pattern may occur in the pattern sequences.
773 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
776 /// A macro pattern; pre-expansion.
780 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
781 #[derive(HashStable_Generic, Encodable, Decodable)]
782 pub enum Mutability {
788 pub fn invert(self) -> Self {
790 Mutability::Mut => Mutability::Not,
791 Mutability::Not => Mutability::Mut,
795 pub fn prefix_str(&self) -> &'static str {
797 Mutability::Mut => "mut ",
798 Mutability::Not => "",
803 /// The kind of borrow in an `AddrOf` expression,
804 /// e.g., `&place` or `&raw const place`.
805 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
806 #[derive(Encodable, Decodable, HashStable_Generic)]
807 pub enum BorrowKind {
808 /// A normal borrow, `&$expr` or `&mut $expr`.
809 /// The resulting type is either `&'a T` or `&'a mut T`
810 /// where `T = typeof($expr)` and `'a` is some lifetime.
812 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
813 /// The resulting type is either `*const T` or `*mut T`
814 /// where `T = typeof($expr)`.
818 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
820 /// The `+` operator (addition)
822 /// The `-` operator (subtraction)
824 /// The `*` operator (multiplication)
826 /// The `/` operator (division)
828 /// The `%` operator (modulus)
830 /// The `&&` operator (logical and)
832 /// The `||` operator (logical or)
834 /// The `^` operator (bitwise xor)
836 /// The `&` operator (bitwise and)
838 /// The `|` operator (bitwise or)
840 /// The `<<` operator (shift left)
842 /// The `>>` operator (shift right)
844 /// The `==` operator (equality)
846 /// The `<` operator (less than)
848 /// The `<=` operator (less than or equal to)
850 /// The `!=` operator (not equal to)
852 /// The `>=` operator (greater than or equal to)
854 /// The `>` operator (greater than)
859 pub fn to_string(&self) -> &'static str {
882 pub fn lazy(&self) -> bool {
883 matches!(self, BinOpKind::And | BinOpKind::Or)
886 pub fn is_comparison(&self) -> bool {
888 // Note for developers: please keep this as is;
889 // we want compilation to fail if another variant is added.
891 Eq | Lt | Le | Ne | Gt | Ge => true,
892 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
897 pub type BinOp = Spanned<BinOpKind>;
901 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
902 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
904 /// The `*` operator for dereferencing
906 /// The `!` operator for logical inversion
908 /// The `-` operator for negation
913 pub fn to_string(op: UnOp) -> &'static str {
923 #[derive(Clone, Encodable, Decodable, Debug)]
931 pub fn tokens(&self) -> Option<&LazyTokenStream> {
933 StmtKind::Local(ref local) => local.tokens.as_ref(),
934 StmtKind::Item(ref item) => item.tokens.as_ref(),
935 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(),
936 StmtKind::Empty => None,
937 StmtKind::MacCall(ref mac) => mac.tokens.as_ref(),
941 pub fn has_trailing_semicolon(&self) -> bool {
943 StmtKind::Semi(_) => true,
944 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
949 /// Converts a parsed `Stmt` to a `Stmt` with
950 /// a trailing semicolon.
952 /// This only modifies the parsed AST struct, not the attached
953 /// `LazyTokenStream`. The parser is responsible for calling
954 /// `CreateTokenStream::add_trailing_semi` when there is actually
955 /// a semicolon in the tokenstream.
956 pub fn add_trailing_semicolon(mut self) -> Self {
957 self.kind = match self.kind {
958 StmtKind::Expr(expr) => StmtKind::Semi(expr),
959 StmtKind::MacCall(mac) => {
960 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
961 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
970 pub fn is_item(&self) -> bool {
971 matches!(self.kind, StmtKind::Item(_))
974 pub fn is_expr(&self) -> bool {
975 matches!(self.kind, StmtKind::Expr(_))
979 #[derive(Clone, Encodable, Decodable, Debug)]
981 /// A local (let) binding.
983 /// An item definition.
985 /// Expr without trailing semi-colon.
987 /// Expr with a trailing semi-colon.
989 /// Just a trailing semi-colon.
992 MacCall(P<MacCallStmt>),
995 #[derive(Clone, Encodable, Decodable, Debug)]
996 pub struct MacCallStmt {
998 pub style: MacStmtStyle,
1000 pub tokens: Option<LazyTokenStream>,
1003 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1004 pub enum MacStmtStyle {
1005 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1006 /// `foo!(...);`, `foo![...];`).
1008 /// The macro statement had braces (e.g., `foo! { ... }`).
1010 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1011 /// `foo!(...)`). All of these will end up being converted into macro
1016 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1017 #[derive(Clone, Encodable, Decodable, Debug)]
1021 pub ty: Option<P<Ty>>,
1022 pub kind: LocalKind,
1025 pub tokens: Option<LazyTokenStream>,
1028 #[derive(Clone, Encodable, Decodable, Debug)]
1029 pub enum LocalKind {
1030 /// Local declaration.
1031 /// Example: `let x;`
1033 /// Local declaration with an initializer.
1034 /// Example: `let x = y;`
1036 /// Local declaration with an initializer and an `else` clause.
1037 /// Example: `let Some(x) = y else { return };`
1038 InitElse(P<Expr>, P<Block>),
1042 pub fn init(&self) -> Option<&Expr> {
1045 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1049 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1052 Self::Init(init) => Some((init, None)),
1053 Self::InitElse(init, els) => Some((init, Some(els))),
1058 /// An arm of a 'match'.
1060 /// E.g., `0..=10 => { println!("match!") }` as in
1064 /// 0..=10 => { println!("match!") },
1065 /// _ => { println!("no match!") },
1068 #[derive(Clone, Encodable, Decodable, Debug)]
1071 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1073 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1074 pub guard: Option<P<Expr>>,
1079 pub is_placeholder: bool,
1082 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1083 #[derive(Clone, Encodable, Decodable, Debug)]
1084 pub struct ExprField {
1090 pub is_shorthand: bool,
1091 pub is_placeholder: bool,
1094 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1095 pub enum BlockCheckMode {
1097 Unsafe(UnsafeSource),
1100 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1101 pub enum UnsafeSource {
1106 /// A constant (expression) that's not an item or associated item,
1107 /// but needs its own `DefId` for type-checking, const-eval, etc.
1108 /// These are usually found nested inside types (e.g., array lengths)
1109 /// or expressions (e.g., repeat counts), and also used to define
1110 /// explicit discriminant values for enum variants.
1111 #[derive(Clone, Encodable, Decodable, Debug)]
1112 pub struct AnonConst {
1118 #[derive(Clone, Encodable, Decodable, Debug)]
1124 pub tokens: Option<LazyTokenStream>,
1127 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1128 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1129 rustc_data_structures::static_assert_size!(Expr, 104);
1132 /// Returns `true` if this expression would be valid somewhere that expects a value;
1133 /// for example, an `if` condition.
1134 pub fn returns(&self) -> bool {
1135 if let ExprKind::Block(ref block, _) = self.kind {
1136 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1138 Some(StmtKind::Expr(_)) => true,
1139 // Last statement is an explicit return?
1140 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1141 // This is a block that doesn't end in either an implicit or explicit return.
1145 // This is not a block, it is a value.
1150 /// Is this expr either `N`, or `{ N }`.
1152 /// If this is not the case, name resolution does not resolve `N` when using
1153 /// `min_const_generics` as more complex expressions are not supported.
1154 pub fn is_potential_trivial_const_param(&self) -> bool {
1155 let this = if let ExprKind::Block(ref block, None) = self.kind {
1156 if block.stmts.len() == 1 {
1157 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1165 if let ExprKind::Path(None, ref path) = this.kind {
1166 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1174 pub fn to_bound(&self) -> Option<GenericBound> {
1176 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1177 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1178 TraitBoundModifier::None,
1184 pub fn peel_parens(&self) -> &Expr {
1185 let mut expr = self;
1186 while let ExprKind::Paren(inner) = &expr.kind {
1192 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1193 pub fn to_ty(&self) -> Option<P<Ty>> {
1194 let kind = match &self.kind {
1195 // Trivial conversions.
1196 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1197 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1199 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1201 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1202 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1205 ExprKind::Repeat(expr, expr_len) => {
1206 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1209 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1211 ExprKind::Tup(exprs) => {
1212 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1216 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1217 // then type of result is trait object.
1218 // Otherwise we don't assume the result type.
1219 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1220 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1221 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1227 ExprKind::Underscore => TyKind::Infer,
1229 // This expression doesn't look like a type syntactically.
1233 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1236 pub fn precedence(&self) -> ExprPrecedence {
1238 ExprKind::Box(_) => ExprPrecedence::Box,
1239 ExprKind::Array(_) => ExprPrecedence::Array,
1240 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1241 ExprKind::Call(..) => ExprPrecedence::Call,
1242 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1243 ExprKind::Tup(_) => ExprPrecedence::Tup,
1244 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1245 ExprKind::Unary(..) => ExprPrecedence::Unary,
1246 ExprKind::Lit(_) => ExprPrecedence::Lit,
1247 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1248 ExprKind::Let(..) => ExprPrecedence::Let,
1249 ExprKind::If(..) => ExprPrecedence::If,
1250 ExprKind::While(..) => ExprPrecedence::While,
1251 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1252 ExprKind::Loop(..) => ExprPrecedence::Loop,
1253 ExprKind::Match(..) => ExprPrecedence::Match,
1254 ExprKind::Closure(..) => ExprPrecedence::Closure,
1255 ExprKind::Block(..) => ExprPrecedence::Block,
1256 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1257 ExprKind::Async(..) => ExprPrecedence::Async,
1258 ExprKind::Await(..) => ExprPrecedence::Await,
1259 ExprKind::Assign(..) => ExprPrecedence::Assign,
1260 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1261 ExprKind::Field(..) => ExprPrecedence::Field,
1262 ExprKind::Index(..) => ExprPrecedence::Index,
1263 ExprKind::Range(..) => ExprPrecedence::Range,
1264 ExprKind::Underscore => ExprPrecedence::Path,
1265 ExprKind::Path(..) => ExprPrecedence::Path,
1266 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1267 ExprKind::Break(..) => ExprPrecedence::Break,
1268 ExprKind::Continue(..) => ExprPrecedence::Continue,
1269 ExprKind::Ret(..) => ExprPrecedence::Ret,
1270 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1271 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1272 ExprKind::Struct(..) => ExprPrecedence::Struct,
1273 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1274 ExprKind::Paren(..) => ExprPrecedence::Paren,
1275 ExprKind::Try(..) => ExprPrecedence::Try,
1276 ExprKind::Yield(..) => ExprPrecedence::Yield,
1277 ExprKind::Err => ExprPrecedence::Err,
1281 pub fn take(&mut self) -> Self {
1286 kind: ExprKind::Err,
1288 attrs: ThinVec::new(),
1295 /// Limit types of a range (inclusive or exclusive)
1296 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1297 pub enum RangeLimits {
1298 /// Inclusive at the beginning, exclusive at the end
1300 /// Inclusive at the beginning and end
1304 #[derive(Clone, Encodable, Decodable, Debug)]
1305 pub enum StructRest {
1310 /// No trailing `..` or expression.
1314 #[derive(Clone, Encodable, Decodable, Debug)]
1315 pub struct StructExpr {
1316 pub qself: Option<QSelf>,
1318 pub fields: Vec<ExprField>,
1319 pub rest: StructRest,
1322 #[derive(Clone, Encodable, Decodable, Debug)]
1324 /// A `box x` expression.
1326 /// An array (`[a, b, c, d]`)
1327 Array(Vec<P<Expr>>),
1328 /// Allow anonymous constants from an inline `const` block
1329 ConstBlock(AnonConst),
1332 /// The first field resolves to the function itself,
1333 /// and the second field is the list of arguments.
1334 /// This also represents calling the constructor of
1335 /// tuple-like ADTs such as tuple structs and enum variants.
1336 Call(P<Expr>, Vec<P<Expr>>),
1337 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1339 /// The `PathSegment` represents the method name and its generic arguments
1340 /// (within the angle brackets).
1341 /// The first element of the vector of an `Expr` is the expression that evaluates
1342 /// to the object on which the method is being called on (the receiver),
1343 /// and the remaining elements are the rest of the arguments.
1344 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1345 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1346 /// This `Span` is the span of the function, without the dot and receiver
1347 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1348 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1349 /// A tuple (e.g., `(a, b, c, d)`).
1351 /// A binary operation (e.g., `a + b`, `a * b`).
1352 Binary(BinOp, P<Expr>, P<Expr>),
1353 /// A unary operation (e.g., `!x`, `*x`).
1354 Unary(UnOp, P<Expr>),
1355 /// A literal (e.g., `1`, `"foo"`).
1357 /// A cast (e.g., `foo as f64`).
1358 Cast(P<Expr>, P<Ty>),
1359 /// A type ascription (e.g., `42: usize`).
1360 Type(P<Expr>, P<Ty>),
1361 /// A `let pat = expr` expression that is only semantically allowed in the condition
1362 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1364 /// `Span` represents the whole `let pat = expr` statement.
1365 Let(P<Pat>, P<Expr>, Span),
1366 /// An `if` block, with an optional `else` block.
1368 /// `if expr { block } else { expr }`
1369 If(P<Expr>, P<Block>, Option<P<Expr>>),
1370 /// A while loop, with an optional label.
1372 /// `'label: while expr { block }`
1373 While(P<Expr>, P<Block>, Option<Label>),
1374 /// A `for` loop, with an optional label.
1376 /// `'label: for pat in expr { block }`
1378 /// This is desugared to a combination of `loop` and `match` expressions.
1379 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1380 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1382 /// `'label: loop { block }`
1383 Loop(P<Block>, Option<Label>),
1384 /// A `match` block.
1385 Match(P<Expr>, Vec<Arm>),
1386 /// A closure (e.g., `move |a, b, c| a + b + c`).
1388 /// The final span is the span of the argument block `|...|`.
1389 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1390 /// A block (`'label: { ... }`).
1391 Block(P<Block>, Option<Label>),
1392 /// An async block (`async move { ... }`).
1394 /// The `NodeId` is the `NodeId` for the closure that results from
1395 /// desugaring an async block, just like the NodeId field in the
1396 /// `Async::Yes` variant. This is necessary in order to create a def for the
1397 /// closure which can be used as a parent of any child defs. Defs
1398 /// created during lowering cannot be made the parent of any other
1399 /// preexisting defs.
1400 Async(CaptureBy, NodeId, P<Block>),
1401 /// An await expression (`my_future.await`).
1404 /// A try block (`try { ... }`).
1407 /// An assignment (`a = foo()`).
1408 /// The `Span` argument is the span of the `=` token.
1409 Assign(P<Expr>, P<Expr>, Span),
1410 /// An assignment with an operator.
1413 AssignOp(BinOp, P<Expr>, P<Expr>),
1414 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1415 Field(P<Expr>, Ident),
1416 /// An indexing operation (e.g., `foo[2]`).
1417 Index(P<Expr>, P<Expr>),
1418 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1419 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1420 /// An underscore, used in destructuring assignment to ignore a value.
1423 /// Variable reference, possibly containing `::` and/or type
1424 /// parameters (e.g., `foo::bar::<baz>`).
1426 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1427 Path(Option<QSelf>, Path),
1429 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1430 AddrOf(BorrowKind, Mutability, P<Expr>),
1431 /// A `break`, with an optional label to break, and an optional expression.
1432 Break(Option<Label>, Option<P<Expr>>),
1433 /// A `continue`, with an optional label.
1434 Continue(Option<Label>),
1435 /// A `return`, with an optional value to be returned.
1436 Ret(Option<P<Expr>>),
1438 /// Output of the `asm!()` macro.
1439 InlineAsm(P<InlineAsm>),
1441 /// A macro invocation; pre-expansion.
1444 /// A struct literal expression.
1446 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1447 Struct(P<StructExpr>),
1449 /// An array literal constructed from one repeated element.
1451 /// E.g., `[1; 5]`. The expression is the element to be
1452 /// repeated; the constant is the number of times to repeat it.
1453 Repeat(P<Expr>, AnonConst),
1455 /// No-op: used solely so we can pretty-print faithfully.
1458 /// A try expression (`expr?`).
1461 /// A `yield`, with an optional value to be yielded.
1462 Yield(Option<P<Expr>>),
1464 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1468 /// The explicit `Self` type in a "qualified path". The actual
1469 /// path, including the trait and the associated item, is stored
1470 /// separately. `position` represents the index of the associated
1471 /// item qualified with this `Self` type.
1473 /// ```ignore (only-for-syntax-highlight)
1474 /// <Vec<T> as a::b::Trait>::AssociatedItem
1475 /// ^~~~~ ~~~~~~~~~~~~~~^
1478 /// <Vec<T>>::AssociatedItem
1482 #[derive(Clone, Encodable, Decodable, Debug)]
1486 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1487 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1488 /// 0`, this is an empty span.
1489 pub path_span: Span,
1490 pub position: usize,
1493 /// A capture clause used in closures and `async` blocks.
1494 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1495 pub enum CaptureBy {
1496 /// `move |x| y + x`.
1498 /// `move` keyword was not specified.
1502 /// The movability of a generator / closure literal:
1503 /// whether a generator contains self-references, causing it to be `!Unpin`.
1504 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1505 #[derive(HashStable_Generic)]
1506 pub enum Movability {
1507 /// May contain self-references, `!Unpin`.
1509 /// Must not contain self-references, `Unpin`.
1513 /// Represents a macro invocation. The `path` indicates which macro
1514 /// is being invoked, and the `args` are arguments passed to it.
1515 #[derive(Clone, Encodable, Decodable, Debug)]
1516 pub struct MacCall {
1518 pub args: P<MacArgs>,
1519 pub prior_type_ascription: Option<(Span, bool)>,
1523 pub fn span(&self) -> Span {
1524 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1528 /// Arguments passed to an attribute or a function-like macro.
1529 #[derive(Clone, Encodable, Decodable, Debug)]
1531 /// No arguments - `#[attr]`.
1533 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1534 Delimited(DelimSpan, MacDelimiter, TokenStream),
1535 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1537 /// Span of the `=` token.
1544 // The RHS of a `MacArgs::Eq` starts out as an expression. Once macro expansion
1545 // is completed, all cases end up either as a literal, which is the form used
1546 // after lowering to HIR, or as an error.
1547 #[derive(Clone, Encodable, Decodable, Debug)]
1548 pub enum MacArgsEq {
1554 pub fn delim(&self) -> Option<Delimiter> {
1556 MacArgs::Delimited(_, delim, _) => Some(delim.to_token()),
1557 MacArgs::Empty | MacArgs::Eq(..) => None,
1561 pub fn span(&self) -> Option<Span> {
1563 MacArgs::Empty => None,
1564 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1565 MacArgs::Eq(eq_span, MacArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1566 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1567 unreachable!("in literal form when getting span: {:?}", lit);
1572 /// Tokens inside the delimiters or after `=`.
1573 /// Proc macros see these tokens, for example.
1574 pub fn inner_tokens(&self) -> TokenStream {
1576 MacArgs::Empty => TokenStream::default(),
1577 MacArgs::Delimited(.., tokens) => tokens.clone(),
1578 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => {
1579 // Currently only literals are allowed here. If more complex expression kinds are
1580 // allowed in the future, then `nt_to_tokenstream` should be used to extract the
1581 // token stream. This will require some cleverness, perhaps with a function
1582 // pointer, because `nt_to_tokenstream` is not directly usable from this crate.
1583 // It will also require changing the `parse_expr` call in `parse_mac_args_common`
1584 // to `parse_expr_force_collect`.
1585 if let ExprKind::Lit(lit) = &expr.kind {
1586 let token = Token::new(TokenKind::Literal(lit.token), lit.span);
1587 TokenTree::Token(token).into()
1589 unreachable!("couldn't extract literal when getting inner tokens: {:?}", expr)
1592 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1593 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1598 /// Whether a macro with these arguments needs a semicolon
1599 /// when used as a standalone item or statement.
1600 pub fn need_semicolon(&self) -> bool {
1601 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1605 impl<CTX> HashStable<CTX> for MacArgs
1607 CTX: crate::HashStableContext,
1609 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1610 mem::discriminant(self).hash_stable(ctx, hasher);
1612 MacArgs::Empty => {}
1613 MacArgs::Delimited(dspan, delim, tokens) => {
1614 dspan.hash_stable(ctx, hasher);
1615 delim.hash_stable(ctx, hasher);
1616 tokens.hash_stable(ctx, hasher);
1618 MacArgs::Eq(_eq_span, MacArgsEq::Ast(expr)) => {
1619 unreachable!("hash_stable {:?}", expr);
1621 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit)) => {
1622 eq_span.hash_stable(ctx, hasher);
1623 lit.hash_stable(ctx, hasher);
1629 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1630 pub enum MacDelimiter {
1637 pub fn to_token(self) -> Delimiter {
1639 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1640 MacDelimiter::Bracket => Delimiter::Bracket,
1641 MacDelimiter::Brace => Delimiter::Brace,
1645 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1647 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1648 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1649 Delimiter::Brace => Some(MacDelimiter::Brace),
1650 Delimiter::Invisible => None,
1655 /// Represents a macro definition.
1656 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1657 pub struct MacroDef {
1658 pub body: P<MacArgs>,
1659 /// `true` if macro was defined with `macro_rules`.
1660 pub macro_rules: bool,
1663 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1664 #[derive(HashStable_Generic)]
1666 /// A regular string, like `"foo"`.
1668 /// A raw string, like `r##"foo"##`.
1670 /// The value is the number of `#` symbols used.
1675 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1677 /// The original literal token as written in source code.
1678 pub token: token::Lit,
1679 /// The "semantic" representation of the literal lowered from the original tokens.
1680 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1681 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1686 /// Same as `Lit`, but restricted to string literals.
1687 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1689 /// The original literal token as written in source code.
1690 pub style: StrStyle,
1692 pub suffix: Option<Symbol>,
1694 /// The unescaped "semantic" representation of the literal lowered from the original token.
1695 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1696 pub symbol_unescaped: Symbol,
1700 pub fn as_lit(&self) -> Lit {
1701 let token_kind = match self.style {
1702 StrStyle::Cooked => token::Str,
1703 StrStyle::Raw(n) => token::StrRaw(n),
1706 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1708 kind: LitKind::Str(self.symbol_unescaped, self.style),
1713 /// Type of the integer literal based on provided suffix.
1714 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1715 #[derive(HashStable_Generic)]
1716 pub enum LitIntType {
1725 /// Type of the float literal based on provided suffix.
1726 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1727 #[derive(HashStable_Generic)]
1728 pub enum LitFloatType {
1729 /// A float literal with a suffix (`1f32` or `1E10f32`).
1731 /// A float literal without a suffix (`1.0 or 1.0E10`).
1737 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1738 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1740 /// A string literal (`"foo"`).
1741 Str(Symbol, StrStyle),
1742 /// A byte string (`b"foo"`).
1744 /// A byte char (`b'f'`).
1746 /// A character literal (`'a'`).
1748 /// An integer literal (`1`).
1749 Int(u128, LitIntType),
1750 /// A float literal (`1f64` or `1E10f64`).
1751 Float(Symbol, LitFloatType),
1752 /// A boolean literal.
1754 /// Placeholder for a literal that wasn't well-formed in some way.
1759 /// Returns `true` if this literal is a string.
1760 pub fn is_str(&self) -> bool {
1761 matches!(self, LitKind::Str(..))
1764 /// Returns `true` if this literal is byte literal string.
1765 pub fn is_bytestr(&self) -> bool {
1766 matches!(self, LitKind::ByteStr(_))
1769 /// Returns `true` if this is a numeric literal.
1770 pub fn is_numeric(&self) -> bool {
1771 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1774 /// Returns `true` if this literal has no suffix.
1775 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1776 pub fn is_unsuffixed(&self) -> bool {
1780 /// Returns `true` if this literal has a suffix.
1781 pub fn is_suffixed(&self) -> bool {
1783 // suffixed variants
1784 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1785 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1786 // unsuffixed variants
1788 | LitKind::ByteStr(..)
1791 | LitKind::Int(_, LitIntType::Unsuffixed)
1792 | LitKind::Float(_, LitFloatType::Unsuffixed)
1794 | LitKind::Err(..) => false,
1799 // N.B., If you change this, you'll probably want to change the corresponding
1800 // type structure in `middle/ty.rs` as well.
1801 #[derive(Clone, Encodable, Decodable, Debug)]
1804 pub mutbl: Mutability,
1807 /// Represents a function's signature in a trait declaration,
1808 /// trait implementation, or free function.
1809 #[derive(Clone, Encodable, Decodable, Debug)]
1811 pub header: FnHeader,
1812 pub decl: P<FnDecl>,
1816 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1817 #[derive(Encodable, Decodable, HashStable_Generic)]
1824 pub fn name_str(self) -> &'static str {
1826 FloatTy::F32 => "f32",
1827 FloatTy::F64 => "f64",
1831 pub fn name(self) -> Symbol {
1833 FloatTy::F32 => sym::f32,
1834 FloatTy::F64 => sym::f64,
1839 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1840 #[derive(Encodable, Decodable, HashStable_Generic)]
1851 pub fn name_str(&self) -> &'static str {
1853 IntTy::Isize => "isize",
1855 IntTy::I16 => "i16",
1856 IntTy::I32 => "i32",
1857 IntTy::I64 => "i64",
1858 IntTy::I128 => "i128",
1862 pub fn name(&self) -> Symbol {
1864 IntTy::Isize => sym::isize,
1865 IntTy::I8 => sym::i8,
1866 IntTy::I16 => sym::i16,
1867 IntTy::I32 => sym::i32,
1868 IntTy::I64 => sym::i64,
1869 IntTy::I128 => sym::i128,
1874 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1875 #[derive(Encodable, Decodable, HashStable_Generic)]
1886 pub fn name_str(&self) -> &'static str {
1888 UintTy::Usize => "usize",
1890 UintTy::U16 => "u16",
1891 UintTy::U32 => "u32",
1892 UintTy::U64 => "u64",
1893 UintTy::U128 => "u128",
1897 pub fn name(&self) -> Symbol {
1899 UintTy::Usize => sym::usize,
1900 UintTy::U8 => sym::u8,
1901 UintTy::U16 => sym::u16,
1902 UintTy::U32 => sym::u32,
1903 UintTy::U64 => sym::u64,
1904 UintTy::U128 => sym::u128,
1909 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1910 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1911 #[derive(Clone, Encodable, Decodable, Debug)]
1912 pub struct AssocConstraint {
1915 pub gen_args: Option<GenericArgs>,
1916 pub kind: AssocConstraintKind,
1920 /// The kinds of an `AssocConstraint`.
1921 #[derive(Clone, Encodable, Decodable, Debug)]
1927 impl From<P<Ty>> for Term {
1928 fn from(v: P<Ty>) -> Self {
1933 impl From<AnonConst> for Term {
1934 fn from(v: AnonConst) -> Self {
1939 /// The kinds of an `AssocConstraint`.
1940 #[derive(Clone, Encodable, Decodable, Debug)]
1941 pub enum AssocConstraintKind {
1942 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1943 Equality { term: Term },
1944 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1945 Bound { bounds: GenericBounds },
1948 #[derive(Encodable, Decodable, Debug)]
1953 pub tokens: Option<LazyTokenStream>,
1957 fn clone(&self) -> Self {
1958 ensure_sufficient_stack(|| Self {
1960 kind: self.kind.clone(),
1962 tokens: self.tokens.clone(),
1968 pub fn peel_refs(&self) -> &Self {
1969 let mut final_ty = self;
1970 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1977 #[derive(Clone, Encodable, Decodable, Debug)]
1978 pub struct BareFnTy {
1979 pub unsafety: Unsafe,
1981 pub generic_params: Vec<GenericParam>,
1982 pub decl: P<FnDecl>,
1985 /// The various kinds of type recognized by the compiler.
1986 #[derive(Clone, Encodable, Decodable, Debug)]
1988 /// A variable-length slice (`[T]`).
1990 /// A fixed length array (`[T; n]`).
1991 Array(P<Ty>, AnonConst),
1992 /// A raw pointer (`*const T` or `*mut T`).
1994 /// A reference (`&'a T` or `&'a mut T`).
1995 Rptr(Option<Lifetime>, MutTy),
1996 /// A bare function (e.g., `fn(usize) -> bool`).
1997 BareFn(P<BareFnTy>),
1998 /// The never type (`!`).
2000 /// A tuple (`(A, B, C, D,...)`).
2002 /// A path (`module::module::...::Type`), optionally
2003 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2005 /// Type parameters are stored in the `Path` itself.
2006 Path(Option<QSelf>, Path),
2007 /// A trait object type `Bound1 + Bound2 + Bound3`
2008 /// where `Bound` is a trait or a lifetime.
2009 TraitObject(GenericBounds, TraitObjectSyntax),
2010 /// An `impl Bound1 + Bound2 + Bound3` type
2011 /// where `Bound` is a trait or a lifetime.
2013 /// The `NodeId` exists to prevent lowering from having to
2014 /// generate `NodeId`s on the fly, which would complicate
2015 /// the generation of opaque `type Foo = impl Trait` items significantly.
2016 ImplTrait(NodeId, GenericBounds),
2017 /// No-op; kept solely so that we can pretty-print faithfully.
2021 /// This means the type should be inferred instead of it having been
2022 /// specified. This can appear anywhere in a type.
2024 /// Inferred type of a `self` or `&self` argument in a method.
2026 /// A macro in the type position.
2028 /// Placeholder for a kind that has failed to be defined.
2030 /// Placeholder for a `va_list`.
2035 pub fn is_implicit_self(&self) -> bool {
2036 matches!(self, TyKind::ImplicitSelf)
2039 pub fn is_unit(&self) -> bool {
2040 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2044 /// Syntax used to declare a trait object.
2045 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2046 pub enum TraitObjectSyntax {
2051 /// Inline assembly operand explicit register or register class.
2053 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2054 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2055 pub enum InlineAsmRegOrRegClass {
2060 bitflags::bitflags! {
2061 #[derive(Encodable, Decodable, HashStable_Generic)]
2062 pub struct InlineAsmOptions: u16 {
2063 const PURE = 1 << 0;
2064 const NOMEM = 1 << 1;
2065 const READONLY = 1 << 2;
2066 const PRESERVES_FLAGS = 1 << 3;
2067 const NORETURN = 1 << 4;
2068 const NOSTACK = 1 << 5;
2069 const ATT_SYNTAX = 1 << 6;
2071 const MAY_UNWIND = 1 << 8;
2075 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2076 pub enum InlineAsmTemplatePiece {
2078 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2081 impl fmt::Display for InlineAsmTemplatePiece {
2082 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2084 Self::String(s) => {
2085 for c in s.chars() {
2087 '{' => f.write_str("{{")?,
2088 '}' => f.write_str("}}")?,
2094 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2095 write!(f, "{{{}:{}}}", operand_idx, modifier)
2097 Self::Placeholder { operand_idx, modifier: None, .. } => {
2098 write!(f, "{{{}}}", operand_idx)
2104 impl InlineAsmTemplatePiece {
2105 /// Rebuilds the asm template string from its pieces.
2106 pub fn to_string(s: &[Self]) -> String {
2108 let mut out = String::new();
2110 let _ = write!(out, "{}", p);
2116 /// Inline assembly symbol operands get their own AST node that is somewhat
2117 /// similar to `AnonConst`.
2119 /// The main difference is that we specifically don't assign it `DefId` in
2120 /// `DefCollector`. Instead this is deferred until AST lowering where we
2121 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2122 /// depending on what the path resolves to.
2123 #[derive(Clone, Encodable, Decodable, Debug)]
2124 pub struct InlineAsmSym {
2126 pub qself: Option<QSelf>,
2130 /// Inline assembly operand.
2132 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2133 #[derive(Clone, Encodable, Decodable, Debug)]
2134 pub enum InlineAsmOperand {
2136 reg: InlineAsmRegOrRegClass,
2140 reg: InlineAsmRegOrRegClass,
2142 expr: Option<P<Expr>>,
2145 reg: InlineAsmRegOrRegClass,
2150 reg: InlineAsmRegOrRegClass,
2153 out_expr: Option<P<Expr>>,
2156 anon_const: AnonConst,
2163 /// Inline assembly.
2165 /// E.g., `asm!("NOP");`.
2166 #[derive(Clone, Encodable, Decodable, Debug)]
2167 pub struct InlineAsm {
2168 pub template: Vec<InlineAsmTemplatePiece>,
2169 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2170 pub operands: Vec<(InlineAsmOperand, Span)>,
2171 pub clobber_abis: Vec<(Symbol, Span)>,
2172 pub options: InlineAsmOptions,
2173 pub line_spans: Vec<Span>,
2176 /// A parameter in a function header.
2178 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2179 #[derive(Clone, Encodable, Decodable, Debug)]
2186 pub is_placeholder: bool,
2189 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2191 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2192 #[derive(Clone, Encodable, Decodable, Debug)]
2194 /// `self`, `mut self`
2196 /// `&'lt self`, `&'lt mut self`
2197 Region(Option<Lifetime>, Mutability),
2198 /// `self: TYPE`, `mut self: TYPE`
2199 Explicit(P<Ty>, Mutability),
2202 pub type ExplicitSelf = Spanned<SelfKind>;
2205 /// Attempts to cast parameter to `ExplicitSelf`.
2206 pub fn to_self(&self) -> Option<ExplicitSelf> {
2207 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2208 if ident.name == kw::SelfLower {
2209 return match self.ty.kind {
2210 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2211 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2212 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2215 self.pat.span.to(self.ty.span),
2216 SelfKind::Explicit(self.ty.clone(), mutbl),
2224 /// Returns `true` if parameter is `self`.
2225 pub fn is_self(&self) -> bool {
2226 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2227 ident.name == kw::SelfLower
2233 /// Builds a `Param` object from `ExplicitSelf`.
2234 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2235 let span = eself.span.to(eself_ident.span);
2236 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2237 let param = |mutbl, ty| Param {
2241 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2248 is_placeholder: false,
2251 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2252 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2253 SelfKind::Region(lt, mutbl) => param(
2257 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2266 /// A signature (not the body) of a function declaration.
2268 /// E.g., `fn foo(bar: baz)`.
2270 /// Please note that it's different from `FnHeader` structure
2271 /// which contains metadata about function safety, asyncness, constness and ABI.
2272 #[derive(Clone, Encodable, Decodable, Debug)]
2274 pub inputs: Vec<Param>,
2275 pub output: FnRetTy,
2279 pub fn has_self(&self) -> bool {
2280 self.inputs.get(0).map_or(false, Param::is_self)
2282 pub fn c_variadic(&self) -> bool {
2283 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2287 /// Is the trait definition an auto trait?
2288 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2294 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2295 #[derive(HashStable_Generic)]
2301 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2303 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2308 pub fn is_async(self) -> bool {
2309 matches!(self, Async::Yes { .. })
2312 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2313 pub fn opt_return_id(self) -> Option<NodeId> {
2315 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2321 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2322 #[derive(HashStable_Generic)]
2328 /// Item defaultness.
2329 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2330 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2331 pub enum Defaultness {
2336 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2337 pub enum ImplPolarity {
2338 /// `impl Trait for Type`
2340 /// `impl !Trait for Type`
2344 impl fmt::Debug for ImplPolarity {
2345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2347 ImplPolarity::Positive => "positive".fmt(f),
2348 ImplPolarity::Negative(_) => "negative".fmt(f),
2353 #[derive(Clone, Encodable, Decodable, Debug)]
2355 /// Returns type is not specified.
2357 /// Functions default to `()` and closures default to inference.
2358 /// Span points to where return type would be inserted.
2360 /// Everything else.
2365 pub fn span(&self) -> Span {
2367 FnRetTy::Default(span) => span,
2368 FnRetTy::Ty(ref ty) => ty.span,
2373 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2379 /// Module item kind.
2380 #[derive(Clone, Encodable, Decodable, Debug)]
2382 /// Module with inlined definition `mod foo { ... }`,
2383 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2384 /// The inner span is from the first token past `{` to the last token until `}`,
2385 /// or from the first to the last token in the loaded file.
2386 Loaded(Vec<P<Item>>, Inline, ModSpans),
2387 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2391 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2392 pub struct ModSpans {
2393 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2394 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2395 pub inner_span: Span,
2396 pub inject_use_span: Span,
2399 impl Default for ModSpans {
2400 fn default() -> ModSpans {
2401 ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2405 /// Foreign module declaration.
2407 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2408 #[derive(Clone, Encodable, Decodable, Debug)]
2409 pub struct ForeignMod {
2410 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2411 /// semantically by Rust.
2412 pub unsafety: Unsafe,
2413 pub abi: Option<StrLit>,
2414 pub items: Vec<P<ForeignItem>>,
2417 #[derive(Clone, Encodable, Decodable, Debug)]
2418 pub struct EnumDef {
2419 pub variants: Vec<Variant>,
2422 #[derive(Clone, Encodable, Decodable, Debug)]
2423 pub struct Variant {
2424 /// Attributes of the variant.
2426 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2430 /// The visibility of the variant. Syntactically accepted but not semantically.
2431 pub vis: Visibility,
2432 /// Name of the variant.
2435 /// Fields and constructor id of the variant.
2436 pub data: VariantData,
2437 /// Explicit discriminant, e.g., `Foo = 1`.
2438 pub disr_expr: Option<AnonConst>,
2439 /// Is a macro placeholder
2440 pub is_placeholder: bool,
2443 /// Part of `use` item to the right of its prefix.
2444 #[derive(Clone, Encodable, Decodable, Debug)]
2445 pub enum UseTreeKind {
2446 /// `use prefix` or `use prefix as rename`
2448 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2450 Simple(Option<Ident>, NodeId, NodeId),
2451 /// `use prefix::{...}`
2452 Nested(Vec<(UseTree, NodeId)>),
2457 /// A tree of paths sharing common prefixes.
2458 /// Used in `use` items both at top-level and inside of braces in import groups.
2459 #[derive(Clone, Encodable, Decodable, Debug)]
2460 pub struct UseTree {
2462 pub kind: UseTreeKind,
2467 pub fn ident(&self) -> Ident {
2469 UseTreeKind::Simple(Some(rename), ..) => rename,
2470 UseTreeKind::Simple(None, ..) => {
2471 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2473 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2478 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2479 /// are contained as statements within items. These two cases need to be
2480 /// distinguished for pretty-printing.
2481 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2482 pub enum AttrStyle {
2487 rustc_index::newtype_index! {
2490 DEBUG_FORMAT = "AttrId({})"
2494 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2495 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2500 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2501 fn decode(_: &mut D) -> AttrId {
2502 crate::attr::mk_attr_id()
2506 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2507 pub struct AttrItem {
2510 pub tokens: Option<LazyTokenStream>,
2513 /// A list of attributes.
2514 pub type AttrVec = ThinVec<Attribute>;
2516 /// Metadata associated with an item.
2517 #[derive(Clone, Encodable, Decodable, Debug)]
2518 pub struct Attribute {
2521 /// Denotes if the attribute decorates the following construct (outer)
2522 /// or the construct this attribute is contained within (inner).
2523 pub style: AttrStyle,
2527 #[derive(Clone, Encodable, Decodable, Debug)]
2529 /// A normal attribute.
2530 Normal(AttrItem, Option<LazyTokenStream>),
2532 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2533 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2534 /// variant (which is much less compact and thus more expensive).
2535 DocComment(CommentKind, Symbol),
2538 /// `TraitRef`s appear in impls.
2540 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2541 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2542 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2543 /// same as the impl's `NodeId`).
2544 #[derive(Clone, Encodable, Decodable, Debug)]
2545 pub struct TraitRef {
2550 #[derive(Clone, Encodable, Decodable, Debug)]
2551 pub struct PolyTraitRef {
2552 /// The `'a` in `for<'a> Foo<&'a T>`.
2553 pub bound_generic_params: Vec<GenericParam>,
2555 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2556 pub trait_ref: TraitRef,
2562 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2564 bound_generic_params: generic_params,
2565 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2571 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2572 pub enum CrateSugar {
2573 /// Source is `pub(crate)`.
2576 /// Source is (just) `crate`.
2580 #[derive(Clone, Encodable, Decodable, Debug)]
2581 pub struct Visibility {
2582 pub kind: VisibilityKind,
2584 pub tokens: Option<LazyTokenStream>,
2587 #[derive(Clone, Encodable, Decodable, Debug)]
2588 pub enum VisibilityKind {
2591 Restricted { path: P<Path>, id: NodeId },
2595 impl VisibilityKind {
2596 pub fn is_pub(&self) -> bool {
2597 matches!(self, VisibilityKind::Public)
2601 /// Field definition in a struct, variant or union.
2603 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2604 #[derive(Clone, Encodable, Decodable, Debug)]
2605 pub struct FieldDef {
2609 pub vis: Visibility,
2610 pub ident: Option<Ident>,
2613 pub is_placeholder: bool,
2616 /// Fields and constructor ids of enum variants and structs.
2617 #[derive(Clone, Encodable, Decodable, Debug)]
2618 pub enum VariantData {
2621 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2622 Struct(Vec<FieldDef>, bool),
2625 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2626 Tuple(Vec<FieldDef>, NodeId),
2629 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2634 /// Return the fields of this variant.
2635 pub fn fields(&self) -> &[FieldDef] {
2637 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2642 /// Return the `NodeId` of this variant's constructor, if it has one.
2643 pub fn ctor_id(&self) -> Option<NodeId> {
2645 VariantData::Struct(..) => None,
2646 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2651 /// An item definition.
2652 #[derive(Clone, Encodable, Decodable, Debug)]
2653 pub struct Item<K = ItemKind> {
2654 pub attrs: Vec<Attribute>,
2657 pub vis: Visibility,
2658 /// The name of the item.
2659 /// It might be a dummy name in case of anonymous items.
2664 /// Original tokens this item was parsed from. This isn't necessarily
2665 /// available for all items, although over time more and more items should
2666 /// have this be `Some`. Right now this is primarily used for procedural
2667 /// macros, notably custom attributes.
2669 /// Note that the tokens here do not include the outer attributes, but will
2670 /// include inner attributes.
2671 pub tokens: Option<LazyTokenStream>,
2675 /// Return the span that encompasses the attributes.
2676 pub fn span_with_attributes(&self) -> Span {
2677 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2681 impl<K: Into<ItemKind>> Item<K> {
2682 pub fn into_item(self) -> Item {
2683 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2684 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2688 /// `extern` qualifier on a function item or function type.
2689 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2697 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2698 abi.map_or(Extern::Implicit, Extern::Explicit)
2702 /// A function header.
2704 /// All the information between the visibility and the name of the function is
2705 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2706 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2707 pub struct FnHeader {
2708 pub unsafety: Unsafe,
2709 pub asyncness: Async,
2710 pub constness: Const,
2715 /// Does this function header have any qualifiers or is it empty?
2716 pub fn has_qualifiers(&self) -> bool {
2717 let Self { unsafety, asyncness, constness, ext } = self;
2718 matches!(unsafety, Unsafe::Yes(_))
2719 || asyncness.is_async()
2720 || matches!(constness, Const::Yes(_))
2721 || !matches!(ext, Extern::None)
2725 impl Default for FnHeader {
2726 fn default() -> FnHeader {
2728 unsafety: Unsafe::No,
2729 asyncness: Async::No,
2730 constness: Const::No,
2736 #[derive(Clone, Encodable, Decodable, Debug)]
2738 pub unsafety: Unsafe,
2739 pub is_auto: IsAuto,
2740 pub generics: Generics,
2741 pub bounds: GenericBounds,
2742 pub items: Vec<P<AssocItem>>,
2745 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2746 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2747 /// are two locations for where clause on type aliases, but their predicates
2748 /// are concatenated together.
2750 /// Take this example:
2751 /// ```ignore (only-for-syntax-highlight)
2753 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2755 /// impl Foo for () {
2756 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2757 /// // ^^^^^^^^^^^^^^ first where clause
2758 /// // ^^^^^^^^^^^^^^ second where clause
2762 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2763 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2764 pub struct TyAliasWhereClause(pub bool, pub Span);
2766 #[derive(Clone, Encodable, Decodable, Debug)]
2767 pub struct TyAlias {
2768 pub defaultness: Defaultness,
2769 pub generics: Generics,
2770 /// The span information for the two where clauses (before equals, after equals)
2771 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2772 /// The index in `generics.where_clause.predicates` that would split into
2773 /// predicates from the where clause before the equals and the predicates
2774 /// from the where clause after the equals
2775 pub where_predicates_split: usize,
2776 pub bounds: GenericBounds,
2777 pub ty: Option<P<Ty>>,
2780 #[derive(Clone, Encodable, Decodable, Debug)]
2782 pub defaultness: Defaultness,
2783 pub unsafety: Unsafe,
2784 pub generics: Generics,
2785 pub constness: Const,
2786 pub polarity: ImplPolarity,
2787 /// The trait being implemented, if any.
2788 pub of_trait: Option<TraitRef>,
2790 pub items: Vec<P<AssocItem>>,
2793 #[derive(Clone, Encodable, Decodable, Debug)]
2795 pub defaultness: Defaultness,
2796 pub generics: Generics,
2798 pub body: Option<P<Block>>,
2801 #[derive(Clone, Encodable, Decodable, Debug)]
2803 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2805 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2806 ExternCrate(Option<Symbol>),
2807 /// A use declaration item (`use`).
2809 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2811 /// A static item (`static`).
2813 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2814 Static(P<Ty>, Mutability, Option<P<Expr>>),
2815 /// A constant item (`const`).
2817 /// E.g., `const FOO: i32 = 42;`.
2818 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2819 /// A function declaration (`fn`).
2821 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2823 /// A module declaration (`mod`).
2825 /// E.g., `mod foo;` or `mod foo { .. }`.
2826 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2827 /// semantically by Rust.
2828 Mod(Unsafe, ModKind),
2829 /// An external module (`extern`).
2831 /// E.g., `extern {}` or `extern "C" {}`.
2832 ForeignMod(ForeignMod),
2833 /// Module-level inline assembly (from `global_asm!()`).
2834 GlobalAsm(Box<InlineAsm>),
2835 /// A type alias (`type`).
2837 /// E.g., `type Foo = Bar<u8>;`.
2838 TyAlias(Box<TyAlias>),
2839 /// An enum definition (`enum`).
2841 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2842 Enum(EnumDef, Generics),
2843 /// A struct definition (`struct`).
2845 /// E.g., `struct Foo<A> { x: A }`.
2846 Struct(VariantData, Generics),
2847 /// A union definition (`union`).
2849 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2850 Union(VariantData, Generics),
2851 /// A trait declaration (`trait`).
2853 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2857 /// E.g., `trait Foo = Bar + Quux;`.
2858 TraitAlias(Generics, GenericBounds),
2859 /// An implementation.
2861 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2863 /// A macro invocation.
2865 /// E.g., `foo!(..)`.
2868 /// A macro definition.
2872 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2873 rustc_data_structures::static_assert_size!(ItemKind, 112);
2876 pub fn article(&self) -> &str {
2879 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2880 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2881 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2885 pub fn descr(&self) -> &str {
2887 ItemKind::ExternCrate(..) => "extern crate",
2888 ItemKind::Use(..) => "`use` import",
2889 ItemKind::Static(..) => "static item",
2890 ItemKind::Const(..) => "constant item",
2891 ItemKind::Fn(..) => "function",
2892 ItemKind::Mod(..) => "module",
2893 ItemKind::ForeignMod(..) => "extern block",
2894 ItemKind::GlobalAsm(..) => "global asm item",
2895 ItemKind::TyAlias(..) => "type alias",
2896 ItemKind::Enum(..) => "enum",
2897 ItemKind::Struct(..) => "struct",
2898 ItemKind::Union(..) => "union",
2899 ItemKind::Trait(..) => "trait",
2900 ItemKind::TraitAlias(..) => "trait alias",
2901 ItemKind::MacCall(..) => "item macro invocation",
2902 ItemKind::MacroDef(..) => "macro definition",
2903 ItemKind::Impl { .. } => "implementation",
2907 pub fn generics(&self) -> Option<&Generics> {
2909 Self::Fn(box Fn { generics, .. })
2910 | Self::TyAlias(box TyAlias { generics, .. })
2911 | Self::Enum(_, generics)
2912 | Self::Struct(_, generics)
2913 | Self::Union(_, generics)
2914 | Self::Trait(box Trait { generics, .. })
2915 | Self::TraitAlias(generics, _)
2916 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2922 /// Represents associated items.
2923 /// These include items in `impl` and `trait` definitions.
2924 pub type AssocItem = Item<AssocItemKind>;
2926 /// Represents associated item kinds.
2928 /// The term "provided" in the variants below refers to the item having a default
2929 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2930 /// In an implementation, all items must be provided.
2931 /// The `Option`s below denote the bodies, where `Some(_)`
2932 /// means "provided" and conversely `None` means "required".
2933 #[derive(Clone, Encodable, Decodable, Debug)]
2934 pub enum AssocItemKind {
2935 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2936 /// If `def` is parsed, then the constant is provided, and otherwise required.
2937 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2938 /// An associated function.
2940 /// An associated type.
2941 TyAlias(Box<TyAlias>),
2942 /// A macro expanding to associated items.
2946 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2947 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2949 impl AssocItemKind {
2950 pub fn defaultness(&self) -> Defaultness {
2952 Self::Const(defaultness, ..)
2953 | Self::Fn(box Fn { defaultness, .. })
2954 | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness,
2955 Self::MacCall(..) => Defaultness::Final,
2960 impl From<AssocItemKind> for ItemKind {
2961 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2962 match assoc_item_kind {
2963 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2964 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2965 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2966 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2971 impl TryFrom<ItemKind> for AssocItemKind {
2972 type Error = ItemKind;
2974 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2975 Ok(match item_kind {
2976 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2977 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2978 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2979 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2980 _ => return Err(item_kind),
2985 /// An item in `extern` block.
2986 #[derive(Clone, Encodable, Decodable, Debug)]
2987 pub enum ForeignItemKind {
2988 /// A foreign static item (`static FOO: u8`).
2989 Static(P<Ty>, Mutability, Option<P<Expr>>),
2990 /// An foreign function.
2992 /// An foreign type.
2993 TyAlias(Box<TyAlias>),
2994 /// A macro expanding to foreign items.
2998 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2999 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
3001 impl From<ForeignItemKind> for ItemKind {
3002 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3003 match foreign_item_kind {
3004 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3005 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3006 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3007 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3012 impl TryFrom<ItemKind> for ForeignItemKind {
3013 type Error = ItemKind;
3015 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3016 Ok(match item_kind {
3017 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3018 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3019 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3020 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3021 _ => return Err(item_kind),
3026 pub type ForeignItem = Item<ForeignItemKind>;