1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
26 use crate::token::{self, CommentKind, Delimiter};
27 use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream};
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::{Decodable, Decoder, Encodable, 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;
44 /// A "Label" is an identifier of some point in sources,
45 /// e.g. in the following code:
53 /// `'outer` is a label.
54 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
59 impl fmt::Debug for Label {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "label({:?})", self.ident)
65 /// A "Lifetime" is an annotation of the scope in which variable
66 /// can be used, e.g. `'a` in `&'a i32`.
67 #[derive(Clone, Encodable, Decodable, Copy, PartialEq, Eq)]
73 impl fmt::Debug for Lifetime {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 write!(f, "lifetime({}: {})", self.id, self)
79 impl fmt::Display for Lifetime {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(f, "{}", self.ident.name)
85 /// A "Path" is essentially Rust's notion of a name.
87 /// It's represented as a sequence of identifiers,
88 /// along with a bunch of supporting information.
90 /// E.g., `std::cmp::PartialEq`.
91 #[derive(Clone, Encodable, Decodable, Debug)]
94 /// The segments in the path: the things separated by `::`.
95 /// Global paths begin with `kw::PathRoot`.
96 pub segments: Vec<PathSegment>,
97 pub tokens: Option<LazyTokenStream>,
100 impl PartialEq<Symbol> for Path {
102 fn eq(&self, symbol: &Symbol) -> bool {
103 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
107 impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
108 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
109 self.segments.len().hash_stable(hcx, hasher);
110 for segment in &self.segments {
111 segment.ident.hash_stable(hcx, hasher);
117 // Convert a span and an identifier to the corresponding
119 pub fn from_ident(ident: Ident) -> Path {
120 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
123 pub fn is_global(&self) -> bool {
124 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
128 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
130 /// E.g., `std`, `String` or `Box<T>`.
131 #[derive(Clone, Encodable, Decodable, Debug)]
132 pub struct PathSegment {
133 /// The identifier portion of this path segment.
138 /// Type/lifetime parameters attached to this path. They come in
139 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
140 /// `None` means that no parameter list is supplied (`Path`),
141 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
142 /// but it can be empty (`Path<>`).
143 /// `P` is used as a size optimization for the common case with no parameters.
144 pub args: Option<P<GenericArgs>>,
148 pub fn from_ident(ident: Ident) -> Self {
149 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
152 pub fn path_root(span: Span) -> Self {
153 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
156 pub fn span(&self) -> Span {
158 Some(args) => self.ident.span.to(args.span()),
159 None => self.ident.span,
164 /// The arguments of a path segment.
166 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
167 #[derive(Clone, Encodable, Decodable, Debug)]
168 pub enum GenericArgs {
169 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
170 AngleBracketed(AngleBracketedArgs),
171 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
172 Parenthesized(ParenthesizedArgs),
176 pub fn is_angle_bracketed(&self) -> bool {
177 matches!(self, AngleBracketed(..))
180 pub fn span(&self) -> Span {
182 AngleBracketed(ref data) => data.span,
183 Parenthesized(ref data) => data.span,
188 /// Concrete argument in the sequence of generic args.
189 #[derive(Clone, Encodable, Decodable, Debug)]
190 pub enum GenericArg {
191 /// `'a` in `Foo<'a>`
193 /// `Bar` in `Foo<Bar>`
200 pub fn span(&self) -> Span {
202 GenericArg::Lifetime(lt) => lt.ident.span,
203 GenericArg::Type(ty) => ty.span,
204 GenericArg::Const(ct) => ct.value.span,
209 /// A path like `Foo<'a, T>`.
210 #[derive(Clone, Encodable, Decodable, Debug, Default)]
211 pub struct AngleBracketedArgs {
212 /// The overall span.
214 /// The comma separated parts in the `<...>`.
215 pub args: Vec<AngleBracketedArg>,
218 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
219 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
220 #[derive(Clone, Encodable, Decodable, Debug)]
221 pub enum AngleBracketedArg {
222 /// Argument for a generic parameter.
224 /// Constraint for an associated item.
225 Constraint(AssocConstraint),
228 impl AngleBracketedArg {
229 pub fn span(&self) -> Span {
231 AngleBracketedArg::Arg(arg) => arg.span(),
232 AngleBracketedArg::Constraint(constraint) => constraint.span,
237 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
238 fn into(self) -> Option<P<GenericArgs>> {
239 Some(P(GenericArgs::AngleBracketed(self)))
243 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
244 fn into(self) -> Option<P<GenericArgs>> {
245 Some(P(GenericArgs::Parenthesized(self)))
249 /// A path like `Foo(A, B) -> C`.
250 #[derive(Clone, Encodable, Decodable, Debug)]
251 pub struct ParenthesizedArgs {
259 pub inputs: Vec<P<Ty>>,
265 pub inputs_span: Span,
271 impl ParenthesizedArgs {
272 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
277 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
279 AngleBracketedArgs { span: self.inputs_span, args }
283 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
285 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
287 /// Negative bounds should also be handled here.
288 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
289 pub enum TraitBoundModifier {
301 // This parses but will be rejected during AST validation.
305 /// The AST represents all type param bounds as types.
306 /// `typeck::collect::compute_bounds` matches these against
307 /// the "special" built-in traits (see `middle::lang_items`) and
308 /// detects `Copy`, `Send` and `Sync`.
309 #[derive(Clone, Encodable, Decodable, Debug)]
310 pub enum GenericBound {
311 Trait(PolyTraitRef, TraitBoundModifier),
316 pub fn span(&self) -> Span {
318 GenericBound::Trait(ref t, ..) => t.span,
319 GenericBound::Outlives(ref l) => l.ident.span,
324 pub type GenericBounds = Vec<GenericBound>;
326 /// Specifies the enforced ordering for generic parameters. In the future,
327 /// if we wanted to relax this order, we could override `PartialEq` and
328 /// `PartialOrd`, to allow the kinds to be unordered.
329 #[derive(Hash, Clone, Copy)]
330 pub enum ParamKindOrd {
334 // `Infer` is not actually constructed directly from the AST, but is implicitly constructed
335 // during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last.
339 impl Ord for ParamKindOrd {
340 fn cmp(&self, other: &Self) -> Ordering {
342 let to_int = |v| match v {
344 Infer | Type | Const => 1,
347 to_int(*self).cmp(&to_int(*other))
350 impl PartialOrd for ParamKindOrd {
351 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
352 Some(self.cmp(other))
355 impl PartialEq for ParamKindOrd {
356 fn eq(&self, other: &Self) -> bool {
357 self.cmp(other) == Ordering::Equal
360 impl Eq for ParamKindOrd {}
362 impl fmt::Display for ParamKindOrd {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365 ParamKindOrd::Lifetime => "lifetime".fmt(f),
366 ParamKindOrd::Type => "type".fmt(f),
367 ParamKindOrd::Const { .. } => "const".fmt(f),
368 ParamKindOrd::Infer => "infer".fmt(f),
373 #[derive(Clone, Encodable, Decodable, Debug)]
374 pub enum GenericParamKind {
375 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
378 default: Option<P<Ty>>,
382 /// Span of the `const` keyword.
384 /// Optional default value for the const generic param
385 default: Option<AnonConst>,
389 #[derive(Clone, Encodable, Decodable, Debug)]
390 pub struct GenericParam {
394 pub bounds: GenericBounds,
395 pub is_placeholder: bool,
396 pub kind: GenericParamKind,
397 pub colon_span: Option<Span>,
401 pub fn span(&self) -> Span {
403 GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
406 GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
407 GenericParamKind::Const { kw_span, default: Some(default), .. } => {
408 kw_span.to(default.value.span)
410 GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
415 /// Represents lifetime, type and const parameters attached to a declaration of
416 /// a function, enum, trait, etc.
417 #[derive(Clone, Encodable, Decodable, Debug)]
418 pub struct Generics {
419 pub params: Vec<GenericParam>,
420 pub where_clause: WhereClause,
424 impl Default for Generics {
425 /// Creates an instance of `Generics`.
426 fn default() -> Generics {
429 where_clause: WhereClause {
430 has_where_token: false,
431 predicates: Vec::new(),
439 /// A where-clause in a definition.
440 #[derive(Clone, Encodable, Decodable, Debug)]
441 pub struct WhereClause {
442 /// `true` if we ate a `where` token: this can happen
443 /// if we parsed no predicates (e.g. `struct Foo where {}`).
444 /// This allows us to pretty-print accurately.
445 pub has_where_token: bool,
446 pub predicates: Vec<WherePredicate>,
450 /// A single predicate in a where-clause.
451 #[derive(Clone, Encodable, Decodable, Debug)]
452 pub enum WherePredicate {
453 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
454 BoundPredicate(WhereBoundPredicate),
455 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
456 RegionPredicate(WhereRegionPredicate),
457 /// An equality predicate (unsupported).
458 EqPredicate(WhereEqPredicate),
461 impl WherePredicate {
462 pub fn span(&self) -> Span {
464 WherePredicate::BoundPredicate(p) => p.span,
465 WherePredicate::RegionPredicate(p) => p.span,
466 WherePredicate::EqPredicate(p) => p.span,
473 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
474 #[derive(Clone, Encodable, Decodable, Debug)]
475 pub struct WhereBoundPredicate {
477 /// Any generics from a `for` binding.
478 pub bound_generic_params: Vec<GenericParam>,
479 /// The type being bounded.
480 pub bounded_ty: P<Ty>,
481 /// Trait and lifetime bounds (`Clone + Send + 'static`).
482 pub bounds: GenericBounds,
485 /// A lifetime predicate.
487 /// E.g., `'a: 'b + 'c`.
488 #[derive(Clone, Encodable, Decodable, Debug)]
489 pub struct WhereRegionPredicate {
491 pub lifetime: Lifetime,
492 pub bounds: GenericBounds,
495 /// An equality predicate (unsupported).
498 #[derive(Clone, Encodable, Decodable, Debug)]
499 pub struct WhereEqPredicate {
506 #[derive(Clone, Encodable, Decodable, Debug)]
508 pub attrs: Vec<Attribute>,
509 pub items: Vec<P<Item>>,
511 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
512 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
514 pub is_placeholder: bool,
517 /// Possible values inside of compile-time attribute lists.
519 /// E.g., the '..' in `#[name(..)]`.
520 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
521 pub enum NestedMetaItem {
522 /// A full MetaItem, for recursive meta items.
526 /// E.g., `"foo"`, `64`, `true`.
530 /// A spanned compile-time attribute item.
532 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
533 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
534 pub struct MetaItem {
536 pub kind: MetaItemKind,
540 /// A compile-time attribute item.
542 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
543 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
544 pub enum MetaItemKind {
547 /// E.g., `test` as in `#[test]`.
551 /// E.g., `derive(..)` as in `#[derive(..)]`.
552 List(Vec<NestedMetaItem>),
553 /// Name value meta item.
555 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
559 /// A block (`{ .. }`).
561 /// E.g., `{ .. }` as in `fn foo() { .. }`.
562 #[derive(Clone, Encodable, Decodable, Debug)]
564 /// The statements in the block.
565 pub stmts: Vec<Stmt>,
567 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
568 pub rules: BlockCheckMode,
570 pub tokens: Option<LazyTokenStream>,
571 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
578 pub could_be_bare_literal: bool,
583 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
584 #[derive(Clone, Encodable, Decodable, Debug)]
589 pub tokens: Option<LazyTokenStream>,
593 /// Attempt reparsing the pattern as a type.
594 /// This is intended for use by diagnostics.
595 pub fn to_ty(&self) -> Option<P<Ty>> {
596 let kind = match &self.kind {
597 // In a type expression `_` is an inference variable.
598 PatKind::Wild => TyKind::Infer,
599 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
600 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
601 TyKind::Path(None, Path::from_ident(*ident))
603 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
604 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
605 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
606 PatKind::Ref(pat, mutbl) => {
607 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
609 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
610 // when `P` can be reparsed as a type `T`.
611 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
612 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
613 // assuming `T0` to `Tn` are all syntactically valid as types.
614 PatKind::Tuple(pats) => {
615 let mut tys = Vec::with_capacity(pats.len());
616 // FIXME(#48994) - could just be collected into an Option<Vec>
618 tys.push(pat.to_ty()?);
625 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
628 /// Walk top-down and call `it` in each place where a pattern occurs
629 /// starting with the root pattern `walk` is called on. If `it` returns
630 /// false then we will descend no further but siblings will be processed.
631 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
637 // Walk into the pattern associated with `Ident` (if any).
638 PatKind::Ident(_, _, Some(p)) => p.walk(it),
640 // Walk into each field of struct.
641 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
643 // Sequence of patterns.
644 PatKind::TupleStruct(_, _, s)
647 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
649 // Trivial wrappers over inner patterns.
650 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
652 // These patterns do not contain subpatterns, skip.
659 | PatKind::MacCall(_) => {}
663 /// Is this a `..` pattern?
664 pub fn is_rest(&self) -> bool {
665 matches!(self.kind, PatKind::Rest)
669 /// A single field in a struct pattern.
671 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
672 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
673 /// except when `is_shorthand` is true.
674 #[derive(Clone, Encodable, Decodable, Debug)]
675 pub struct PatField {
676 /// The identifier for the field.
678 /// The pattern the field is destructured to.
680 pub is_shorthand: bool,
684 pub is_placeholder: bool,
687 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
688 pub enum BindingMode {
693 #[derive(Clone, Encodable, Decodable, Debug)]
696 Included(RangeSyntax),
701 #[derive(Clone, Encodable, Decodable, Debug)]
702 pub enum RangeSyntax {
709 /// All the different flavors of pattern that Rust recognizes.
710 #[derive(Clone, Encodable, Decodable, Debug)]
712 /// Represents a wildcard pattern (`_`).
715 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
716 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
717 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
718 /// during name resolution.
719 Ident(BindingMode, Ident, Option<P<Pat>>),
721 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
722 /// The `bool` is `true` in the presence of a `..`.
723 Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool),
725 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
726 TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>),
728 /// An or-pattern `A | B | C`.
729 /// Invariant: `pats.len() >= 2`.
732 /// A possibly qualified path pattern.
733 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
734 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
735 /// only legally refer to associated constants.
736 Path(Option<QSelf>, Path),
738 /// A tuple pattern (`(a, b)`).
744 /// A reference pattern (e.g., `&mut (a, b)`).
745 Ref(P<Pat>, Mutability),
750 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
751 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
753 /// A slice pattern `[a, b, c]`.
756 /// A rest pattern `..`.
758 /// Syntactically it is valid anywhere.
760 /// Semantically however, it only has meaning immediately inside:
761 /// - a slice pattern: `[a, .., b]`,
762 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
763 /// - a tuple pattern: `(a, .., b)`,
764 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
766 /// In all of these cases, an additional restriction applies,
767 /// only one rest pattern may occur in the pattern sequences.
770 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
773 /// A macro pattern; pre-expansion.
777 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
778 #[derive(HashStable_Generic, Encodable, Decodable)]
779 pub enum Mutability {
785 pub fn invert(self) -> Self {
787 Mutability::Mut => Mutability::Not,
788 Mutability::Not => Mutability::Mut,
792 pub fn prefix_str(&self) -> &'static str {
794 Mutability::Mut => "mut ",
795 Mutability::Not => "",
800 /// The kind of borrow in an `AddrOf` expression,
801 /// e.g., `&place` or `&raw const place`.
802 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
803 #[derive(Encodable, Decodable, HashStable_Generic)]
804 pub enum BorrowKind {
805 /// A normal borrow, `&$expr` or `&mut $expr`.
806 /// The resulting type is either `&'a T` or `&'a mut T`
807 /// where `T = typeof($expr)` and `'a` is some lifetime.
809 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
810 /// The resulting type is either `*const T` or `*mut T`
811 /// where `T = typeof($expr)`.
815 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
817 /// The `+` operator (addition)
819 /// The `-` operator (subtraction)
821 /// The `*` operator (multiplication)
823 /// The `/` operator (division)
825 /// The `%` operator (modulus)
827 /// The `&&` operator (logical and)
829 /// The `||` operator (logical or)
831 /// The `^` operator (bitwise xor)
833 /// The `&` operator (bitwise and)
835 /// The `|` operator (bitwise or)
837 /// The `<<` operator (shift left)
839 /// The `>>` operator (shift right)
841 /// The `==` operator (equality)
843 /// The `<` operator (less than)
845 /// The `<=` operator (less than or equal to)
847 /// The `!=` operator (not equal to)
849 /// The `>=` operator (greater than or equal to)
851 /// The `>` operator (greater than)
856 pub fn to_string(&self) -> &'static str {
879 pub fn lazy(&self) -> bool {
880 matches!(self, BinOpKind::And | BinOpKind::Or)
883 pub fn is_comparison(&self) -> bool {
885 // Note for developers: please keep this as is;
886 // we want compilation to fail if another variant is added.
888 Eq | Lt | Le | Ne | Gt | Ge => true,
889 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
894 pub type BinOp = Spanned<BinOpKind>;
898 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
899 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
901 /// The `*` operator for dereferencing
903 /// The `!` operator for logical inversion
905 /// The `-` operator for negation
910 pub fn to_string(op: UnOp) -> &'static str {
920 #[derive(Clone, Encodable, Decodable, Debug)]
928 pub fn has_trailing_semicolon(&self) -> bool {
930 StmtKind::Semi(_) => true,
931 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
936 /// Converts a parsed `Stmt` to a `Stmt` with
937 /// a trailing semicolon.
939 /// This only modifies the parsed AST struct, not the attached
940 /// `LazyTokenStream`. The parser is responsible for calling
941 /// `CreateTokenStream::add_trailing_semi` when there is actually
942 /// a semicolon in the tokenstream.
943 pub fn add_trailing_semicolon(mut self) -> Self {
944 self.kind = match self.kind {
945 StmtKind::Expr(expr) => StmtKind::Semi(expr),
946 StmtKind::MacCall(mac) => {
947 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
948 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
957 pub fn is_item(&self) -> bool {
958 matches!(self.kind, StmtKind::Item(_))
961 pub fn is_expr(&self) -> bool {
962 matches!(self.kind, StmtKind::Expr(_))
966 #[derive(Clone, Encodable, Decodable, Debug)]
968 /// A local (let) binding.
970 /// An item definition.
972 /// Expr without trailing semi-colon.
974 /// Expr with a trailing semi-colon.
976 /// Just a trailing semi-colon.
979 MacCall(P<MacCallStmt>),
982 #[derive(Clone, Encodable, Decodable, Debug)]
983 pub struct MacCallStmt {
985 pub style: MacStmtStyle,
987 pub tokens: Option<LazyTokenStream>,
990 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
991 pub enum MacStmtStyle {
992 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
993 /// `foo!(...);`, `foo![...];`).
995 /// The macro statement had braces (e.g., `foo! { ... }`).
997 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
998 /// `foo!(...)`). All of these will end up being converted into macro
1003 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1004 #[derive(Clone, Encodable, Decodable, Debug)]
1008 pub ty: Option<P<Ty>>,
1009 pub kind: LocalKind,
1012 pub tokens: Option<LazyTokenStream>,
1015 #[derive(Clone, Encodable, Decodable, Debug)]
1016 pub enum LocalKind {
1017 /// Local declaration.
1018 /// Example: `let x;`
1020 /// Local declaration with an initializer.
1021 /// Example: `let x = y;`
1023 /// Local declaration with an initializer and an `else` clause.
1024 /// Example: `let Some(x) = y else { return };`
1025 InitElse(P<Expr>, P<Block>),
1029 pub fn init(&self) -> Option<&Expr> {
1032 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1036 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1039 Self::Init(init) => Some((init, None)),
1040 Self::InitElse(init, els) => Some((init, Some(els))),
1045 /// An arm of a 'match'.
1047 /// E.g., `0..=10 => { println!("match!") }` as in
1051 /// 0..=10 => { println!("match!") },
1052 /// _ => { println!("no match!") },
1055 #[derive(Clone, Encodable, Decodable, Debug)]
1058 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1060 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1061 pub guard: Option<P<Expr>>,
1066 pub is_placeholder: bool,
1069 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1070 #[derive(Clone, Encodable, Decodable, Debug)]
1071 pub struct ExprField {
1077 pub is_shorthand: bool,
1078 pub is_placeholder: bool,
1081 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1082 pub enum BlockCheckMode {
1084 Unsafe(UnsafeSource),
1087 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1088 pub enum UnsafeSource {
1093 /// A constant (expression) that's not an item or associated item,
1094 /// but needs its own `DefId` for type-checking, const-eval, etc.
1095 /// These are usually found nested inside types (e.g., array lengths)
1096 /// or expressions (e.g., repeat counts), and also used to define
1097 /// explicit discriminant values for enum variants.
1098 #[derive(Clone, Encodable, Decodable, Debug)]
1099 pub struct AnonConst {
1105 #[derive(Clone, Encodable, Decodable, Debug)]
1111 pub tokens: Option<LazyTokenStream>,
1115 /// Returns `true` if this expression would be valid somewhere that expects a value;
1116 /// for example, an `if` condition.
1117 pub fn returns(&self) -> bool {
1118 if let ExprKind::Block(ref block, _) = self.kind {
1119 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1121 Some(StmtKind::Expr(_)) => true,
1122 // Last statement is an explicit return?
1123 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1124 // This is a block that doesn't end in either an implicit or explicit return.
1128 // This is not a block, it is a value.
1133 /// Is this expr either `N`, or `{ N }`.
1135 /// If this is not the case, name resolution does not resolve `N` when using
1136 /// `min_const_generics` as more complex expressions are not supported.
1137 pub fn is_potential_trivial_const_param(&self) -> bool {
1138 let this = if let ExprKind::Block(ref block, None) = self.kind {
1139 if block.stmts.len() == 1 {
1140 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1148 if let ExprKind::Path(None, ref path) = this.kind {
1149 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1157 pub fn to_bound(&self) -> Option<GenericBound> {
1159 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1160 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1161 TraitBoundModifier::None,
1167 pub fn peel_parens(&self) -> &Expr {
1168 let mut expr = self;
1169 while let ExprKind::Paren(inner) = &expr.kind {
1175 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1176 pub fn to_ty(&self) -> Option<P<Ty>> {
1177 let kind = match &self.kind {
1178 // Trivial conversions.
1179 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1180 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1182 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1184 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1185 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1188 ExprKind::Repeat(expr, expr_len) => {
1189 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1192 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1194 ExprKind::Tup(exprs) => {
1195 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1199 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1200 // then type of result is trait object.
1201 // Otherwise we don't assume the result type.
1202 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1203 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1204 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1210 ExprKind::Underscore => TyKind::Infer,
1212 // This expression doesn't look like a type syntactically.
1216 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1219 pub fn precedence(&self) -> ExprPrecedence {
1221 ExprKind::Box(_) => ExprPrecedence::Box,
1222 ExprKind::Array(_) => ExprPrecedence::Array,
1223 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1224 ExprKind::Call(..) => ExprPrecedence::Call,
1225 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1226 ExprKind::Tup(_) => ExprPrecedence::Tup,
1227 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1228 ExprKind::Unary(..) => ExprPrecedence::Unary,
1229 ExprKind::Lit(_) => ExprPrecedence::Lit,
1230 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1231 ExprKind::Let(..) => ExprPrecedence::Let,
1232 ExprKind::If(..) => ExprPrecedence::If,
1233 ExprKind::While(..) => ExprPrecedence::While,
1234 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1235 ExprKind::Loop(..) => ExprPrecedence::Loop,
1236 ExprKind::Match(..) => ExprPrecedence::Match,
1237 ExprKind::Closure(..) => ExprPrecedence::Closure,
1238 ExprKind::Block(..) => ExprPrecedence::Block,
1239 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1240 ExprKind::Async(..) => ExprPrecedence::Async,
1241 ExprKind::Await(..) => ExprPrecedence::Await,
1242 ExprKind::Assign(..) => ExprPrecedence::Assign,
1243 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1244 ExprKind::Field(..) => ExprPrecedence::Field,
1245 ExprKind::Index(..) => ExprPrecedence::Index,
1246 ExprKind::Range(..) => ExprPrecedence::Range,
1247 ExprKind::Underscore => ExprPrecedence::Path,
1248 ExprKind::Path(..) => ExprPrecedence::Path,
1249 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1250 ExprKind::Break(..) => ExprPrecedence::Break,
1251 ExprKind::Continue(..) => ExprPrecedence::Continue,
1252 ExprKind::Ret(..) => ExprPrecedence::Ret,
1253 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1254 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1255 ExprKind::Struct(..) => ExprPrecedence::Struct,
1256 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1257 ExprKind::Paren(..) => ExprPrecedence::Paren,
1258 ExprKind::Try(..) => ExprPrecedence::Try,
1259 ExprKind::Yield(..) => ExprPrecedence::Yield,
1260 ExprKind::Yeet(..) => ExprPrecedence::Yeet,
1261 ExprKind::Err => ExprPrecedence::Err,
1265 pub fn take(&mut self) -> Self {
1270 kind: ExprKind::Err,
1272 attrs: ThinVec::new(),
1278 // To a first-order approximation, is this a pattern
1279 pub fn is_approximately_pattern(&self) -> bool {
1280 match &self.peel_parens().kind {
1282 | ExprKind::Array(_)
1283 | ExprKind::Call(_, _)
1286 | ExprKind::Range(_, _, _)
1287 | ExprKind::Underscore
1288 | ExprKind::Path(_, _)
1289 | ExprKind::Struct(_) => true,
1295 /// Limit types of a range (inclusive or exclusive)
1296 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1297 pub enum RangeLimits {
1298 /// Inclusive at the beginning, exclusive at the end
1300 /// Inclusive at the beginning and end
1304 #[derive(Clone, Encodable, Decodable, Debug)]
1305 pub enum StructRest {
1310 /// No trailing `..` or expression.
1314 #[derive(Clone, Encodable, Decodable, Debug)]
1315 pub struct StructExpr {
1316 pub qself: Option<QSelf>,
1318 pub fields: Vec<ExprField>,
1319 pub rest: StructRest,
1322 #[derive(Clone, Encodable, Decodable, Debug)]
1324 /// A `box x` expression.
1326 /// An array (`[a, b, c, d]`)
1327 Array(Vec<P<Expr>>),
1328 /// Allow anonymous constants from an inline `const` block
1329 ConstBlock(AnonConst),
1332 /// The first field resolves to the function itself,
1333 /// and the second field is the list of arguments.
1334 /// This also represents calling the constructor of
1335 /// tuple-like ADTs such as tuple structs and enum variants.
1336 Call(P<Expr>, Vec<P<Expr>>),
1337 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1339 /// The `PathSegment` represents the method name and its generic arguments
1340 /// (within the angle brackets).
1341 /// The standalone `Expr` is the receiver expression.
1342 /// The vector of `Expr` is the arguments.
1343 /// `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1344 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d])`.
1345 /// This `Span` is the span of the function, without the dot and receiver
1346 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1347 MethodCall(PathSegment, P<Expr>, Vec<P<Expr>>, Span),
1348 /// A tuple (e.g., `(a, b, c, d)`).
1350 /// A binary operation (e.g., `a + b`, `a * b`).
1351 Binary(BinOp, P<Expr>, P<Expr>),
1352 /// A unary operation (e.g., `!x`, `*x`).
1353 Unary(UnOp, P<Expr>),
1354 /// A literal (e.g., `1`, `"foo"`).
1356 /// A cast (e.g., `foo as f64`).
1357 Cast(P<Expr>, P<Ty>),
1358 /// A type ascription (e.g., `42: usize`).
1359 Type(P<Expr>, P<Ty>),
1360 /// A `let pat = expr` expression that is only semantically allowed in the condition
1361 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1363 /// `Span` represents the whole `let pat = expr` statement.
1364 Let(P<Pat>, P<Expr>, Span),
1365 /// An `if` block, with an optional `else` block.
1367 /// `if expr { block } else { expr }`
1368 If(P<Expr>, P<Block>, Option<P<Expr>>),
1369 /// A while loop, with an optional label.
1371 /// `'label: while expr { block }`
1372 While(P<Expr>, P<Block>, Option<Label>),
1373 /// A `for` loop, with an optional label.
1375 /// `'label: for pat in expr { block }`
1377 /// This is desugared to a combination of `loop` and `match` expressions.
1378 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1379 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1381 /// `'label: loop { block }`
1382 Loop(P<Block>, Option<Label>),
1383 /// A `match` block.
1384 Match(P<Expr>, Vec<Arm>),
1385 /// A closure (e.g., `move |a, b, c| a + b + c`).
1387 /// The final span is the span of the argument block `|...|`.
1388 Closure(ClosureBinder, CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1389 /// A block (`'label: { ... }`).
1390 Block(P<Block>, Option<Label>),
1391 /// An async block (`async move { ... }`).
1393 /// The `NodeId` is the `NodeId` for the closure that results from
1394 /// desugaring an async block, just like the NodeId field in the
1395 /// `Async::Yes` variant. This is necessary in order to create a def for the
1396 /// closure which can be used as a parent of any child defs. Defs
1397 /// created during lowering cannot be made the parent of any other
1398 /// preexisting defs.
1399 Async(CaptureBy, NodeId, P<Block>),
1400 /// An await expression (`my_future.await`).
1403 /// A try block (`try { ... }`).
1406 /// An assignment (`a = foo()`).
1407 /// The `Span` argument is the span of the `=` token.
1408 Assign(P<Expr>, P<Expr>, Span),
1409 /// An assignment with an operator.
1412 AssignOp(BinOp, P<Expr>, P<Expr>),
1413 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1414 Field(P<Expr>, Ident),
1415 /// An indexing operation (e.g., `foo[2]`).
1416 Index(P<Expr>, P<Expr>),
1417 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1418 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1419 /// An underscore, used in destructuring assignment to ignore a value.
1422 /// Variable reference, possibly containing `::` and/or type
1423 /// parameters (e.g., `foo::bar::<baz>`).
1425 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1426 Path(Option<QSelf>, Path),
1428 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1429 AddrOf(BorrowKind, Mutability, P<Expr>),
1430 /// A `break`, with an optional label to break, and an optional expression.
1431 Break(Option<Label>, Option<P<Expr>>),
1432 /// A `continue`, with an optional label.
1433 Continue(Option<Label>),
1434 /// A `return`, with an optional value to be returned.
1435 Ret(Option<P<Expr>>),
1437 /// Output of the `asm!()` macro.
1438 InlineAsm(P<InlineAsm>),
1440 /// A macro invocation; pre-expansion.
1443 /// A struct literal expression.
1445 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1446 Struct(P<StructExpr>),
1448 /// An array literal constructed from one repeated element.
1450 /// E.g., `[1; 5]`. The expression is the element to be
1451 /// repeated; the constant is the number of times to repeat it.
1452 Repeat(P<Expr>, AnonConst),
1454 /// No-op: used solely so we can pretty-print faithfully.
1457 /// A try expression (`expr?`).
1460 /// A `yield`, with an optional value to be yielded.
1461 Yield(Option<P<Expr>>),
1463 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1464 /// with an optional value to be returned.
1465 Yeet(Option<P<Expr>>),
1467 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1471 /// The explicit `Self` type in a "qualified path". The actual
1472 /// path, including the trait and the associated item, is stored
1473 /// separately. `position` represents the index of the associated
1474 /// item qualified with this `Self` type.
1476 /// ```ignore (only-for-syntax-highlight)
1477 /// <Vec<T> as a::b::Trait>::AssociatedItem
1478 /// ^~~~~ ~~~~~~~~~~~~~~^
1481 /// <Vec<T>>::AssociatedItem
1485 #[derive(Clone, Encodable, Decodable, Debug)]
1489 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1490 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1491 /// 0`, this is an empty span.
1492 pub path_span: Span,
1493 pub position: usize,
1496 /// A capture clause used in closures and `async` blocks.
1497 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1498 pub enum CaptureBy {
1499 /// `move |x| y + x`.
1501 /// `move` keyword was not specified.
1505 /// The movability of a generator / closure literal:
1506 /// whether a generator contains self-references, causing it to be `!Unpin`.
1507 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1508 #[derive(HashStable_Generic)]
1509 pub enum Movability {
1510 /// May contain self-references, `!Unpin`.
1512 /// Must not contain self-references, `Unpin`.
1516 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1517 #[derive(Clone, Encodable, Decodable, Debug)]
1518 pub enum ClosureBinder {
1519 /// The binder is not present, all closure lifetimes are inferred.
1521 /// The binder is present.
1523 /// Span of the whole `for<>` clause
1526 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1527 /// ^^^^^^^^^^^ -- this
1531 /// Lifetimes in the `for<>` closure
1534 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1537 generic_params: P<[GenericParam]>,
1541 /// Represents a macro invocation. The `path` indicates which macro
1542 /// is being invoked, and the `args` are arguments passed to it.
1543 #[derive(Clone, Encodable, Decodable, Debug)]
1544 pub struct MacCall {
1546 pub args: P<MacArgs>,
1547 pub prior_type_ascription: Option<(Span, bool)>,
1551 pub fn span(&self) -> Span {
1552 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1556 /// Arguments passed to an attribute or a function-like macro.
1557 #[derive(Clone, Encodable, Decodable, Debug)]
1559 /// No arguments - `#[attr]`.
1561 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1562 Delimited(DelimSpan, MacDelimiter, TokenStream),
1563 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1565 /// Span of the `=` token.
1572 // The RHS of a `MacArgs::Eq` starts out as an expression. Once macro expansion
1573 // is completed, all cases end up either as a literal, which is the form used
1574 // after lowering to HIR, or as an error.
1575 #[derive(Clone, Encodable, Decodable, Debug)]
1576 pub enum MacArgsEq {
1582 pub fn delim(&self) -> Option<Delimiter> {
1584 MacArgs::Delimited(_, delim, _) => Some(delim.to_token()),
1585 MacArgs::Empty | MacArgs::Eq(..) => None,
1589 pub fn span(&self) -> Option<Span> {
1591 MacArgs::Empty => None,
1592 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1593 MacArgs::Eq(eq_span, MacArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1594 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1595 unreachable!("in literal form when getting span: {:?}", lit);
1600 /// Tokens inside the delimiters or after `=`.
1601 /// Proc macros see these tokens, for example.
1602 pub fn inner_tokens(&self) -> TokenStream {
1604 MacArgs::Empty => TokenStream::default(),
1605 MacArgs::Delimited(.., tokens) => tokens.clone(),
1606 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => TokenStream::from_ast(expr),
1607 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1608 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1613 /// Whether a macro with these arguments needs a semicolon
1614 /// when used as a standalone item or statement.
1615 pub fn need_semicolon(&self) -> bool {
1616 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1620 impl<CTX> HashStable<CTX> for MacArgs
1622 CTX: crate::HashStableContext,
1624 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1625 mem::discriminant(self).hash_stable(ctx, hasher);
1627 MacArgs::Empty => {}
1628 MacArgs::Delimited(dspan, delim, tokens) => {
1629 dspan.hash_stable(ctx, hasher);
1630 delim.hash_stable(ctx, hasher);
1631 tokens.hash_stable(ctx, hasher);
1633 MacArgs::Eq(_eq_span, MacArgsEq::Ast(expr)) => {
1634 unreachable!("hash_stable {:?}", expr);
1636 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit)) => {
1637 eq_span.hash_stable(ctx, hasher);
1638 lit.hash_stable(ctx, hasher);
1644 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1645 pub enum MacDelimiter {
1652 pub fn to_token(self) -> Delimiter {
1654 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1655 MacDelimiter::Bracket => Delimiter::Bracket,
1656 MacDelimiter::Brace => Delimiter::Brace,
1660 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1662 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1663 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1664 Delimiter::Brace => Some(MacDelimiter::Brace),
1665 Delimiter::Invisible => None,
1670 /// Represents a macro definition.
1671 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1672 pub struct MacroDef {
1673 pub body: P<MacArgs>,
1674 /// `true` if macro was defined with `macro_rules`.
1675 pub macro_rules: bool,
1678 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1679 #[derive(HashStable_Generic)]
1681 /// A regular string, like `"foo"`.
1683 /// A raw string, like `r##"foo"##`.
1685 /// The value is the number of `#` symbols used.
1690 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1692 /// The original literal token as written in source code.
1693 pub token: token::Lit,
1694 /// The "semantic" representation of the literal lowered from the original tokens.
1695 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1696 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1701 /// Same as `Lit`, but restricted to string literals.
1702 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1704 /// The original literal token as written in source code.
1705 pub style: StrStyle,
1707 pub suffix: Option<Symbol>,
1709 /// The unescaped "semantic" representation of the literal lowered from the original token.
1710 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1711 pub symbol_unescaped: Symbol,
1715 pub fn as_lit(&self) -> Lit {
1716 let token_kind = match self.style {
1717 StrStyle::Cooked => token::Str,
1718 StrStyle::Raw(n) => token::StrRaw(n),
1721 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1723 kind: LitKind::Str(self.symbol_unescaped, self.style),
1728 /// Type of the integer literal based on provided suffix.
1729 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1730 #[derive(HashStable_Generic)]
1731 pub enum LitIntType {
1740 /// Type of the float literal based on provided suffix.
1741 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1742 #[derive(HashStable_Generic)]
1743 pub enum LitFloatType {
1744 /// A float literal with a suffix (`1f32` or `1E10f32`).
1746 /// A float literal without a suffix (`1.0 or 1.0E10`).
1752 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1753 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1755 /// A string literal (`"foo"`).
1756 Str(Symbol, StrStyle),
1757 /// A byte string (`b"foo"`).
1759 /// A byte char (`b'f'`).
1761 /// A character literal (`'a'`).
1763 /// An integer literal (`1`).
1764 Int(u128, LitIntType),
1765 /// A float literal (`1f64` or `1E10f64`).
1766 Float(Symbol, LitFloatType),
1767 /// A boolean literal.
1769 /// Placeholder for a literal that wasn't well-formed in some way.
1774 /// Returns `true` if this literal is a string.
1775 pub fn is_str(&self) -> bool {
1776 matches!(self, LitKind::Str(..))
1779 /// Returns `true` if this literal is byte literal string.
1780 pub fn is_bytestr(&self) -> bool {
1781 matches!(self, LitKind::ByteStr(_))
1784 /// Returns `true` if this is a numeric literal.
1785 pub fn is_numeric(&self) -> bool {
1786 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1789 /// Returns `true` if this literal has no suffix.
1790 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1791 pub fn is_unsuffixed(&self) -> bool {
1795 /// Returns `true` if this literal has a suffix.
1796 pub fn is_suffixed(&self) -> bool {
1798 // suffixed variants
1799 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1800 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1801 // unsuffixed variants
1803 | LitKind::ByteStr(..)
1806 | LitKind::Int(_, LitIntType::Unsuffixed)
1807 | LitKind::Float(_, LitFloatType::Unsuffixed)
1809 | LitKind::Err(..) => false,
1814 // N.B., If you change this, you'll probably want to change the corresponding
1815 // type structure in `middle/ty.rs` as well.
1816 #[derive(Clone, Encodable, Decodable, Debug)]
1819 pub mutbl: Mutability,
1822 /// Represents a function's signature in a trait declaration,
1823 /// trait implementation, or free function.
1824 #[derive(Clone, Encodable, Decodable, Debug)]
1826 pub header: FnHeader,
1827 pub decl: P<FnDecl>,
1831 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1832 #[derive(Encodable, Decodable, HashStable_Generic)]
1839 pub fn name_str(self) -> &'static str {
1841 FloatTy::F32 => "f32",
1842 FloatTy::F64 => "f64",
1846 pub fn name(self) -> Symbol {
1848 FloatTy::F32 => sym::f32,
1849 FloatTy::F64 => sym::f64,
1854 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1855 #[derive(Encodable, Decodable, HashStable_Generic)]
1866 pub fn name_str(&self) -> &'static str {
1868 IntTy::Isize => "isize",
1870 IntTy::I16 => "i16",
1871 IntTy::I32 => "i32",
1872 IntTy::I64 => "i64",
1873 IntTy::I128 => "i128",
1877 pub fn name(&self) -> Symbol {
1879 IntTy::Isize => sym::isize,
1880 IntTy::I8 => sym::i8,
1881 IntTy::I16 => sym::i16,
1882 IntTy::I32 => sym::i32,
1883 IntTy::I64 => sym::i64,
1884 IntTy::I128 => sym::i128,
1889 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1890 #[derive(Encodable, Decodable, HashStable_Generic)]
1901 pub fn name_str(&self) -> &'static str {
1903 UintTy::Usize => "usize",
1905 UintTy::U16 => "u16",
1906 UintTy::U32 => "u32",
1907 UintTy::U64 => "u64",
1908 UintTy::U128 => "u128",
1912 pub fn name(&self) -> Symbol {
1914 UintTy::Usize => sym::usize,
1915 UintTy::U8 => sym::u8,
1916 UintTy::U16 => sym::u16,
1917 UintTy::U32 => sym::u32,
1918 UintTy::U64 => sym::u64,
1919 UintTy::U128 => sym::u128,
1924 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1925 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1926 #[derive(Clone, Encodable, Decodable, Debug)]
1927 pub struct AssocConstraint {
1930 pub gen_args: Option<GenericArgs>,
1931 pub kind: AssocConstraintKind,
1935 /// The kinds of an `AssocConstraint`.
1936 #[derive(Clone, Encodable, Decodable, Debug)]
1942 impl From<P<Ty>> for Term {
1943 fn from(v: P<Ty>) -> Self {
1948 impl From<AnonConst> for Term {
1949 fn from(v: AnonConst) -> Self {
1954 /// The kinds of an `AssocConstraint`.
1955 #[derive(Clone, Encodable, Decodable, Debug)]
1956 pub enum AssocConstraintKind {
1957 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1958 Equality { term: Term },
1959 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1960 Bound { bounds: GenericBounds },
1963 #[derive(Encodable, Decodable, Debug)]
1968 pub tokens: Option<LazyTokenStream>,
1972 fn clone(&self) -> Self {
1973 ensure_sufficient_stack(|| Self {
1975 kind: self.kind.clone(),
1977 tokens: self.tokens.clone(),
1983 pub fn peel_refs(&self) -> &Self {
1984 let mut final_ty = self;
1985 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1992 #[derive(Clone, Encodable, Decodable, Debug)]
1993 pub struct BareFnTy {
1994 pub unsafety: Unsafe,
1996 pub generic_params: Vec<GenericParam>,
1997 pub decl: P<FnDecl>,
1998 /// Span of the `fn(...) -> ...` part.
1999 pub decl_span: Span,
2002 /// The various kinds of type recognized by the compiler.
2003 #[derive(Clone, Encodable, Decodable, Debug)]
2005 /// A variable-length slice (`[T]`).
2007 /// A fixed length array (`[T; n]`).
2008 Array(P<Ty>, AnonConst),
2009 /// A raw pointer (`*const T` or `*mut T`).
2011 /// A reference (`&'a T` or `&'a mut T`).
2012 Rptr(Option<Lifetime>, MutTy),
2013 /// A bare function (e.g., `fn(usize) -> bool`).
2014 BareFn(P<BareFnTy>),
2015 /// The never type (`!`).
2017 /// A tuple (`(A, B, C, D,...)`).
2019 /// A path (`module::module::...::Type`), optionally
2020 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2022 /// Type parameters are stored in the `Path` itself.
2023 Path(Option<QSelf>, Path),
2024 /// A trait object type `Bound1 + Bound2 + Bound3`
2025 /// where `Bound` is a trait or a lifetime.
2026 TraitObject(GenericBounds, TraitObjectSyntax),
2027 /// An `impl Bound1 + Bound2 + Bound3` type
2028 /// where `Bound` is a trait or a lifetime.
2030 /// The `NodeId` exists to prevent lowering from having to
2031 /// generate `NodeId`s on the fly, which would complicate
2032 /// the generation of opaque `type Foo = impl Trait` items significantly.
2033 ImplTrait(NodeId, GenericBounds),
2034 /// No-op; kept solely so that we can pretty-print faithfully.
2038 /// This means the type should be inferred instead of it having been
2039 /// specified. This can appear anywhere in a type.
2041 /// Inferred type of a `self` or `&self` argument in a method.
2043 /// A macro in the type position.
2045 /// Placeholder for a kind that has failed to be defined.
2047 /// Placeholder for a `va_list`.
2052 pub fn is_implicit_self(&self) -> bool {
2053 matches!(self, TyKind::ImplicitSelf)
2056 pub fn is_unit(&self) -> bool {
2057 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2060 pub fn is_simple_path(&self) -> Option<Symbol> {
2061 if let TyKind::Path(None, Path { segments, .. }) = &self && segments.len() == 1 {
2062 Some(segments[0].ident.name)
2069 /// Syntax used to declare a trait object.
2070 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2071 pub enum TraitObjectSyntax {
2076 /// Inline assembly operand explicit register or register class.
2078 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2079 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2080 pub enum InlineAsmRegOrRegClass {
2085 bitflags::bitflags! {
2086 #[derive(Encodable, Decodable, HashStable_Generic)]
2087 pub struct InlineAsmOptions: u16 {
2088 const PURE = 1 << 0;
2089 const NOMEM = 1 << 1;
2090 const READONLY = 1 << 2;
2091 const PRESERVES_FLAGS = 1 << 3;
2092 const NORETURN = 1 << 4;
2093 const NOSTACK = 1 << 5;
2094 const ATT_SYNTAX = 1 << 6;
2096 const MAY_UNWIND = 1 << 8;
2100 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2101 pub enum InlineAsmTemplatePiece {
2103 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2106 impl fmt::Display for InlineAsmTemplatePiece {
2107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2109 Self::String(s) => {
2110 for c in s.chars() {
2112 '{' => f.write_str("{{")?,
2113 '}' => f.write_str("}}")?,
2119 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2120 write!(f, "{{{}:{}}}", operand_idx, modifier)
2122 Self::Placeholder { operand_idx, modifier: None, .. } => {
2123 write!(f, "{{{}}}", operand_idx)
2129 impl InlineAsmTemplatePiece {
2130 /// Rebuilds the asm template string from its pieces.
2131 pub fn to_string(s: &[Self]) -> String {
2133 let mut out = String::new();
2135 let _ = write!(out, "{}", p);
2141 /// Inline assembly symbol operands get their own AST node that is somewhat
2142 /// similar to `AnonConst`.
2144 /// The main difference is that we specifically don't assign it `DefId` in
2145 /// `DefCollector`. Instead this is deferred until AST lowering where we
2146 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2147 /// depending on what the path resolves to.
2148 #[derive(Clone, Encodable, Decodable, Debug)]
2149 pub struct InlineAsmSym {
2151 pub qself: Option<QSelf>,
2155 /// Inline assembly operand.
2157 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2158 #[derive(Clone, Encodable, Decodable, Debug)]
2159 pub enum InlineAsmOperand {
2161 reg: InlineAsmRegOrRegClass,
2165 reg: InlineAsmRegOrRegClass,
2167 expr: Option<P<Expr>>,
2170 reg: InlineAsmRegOrRegClass,
2175 reg: InlineAsmRegOrRegClass,
2178 out_expr: Option<P<Expr>>,
2181 anon_const: AnonConst,
2188 /// Inline assembly.
2190 /// E.g., `asm!("NOP");`.
2191 #[derive(Clone, Encodable, Decodable, Debug)]
2192 pub struct InlineAsm {
2193 pub template: Vec<InlineAsmTemplatePiece>,
2194 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2195 pub operands: Vec<(InlineAsmOperand, Span)>,
2196 pub clobber_abis: Vec<(Symbol, Span)>,
2197 pub options: InlineAsmOptions,
2198 pub line_spans: Vec<Span>,
2201 /// A parameter in a function header.
2203 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2204 #[derive(Clone, Encodable, Decodable, Debug)]
2211 pub is_placeholder: bool,
2214 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2216 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2217 #[derive(Clone, Encodable, Decodable, Debug)]
2219 /// `self`, `mut self`
2221 /// `&'lt self`, `&'lt mut self`
2222 Region(Option<Lifetime>, Mutability),
2223 /// `self: TYPE`, `mut self: TYPE`
2224 Explicit(P<Ty>, Mutability),
2227 pub type ExplicitSelf = Spanned<SelfKind>;
2230 /// Attempts to cast parameter to `ExplicitSelf`.
2231 pub fn to_self(&self) -> Option<ExplicitSelf> {
2232 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2233 if ident.name == kw::SelfLower {
2234 return match self.ty.kind {
2235 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2236 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2237 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2240 self.pat.span.to(self.ty.span),
2241 SelfKind::Explicit(self.ty.clone(), mutbl),
2249 /// Returns `true` if parameter is `self`.
2250 pub fn is_self(&self) -> bool {
2251 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2252 ident.name == kw::SelfLower
2258 /// Builds a `Param` object from `ExplicitSelf`.
2259 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2260 let span = eself.span.to(eself_ident.span);
2261 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2262 let param = |mutbl, ty| Param {
2266 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2273 is_placeholder: false,
2276 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2277 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2278 SelfKind::Region(lt, mutbl) => param(
2282 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2291 /// A signature (not the body) of a function declaration.
2293 /// E.g., `fn foo(bar: baz)`.
2295 /// Please note that it's different from `FnHeader` structure
2296 /// which contains metadata about function safety, asyncness, constness and ABI.
2297 #[derive(Clone, Encodable, Decodable, Debug)]
2299 pub inputs: Vec<Param>,
2300 pub output: FnRetTy,
2304 pub fn has_self(&self) -> bool {
2305 self.inputs.get(0).map_or(false, Param::is_self)
2307 pub fn c_variadic(&self) -> bool {
2308 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2312 /// Is the trait definition an auto trait?
2313 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2319 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2320 #[derive(HashStable_Generic)]
2326 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2328 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2333 pub fn is_async(self) -> bool {
2334 matches!(self, Async::Yes { .. })
2337 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2338 pub fn opt_return_id(self) -> Option<NodeId> {
2340 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2346 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2347 #[derive(HashStable_Generic)]
2353 /// Item defaultness.
2354 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2355 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2356 pub enum Defaultness {
2361 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2362 pub enum ImplPolarity {
2363 /// `impl Trait for Type`
2365 /// `impl !Trait for Type`
2369 impl fmt::Debug for ImplPolarity {
2370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2372 ImplPolarity::Positive => "positive".fmt(f),
2373 ImplPolarity::Negative(_) => "negative".fmt(f),
2378 #[derive(Clone, Encodable, Decodable, Debug)]
2380 /// Returns type is not specified.
2382 /// Functions default to `()` and closures default to inference.
2383 /// Span points to where return type would be inserted.
2385 /// Everything else.
2390 pub fn span(&self) -> Span {
2392 FnRetTy::Default(span) => span,
2393 FnRetTy::Ty(ref ty) => ty.span,
2398 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2404 /// Module item kind.
2405 #[derive(Clone, Encodable, Decodable, Debug)]
2407 /// Module with inlined definition `mod foo { ... }`,
2408 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2409 /// The inner span is from the first token past `{` to the last token until `}`,
2410 /// or from the first to the last token in the loaded file.
2411 Loaded(Vec<P<Item>>, Inline, ModSpans),
2412 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2416 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2417 pub struct ModSpans {
2418 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2419 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2420 pub inner_span: Span,
2421 pub inject_use_span: Span,
2424 impl Default for ModSpans {
2425 fn default() -> ModSpans {
2426 ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2430 /// Foreign module declaration.
2432 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2433 #[derive(Clone, Encodable, Decodable, Debug)]
2434 pub struct ForeignMod {
2435 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2436 /// semantically by Rust.
2437 pub unsafety: Unsafe,
2438 pub abi: Option<StrLit>,
2439 pub items: Vec<P<ForeignItem>>,
2442 #[derive(Clone, Encodable, Decodable, Debug)]
2443 pub struct EnumDef {
2444 pub variants: Vec<Variant>,
2447 #[derive(Clone, Encodable, Decodable, Debug)]
2448 pub struct Variant {
2449 /// Attributes of the variant.
2451 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2455 /// The visibility of the variant. Syntactically accepted but not semantically.
2456 pub vis: Visibility,
2457 /// Name of the variant.
2460 /// Fields and constructor id of the variant.
2461 pub data: VariantData,
2462 /// Explicit discriminant, e.g., `Foo = 1`.
2463 pub disr_expr: Option<AnonConst>,
2464 /// Is a macro placeholder
2465 pub is_placeholder: bool,
2468 /// Part of `use` item to the right of its prefix.
2469 #[derive(Clone, Encodable, Decodable, Debug)]
2470 pub enum UseTreeKind {
2471 /// `use prefix` or `use prefix as rename`
2473 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2475 Simple(Option<Ident>, NodeId, NodeId),
2476 /// `use prefix::{...}`
2477 Nested(Vec<(UseTree, NodeId)>),
2482 /// A tree of paths sharing common prefixes.
2483 /// Used in `use` items both at top-level and inside of braces in import groups.
2484 #[derive(Clone, Encodable, Decodable, Debug)]
2485 pub struct UseTree {
2487 pub kind: UseTreeKind,
2492 pub fn ident(&self) -> Ident {
2494 UseTreeKind::Simple(Some(rename), ..) => rename,
2495 UseTreeKind::Simple(None, ..) => {
2496 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2498 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2503 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2504 /// are contained as statements within items. These two cases need to be
2505 /// distinguished for pretty-printing.
2506 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2507 pub enum AttrStyle {
2512 rustc_index::newtype_index! {
2515 DEBUG_FORMAT = "AttrId({})"
2519 impl<S: Encoder> Encodable<S> for AttrId {
2520 fn encode(&self, _s: &mut S) {}
2523 impl<D: Decoder> Decodable<D> for AttrId {
2524 fn decode(_: &mut D) -> AttrId {
2525 crate::attr::mk_attr_id()
2529 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2530 pub struct AttrItem {
2533 pub tokens: Option<LazyTokenStream>,
2536 /// A list of attributes.
2537 pub type AttrVec = ThinVec<Attribute>;
2539 /// Metadata associated with an item.
2540 #[derive(Clone, Encodable, Decodable, Debug)]
2541 pub struct Attribute {
2544 /// Denotes if the attribute decorates the following construct (outer)
2545 /// or the construct this attribute is contained within (inner).
2546 pub style: AttrStyle,
2550 #[derive(Clone, Encodable, Decodable, Debug)]
2552 /// A normal attribute.
2553 Normal(AttrItem, Option<LazyTokenStream>),
2555 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2556 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2557 /// variant (which is much less compact and thus more expensive).
2558 DocComment(CommentKind, Symbol),
2561 /// `TraitRef`s appear in impls.
2563 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2564 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2565 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2566 /// same as the impl's `NodeId`).
2567 #[derive(Clone, Encodable, Decodable, Debug)]
2568 pub struct TraitRef {
2573 #[derive(Clone, Encodable, Decodable, Debug)]
2574 pub struct PolyTraitRef {
2575 /// The `'a` in `for<'a> Foo<&'a T>`.
2576 pub bound_generic_params: Vec<GenericParam>,
2578 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2579 pub trait_ref: TraitRef,
2585 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2587 bound_generic_params: generic_params,
2588 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2594 #[derive(Clone, Encodable, Decodable, Debug)]
2595 pub struct Visibility {
2596 pub kind: VisibilityKind,
2598 pub tokens: Option<LazyTokenStream>,
2601 #[derive(Clone, Encodable, Decodable, Debug)]
2602 pub enum VisibilityKind {
2604 Restricted { path: P<Path>, id: NodeId },
2608 impl VisibilityKind {
2609 pub fn is_pub(&self) -> bool {
2610 matches!(self, VisibilityKind::Public)
2614 /// Field definition in a struct, variant or union.
2616 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2617 #[derive(Clone, Encodable, Decodable, Debug)]
2618 pub struct FieldDef {
2622 pub vis: Visibility,
2623 pub ident: Option<Ident>,
2626 pub is_placeholder: bool,
2629 /// Fields and constructor ids of enum variants and structs.
2630 #[derive(Clone, Encodable, Decodable, Debug)]
2631 pub enum VariantData {
2634 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2635 Struct(Vec<FieldDef>, bool),
2638 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2639 Tuple(Vec<FieldDef>, NodeId),
2642 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2647 /// Return the fields of this variant.
2648 pub fn fields(&self) -> &[FieldDef] {
2650 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2655 /// Return the `NodeId` of this variant's constructor, if it has one.
2656 pub fn ctor_id(&self) -> Option<NodeId> {
2658 VariantData::Struct(..) => None,
2659 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2664 /// An item definition.
2665 #[derive(Clone, Encodable, Decodable, Debug)]
2666 pub struct Item<K = ItemKind> {
2667 pub attrs: Vec<Attribute>,
2670 pub vis: Visibility,
2671 /// The name of the item.
2672 /// It might be a dummy name in case of anonymous items.
2677 /// Original tokens this item was parsed from. This isn't necessarily
2678 /// available for all items, although over time more and more items should
2679 /// have this be `Some`. Right now this is primarily used for procedural
2680 /// macros, notably custom attributes.
2682 /// Note that the tokens here do not include the outer attributes, but will
2683 /// include inner attributes.
2684 pub tokens: Option<LazyTokenStream>,
2688 /// Return the span that encompasses the attributes.
2689 pub fn span_with_attributes(&self) -> Span {
2690 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2694 /// `extern` qualifier on a function item or function type.
2695 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2699 Explicit(StrLit, Span),
2703 pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2705 Some(name) => Extern::Explicit(name, span),
2706 None => Extern::Implicit(span),
2711 /// A function header.
2713 /// All the information between the visibility and the name of the function is
2714 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2715 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2716 pub struct FnHeader {
2717 pub unsafety: Unsafe,
2718 pub asyncness: Async,
2719 pub constness: Const,
2724 /// Does this function header have any qualifiers or is it empty?
2725 pub fn has_qualifiers(&self) -> bool {
2726 let Self { unsafety, asyncness, constness, ext } = self;
2727 matches!(unsafety, Unsafe::Yes(_))
2728 || asyncness.is_async()
2729 || matches!(constness, Const::Yes(_))
2730 || !matches!(ext, Extern::None)
2734 impl Default for FnHeader {
2735 fn default() -> FnHeader {
2737 unsafety: Unsafe::No,
2738 asyncness: Async::No,
2739 constness: Const::No,
2745 #[derive(Clone, Encodable, Decodable, Debug)]
2747 pub unsafety: Unsafe,
2748 pub is_auto: IsAuto,
2749 pub generics: Generics,
2750 pub bounds: GenericBounds,
2751 pub items: Vec<P<AssocItem>>,
2754 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2755 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2756 /// are two locations for where clause on type aliases, but their predicates
2757 /// are concatenated together.
2759 /// Take this example:
2760 /// ```ignore (only-for-syntax-highlight)
2762 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2764 /// impl Foo for () {
2765 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2766 /// // ^^^^^^^^^^^^^^ first where clause
2767 /// // ^^^^^^^^^^^^^^ second where clause
2771 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2772 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2773 pub struct TyAliasWhereClause(pub bool, pub Span);
2775 #[derive(Clone, Encodable, Decodable, Debug)]
2776 pub struct TyAlias {
2777 pub defaultness: Defaultness,
2778 pub generics: Generics,
2779 /// The span information for the two where clauses (before equals, after equals)
2780 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2781 /// The index in `generics.where_clause.predicates` that would split into
2782 /// predicates from the where clause before the equals and the predicates
2783 /// from the where clause after the equals
2784 pub where_predicates_split: usize,
2785 pub bounds: GenericBounds,
2786 pub ty: Option<P<Ty>>,
2789 #[derive(Clone, Encodable, Decodable, Debug)]
2791 pub defaultness: Defaultness,
2792 pub unsafety: Unsafe,
2793 pub generics: Generics,
2794 pub constness: Const,
2795 pub polarity: ImplPolarity,
2796 /// The trait being implemented, if any.
2797 pub of_trait: Option<TraitRef>,
2799 pub items: Vec<P<AssocItem>>,
2802 #[derive(Clone, Encodable, Decodable, Debug)]
2804 pub defaultness: Defaultness,
2805 pub generics: Generics,
2807 pub body: Option<P<Block>>,
2810 #[derive(Clone, Encodable, Decodable, Debug)]
2812 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2814 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2815 ExternCrate(Option<Symbol>),
2816 /// A use declaration item (`use`).
2818 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2820 /// A static item (`static`).
2822 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2823 Static(P<Ty>, Mutability, Option<P<Expr>>),
2824 /// A constant item (`const`).
2826 /// E.g., `const FOO: i32 = 42;`.
2827 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2828 /// A function declaration (`fn`).
2830 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2832 /// A module declaration (`mod`).
2834 /// E.g., `mod foo;` or `mod foo { .. }`.
2835 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2836 /// semantically by Rust.
2837 Mod(Unsafe, ModKind),
2838 /// An external module (`extern`).
2840 /// E.g., `extern {}` or `extern "C" {}`.
2841 ForeignMod(ForeignMod),
2842 /// Module-level inline assembly (from `global_asm!()`).
2843 GlobalAsm(Box<InlineAsm>),
2844 /// A type alias (`type`).
2846 /// E.g., `type Foo = Bar<u8>;`.
2847 TyAlias(Box<TyAlias>),
2848 /// An enum definition (`enum`).
2850 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2851 Enum(EnumDef, Generics),
2852 /// A struct definition (`struct`).
2854 /// E.g., `struct Foo<A> { x: A }`.
2855 Struct(VariantData, Generics),
2856 /// A union definition (`union`).
2858 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2859 Union(VariantData, Generics),
2860 /// A trait declaration (`trait`).
2862 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2866 /// E.g., `trait Foo = Bar + Quux;`.
2867 TraitAlias(Generics, GenericBounds),
2868 /// An implementation.
2870 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2872 /// A macro invocation.
2874 /// E.g., `foo!(..)`.
2877 /// A macro definition.
2882 pub fn article(&self) -> &str {
2885 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2886 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2887 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2891 pub fn descr(&self) -> &str {
2893 ItemKind::ExternCrate(..) => "extern crate",
2894 ItemKind::Use(..) => "`use` import",
2895 ItemKind::Static(..) => "static item",
2896 ItemKind::Const(..) => "constant item",
2897 ItemKind::Fn(..) => "function",
2898 ItemKind::Mod(..) => "module",
2899 ItemKind::ForeignMod(..) => "extern block",
2900 ItemKind::GlobalAsm(..) => "global asm item",
2901 ItemKind::TyAlias(..) => "type alias",
2902 ItemKind::Enum(..) => "enum",
2903 ItemKind::Struct(..) => "struct",
2904 ItemKind::Union(..) => "union",
2905 ItemKind::Trait(..) => "trait",
2906 ItemKind::TraitAlias(..) => "trait alias",
2907 ItemKind::MacCall(..) => "item macro invocation",
2908 ItemKind::MacroDef(..) => "macro definition",
2909 ItemKind::Impl { .. } => "implementation",
2913 pub fn generics(&self) -> Option<&Generics> {
2915 Self::Fn(box Fn { generics, .. })
2916 | Self::TyAlias(box TyAlias { generics, .. })
2917 | Self::Enum(_, generics)
2918 | Self::Struct(_, generics)
2919 | Self::Union(_, generics)
2920 | Self::Trait(box Trait { generics, .. })
2921 | Self::TraitAlias(generics, _)
2922 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2928 /// Represents associated items.
2929 /// These include items in `impl` and `trait` definitions.
2930 pub type AssocItem = Item<AssocItemKind>;
2932 /// Represents associated item kinds.
2934 /// The term "provided" in the variants below refers to the item having a default
2935 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2936 /// In an implementation, all items must be provided.
2937 /// The `Option`s below denote the bodies, where `Some(_)`
2938 /// means "provided" and conversely `None` means "required".
2939 #[derive(Clone, Encodable, Decodable, Debug)]
2940 pub enum AssocItemKind {
2941 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2942 /// If `def` is parsed, then the constant is provided, and otherwise required.
2943 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2944 /// An associated function.
2946 /// An associated type.
2947 TyAlias(Box<TyAlias>),
2948 /// A macro expanding to associated items.
2952 impl AssocItemKind {
2953 pub fn defaultness(&self) -> Defaultness {
2955 Self::Const(defaultness, ..)
2956 | Self::Fn(box Fn { defaultness, .. })
2957 | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness,
2958 Self::MacCall(..) => Defaultness::Final,
2963 impl From<AssocItemKind> for ItemKind {
2964 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2965 match assoc_item_kind {
2966 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2967 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2968 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2969 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2974 impl TryFrom<ItemKind> for AssocItemKind {
2975 type Error = ItemKind;
2977 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2978 Ok(match item_kind {
2979 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2980 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2981 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2982 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2983 _ => return Err(item_kind),
2988 /// An item in `extern` block.
2989 #[derive(Clone, Encodable, Decodable, Debug)]
2990 pub enum ForeignItemKind {
2991 /// A foreign static item (`static FOO: u8`).
2992 Static(P<Ty>, Mutability, Option<P<Expr>>),
2993 /// An foreign function.
2995 /// An foreign type.
2996 TyAlias(Box<TyAlias>),
2997 /// A macro expanding to foreign items.
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>;
3028 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3029 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3032 use rustc_data_structures::static_assert_size;
3033 // These are in alphabetical order, which is easy to maintain.
3034 static_assert_size!(AssocItem, 160);
3035 static_assert_size!(AssocItemKind, 72);
3036 static_assert_size!(Attribute, 152);
3037 static_assert_size!(Block, 48);
3038 static_assert_size!(Expr, 104);
3039 static_assert_size!(Fn, 192);
3040 static_assert_size!(ForeignItem, 160);
3041 static_assert_size!(ForeignItemKind, 72);
3042 static_assert_size!(GenericBound, 88);
3043 static_assert_size!(Generics, 72);
3044 static_assert_size!(Impl, 200);
3045 static_assert_size!(Item, 200);
3046 static_assert_size!(ItemKind, 112);
3047 static_assert_size!(Lit, 48);
3048 static_assert_size!(Pat, 120);
3049 static_assert_size!(Path, 40);
3050 static_assert_size!(PathSegment, 24);
3051 static_assert_size!(Stmt, 32);
3052 static_assert_size!(Ty, 96);