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};
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_data_structures::stack::ensure_sufficient_stack;
30 use rustc_data_structures::sync::Lrc;
31 use rustc_macros::HashStable_Generic;
32 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
33 use rustc_span::source_map::{respan, Spanned};
34 use rustc_span::symbol::{kw, sym, Ident, Symbol};
35 use rustc_span::{Span, DUMMY_SP};
36 use std::cmp::Ordering;
37 use std::convert::TryFrom;
40 use thin_vec::ThinVec;
42 /// A "Label" is an identifier of some point in sources,
43 /// e.g. in the following code:
51 /// `'outer` is a label.
52 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
57 impl fmt::Debug for Label {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 write!(f, "label({:?})", self.ident)
63 /// A "Lifetime" is an annotation of the scope in which variable
64 /// can be used, e.g. `'a` in `&'a i32`.
65 #[derive(Clone, Encodable, Decodable, Copy, PartialEq, Eq)]
71 impl fmt::Debug for Lifetime {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "lifetime({}: {})", self.id, self)
77 impl fmt::Display for Lifetime {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 write!(f, "{}", self.ident.name)
83 /// A "Path" is essentially Rust's notion of a name.
85 /// It's represented as a sequence of identifiers,
86 /// along with a bunch of supporting information.
88 /// E.g., `std::cmp::PartialEq`.
89 #[derive(Clone, Encodable, Decodable, Debug)]
92 /// The segments in the path: the things separated by `::`.
93 /// Global paths begin with `kw::PathRoot`.
94 pub segments: Vec<PathSegment>,
95 pub tokens: Option<LazyTokenStream>,
98 impl PartialEq<Symbol> for Path {
100 fn eq(&self, symbol: &Symbol) -> bool {
101 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
105 impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
106 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
107 self.segments.len().hash_stable(hcx, hasher);
108 for segment in &self.segments {
109 segment.ident.hash_stable(hcx, hasher);
115 // Convert a span and an identifier to the corresponding
117 pub fn from_ident(ident: Ident) -> Path {
118 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
121 pub fn is_global(&self) -> bool {
122 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
126 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
128 /// E.g., `std`, `String` or `Box<T>`.
129 #[derive(Clone, Encodable, Decodable, Debug)]
130 pub struct PathSegment {
131 /// The identifier portion of this path segment.
136 /// Type/lifetime parameters attached to this path. They come in
137 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
138 /// `None` means that no parameter list is supplied (`Path`),
139 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
140 /// but it can be empty (`Path<>`).
141 /// `P` is used as a size optimization for the common case with no parameters.
142 pub args: Option<P<GenericArgs>>,
146 pub fn from_ident(ident: Ident) -> Self {
147 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
150 pub fn path_root(span: Span) -> Self {
151 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
154 pub fn span(&self) -> Span {
156 Some(args) => self.ident.span.to(args.span()),
157 None => self.ident.span,
162 /// The arguments of a path segment.
164 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
165 #[derive(Clone, Encodable, Decodable, Debug)]
166 pub enum GenericArgs {
167 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
168 AngleBracketed(AngleBracketedArgs),
169 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
170 Parenthesized(ParenthesizedArgs),
174 pub fn is_angle_bracketed(&self) -> bool {
175 matches!(self, AngleBracketed(..))
178 pub fn span(&self) -> Span {
180 AngleBracketed(ref data) => data.span,
181 Parenthesized(ref data) => data.span,
186 /// Concrete argument in the sequence of generic args.
187 #[derive(Clone, Encodable, Decodable, Debug)]
188 pub enum GenericArg {
189 /// `'a` in `Foo<'a>`
191 /// `Bar` in `Foo<Bar>`
198 pub fn span(&self) -> Span {
200 GenericArg::Lifetime(lt) => lt.ident.span,
201 GenericArg::Type(ty) => ty.span,
202 GenericArg::Const(ct) => ct.value.span,
207 /// A path like `Foo<'a, T>`.
208 #[derive(Clone, Encodable, Decodable, Debug, Default)]
209 pub struct AngleBracketedArgs {
210 /// The overall span.
212 /// The comma separated parts in the `<...>`.
213 pub args: Vec<AngleBracketedArg>,
216 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
217 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
218 #[derive(Clone, Encodable, Decodable, Debug)]
219 pub enum AngleBracketedArg {
220 /// Argument for a generic parameter.
222 /// Constraint for an associated item.
223 Constraint(AssocConstraint),
226 impl AngleBracketedArg {
227 pub fn span(&self) -> Span {
229 AngleBracketedArg::Arg(arg) => arg.span(),
230 AngleBracketedArg::Constraint(constraint) => constraint.span,
235 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
236 fn into(self) -> Option<P<GenericArgs>> {
237 Some(P(GenericArgs::AngleBracketed(self)))
241 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
242 fn into(self) -> Option<P<GenericArgs>> {
243 Some(P(GenericArgs::Parenthesized(self)))
247 /// A path like `Foo(A, B) -> C`.
248 #[derive(Clone, Encodable, Decodable, Debug)]
249 pub struct ParenthesizedArgs {
257 pub inputs: Vec<P<Ty>>,
263 pub inputs_span: Span,
269 impl ParenthesizedArgs {
270 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
275 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
277 AngleBracketedArgs { span: self.inputs_span, args }
281 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
283 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
285 /// Negative bounds should also be handled here.
286 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
287 pub enum TraitBoundModifier {
299 // This parses but will be rejected during AST validation.
303 /// The AST represents all type param bounds as types.
304 /// `typeck::collect::compute_bounds` matches these against
305 /// the "special" built-in traits (see `middle::lang_items`) and
306 /// detects `Copy`, `Send` and `Sync`.
307 #[derive(Clone, Encodable, Decodable, Debug)]
308 pub enum GenericBound {
309 Trait(PolyTraitRef, TraitBoundModifier),
314 pub fn span(&self) -> Span {
316 GenericBound::Trait(ref t, ..) => t.span,
317 GenericBound::Outlives(ref l) => l.ident.span,
322 pub type GenericBounds = Vec<GenericBound>;
324 /// Specifies the enforced ordering for generic parameters. In the future,
325 /// if we wanted to relax this order, we could override `PartialEq` and
326 /// `PartialOrd`, to allow the kinds to be unordered.
327 #[derive(Hash, Clone, Copy)]
328 pub enum ParamKindOrd {
332 // `Infer` is not actually constructed directly from the AST, but is implicitly constructed
333 // during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last.
337 impl Ord for ParamKindOrd {
338 fn cmp(&self, other: &Self) -> Ordering {
340 let to_int = |v| match v {
342 Infer | Type | Const => 1,
345 to_int(*self).cmp(&to_int(*other))
348 impl PartialOrd for ParamKindOrd {
349 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
350 Some(self.cmp(other))
353 impl PartialEq for ParamKindOrd {
354 fn eq(&self, other: &Self) -> bool {
355 self.cmp(other) == Ordering::Equal
358 impl Eq for ParamKindOrd {}
360 impl fmt::Display for ParamKindOrd {
361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 ParamKindOrd::Lifetime => "lifetime".fmt(f),
364 ParamKindOrd::Type => "type".fmt(f),
365 ParamKindOrd::Const { .. } => "const".fmt(f),
366 ParamKindOrd::Infer => "infer".fmt(f),
371 #[derive(Clone, Encodable, Decodable, Debug)]
372 pub enum GenericParamKind {
373 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
376 default: Option<P<Ty>>,
380 /// Span of the `const` keyword.
382 /// Optional default value for the const generic param
383 default: Option<AnonConst>,
387 #[derive(Clone, Encodable, Decodable, Debug)]
388 pub struct GenericParam {
392 pub bounds: GenericBounds,
393 pub is_placeholder: bool,
394 pub kind: GenericParamKind,
395 pub colon_span: Option<Span>,
399 pub fn span(&self) -> Span {
401 GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
404 GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
405 GenericParamKind::Const { kw_span, default: Some(default), .. } => {
406 kw_span.to(default.value.span)
408 GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
413 /// Represents lifetime, type and const parameters attached to a declaration of
414 /// a function, enum, trait, etc.
415 #[derive(Clone, Encodable, Decodable, Debug)]
416 pub struct Generics {
417 pub params: Vec<GenericParam>,
418 pub where_clause: WhereClause,
422 impl Default for Generics {
423 /// Creates an instance of `Generics`.
424 fn default() -> Generics {
427 where_clause: WhereClause {
428 has_where_token: false,
429 predicates: Vec::new(),
437 /// A where-clause in a definition.
438 #[derive(Clone, Encodable, Decodable, Debug)]
439 pub struct WhereClause {
440 /// `true` if we ate a `where` token: this can happen
441 /// if we parsed no predicates (e.g. `struct Foo where {}`).
442 /// This allows us to pretty-print accurately.
443 pub has_where_token: bool,
444 pub predicates: Vec<WherePredicate>,
448 /// A single predicate in a where-clause.
449 #[derive(Clone, Encodable, Decodable, Debug)]
450 pub enum WherePredicate {
451 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
452 BoundPredicate(WhereBoundPredicate),
453 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
454 RegionPredicate(WhereRegionPredicate),
455 /// An equality predicate (unsupported).
456 EqPredicate(WhereEqPredicate),
459 impl WherePredicate {
460 pub fn span(&self) -> Span {
462 WherePredicate::BoundPredicate(p) => p.span,
463 WherePredicate::RegionPredicate(p) => p.span,
464 WherePredicate::EqPredicate(p) => p.span,
471 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
472 #[derive(Clone, Encodable, Decodable, Debug)]
473 pub struct WhereBoundPredicate {
475 /// Any generics from a `for` binding.
476 pub bound_generic_params: Vec<GenericParam>,
477 /// The type being bounded.
478 pub bounded_ty: P<Ty>,
479 /// Trait and lifetime bounds (`Clone + Send + 'static`).
480 pub bounds: GenericBounds,
483 /// A lifetime predicate.
485 /// E.g., `'a: 'b + 'c`.
486 #[derive(Clone, Encodable, Decodable, Debug)]
487 pub struct WhereRegionPredicate {
489 pub lifetime: Lifetime,
490 pub bounds: GenericBounds,
493 /// An equality predicate (unsupported).
496 #[derive(Clone, Encodable, Decodable, Debug)]
497 pub struct WhereEqPredicate {
503 #[derive(Clone, Encodable, Decodable, Debug)]
506 pub items: Vec<P<Item>>,
508 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
509 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
511 pub is_placeholder: bool,
514 /// Possible values inside of compile-time attribute lists.
516 /// E.g., the '..' in `#[name(..)]`.
517 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
518 pub enum NestedMetaItem {
519 /// A full MetaItem, for recursive meta items.
523 /// E.g., `"foo"`, `64`, `true`.
527 /// A spanned compile-time attribute item.
529 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
530 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
531 pub struct MetaItem {
533 pub kind: MetaItemKind,
537 /// A compile-time attribute item.
539 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
540 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
541 pub enum MetaItemKind {
544 /// E.g., `test` as in `#[test]`.
548 /// E.g., `derive(..)` as in `#[derive(..)]`.
549 List(Vec<NestedMetaItem>),
550 /// Name value meta item.
552 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
556 /// A block (`{ .. }`).
558 /// E.g., `{ .. }` as in `fn foo() { .. }`.
559 #[derive(Clone, Encodable, Decodable, Debug)]
561 /// The statements in the block.
562 pub stmts: Vec<Stmt>,
564 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
565 pub rules: BlockCheckMode,
567 pub tokens: Option<LazyTokenStream>,
568 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
575 pub could_be_bare_literal: bool,
580 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
581 #[derive(Clone, Encodable, Decodable, Debug)]
586 pub tokens: Option<LazyTokenStream>,
590 /// Attempt reparsing the pattern as a type.
591 /// This is intended for use by diagnostics.
592 pub fn to_ty(&self) -> Option<P<Ty>> {
593 let kind = match &self.kind {
594 // In a type expression `_` is an inference variable.
595 PatKind::Wild => TyKind::Infer,
596 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
597 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
598 TyKind::Path(None, Path::from_ident(*ident))
600 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
601 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
602 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
603 PatKind::Ref(pat, mutbl) => {
604 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
606 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
607 // when `P` can be reparsed as a type `T`.
608 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
609 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
610 // assuming `T0` to `Tn` are all syntactically valid as types.
611 PatKind::Tuple(pats) => {
612 let mut tys = Vec::with_capacity(pats.len());
613 // FIXME(#48994) - could just be collected into an Option<Vec>
615 tys.push(pat.to_ty()?);
622 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
625 /// Walk top-down and call `it` in each place where a pattern occurs
626 /// starting with the root pattern `walk` is called on. If `it` returns
627 /// false then we will descend no further but siblings will be processed.
628 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
634 // Walk into the pattern associated with `Ident` (if any).
635 PatKind::Ident(_, _, Some(p)) => p.walk(it),
637 // Walk into each field of struct.
638 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
640 // Sequence of patterns.
641 PatKind::TupleStruct(_, _, s)
644 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
646 // Trivial wrappers over inner patterns.
647 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
649 // These patterns do not contain subpatterns, skip.
656 | PatKind::MacCall(_) => {}
660 /// Is this a `..` pattern?
661 pub fn is_rest(&self) -> bool {
662 matches!(self.kind, PatKind::Rest)
666 /// A single field in a struct pattern.
668 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
669 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
670 /// except when `is_shorthand` is true.
671 #[derive(Clone, Encodable, Decodable, Debug)]
672 pub struct PatField {
673 /// The identifier for the field.
675 /// The pattern the field is destructured to.
677 pub is_shorthand: bool,
681 pub is_placeholder: bool,
684 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
685 #[derive(Encodable, Decodable, HashStable_Generic)]
691 impl From<bool> for ByRef {
692 fn from(b: bool) -> ByRef {
700 /// Explicit binding annotations given in the HIR for a binding. Note
701 /// that this is not the final binding *mode* that we infer after type
703 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
704 #[derive(Encodable, Decodable, HashStable_Generic)]
705 pub struct BindingAnnotation(pub ByRef, pub Mutability);
707 impl BindingAnnotation {
708 pub const NONE: Self = Self(ByRef::No, Mutability::Not);
709 pub const REF: Self = Self(ByRef::Yes, Mutability::Not);
710 pub const MUT: Self = Self(ByRef::No, Mutability::Mut);
711 pub const REF_MUT: Self = Self(ByRef::Yes, Mutability::Mut);
713 pub fn prefix_str(self) -> &'static str {
718 Self::REF_MUT => "ref mut ",
723 #[derive(Clone, Encodable, Decodable, Debug)]
726 Included(RangeSyntax),
731 #[derive(Clone, Encodable, Decodable, Debug)]
732 pub enum RangeSyntax {
739 /// All the different flavors of pattern that Rust recognizes.
740 #[derive(Clone, Encodable, Decodable, Debug)]
742 /// Represents a wildcard pattern (`_`).
745 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
746 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
747 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
748 /// during name resolution.
749 Ident(BindingAnnotation, Ident, Option<P<Pat>>),
751 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
752 /// The `bool` is `true` in the presence of a `..`.
753 Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool),
755 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
756 TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>),
758 /// An or-pattern `A | B | C`.
759 /// Invariant: `pats.len() >= 2`.
762 /// A possibly qualified path pattern.
763 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
764 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
765 /// only legally refer to associated constants.
766 Path(Option<QSelf>, Path),
768 /// A tuple pattern (`(a, b)`).
774 /// A reference pattern (e.g., `&mut (a, b)`).
775 Ref(P<Pat>, Mutability),
780 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
781 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
783 /// A slice pattern `[a, b, c]`.
786 /// A rest pattern `..`.
788 /// Syntactically it is valid anywhere.
790 /// Semantically however, it only has meaning immediately inside:
791 /// - a slice pattern: `[a, .., b]`,
792 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
793 /// - a tuple pattern: `(a, .., b)`,
794 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
796 /// In all of these cases, an additional restriction applies,
797 /// only one rest pattern may occur in the pattern sequences.
800 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
803 /// A macro pattern; pre-expansion.
807 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
808 #[derive(HashStable_Generic, Encodable, Decodable)]
809 pub enum Mutability {
815 pub fn invert(self) -> Self {
817 Mutability::Mut => Mutability::Not,
818 Mutability::Not => Mutability::Mut,
822 pub fn prefix_str(&self) -> &'static str {
824 Mutability::Mut => "mut ",
825 Mutability::Not => "",
830 /// The kind of borrow in an `AddrOf` expression,
831 /// e.g., `&place` or `&raw const place`.
832 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
833 #[derive(Encodable, Decodable, HashStable_Generic)]
834 pub enum BorrowKind {
835 /// A normal borrow, `&$expr` or `&mut $expr`.
836 /// The resulting type is either `&'a T` or `&'a mut T`
837 /// where `T = typeof($expr)` and `'a` is some lifetime.
839 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
840 /// The resulting type is either `*const T` or `*mut T`
841 /// where `T = typeof($expr)`.
845 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
847 /// The `+` operator (addition)
849 /// The `-` operator (subtraction)
851 /// The `*` operator (multiplication)
853 /// The `/` operator (division)
855 /// The `%` operator (modulus)
857 /// The `&&` operator (logical and)
859 /// The `||` operator (logical or)
861 /// The `^` operator (bitwise xor)
863 /// The `&` operator (bitwise and)
865 /// The `|` operator (bitwise or)
867 /// The `<<` operator (shift left)
869 /// The `>>` operator (shift right)
871 /// The `==` operator (equality)
873 /// The `<` operator (less than)
875 /// The `<=` operator (less than or equal to)
877 /// The `!=` operator (not equal to)
879 /// The `>=` operator (greater than or equal to)
881 /// The `>` operator (greater than)
886 pub fn to_string(&self) -> &'static str {
909 pub fn lazy(&self) -> bool {
910 matches!(self, BinOpKind::And | BinOpKind::Or)
913 pub fn is_comparison(&self) -> bool {
915 // Note for developers: please keep this as is;
916 // we want compilation to fail if another variant is added.
918 Eq | Lt | Le | Ne | Gt | Ge => true,
919 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
924 pub type BinOp = Spanned<BinOpKind>;
928 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
929 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
931 /// The `*` operator for dereferencing
933 /// The `!` operator for logical inversion
935 /// The `-` operator for negation
940 pub fn to_string(op: UnOp) -> &'static str {
950 #[derive(Clone, Encodable, Decodable, Debug)]
958 pub fn has_trailing_semicolon(&self) -> bool {
960 StmtKind::Semi(_) => true,
961 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
966 /// Converts a parsed `Stmt` to a `Stmt` with
967 /// a trailing semicolon.
969 /// This only modifies the parsed AST struct, not the attached
970 /// `LazyTokenStream`. The parser is responsible for calling
971 /// `CreateTokenStream::add_trailing_semi` when there is actually
972 /// a semicolon in the tokenstream.
973 pub fn add_trailing_semicolon(mut self) -> Self {
974 self.kind = match self.kind {
975 StmtKind::Expr(expr) => StmtKind::Semi(expr),
976 StmtKind::MacCall(mac) => {
977 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
978 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
987 pub fn is_item(&self) -> bool {
988 matches!(self.kind, StmtKind::Item(_))
991 pub fn is_expr(&self) -> bool {
992 matches!(self.kind, StmtKind::Expr(_))
996 #[derive(Clone, Encodable, Decodable, Debug)]
998 /// A local (let) binding.
1000 /// An item definition.
1002 /// Expr without trailing semi-colon.
1004 /// Expr with a trailing semi-colon.
1006 /// Just a trailing semi-colon.
1009 MacCall(P<MacCallStmt>),
1012 #[derive(Clone, Encodable, Decodable, Debug)]
1013 pub struct MacCallStmt {
1014 pub mac: P<MacCall>,
1015 pub style: MacStmtStyle,
1017 pub tokens: Option<LazyTokenStream>,
1020 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1021 pub enum MacStmtStyle {
1022 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1023 /// `foo!(...);`, `foo![...];`).
1025 /// The macro statement had braces (e.g., `foo! { ... }`).
1027 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1028 /// `foo!(...)`). All of these will end up being converted into macro
1033 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1034 #[derive(Clone, Encodable, Decodable, Debug)]
1038 pub ty: Option<P<Ty>>,
1039 pub kind: LocalKind,
1042 pub tokens: Option<LazyTokenStream>,
1045 #[derive(Clone, Encodable, Decodable, Debug)]
1046 pub enum LocalKind {
1047 /// Local declaration.
1048 /// Example: `let x;`
1050 /// Local declaration with an initializer.
1051 /// Example: `let x = y;`
1053 /// Local declaration with an initializer and an `else` clause.
1054 /// Example: `let Some(x) = y else { return };`
1055 InitElse(P<Expr>, P<Block>),
1059 pub fn init(&self) -> Option<&Expr> {
1062 Self::Init(i) | Self::InitElse(i, _) => Some(i),
1066 pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1069 Self::Init(init) => Some((init, None)),
1070 Self::InitElse(init, els) => Some((init, Some(els))),
1075 /// An arm of a 'match'.
1077 /// E.g., `0..=10 => { println!("match!") }` as in
1081 /// 0..=10 => { println!("match!") },
1082 /// _ => { println!("no match!") },
1085 #[derive(Clone, Encodable, Decodable, Debug)]
1088 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1090 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1091 pub guard: Option<P<Expr>>,
1096 pub is_placeholder: bool,
1099 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1100 #[derive(Clone, Encodable, Decodable, Debug)]
1101 pub struct ExprField {
1107 pub is_shorthand: bool,
1108 pub is_placeholder: bool,
1111 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1112 pub enum BlockCheckMode {
1114 Unsafe(UnsafeSource),
1117 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1118 pub enum UnsafeSource {
1123 /// A constant (expression) that's not an item or associated item,
1124 /// but needs its own `DefId` for type-checking, const-eval, etc.
1125 /// These are usually found nested inside types (e.g., array lengths)
1126 /// or expressions (e.g., repeat counts), and also used to define
1127 /// explicit discriminant values for enum variants.
1128 #[derive(Clone, Encodable, Decodable, Debug)]
1129 pub struct AnonConst {
1135 #[derive(Clone, Encodable, Decodable, Debug)]
1141 pub tokens: Option<LazyTokenStream>,
1145 /// Returns `true` if this expression would be valid somewhere that expects a value;
1146 /// for example, an `if` condition.
1147 pub fn returns(&self) -> bool {
1148 if let ExprKind::Block(ref block, _) = self.kind {
1149 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1151 Some(StmtKind::Expr(_)) => true,
1152 // Last statement is an explicit return?
1153 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1154 // This is a block that doesn't end in either an implicit or explicit return.
1158 // This is not a block, it is a value.
1163 /// Is this expr either `N`, or `{ N }`.
1165 /// If this is not the case, name resolution does not resolve `N` when using
1166 /// `min_const_generics` as more complex expressions are not supported.
1167 pub fn is_potential_trivial_const_param(&self) -> bool {
1168 let this = if let ExprKind::Block(ref block, None) = self.kind {
1169 if block.stmts.len() == 1 {
1170 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1178 if let ExprKind::Path(None, ref path) = this.kind {
1179 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1187 pub fn to_bound(&self) -> Option<GenericBound> {
1189 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1190 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1191 TraitBoundModifier::None,
1197 pub fn peel_parens(&self) -> &Expr {
1198 let mut expr = self;
1199 while let ExprKind::Paren(inner) = &expr.kind {
1205 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1206 pub fn to_ty(&self) -> Option<P<Ty>> {
1207 let kind = match &self.kind {
1208 // Trivial conversions.
1209 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1210 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1212 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1214 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1215 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1218 ExprKind::Repeat(expr, expr_len) => {
1219 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1222 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1224 ExprKind::Tup(exprs) => {
1225 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1229 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1230 // then type of result is trait object.
1231 // Otherwise we don't assume the result type.
1232 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1233 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1234 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1240 ExprKind::Underscore => TyKind::Infer,
1242 // This expression doesn't look like a type syntactically.
1246 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1249 pub fn precedence(&self) -> ExprPrecedence {
1251 ExprKind::Box(_) => ExprPrecedence::Box,
1252 ExprKind::Array(_) => ExprPrecedence::Array,
1253 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1254 ExprKind::Call(..) => ExprPrecedence::Call,
1255 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1256 ExprKind::Tup(_) => ExprPrecedence::Tup,
1257 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1258 ExprKind::Unary(..) => ExprPrecedence::Unary,
1259 ExprKind::Lit(_) => ExprPrecedence::Lit,
1260 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1261 ExprKind::Let(..) => ExprPrecedence::Let,
1262 ExprKind::If(..) => ExprPrecedence::If,
1263 ExprKind::While(..) => ExprPrecedence::While,
1264 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1265 ExprKind::Loop(..) => ExprPrecedence::Loop,
1266 ExprKind::Match(..) => ExprPrecedence::Match,
1267 ExprKind::Closure(..) => ExprPrecedence::Closure,
1268 ExprKind::Block(..) => ExprPrecedence::Block,
1269 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1270 ExprKind::Async(..) => ExprPrecedence::Async,
1271 ExprKind::Await(..) => ExprPrecedence::Await,
1272 ExprKind::Assign(..) => ExprPrecedence::Assign,
1273 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1274 ExprKind::Field(..) => ExprPrecedence::Field,
1275 ExprKind::Index(..) => ExprPrecedence::Index,
1276 ExprKind::Range(..) => ExprPrecedence::Range,
1277 ExprKind::Underscore => ExprPrecedence::Path,
1278 ExprKind::Path(..) => ExprPrecedence::Path,
1279 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1280 ExprKind::Break(..) => ExprPrecedence::Break,
1281 ExprKind::Continue(..) => ExprPrecedence::Continue,
1282 ExprKind::Ret(..) => ExprPrecedence::Ret,
1283 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1284 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1285 ExprKind::Struct(..) => ExprPrecedence::Struct,
1286 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1287 ExprKind::Paren(..) => ExprPrecedence::Paren,
1288 ExprKind::Try(..) => ExprPrecedence::Try,
1289 ExprKind::Yield(..) => ExprPrecedence::Yield,
1290 ExprKind::Yeet(..) => ExprPrecedence::Yeet,
1291 ExprKind::Err => ExprPrecedence::Err,
1295 pub fn take(&mut self) -> Self {
1300 kind: ExprKind::Err,
1302 attrs: AttrVec::new(),
1308 // To a first-order approximation, is this a pattern
1309 pub fn is_approximately_pattern(&self) -> bool {
1310 match &self.peel_parens().kind {
1312 | ExprKind::Array(_)
1313 | ExprKind::Call(_, _)
1316 | ExprKind::Range(_, _, _)
1317 | ExprKind::Underscore
1318 | ExprKind::Path(_, _)
1319 | ExprKind::Struct(_) => true,
1325 /// Limit types of a range (inclusive or exclusive)
1326 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1327 pub enum RangeLimits {
1328 /// Inclusive at the beginning, exclusive at the end
1330 /// Inclusive at the beginning and end
1334 #[derive(Clone, Encodable, Decodable, Debug)]
1335 pub enum StructRest {
1340 /// No trailing `..` or expression.
1344 #[derive(Clone, Encodable, Decodable, Debug)]
1345 pub struct StructExpr {
1346 pub qself: Option<QSelf>,
1348 pub fields: Vec<ExprField>,
1349 pub rest: StructRest,
1352 #[derive(Clone, Encodable, Decodable, Debug)]
1354 /// A `box x` expression.
1356 /// An array (`[a, b, c, d]`)
1357 Array(Vec<P<Expr>>),
1358 /// Allow anonymous constants from an inline `const` block
1359 ConstBlock(AnonConst),
1362 /// The first field resolves to the function itself,
1363 /// and the second field is the list of arguments.
1364 /// This also represents calling the constructor of
1365 /// tuple-like ADTs such as tuple structs and enum variants.
1366 Call(P<Expr>, Vec<P<Expr>>),
1367 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1369 /// The `PathSegment` represents the method name and its generic arguments
1370 /// (within the angle brackets).
1371 /// The standalone `Expr` is the receiver expression.
1372 /// The vector of `Expr` is the arguments.
1373 /// `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1374 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d])`.
1375 /// This `Span` is the span of the function, without the dot and receiver
1376 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1377 MethodCall(PathSegment, P<Expr>, Vec<P<Expr>>, Span),
1378 /// A tuple (e.g., `(a, b, c, d)`).
1380 /// A binary operation (e.g., `a + b`, `a * b`).
1381 Binary(BinOp, P<Expr>, P<Expr>),
1382 /// A unary operation (e.g., `!x`, `*x`).
1383 Unary(UnOp, P<Expr>),
1384 /// A literal (e.g., `1`, `"foo"`).
1386 /// A cast (e.g., `foo as f64`).
1387 Cast(P<Expr>, P<Ty>),
1388 /// A type ascription (e.g., `42: usize`).
1389 Type(P<Expr>, P<Ty>),
1390 /// A `let pat = expr` expression that is only semantically allowed in the condition
1391 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1393 /// `Span` represents the whole `let pat = expr` statement.
1394 Let(P<Pat>, P<Expr>, Span),
1395 /// An `if` block, with an optional `else` block.
1397 /// `if expr { block } else { expr }`
1398 If(P<Expr>, P<Block>, Option<P<Expr>>),
1399 /// A while loop, with an optional label.
1401 /// `'label: while expr { block }`
1402 While(P<Expr>, P<Block>, Option<Label>),
1403 /// A `for` loop, with an optional label.
1405 /// `'label: for pat in expr { block }`
1407 /// This is desugared to a combination of `loop` and `match` expressions.
1408 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1409 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1411 /// `'label: loop { block }`
1412 Loop(P<Block>, Option<Label>),
1413 /// A `match` block.
1414 Match(P<Expr>, Vec<Arm>),
1415 /// A closure (e.g., `move |a, b, c| a + b + c`).
1417 /// The final span is the span of the argument block `|...|`.
1418 Closure(ClosureBinder, CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1419 /// A block (`'label: { ... }`).
1420 Block(P<Block>, Option<Label>),
1421 /// An async block (`async move { ... }`).
1423 /// The `NodeId` is the `NodeId` for the closure that results from
1424 /// desugaring an async block, just like the NodeId field in the
1425 /// `Async::Yes` variant. This is necessary in order to create a def for the
1426 /// closure which can be used as a parent of any child defs. Defs
1427 /// created during lowering cannot be made the parent of any other
1428 /// preexisting defs.
1429 Async(CaptureBy, NodeId, P<Block>),
1430 /// An await expression (`my_future.await`).
1433 /// A try block (`try { ... }`).
1436 /// An assignment (`a = foo()`).
1437 /// The `Span` argument is the span of the `=` token.
1438 Assign(P<Expr>, P<Expr>, Span),
1439 /// An assignment with an operator.
1442 AssignOp(BinOp, P<Expr>, P<Expr>),
1443 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1444 Field(P<Expr>, Ident),
1445 /// An indexing operation (e.g., `foo[2]`).
1446 Index(P<Expr>, P<Expr>),
1447 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1448 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1449 /// An underscore, used in destructuring assignment to ignore a value.
1452 /// Variable reference, possibly containing `::` and/or type
1453 /// parameters (e.g., `foo::bar::<baz>`).
1455 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1456 Path(Option<QSelf>, Path),
1458 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1459 AddrOf(BorrowKind, Mutability, P<Expr>),
1460 /// A `break`, with an optional label to break, and an optional expression.
1461 Break(Option<Label>, Option<P<Expr>>),
1462 /// A `continue`, with an optional label.
1463 Continue(Option<Label>),
1464 /// A `return`, with an optional value to be returned.
1465 Ret(Option<P<Expr>>),
1467 /// Output of the `asm!()` macro.
1468 InlineAsm(P<InlineAsm>),
1470 /// A macro invocation; pre-expansion.
1471 MacCall(P<MacCall>),
1473 /// A struct literal expression.
1475 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1476 Struct(P<StructExpr>),
1478 /// An array literal constructed from one repeated element.
1480 /// E.g., `[1; 5]`. The expression is the element to be
1481 /// repeated; the constant is the number of times to repeat it.
1482 Repeat(P<Expr>, AnonConst),
1484 /// No-op: used solely so we can pretty-print faithfully.
1487 /// A try expression (`expr?`).
1490 /// A `yield`, with an optional value to be yielded.
1491 Yield(Option<P<Expr>>),
1493 /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1494 /// with an optional value to be returned.
1495 Yeet(Option<P<Expr>>),
1497 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1501 /// The explicit `Self` type in a "qualified path". The actual
1502 /// path, including the trait and the associated item, is stored
1503 /// separately. `position` represents the index of the associated
1504 /// item qualified with this `Self` type.
1506 /// ```ignore (only-for-syntax-highlight)
1507 /// <Vec<T> as a::b::Trait>::AssociatedItem
1508 /// ^~~~~ ~~~~~~~~~~~~~~^
1511 /// <Vec<T>>::AssociatedItem
1515 #[derive(Clone, Encodable, Decodable, Debug)]
1519 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1520 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1521 /// 0`, this is an empty span.
1522 pub path_span: Span,
1523 pub position: usize,
1526 /// A capture clause used in closures and `async` blocks.
1527 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1528 pub enum CaptureBy {
1529 /// `move |x| y + x`.
1531 /// `move` keyword was not specified.
1535 /// The movability of a generator / closure literal:
1536 /// whether a generator contains self-references, causing it to be `!Unpin`.
1537 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1538 #[derive(HashStable_Generic)]
1539 pub enum Movability {
1540 /// May contain self-references, `!Unpin`.
1542 /// Must not contain self-references, `Unpin`.
1546 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1547 #[derive(Clone, Encodable, Decodable, Debug)]
1548 pub enum ClosureBinder {
1549 /// The binder is not present, all closure lifetimes are inferred.
1551 /// The binder is present.
1553 /// Span of the whole `for<>` clause
1556 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1557 /// ^^^^^^^^^^^ -- this
1561 /// Lifetimes in the `for<>` closure
1564 /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1567 generic_params: P<[GenericParam]>,
1571 /// Represents a macro invocation. The `path` indicates which macro
1572 /// is being invoked, and the `args` are arguments passed to it.
1573 #[derive(Clone, Encodable, Decodable, Debug)]
1574 pub struct MacCall {
1576 pub args: P<MacArgs>,
1577 pub prior_type_ascription: Option<(Span, bool)>,
1581 pub fn span(&self) -> Span {
1582 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1586 /// Arguments passed to an attribute or a function-like macro.
1587 #[derive(Clone, Encodable, Decodable, Debug)]
1589 /// No arguments - `#[attr]`.
1591 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1592 Delimited(DelimSpan, MacDelimiter, TokenStream),
1593 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1595 /// Span of the `=` token.
1602 // The RHS of a `MacArgs::Eq` starts out as an expression. Once macro expansion
1603 // is completed, all cases end up either as a literal, which is the form used
1604 // after lowering to HIR, or as an error.
1605 #[derive(Clone, Encodable, Decodable, Debug)]
1606 pub enum MacArgsEq {
1612 pub fn delim(&self) -> Option<Delimiter> {
1614 MacArgs::Delimited(_, delim, _) => Some(delim.to_token()),
1615 MacArgs::Empty | MacArgs::Eq(..) => None,
1619 pub fn span(&self) -> Option<Span> {
1621 MacArgs::Empty => None,
1622 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1623 MacArgs::Eq(eq_span, MacArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1624 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1625 unreachable!("in literal form when getting span: {:?}", lit);
1630 /// Tokens inside the delimiters or after `=`.
1631 /// Proc macros see these tokens, for example.
1632 pub fn inner_tokens(&self) -> TokenStream {
1634 MacArgs::Empty => TokenStream::default(),
1635 MacArgs::Delimited(.., tokens) => tokens.clone(),
1636 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => TokenStream::from_ast(expr),
1637 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1638 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1643 /// Whether a macro with these arguments needs a semicolon
1644 /// when used as a standalone item or statement.
1645 pub fn need_semicolon(&self) -> bool {
1646 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1650 impl<CTX> HashStable<CTX> for MacArgs
1652 CTX: crate::HashStableContext,
1654 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1655 mem::discriminant(self).hash_stable(ctx, hasher);
1657 MacArgs::Empty => {}
1658 MacArgs::Delimited(dspan, delim, tokens) => {
1659 dspan.hash_stable(ctx, hasher);
1660 delim.hash_stable(ctx, hasher);
1661 tokens.hash_stable(ctx, hasher);
1663 MacArgs::Eq(_eq_span, MacArgsEq::Ast(expr)) => {
1664 unreachable!("hash_stable {:?}", expr);
1666 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit)) => {
1667 eq_span.hash_stable(ctx, hasher);
1668 lit.hash_stable(ctx, hasher);
1674 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1675 pub enum MacDelimiter {
1682 pub fn to_token(self) -> Delimiter {
1684 MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1685 MacDelimiter::Bracket => Delimiter::Bracket,
1686 MacDelimiter::Brace => Delimiter::Brace,
1690 pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1692 Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1693 Delimiter::Bracket => Some(MacDelimiter::Bracket),
1694 Delimiter::Brace => Some(MacDelimiter::Brace),
1695 Delimiter::Invisible => None,
1700 /// Represents a macro definition.
1701 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1702 pub struct MacroDef {
1703 pub body: P<MacArgs>,
1704 /// `true` if macro was defined with `macro_rules`.
1705 pub macro_rules: bool,
1708 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1709 #[derive(HashStable_Generic)]
1711 /// A regular string, like `"foo"`.
1713 /// A raw string, like `r##"foo"##`.
1715 /// The value is the number of `#` symbols used.
1720 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1722 /// The original literal token as written in source code.
1723 pub token_lit: token::Lit,
1724 /// The "semantic" representation of the literal lowered from the original tokens.
1725 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1726 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1731 /// Same as `Lit`, but restricted to string literals.
1732 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1734 /// The original literal token as written in source code.
1735 pub style: StrStyle,
1737 pub suffix: Option<Symbol>,
1739 /// The unescaped "semantic" representation of the literal lowered from the original token.
1740 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1741 pub symbol_unescaped: Symbol,
1745 pub fn as_lit(&self) -> Lit {
1746 let token_kind = match self.style {
1747 StrStyle::Cooked => token::Str,
1748 StrStyle::Raw(n) => token::StrRaw(n),
1751 token_lit: token::Lit::new(token_kind, self.symbol, self.suffix),
1753 kind: LitKind::Str(self.symbol_unescaped, self.style),
1758 /// Type of the integer literal based on provided suffix.
1759 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1760 #[derive(HashStable_Generic)]
1761 pub enum LitIntType {
1770 /// Type of the float literal based on provided suffix.
1771 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1772 #[derive(HashStable_Generic)]
1773 pub enum LitFloatType {
1774 /// A float literal with a suffix (`1f32` or `1E10f32`).
1776 /// A float literal without a suffix (`1.0 or 1.0E10`).
1782 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1783 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1785 /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
1786 /// from the original token's symbol.
1787 Str(Symbol, StrStyle),
1788 /// A byte string (`b"foo"`).
1790 /// A byte char (`b'f'`).
1792 /// A character literal (`'a'`).
1794 /// An integer literal (`1`).
1795 Int(u128, LitIntType),
1796 /// A float literal (`1f64` or `1E10f64`). Stored as a symbol rather than
1797 /// `f64` so that `LitKind` can impl `Eq` and `Hash`.
1798 Float(Symbol, LitFloatType),
1799 /// A boolean literal.
1801 /// Placeholder for a literal that wasn't well-formed in some way.
1806 /// Returns `true` if this literal is a string.
1807 pub fn is_str(&self) -> bool {
1808 matches!(self, LitKind::Str(..))
1811 /// Returns `true` if this literal is byte literal string.
1812 pub fn is_bytestr(&self) -> bool {
1813 matches!(self, LitKind::ByteStr(_))
1816 /// Returns `true` if this is a numeric literal.
1817 pub fn is_numeric(&self) -> bool {
1818 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1821 /// Returns `true` if this literal has no suffix.
1822 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1823 pub fn is_unsuffixed(&self) -> bool {
1827 /// Returns `true` if this literal has a suffix.
1828 pub fn is_suffixed(&self) -> bool {
1830 // suffixed variants
1831 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1832 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1833 // unsuffixed variants
1835 | LitKind::ByteStr(..)
1838 | LitKind::Int(_, LitIntType::Unsuffixed)
1839 | LitKind::Float(_, LitFloatType::Unsuffixed)
1841 | LitKind::Err => false,
1846 // N.B., If you change this, you'll probably want to change the corresponding
1847 // type structure in `middle/ty.rs` as well.
1848 #[derive(Clone, Encodable, Decodable, Debug)]
1851 pub mutbl: Mutability,
1854 /// Represents a function's signature in a trait declaration,
1855 /// trait implementation, or free function.
1856 #[derive(Clone, Encodable, Decodable, Debug)]
1858 pub header: FnHeader,
1859 pub decl: P<FnDecl>,
1863 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1864 #[derive(Encodable, Decodable, HashStable_Generic)]
1871 pub fn name_str(self) -> &'static str {
1873 FloatTy::F32 => "f32",
1874 FloatTy::F64 => "f64",
1878 pub fn name(self) -> Symbol {
1880 FloatTy::F32 => sym::f32,
1881 FloatTy::F64 => sym::f64,
1886 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1887 #[derive(Encodable, Decodable, HashStable_Generic)]
1898 pub fn name_str(&self) -> &'static str {
1900 IntTy::Isize => "isize",
1902 IntTy::I16 => "i16",
1903 IntTy::I32 => "i32",
1904 IntTy::I64 => "i64",
1905 IntTy::I128 => "i128",
1909 pub fn name(&self) -> Symbol {
1911 IntTy::Isize => sym::isize,
1912 IntTy::I8 => sym::i8,
1913 IntTy::I16 => sym::i16,
1914 IntTy::I32 => sym::i32,
1915 IntTy::I64 => sym::i64,
1916 IntTy::I128 => sym::i128,
1921 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1922 #[derive(Encodable, Decodable, HashStable_Generic)]
1933 pub fn name_str(&self) -> &'static str {
1935 UintTy::Usize => "usize",
1937 UintTy::U16 => "u16",
1938 UintTy::U32 => "u32",
1939 UintTy::U64 => "u64",
1940 UintTy::U128 => "u128",
1944 pub fn name(&self) -> Symbol {
1946 UintTy::Usize => sym::usize,
1947 UintTy::U8 => sym::u8,
1948 UintTy::U16 => sym::u16,
1949 UintTy::U32 => sym::u32,
1950 UintTy::U64 => sym::u64,
1951 UintTy::U128 => sym::u128,
1956 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1957 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1958 #[derive(Clone, Encodable, Decodable, Debug)]
1959 pub struct AssocConstraint {
1962 pub gen_args: Option<GenericArgs>,
1963 pub kind: AssocConstraintKind,
1967 /// The kinds of an `AssocConstraint`.
1968 #[derive(Clone, Encodable, Decodable, Debug)]
1974 impl From<P<Ty>> for Term {
1975 fn from(v: P<Ty>) -> Self {
1980 impl From<AnonConst> for Term {
1981 fn from(v: AnonConst) -> Self {
1986 /// The kinds of an `AssocConstraint`.
1987 #[derive(Clone, Encodable, Decodable, Debug)]
1988 pub enum AssocConstraintKind {
1989 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1990 Equality { term: Term },
1991 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1992 Bound { bounds: GenericBounds },
1995 #[derive(Encodable, Decodable, Debug)]
2000 pub tokens: Option<LazyTokenStream>,
2004 fn clone(&self) -> Self {
2005 ensure_sufficient_stack(|| Self {
2007 kind: self.kind.clone(),
2009 tokens: self.tokens.clone(),
2015 pub fn peel_refs(&self) -> &Self {
2016 let mut final_ty = self;
2017 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
2024 #[derive(Clone, Encodable, Decodable, Debug)]
2025 pub struct BareFnTy {
2026 pub unsafety: Unsafe,
2028 pub generic_params: Vec<GenericParam>,
2029 pub decl: P<FnDecl>,
2030 /// Span of the `fn(...) -> ...` part.
2031 pub decl_span: Span,
2034 /// The various kinds of type recognized by the compiler.
2035 #[derive(Clone, Encodable, Decodable, Debug)]
2037 /// A variable-length slice (`[T]`).
2039 /// A fixed length array (`[T; n]`).
2040 Array(P<Ty>, AnonConst),
2041 /// A raw pointer (`*const T` or `*mut T`).
2043 /// A reference (`&'a T` or `&'a mut T`).
2044 Rptr(Option<Lifetime>, MutTy),
2045 /// A bare function (e.g., `fn(usize) -> bool`).
2046 BareFn(P<BareFnTy>),
2047 /// The never type (`!`).
2049 /// A tuple (`(A, B, C, D,...)`).
2051 /// A path (`module::module::...::Type`), optionally
2052 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2054 /// Type parameters are stored in the `Path` itself.
2055 Path(Option<QSelf>, Path),
2056 /// A trait object type `Bound1 + Bound2 + Bound3`
2057 /// where `Bound` is a trait or a lifetime.
2058 TraitObject(GenericBounds, TraitObjectSyntax),
2059 /// An `impl Bound1 + Bound2 + Bound3` type
2060 /// where `Bound` is a trait or a lifetime.
2062 /// The `NodeId` exists to prevent lowering from having to
2063 /// generate `NodeId`s on the fly, which would complicate
2064 /// the generation of opaque `type Foo = impl Trait` items significantly.
2065 ImplTrait(NodeId, GenericBounds),
2066 /// No-op; kept solely so that we can pretty-print faithfully.
2070 /// This means the type should be inferred instead of it having been
2071 /// specified. This can appear anywhere in a type.
2073 /// Inferred type of a `self` or `&self` argument in a method.
2075 /// A macro in the type position.
2076 MacCall(P<MacCall>),
2077 /// Placeholder for a kind that has failed to be defined.
2079 /// Placeholder for a `va_list`.
2084 pub fn is_implicit_self(&self) -> bool {
2085 matches!(self, TyKind::ImplicitSelf)
2088 pub fn is_unit(&self) -> bool {
2089 matches!(self, TyKind::Tup(tys) if tys.is_empty())
2092 pub fn is_simple_path(&self) -> Option<Symbol> {
2093 if let TyKind::Path(None, Path { segments, .. }) = &self && segments.len() == 1 {
2094 Some(segments[0].ident.name)
2101 /// Syntax used to declare a trait object.
2102 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2103 pub enum TraitObjectSyntax {
2108 /// Inline assembly operand explicit register or register class.
2110 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2111 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2112 pub enum InlineAsmRegOrRegClass {
2117 bitflags::bitflags! {
2118 #[derive(Encodable, Decodable, HashStable_Generic)]
2119 pub struct InlineAsmOptions: u16 {
2120 const PURE = 1 << 0;
2121 const NOMEM = 1 << 1;
2122 const READONLY = 1 << 2;
2123 const PRESERVES_FLAGS = 1 << 3;
2124 const NORETURN = 1 << 4;
2125 const NOSTACK = 1 << 5;
2126 const ATT_SYNTAX = 1 << 6;
2128 const MAY_UNWIND = 1 << 8;
2132 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2133 pub enum InlineAsmTemplatePiece {
2135 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2138 impl fmt::Display for InlineAsmTemplatePiece {
2139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2141 Self::String(s) => {
2142 for c in s.chars() {
2144 '{' => f.write_str("{{")?,
2145 '}' => f.write_str("}}")?,
2151 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2152 write!(f, "{{{}:{}}}", operand_idx, modifier)
2154 Self::Placeholder { operand_idx, modifier: None, .. } => {
2155 write!(f, "{{{}}}", operand_idx)
2161 impl InlineAsmTemplatePiece {
2162 /// Rebuilds the asm template string from its pieces.
2163 pub fn to_string(s: &[Self]) -> String {
2165 let mut out = String::new();
2167 let _ = write!(out, "{}", p);
2173 /// Inline assembly symbol operands get their own AST node that is somewhat
2174 /// similar to `AnonConst`.
2176 /// The main difference is that we specifically don't assign it `DefId` in
2177 /// `DefCollector`. Instead this is deferred until AST lowering where we
2178 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2179 /// depending on what the path resolves to.
2180 #[derive(Clone, Encodable, Decodable, Debug)]
2181 pub struct InlineAsmSym {
2183 pub qself: Option<QSelf>,
2187 /// Inline assembly operand.
2189 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2190 #[derive(Clone, Encodable, Decodable, Debug)]
2191 pub enum InlineAsmOperand {
2193 reg: InlineAsmRegOrRegClass,
2197 reg: InlineAsmRegOrRegClass,
2199 expr: Option<P<Expr>>,
2202 reg: InlineAsmRegOrRegClass,
2207 reg: InlineAsmRegOrRegClass,
2210 out_expr: Option<P<Expr>>,
2213 anon_const: AnonConst,
2220 /// Inline assembly.
2222 /// E.g., `asm!("NOP");`.
2223 #[derive(Clone, Encodable, Decodable, Debug)]
2224 pub struct InlineAsm {
2225 pub template: Vec<InlineAsmTemplatePiece>,
2226 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2227 pub operands: Vec<(InlineAsmOperand, Span)>,
2228 pub clobber_abis: Vec<(Symbol, Span)>,
2229 pub options: InlineAsmOptions,
2230 pub line_spans: Vec<Span>,
2233 /// A parameter in a function header.
2235 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2236 #[derive(Clone, Encodable, Decodable, Debug)]
2243 pub is_placeholder: bool,
2246 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2248 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2249 #[derive(Clone, Encodable, Decodable, Debug)]
2251 /// `self`, `mut self`
2253 /// `&'lt self`, `&'lt mut self`
2254 Region(Option<Lifetime>, Mutability),
2255 /// `self: TYPE`, `mut self: TYPE`
2256 Explicit(P<Ty>, Mutability),
2259 pub type ExplicitSelf = Spanned<SelfKind>;
2262 /// Attempts to cast parameter to `ExplicitSelf`.
2263 pub fn to_self(&self) -> Option<ExplicitSelf> {
2264 if let PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), ident, _) = self.pat.kind {
2265 if ident.name == kw::SelfLower {
2266 return match self.ty.kind {
2267 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2268 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2269 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2272 self.pat.span.to(self.ty.span),
2273 SelfKind::Explicit(self.ty.clone(), mutbl),
2281 /// Returns `true` if parameter is `self`.
2282 pub fn is_self(&self) -> bool {
2283 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2284 ident.name == kw::SelfLower
2290 /// Builds a `Param` object from `ExplicitSelf`.
2291 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2292 let span = eself.span.to(eself_ident.span);
2293 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2294 let (mutbl, ty) = match eself.node {
2295 SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2296 SelfKind::Value(mutbl) => (mutbl, infer_ty),
2297 SelfKind::Region(lt, mutbl) => (
2301 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2311 kind: PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), eself_ident, None),
2318 is_placeholder: false,
2323 /// A signature (not the body) of a function declaration.
2325 /// E.g., `fn foo(bar: baz)`.
2327 /// Please note that it's different from `FnHeader` structure
2328 /// which contains metadata about function safety, asyncness, constness and ABI.
2329 #[derive(Clone, Encodable, Decodable, Debug)]
2331 pub inputs: Vec<Param>,
2332 pub output: FnRetTy,
2336 pub fn has_self(&self) -> bool {
2337 self.inputs.get(0).map_or(false, Param::is_self)
2339 pub fn c_variadic(&self) -> bool {
2340 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2344 /// Is the trait definition an auto trait?
2345 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2351 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2352 #[derive(HashStable_Generic)]
2358 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2360 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2365 pub fn is_async(self) -> bool {
2366 matches!(self, Async::Yes { .. })
2369 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2370 pub fn opt_return_id(self) -> Option<NodeId> {
2372 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2378 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2379 #[derive(HashStable_Generic)]
2385 /// Item defaultness.
2386 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2387 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2388 pub enum Defaultness {
2393 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2394 pub enum ImplPolarity {
2395 /// `impl Trait for Type`
2397 /// `impl !Trait for Type`
2401 impl fmt::Debug for ImplPolarity {
2402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2404 ImplPolarity::Positive => "positive".fmt(f),
2405 ImplPolarity::Negative(_) => "negative".fmt(f),
2410 #[derive(Clone, Encodable, Decodable, Debug)]
2412 /// Returns type is not specified.
2414 /// Functions default to `()` and closures default to inference.
2415 /// Span points to where return type would be inserted.
2417 /// Everything else.
2422 pub fn span(&self) -> Span {
2424 FnRetTy::Default(span) => span,
2425 FnRetTy::Ty(ref ty) => ty.span,
2430 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2436 /// Module item kind.
2437 #[derive(Clone, Encodable, Decodable, Debug)]
2439 /// Module with inlined definition `mod foo { ... }`,
2440 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2441 /// The inner span is from the first token past `{` to the last token until `}`,
2442 /// or from the first to the last token in the loaded file.
2443 Loaded(Vec<P<Item>>, Inline, ModSpans),
2444 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2448 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2449 pub struct ModSpans {
2450 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2451 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2452 pub inner_span: Span,
2453 pub inject_use_span: Span,
2456 impl Default for ModSpans {
2457 fn default() -> ModSpans {
2458 ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2462 /// Foreign module declaration.
2464 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2465 #[derive(Clone, Encodable, Decodable, Debug)]
2466 pub struct ForeignMod {
2467 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2468 /// semantically by Rust.
2469 pub unsafety: Unsafe,
2470 pub abi: Option<StrLit>,
2471 pub items: Vec<P<ForeignItem>>,
2474 #[derive(Clone, Encodable, Decodable, Debug)]
2475 pub struct EnumDef {
2476 pub variants: Vec<Variant>,
2479 #[derive(Clone, Encodable, Decodable, Debug)]
2480 pub struct Variant {
2481 /// Attributes of the variant.
2483 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2487 /// The visibility of the variant. Syntactically accepted but not semantically.
2488 pub vis: Visibility,
2489 /// Name of the variant.
2492 /// Fields and constructor id of the variant.
2493 pub data: VariantData,
2494 /// Explicit discriminant, e.g., `Foo = 1`.
2495 pub disr_expr: Option<AnonConst>,
2496 /// Is a macro placeholder
2497 pub is_placeholder: bool,
2500 /// Part of `use` item to the right of its prefix.
2501 #[derive(Clone, Encodable, Decodable, Debug)]
2502 pub enum UseTreeKind {
2503 /// `use prefix` or `use prefix as rename`
2505 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2507 Simple(Option<Ident>, NodeId, NodeId),
2508 /// `use prefix::{...}`
2509 Nested(Vec<(UseTree, NodeId)>),
2514 /// A tree of paths sharing common prefixes.
2515 /// Used in `use` items both at top-level and inside of braces in import groups.
2516 #[derive(Clone, Encodable, Decodable, Debug)]
2517 pub struct UseTree {
2519 pub kind: UseTreeKind,
2524 pub fn ident(&self) -> Ident {
2526 UseTreeKind::Simple(Some(rename), ..) => rename,
2527 UseTreeKind::Simple(None, ..) => {
2528 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2530 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2535 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2536 /// are contained as statements within items. These two cases need to be
2537 /// distinguished for pretty-printing.
2538 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2539 pub enum AttrStyle {
2544 rustc_index::newtype_index! {
2547 DEBUG_FORMAT = "AttrId({})"
2551 impl<S: Encoder> Encodable<S> for AttrId {
2552 fn encode(&self, _s: &mut S) {}
2555 impl<D: Decoder> Decodable<D> for AttrId {
2556 fn decode(_: &mut D) -> AttrId {
2557 crate::attr::mk_attr_id()
2561 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2562 pub struct AttrItem {
2565 pub tokens: Option<LazyTokenStream>,
2568 /// A list of attributes.
2569 pub type AttrVec = ThinVec<Attribute>;
2571 /// Metadata associated with an item.
2572 #[derive(Clone, Encodable, Decodable, Debug)]
2573 pub struct Attribute {
2576 /// Denotes if the attribute decorates the following construct (outer)
2577 /// or the construct this attribute is contained within (inner).
2578 pub style: AttrStyle,
2582 #[derive(Clone, Encodable, Decodable, Debug)]
2583 pub struct NormalAttr {
2585 pub tokens: Option<LazyTokenStream>,
2588 #[derive(Clone, Encodable, Decodable, Debug)]
2590 /// A normal attribute.
2591 Normal(P<NormalAttr>),
2593 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2594 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2595 /// variant (which is much less compact and thus more expensive).
2596 DocComment(CommentKind, Symbol),
2599 /// `TraitRef`s appear in impls.
2601 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2602 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2603 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2604 /// same as the impl's `NodeId`).
2605 #[derive(Clone, Encodable, Decodable, Debug)]
2606 pub struct TraitRef {
2611 #[derive(Clone, Encodable, Decodable, Debug)]
2612 pub struct PolyTraitRef {
2613 /// The `'a` in `for<'a> Foo<&'a T>`.
2614 pub bound_generic_params: Vec<GenericParam>,
2616 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2617 pub trait_ref: TraitRef,
2623 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2625 bound_generic_params: generic_params,
2626 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2632 #[derive(Clone, Encodable, Decodable, Debug)]
2633 pub struct Visibility {
2634 pub kind: VisibilityKind,
2636 pub tokens: Option<LazyTokenStream>,
2639 #[derive(Clone, Encodable, Decodable, Debug)]
2640 pub enum VisibilityKind {
2642 Restricted { path: P<Path>, id: NodeId, shorthand: bool },
2646 impl VisibilityKind {
2647 pub fn is_pub(&self) -> bool {
2648 matches!(self, VisibilityKind::Public)
2652 /// Field definition in a struct, variant or union.
2654 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2655 #[derive(Clone, Encodable, Decodable, Debug)]
2656 pub struct FieldDef {
2660 pub vis: Visibility,
2661 pub ident: Option<Ident>,
2664 pub is_placeholder: bool,
2667 /// Fields and constructor ids of enum variants and structs.
2668 #[derive(Clone, Encodable, Decodable, Debug)]
2669 pub enum VariantData {
2672 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2673 Struct(Vec<FieldDef>, bool),
2676 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2677 Tuple(Vec<FieldDef>, NodeId),
2680 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2685 /// Return the fields of this variant.
2686 pub fn fields(&self) -> &[FieldDef] {
2688 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2693 /// Return the `NodeId` of this variant's constructor, if it has one.
2694 pub fn ctor_id(&self) -> Option<NodeId> {
2696 VariantData::Struct(..) => None,
2697 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2702 /// An item definition.
2703 #[derive(Clone, Encodable, Decodable, Debug)]
2704 pub struct Item<K = ItemKind> {
2708 pub vis: Visibility,
2709 /// The name of the item.
2710 /// It might be a dummy name in case of anonymous items.
2715 /// Original tokens this item was parsed from. This isn't necessarily
2716 /// available for all items, although over time more and more items should
2717 /// have this be `Some`. Right now this is primarily used for procedural
2718 /// macros, notably custom attributes.
2720 /// Note that the tokens here do not include the outer attributes, but will
2721 /// include inner attributes.
2722 pub tokens: Option<LazyTokenStream>,
2726 /// Return the span that encompasses the attributes.
2727 pub fn span_with_attributes(&self) -> Span {
2728 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2732 /// `extern` qualifier on a function item or function type.
2733 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2737 Explicit(StrLit, Span),
2741 pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2743 Some(name) => Extern::Explicit(name, span),
2744 None => Extern::Implicit(span),
2749 /// A function header.
2751 /// All the information between the visibility and the name of the function is
2752 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2753 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2754 pub struct FnHeader {
2755 pub unsafety: Unsafe,
2756 pub asyncness: Async,
2757 pub constness: Const,
2762 /// Does this function header have any qualifiers or is it empty?
2763 pub fn has_qualifiers(&self) -> bool {
2764 let Self { unsafety, asyncness, constness, ext } = self;
2765 matches!(unsafety, Unsafe::Yes(_))
2766 || asyncness.is_async()
2767 || matches!(constness, Const::Yes(_))
2768 || !matches!(ext, Extern::None)
2772 impl Default for FnHeader {
2773 fn default() -> FnHeader {
2775 unsafety: Unsafe::No,
2776 asyncness: Async::No,
2777 constness: Const::No,
2783 #[derive(Clone, Encodable, Decodable, Debug)]
2785 pub unsafety: Unsafe,
2786 pub is_auto: IsAuto,
2787 pub generics: Generics,
2788 pub bounds: GenericBounds,
2789 pub items: Vec<P<AssocItem>>,
2792 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2793 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2794 /// are two locations for where clause on type aliases, but their predicates
2795 /// are concatenated together.
2797 /// Take this example:
2798 /// ```ignore (only-for-syntax-highlight)
2800 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2802 /// impl Foo for () {
2803 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2804 /// // ^^^^^^^^^^^^^^ first where clause
2805 /// // ^^^^^^^^^^^^^^ second where clause
2809 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2810 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2811 pub struct TyAliasWhereClause(pub bool, pub Span);
2813 #[derive(Clone, Encodable, Decodable, Debug)]
2814 pub struct TyAlias {
2815 pub defaultness: Defaultness,
2816 pub generics: Generics,
2817 /// The span information for the two where clauses (before equals, after equals)
2818 pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2819 /// The index in `generics.where_clause.predicates` that would split into
2820 /// predicates from the where clause before the equals and the predicates
2821 /// from the where clause after the equals
2822 pub where_predicates_split: usize,
2823 pub bounds: GenericBounds,
2824 pub ty: Option<P<Ty>>,
2827 #[derive(Clone, Encodable, Decodable, Debug)]
2829 pub defaultness: Defaultness,
2830 pub unsafety: Unsafe,
2831 pub generics: Generics,
2832 pub constness: Const,
2833 pub polarity: ImplPolarity,
2834 /// The trait being implemented, if any.
2835 pub of_trait: Option<TraitRef>,
2837 pub items: Vec<P<AssocItem>>,
2840 #[derive(Clone, Encodable, Decodable, Debug)]
2842 pub defaultness: Defaultness,
2843 pub generics: Generics,
2845 pub body: Option<P<Block>>,
2848 #[derive(Clone, Encodable, Decodable, Debug)]
2850 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2852 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2853 ExternCrate(Option<Symbol>),
2854 /// A use declaration item (`use`).
2856 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2858 /// A static item (`static`).
2860 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2861 Static(P<Ty>, Mutability, Option<P<Expr>>),
2862 /// A constant item (`const`).
2864 /// E.g., `const FOO: i32 = 42;`.
2865 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2866 /// A function declaration (`fn`).
2868 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2870 /// A module declaration (`mod`).
2872 /// E.g., `mod foo;` or `mod foo { .. }`.
2873 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2874 /// semantically by Rust.
2875 Mod(Unsafe, ModKind),
2876 /// An external module (`extern`).
2878 /// E.g., `extern {}` or `extern "C" {}`.
2879 ForeignMod(ForeignMod),
2880 /// Module-level inline assembly (from `global_asm!()`).
2881 GlobalAsm(Box<InlineAsm>),
2882 /// A type alias (`type`).
2884 /// E.g., `type Foo = Bar<u8>;`.
2885 TyAlias(Box<TyAlias>),
2886 /// An enum definition (`enum`).
2888 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2889 Enum(EnumDef, Generics),
2890 /// A struct definition (`struct`).
2892 /// E.g., `struct Foo<A> { x: A }`.
2893 Struct(VariantData, Generics),
2894 /// A union definition (`union`).
2896 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2897 Union(VariantData, Generics),
2898 /// A trait declaration (`trait`).
2900 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2904 /// E.g., `trait Foo = Bar + Quux;`.
2905 TraitAlias(Generics, GenericBounds),
2906 /// An implementation.
2908 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2910 /// A macro invocation.
2912 /// E.g., `foo!(..)`.
2913 MacCall(P<MacCall>),
2915 /// A macro definition.
2920 pub fn article(&self) -> &str {
2923 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2924 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2925 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2929 pub fn descr(&self) -> &str {
2931 ItemKind::ExternCrate(..) => "extern crate",
2932 ItemKind::Use(..) => "`use` import",
2933 ItemKind::Static(..) => "static item",
2934 ItemKind::Const(..) => "constant item",
2935 ItemKind::Fn(..) => "function",
2936 ItemKind::Mod(..) => "module",
2937 ItemKind::ForeignMod(..) => "extern block",
2938 ItemKind::GlobalAsm(..) => "global asm item",
2939 ItemKind::TyAlias(..) => "type alias",
2940 ItemKind::Enum(..) => "enum",
2941 ItemKind::Struct(..) => "struct",
2942 ItemKind::Union(..) => "union",
2943 ItemKind::Trait(..) => "trait",
2944 ItemKind::TraitAlias(..) => "trait alias",
2945 ItemKind::MacCall(..) => "item macro invocation",
2946 ItemKind::MacroDef(..) => "macro definition",
2947 ItemKind::Impl { .. } => "implementation",
2951 pub fn generics(&self) -> Option<&Generics> {
2953 Self::Fn(box Fn { generics, .. })
2954 | Self::TyAlias(box TyAlias { generics, .. })
2955 | Self::Enum(_, generics)
2956 | Self::Struct(_, generics)
2957 | Self::Union(_, generics)
2958 | Self::Trait(box Trait { generics, .. })
2959 | Self::TraitAlias(generics, _)
2960 | Self::Impl(box Impl { generics, .. }) => Some(generics),
2966 /// Represents associated items.
2967 /// These include items in `impl` and `trait` definitions.
2968 pub type AssocItem = Item<AssocItemKind>;
2970 /// Represents associated item kinds.
2972 /// The term "provided" in the variants below refers to the item having a default
2973 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2974 /// In an implementation, all items must be provided.
2975 /// The `Option`s below denote the bodies, where `Some(_)`
2976 /// means "provided" and conversely `None` means "required".
2977 #[derive(Clone, Encodable, Decodable, Debug)]
2978 pub enum AssocItemKind {
2979 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2980 /// If `def` is parsed, then the constant is provided, and otherwise required.
2981 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2982 /// An associated function.
2984 /// An associated type.
2985 TyAlias(Box<TyAlias>),
2986 /// A macro expanding to associated items.
2987 MacCall(P<MacCall>),
2990 impl AssocItemKind {
2991 pub fn defaultness(&self) -> Defaultness {
2993 Self::Const(defaultness, ..)
2994 | Self::Fn(box Fn { defaultness, .. })
2995 | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness,
2996 Self::MacCall(..) => Defaultness::Final,
3001 impl From<AssocItemKind> for ItemKind {
3002 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
3003 match assoc_item_kind {
3004 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
3005 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3006 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3007 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
3012 impl TryFrom<ItemKind> for AssocItemKind {
3013 type Error = ItemKind;
3015 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
3016 Ok(match item_kind {
3017 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
3018 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
3019 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
3020 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
3021 _ => return Err(item_kind),
3026 /// An item in `extern` block.
3027 #[derive(Clone, Encodable, Decodable, Debug)]
3028 pub enum ForeignItemKind {
3029 /// A foreign static item (`static FOO: u8`).
3030 Static(P<Ty>, Mutability, Option<P<Expr>>),
3031 /// An foreign function.
3033 /// An foreign type.
3034 TyAlias(Box<TyAlias>),
3035 /// A macro expanding to foreign items.
3036 MacCall(P<MacCall>),
3039 impl From<ForeignItemKind> for ItemKind {
3040 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3041 match foreign_item_kind {
3042 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3043 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3044 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3045 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3050 impl TryFrom<ItemKind> for ForeignItemKind {
3051 type Error = ItemKind;
3053 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3054 Ok(match item_kind {
3055 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3056 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3057 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3058 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3059 _ => return Err(item_kind),
3064 pub type ForeignItem = Item<ForeignItemKind>;
3066 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3067 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3070 use rustc_data_structures::static_assert_size;
3071 // These are in alphabetical order, which is easy to maintain.
3072 static_assert_size!(AssocItem, 104);
3073 static_assert_size!(AssocItemKind, 32);
3074 static_assert_size!(Attribute, 32);
3075 static_assert_size!(Block, 48);
3076 static_assert_size!(Expr, 104);
3077 static_assert_size!(ExprKind, 72);
3078 static_assert_size!(Fn, 192);
3079 static_assert_size!(ForeignItem, 96);
3080 static_assert_size!(ForeignItemKind, 24);
3081 static_assert_size!(GenericArg, 24);
3082 static_assert_size!(GenericBound, 88);
3083 static_assert_size!(Generics, 72);
3084 static_assert_size!(Impl, 200);
3085 static_assert_size!(Item, 184);
3086 static_assert_size!(ItemKind, 112);
3087 static_assert_size!(Lit, 48);
3088 static_assert_size!(LitKind, 24);
3089 static_assert_size!(Local, 72);
3090 static_assert_size!(Param, 40);
3091 static_assert_size!(Pat, 120);
3092 static_assert_size!(PatKind, 96);
3093 static_assert_size!(Path, 40);
3094 static_assert_size!(PathSegment, 24);
3095 static_assert_size!(Stmt, 32);
3096 static_assert_size!(StmtKind, 16);
3097 static_assert_size!(Ty, 96);
3098 static_assert_size!(TyKind, 72);