1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
26 use crate::token::{self, CommentKind, DelimToken, Token};
27 use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree};
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable_Generic;
34 use rustc_serialize::{self, Decoder, Encoder};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
39 use std::cmp::Ordering;
40 use std::convert::TryFrom;
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
55 /// `'outer` is a label.
56 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
61 impl fmt::Debug for Label {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "label({:?})", self.ident)
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, Encodable, Decodable, Copy)]
75 impl fmt::Debug for Lifetime {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "lifetime({}: {})", self.id, self)
81 impl fmt::Display for Lifetime {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "{}", self.ident.name)
87 /// A "Path" is essentially Rust's notion of a name.
89 /// It's represented as a sequence of identifiers,
90 /// along with a bunch of supporting information.
92 /// E.g., `std::cmp::PartialEq`.
93 #[derive(Clone, Encodable, Decodable, Debug)]
96 /// The segments in the path: the things separated by `::`.
97 /// Global paths begin with `kw::PathRoot`.
98 pub segments: Vec<PathSegment>,
99 pub tokens: Option<LazyTokenStream>,
102 impl PartialEq<Symbol> for Path {
103 fn eq(&self, symbol: &Symbol) -> bool {
104 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
108 impl<CTX> HashStable<CTX> for Path {
109 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
110 self.segments.len().hash_stable(hcx, hasher);
111 for segment in &self.segments {
112 segment.ident.name.hash_stable(hcx, hasher);
118 // Convert a span and an identifier to the corresponding
120 pub fn from_ident(ident: Ident) -> Path {
121 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
124 pub fn is_global(&self) -> bool {
125 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
129 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
131 /// E.g., `std`, `String` or `Box<T>`.
132 #[derive(Clone, Encodable, Decodable, Debug)]
133 pub struct PathSegment {
134 /// The identifier portion of this path segment.
139 /// Type/lifetime parameters attached to this path. They come in
140 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
141 /// `None` means that no parameter list is supplied (`Path`),
142 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
143 /// but it can be empty (`Path<>`).
144 /// `P` is used as a size optimization for the common case with no parameters.
145 pub args: Option<P<GenericArgs>>,
149 pub fn from_ident(ident: Ident) -> Self {
150 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))
157 /// The arguments of a path segment.
159 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
160 #[derive(Clone, Encodable, Decodable, Debug)]
161 pub enum GenericArgs {
162 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
163 AngleBracketed(AngleBracketedArgs),
164 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
165 Parenthesized(ParenthesizedArgs),
169 pub fn is_angle_bracketed(&self) -> bool {
170 matches!(self, AngleBracketed(..))
173 pub fn span(&self) -> Span {
175 AngleBracketed(ref data) => data.span,
176 Parenthesized(ref data) => data.span,
181 /// Concrete argument in the sequence of generic args.
182 #[derive(Clone, Encodable, Decodable, Debug)]
183 pub enum GenericArg {
184 /// `'a` in `Foo<'a>`
186 /// `Bar` in `Foo<Bar>`
193 pub fn span(&self) -> Span {
195 GenericArg::Lifetime(lt) => lt.ident.span,
196 GenericArg::Type(ty) => ty.span,
197 GenericArg::Const(ct) => ct.value.span,
202 /// A path like `Foo<'a, T>`.
203 #[derive(Clone, Encodable, Decodable, Debug, Default)]
204 pub struct AngleBracketedArgs {
205 /// The overall span.
207 /// The comma separated parts in the `<...>`.
208 pub args: Vec<AngleBracketedArg>,
211 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
212 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
213 #[derive(Clone, Encodable, Decodable, Debug)]
214 pub enum AngleBracketedArg {
215 /// Argument for a generic parameter.
217 /// Constraint for an associated item.
218 Constraint(AssocTyConstraint),
221 impl AngleBracketedArg {
222 pub fn span(&self) -> Span {
224 AngleBracketedArg::Arg(arg) => arg.span(),
225 AngleBracketedArg::Constraint(constraint) => constraint.span,
230 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
231 fn into(self) -> Option<P<GenericArgs>> {
232 Some(P(GenericArgs::AngleBracketed(self)))
236 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
237 fn into(self) -> Option<P<GenericArgs>> {
238 Some(P(GenericArgs::Parenthesized(self)))
242 /// A path like `Foo(A, B) -> C`.
243 #[derive(Clone, Encodable, Decodable, Debug)]
244 pub struct ParenthesizedArgs {
252 pub inputs: Vec<P<Ty>>,
258 pub inputs_span: Span,
264 impl ParenthesizedArgs {
265 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
270 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
272 AngleBracketedArgs { span: self.span, args }
276 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
278 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
280 /// Negative bounds should also be handled here.
281 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
282 pub enum TraitBoundModifier {
294 // This parses but will be rejected during AST validation.
298 /// The AST represents all type param bounds as types.
299 /// `typeck::collect::compute_bounds` matches these against
300 /// the "special" built-in traits (see `middle::lang_items`) and
301 /// detects `Copy`, `Send` and `Sync`.
302 #[derive(Clone, Encodable, Decodable, Debug)]
303 pub enum GenericBound {
304 Trait(PolyTraitRef, TraitBoundModifier),
309 pub fn span(&self) -> Span {
311 GenericBound::Trait(ref t, ..) => t.span,
312 GenericBound::Outlives(ref l) => l.ident.span,
317 pub type GenericBounds = Vec<GenericBound>;
319 /// Specifies the enforced ordering for generic parameters. In the future,
320 /// if we wanted to relax this order, we could override `PartialEq` and
321 /// `PartialOrd`, to allow the kinds to be unordered.
322 #[derive(Hash, Clone, Copy)]
323 pub enum ParamKindOrd {
326 // `unordered` is only `true` if `sess.has_features().const_generics`
327 // is active. Specifically, if it's only `min_const_generics`, it will still require
328 // ordering consts after types.
329 Const { unordered: bool },
332 impl Ord for ParamKindOrd {
333 fn cmp(&self, other: &Self) -> Ordering {
335 let to_int = |v| match v {
337 Type | Const { unordered: true } => 1,
338 // technically both consts should be ordered equally,
339 // but only one is ever encountered at a time, so this is
341 Const { unordered: false } => 2,
344 to_int(*self).cmp(&to_int(*other))
347 impl PartialOrd for ParamKindOrd {
348 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
349 Some(self.cmp(other))
352 impl PartialEq for ParamKindOrd {
353 fn eq(&self, other: &Self) -> bool {
354 self.cmp(other) == Ordering::Equal
357 impl Eq for ParamKindOrd {}
359 impl fmt::Display for ParamKindOrd {
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 ParamKindOrd::Lifetime => "lifetime".fmt(f),
363 ParamKindOrd::Type => "type".fmt(f),
364 ParamKindOrd::Const { .. } => "const".fmt(f),
369 #[derive(Clone, Encodable, Decodable, Debug)]
370 pub enum GenericParamKind {
371 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
374 default: Option<P<Ty>>,
378 /// Span of the `const` keyword.
380 /// Optional default value for the const generic param
381 default: Option<AnonConst>,
385 #[derive(Clone, Encodable, Decodable, Debug)]
386 pub struct GenericParam {
390 pub bounds: GenericBounds,
391 pub is_placeholder: bool,
392 pub kind: GenericParamKind,
395 /// Represents lifetime, type and const parameters attached to a declaration of
396 /// a function, enum, trait, etc.
397 #[derive(Clone, Encodable, Decodable, Debug)]
398 pub struct Generics {
399 pub params: Vec<GenericParam>,
400 pub where_clause: WhereClause,
404 impl Default for Generics {
405 /// Creates an instance of `Generics`.
406 fn default() -> Generics {
409 where_clause: WhereClause {
410 has_where_token: false,
411 predicates: Vec::new(),
419 /// A where-clause in a definition.
420 #[derive(Clone, Encodable, Decodable, Debug)]
421 pub struct WhereClause {
422 /// `true` if we ate a `where` token: this can happen
423 /// if we parsed no predicates (e.g. `struct Foo where {}`).
424 /// This allows us to accurately pretty-print
425 /// in `nt_to_tokenstream`
426 pub has_where_token: bool,
427 pub predicates: Vec<WherePredicate>,
431 /// A single predicate in a where-clause.
432 #[derive(Clone, Encodable, Decodable, Debug)]
433 pub enum WherePredicate {
434 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
435 BoundPredicate(WhereBoundPredicate),
436 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
437 RegionPredicate(WhereRegionPredicate),
438 /// An equality predicate (unsupported).
439 EqPredicate(WhereEqPredicate),
442 impl WherePredicate {
443 pub fn span(&self) -> Span {
445 WherePredicate::BoundPredicate(p) => p.span,
446 WherePredicate::RegionPredicate(p) => p.span,
447 WherePredicate::EqPredicate(p) => p.span,
454 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
455 #[derive(Clone, Encodable, Decodable, Debug)]
456 pub struct WhereBoundPredicate {
458 /// Any generics from a `for` binding.
459 pub bound_generic_params: Vec<GenericParam>,
460 /// The type being bounded.
461 pub bounded_ty: P<Ty>,
462 /// Trait and lifetime bounds (`Clone + Send + 'static`).
463 pub bounds: GenericBounds,
466 /// A lifetime predicate.
468 /// E.g., `'a: 'b + 'c`.
469 #[derive(Clone, Encodable, Decodable, Debug)]
470 pub struct WhereRegionPredicate {
472 pub lifetime: Lifetime,
473 pub bounds: GenericBounds,
476 /// An equality predicate (unsupported).
479 #[derive(Clone, Encodable, Decodable, Debug)]
480 pub struct WhereEqPredicate {
487 #[derive(Clone, Encodable, Decodable, Debug)]
489 pub attrs: Vec<Attribute>,
490 pub items: Vec<P<Item>>,
492 /// The order of items in the HIR is unrelated to the order of
493 /// items in the AST. However, we generate proc macro harnesses
494 /// based on the AST order, and later refer to these harnesses
495 /// from the HIR. This field keeps track of the order in which
496 /// we generated proc macros harnesses, so that we can map
497 /// HIR proc macros items back to their harness items.
498 pub proc_macros: Vec<NodeId>,
501 /// Possible values inside of compile-time attribute lists.
503 /// E.g., the '..' in `#[name(..)]`.
504 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
505 pub enum NestedMetaItem {
506 /// A full MetaItem, for recursive meta items.
510 /// E.g., `"foo"`, `64`, `true`.
514 /// A spanned compile-time attribute item.
516 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
517 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
518 pub struct MetaItem {
520 pub kind: MetaItemKind,
524 /// A compile-time attribute item.
526 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
527 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
528 pub enum MetaItemKind {
531 /// E.g., `test` as in `#[test]`.
535 /// E.g., `derive(..)` as in `#[derive(..)]`.
536 List(Vec<NestedMetaItem>),
537 /// Name value meta item.
539 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
543 /// A block (`{ .. }`).
545 /// E.g., `{ .. }` as in `fn foo() { .. }`.
546 #[derive(Clone, Encodable, Decodable, Debug)]
548 /// The statements in the block.
549 pub stmts: Vec<Stmt>,
551 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
552 pub rules: BlockCheckMode,
554 pub tokens: Option<LazyTokenStream>,
559 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
560 #[derive(Clone, Encodable, Decodable, Debug)]
565 pub tokens: Option<LazyTokenStream>,
569 /// Attempt reparsing the pattern as a type.
570 /// This is intended for use by diagnostics.
571 pub fn to_ty(&self) -> Option<P<Ty>> {
572 let kind = match &self.kind {
573 // In a type expression `_` is an inference variable.
574 PatKind::Wild => TyKind::Infer,
575 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
576 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
577 TyKind::Path(None, Path::from_ident(*ident))
579 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
580 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
581 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
582 PatKind::Ref(pat, mutbl) => {
583 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
585 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
586 // when `P` can be reparsed as a type `T`.
587 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
588 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
589 // assuming `T0` to `Tn` are all syntactically valid as types.
590 PatKind::Tuple(pats) => {
591 let mut tys = Vec::with_capacity(pats.len());
592 // FIXME(#48994) - could just be collected into an Option<Vec>
594 tys.push(pat.to_ty()?);
601 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
604 /// Walk top-down and call `it` in each place where a pattern occurs
605 /// starting with the root pattern `walk` is called on. If `it` returns
606 /// false then we will descend no further but siblings will be processed.
607 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
613 // Walk into the pattern associated with `Ident` (if any).
614 PatKind::Ident(_, _, Some(p)) => p.walk(it),
616 // Walk into each field of struct.
617 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
619 // Sequence of patterns.
620 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
621 s.iter().for_each(|p| p.walk(it))
624 // Trivial wrappers over inner patterns.
625 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
627 // These patterns do not contain subpatterns, skip.
634 | PatKind::MacCall(_) => {}
638 /// Is this a `..` pattern?
639 pub fn is_rest(&self) -> bool {
640 matches!(self.kind, PatKind::Rest)
644 /// A single field in a struct pattern.
646 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
647 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
648 /// except when `is_shorthand` is true.
649 #[derive(Clone, Encodable, Decodable, Debug)]
650 pub struct FieldPat {
651 /// The identifier for the field.
653 /// The pattern the field is destructured to.
655 pub is_shorthand: bool,
659 pub is_placeholder: bool,
662 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
663 pub enum BindingMode {
668 #[derive(Clone, Encodable, Decodable, Debug)]
670 Included(RangeSyntax),
674 #[derive(Clone, Encodable, Decodable, Debug)]
675 pub enum RangeSyntax {
682 #[derive(Clone, Encodable, Decodable, Debug)]
684 /// Represents a wildcard pattern (`_`).
687 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
688 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
689 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
690 /// during name resolution.
691 Ident(BindingMode, Ident, Option<P<Pat>>),
693 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
694 /// The `bool` is `true` in the presence of a `..`.
695 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
697 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
698 TupleStruct(Path, Vec<P<Pat>>),
700 /// An or-pattern `A | B | C`.
701 /// Invariant: `pats.len() >= 2`.
704 /// A possibly qualified path pattern.
705 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
706 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
707 /// only legally refer to associated constants.
708 Path(Option<QSelf>, Path),
710 /// A tuple pattern (`(a, b)`).
716 /// A reference pattern (e.g., `&mut (a, b)`).
717 Ref(P<Pat>, Mutability),
722 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
723 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
725 /// A slice pattern `[a, b, c]`.
728 /// A rest pattern `..`.
730 /// Syntactically it is valid anywhere.
732 /// Semantically however, it only has meaning immediately inside:
733 /// - a slice pattern: `[a, .., b]`,
734 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
735 /// - a tuple pattern: `(a, .., b)`,
736 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
738 /// In all of these cases, an additional restriction applies,
739 /// only one rest pattern may occur in the pattern sequences.
742 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
745 /// A macro pattern; pre-expansion.
749 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
750 #[derive(HashStable_Generic, Encodable, Decodable)]
751 pub enum Mutability {
757 /// Returns `MutMutable` only if both `self` and `other` are mutable.
758 pub fn and(self, other: Self) -> Self {
760 Mutability::Mut => other,
761 Mutability::Not => Mutability::Not,
765 pub fn invert(self) -> Self {
767 Mutability::Mut => Mutability::Not,
768 Mutability::Not => Mutability::Mut,
772 pub fn prefix_str(&self) -> &'static str {
774 Mutability::Mut => "mut ",
775 Mutability::Not => "",
780 /// The kind of borrow in an `AddrOf` expression,
781 /// e.g., `&place` or `&raw const place`.
782 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
783 #[derive(Encodable, Decodable, HashStable_Generic)]
784 pub enum BorrowKind {
785 /// A normal borrow, `&$expr` or `&mut $expr`.
786 /// The resulting type is either `&'a T` or `&'a mut T`
787 /// where `T = typeof($expr)` and `'a` is some lifetime.
789 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
790 /// The resulting type is either `*const T` or `*mut T`
791 /// where `T = typeof($expr)`.
795 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
797 /// The `+` operator (addition)
799 /// The `-` operator (subtraction)
801 /// The `*` operator (multiplication)
803 /// The `/` operator (division)
805 /// The `%` operator (modulus)
807 /// The `&&` operator (logical and)
809 /// The `||` operator (logical or)
811 /// The `^` operator (bitwise xor)
813 /// The `&` operator (bitwise and)
815 /// The `|` operator (bitwise or)
817 /// The `<<` operator (shift left)
819 /// The `>>` operator (shift right)
821 /// The `==` operator (equality)
823 /// The `<` operator (less than)
825 /// The `<=` operator (less than or equal to)
827 /// The `!=` operator (not equal to)
829 /// The `>=` operator (greater than or equal to)
831 /// The `>` operator (greater than)
836 pub fn to_string(&self) -> &'static str {
859 pub fn lazy(&self) -> bool {
860 matches!(self, BinOpKind::And | BinOpKind::Or)
863 pub fn is_comparison(&self) -> bool {
865 // Note for developers: please keep this as is;
866 // we want compilation to fail if another variant is added.
868 Eq | Lt | Le | Ne | Gt | Ge => true,
869 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
874 pub type BinOp = Spanned<BinOpKind>;
878 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
879 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
881 /// The `*` operator for dereferencing
883 /// The `!` operator for logical inversion
885 /// The `-` operator for negation
890 pub fn to_string(op: UnOp) -> &'static str {
900 #[derive(Clone, Encodable, Decodable, Debug)]
908 pub fn tokens(&self) -> Option<&LazyTokenStream> {
910 StmtKind::Local(ref local) => local.tokens.as_ref(),
911 StmtKind::Item(ref item) => item.tokens.as_ref(),
912 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(),
913 StmtKind::Empty => None,
914 StmtKind::MacCall(ref mac) => mac.tokens.as_ref(),
918 pub fn has_trailing_semicolon(&self) -> bool {
920 StmtKind::Semi(_) => true,
921 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
926 /// Converts a parsed `Stmt` to a `Stmt` with
927 /// a trailing semicolon.
929 /// This only modifies the parsed AST struct, not the attached
930 /// `LazyTokenStream`. The parser is responsible for calling
931 /// `CreateTokenStream::add_trailing_semi` when there is actually
932 /// a semicolon in the tokenstream.
933 pub fn add_trailing_semicolon(mut self) -> Self {
934 self.kind = match self.kind {
935 StmtKind::Expr(expr) => StmtKind::Semi(expr),
936 StmtKind::MacCall(mac) => {
937 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
938 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
947 pub fn is_item(&self) -> bool {
948 matches!(self.kind, StmtKind::Item(_))
951 pub fn is_expr(&self) -> bool {
952 matches!(self.kind, StmtKind::Expr(_))
956 #[derive(Clone, Encodable, Decodable, Debug)]
958 /// A local (let) binding.
960 /// An item definition.
962 /// Expr without trailing semi-colon.
964 /// Expr with a trailing semi-colon.
966 /// Just a trailing semi-colon.
969 MacCall(P<MacCallStmt>),
972 #[derive(Clone, Encodable, Decodable, Debug)]
973 pub struct MacCallStmt {
975 pub style: MacStmtStyle,
977 pub tokens: Option<LazyTokenStream>,
980 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
981 pub enum MacStmtStyle {
982 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
983 /// `foo!(...);`, `foo![...];`).
985 /// The macro statement had braces (e.g., `foo! { ... }`).
987 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
988 /// `foo!(...)`). All of these will end up being converted into macro
993 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
994 #[derive(Clone, Encodable, Decodable, Debug)]
998 pub ty: Option<P<Ty>>,
999 /// Initializer expression to set the value, if any.
1000 pub init: Option<P<Expr>>,
1003 pub tokens: Option<LazyTokenStream>,
1006 /// An arm of a 'match'.
1008 /// E.g., `0..=10 => { println!("match!") }` as in
1012 /// 0..=10 => { println!("match!") },
1013 /// _ => { println!("no match!") },
1016 #[derive(Clone, Encodable, Decodable, Debug)]
1018 pub attrs: Vec<Attribute>,
1019 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1021 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1022 pub guard: Option<P<Expr>>,
1027 pub is_placeholder: bool,
1030 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1031 #[derive(Clone, Encodable, Decodable, Debug)]
1038 pub is_shorthand: bool,
1039 pub is_placeholder: bool,
1042 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1043 pub enum BlockCheckMode {
1045 Unsafe(UnsafeSource),
1048 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1049 pub enum UnsafeSource {
1054 /// A constant (expression) that's not an item or associated item,
1055 /// but needs its own `DefId` for type-checking, const-eval, etc.
1056 /// These are usually found nested inside types (e.g., array lengths)
1057 /// or expressions (e.g., repeat counts), and also used to define
1058 /// explicit discriminant values for enum variants.
1059 #[derive(Clone, Encodable, Decodable, Debug)]
1060 pub struct AnonConst {
1066 #[derive(Clone, Encodable, Decodable, Debug)]
1072 pub tokens: Option<LazyTokenStream>,
1075 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1076 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1077 rustc_data_structures::static_assert_size!(Expr, 120);
1080 /// Returns `true` if this expression would be valid somewhere that expects a value;
1081 /// for example, an `if` condition.
1082 pub fn returns(&self) -> bool {
1083 if let ExprKind::Block(ref block, _) = self.kind {
1084 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1086 Some(StmtKind::Expr(_)) => true,
1087 // Last statement is an explicit return?
1088 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1089 // This is a block that doesn't end in either an implicit or explicit return.
1093 // This is not a block, it is a value.
1098 /// Is this expr either `N`, or `{ N }`.
1100 /// If this is not the case, name resolution does not resolve `N` when using
1101 /// `min_const_generics` as more complex expressions are not supported.
1102 pub fn is_potential_trivial_const_param(&self) -> bool {
1103 let this = if let ExprKind::Block(ref block, None) = self.kind {
1104 if block.stmts.len() == 1 {
1105 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1113 if let ExprKind::Path(None, ref path) = this.kind {
1114 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1122 pub fn to_bound(&self) -> Option<GenericBound> {
1124 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1125 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1126 TraitBoundModifier::None,
1132 pub fn peel_parens(&self) -> &Expr {
1133 let mut expr = self;
1134 while let ExprKind::Paren(inner) = &expr.kind {
1140 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1141 pub fn to_ty(&self) -> Option<P<Ty>> {
1142 let kind = match &self.kind {
1143 // Trivial conversions.
1144 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1145 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1147 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1149 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1150 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1153 ExprKind::Repeat(expr, expr_len) => {
1154 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1157 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1159 ExprKind::Tup(exprs) => {
1160 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1164 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1165 // then type of result is trait object.
1166 // Otherwise we don't assume the result type.
1167 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1168 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1169 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1175 // This expression doesn't look like a type syntactically.
1179 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1182 pub fn precedence(&self) -> ExprPrecedence {
1184 ExprKind::Box(_) => ExprPrecedence::Box,
1185 ExprKind::Array(_) => ExprPrecedence::Array,
1186 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1187 ExprKind::Call(..) => ExprPrecedence::Call,
1188 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1189 ExprKind::Tup(_) => ExprPrecedence::Tup,
1190 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1191 ExprKind::Unary(..) => ExprPrecedence::Unary,
1192 ExprKind::Lit(_) => ExprPrecedence::Lit,
1193 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1194 ExprKind::Let(..) => ExprPrecedence::Let,
1195 ExprKind::If(..) => ExprPrecedence::If,
1196 ExprKind::While(..) => ExprPrecedence::While,
1197 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1198 ExprKind::Loop(..) => ExprPrecedence::Loop,
1199 ExprKind::Match(..) => ExprPrecedence::Match,
1200 ExprKind::Closure(..) => ExprPrecedence::Closure,
1201 ExprKind::Block(..) => ExprPrecedence::Block,
1202 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1203 ExprKind::Async(..) => ExprPrecedence::Async,
1204 ExprKind::Await(..) => ExprPrecedence::Await,
1205 ExprKind::Assign(..) => ExprPrecedence::Assign,
1206 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1207 ExprKind::Field(..) => ExprPrecedence::Field,
1208 ExprKind::Index(..) => ExprPrecedence::Index,
1209 ExprKind::Range(..) => ExprPrecedence::Range,
1210 ExprKind::Underscore => ExprPrecedence::Path,
1211 ExprKind::Path(..) => ExprPrecedence::Path,
1212 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1213 ExprKind::Break(..) => ExprPrecedence::Break,
1214 ExprKind::Continue(..) => ExprPrecedence::Continue,
1215 ExprKind::Ret(..) => ExprPrecedence::Ret,
1216 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1217 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1218 ExprKind::Struct(..) => ExprPrecedence::Struct,
1219 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1220 ExprKind::Paren(..) => ExprPrecedence::Paren,
1221 ExprKind::Try(..) => ExprPrecedence::Try,
1222 ExprKind::Yield(..) => ExprPrecedence::Yield,
1223 ExprKind::Err => ExprPrecedence::Err,
1228 /// Limit types of a range (inclusive or exclusive)
1229 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1230 pub enum RangeLimits {
1231 /// Inclusive at the beginning, exclusive at the end
1233 /// Inclusive at the beginning and end
1237 #[derive(Clone, Encodable, Decodable, Debug)]
1238 pub enum StructRest {
1243 /// No trailing `..` or expression.
1247 #[derive(Clone, Encodable, Decodable, Debug)]
1249 /// A `box x` expression.
1251 /// An array (`[a, b, c, d]`)
1252 Array(Vec<P<Expr>>),
1253 /// Allow anonymous constants from an inline `const` block
1254 ConstBlock(AnonConst),
1257 /// The first field resolves to the function itself,
1258 /// and the second field is the list of arguments.
1259 /// This also represents calling the constructor of
1260 /// tuple-like ADTs such as tuple structs and enum variants.
1261 Call(P<Expr>, Vec<P<Expr>>),
1262 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1264 /// The `PathSegment` represents the method name and its generic arguments
1265 /// (within the angle brackets).
1266 /// The first element of the vector of an `Expr` is the expression that evaluates
1267 /// to the object on which the method is being called on (the receiver),
1268 /// and the remaining elements are the rest of the arguments.
1269 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1270 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1271 /// This `Span` is the span of the function, without the dot and receiver
1272 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1273 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1274 /// A tuple (e.g., `(a, b, c, d)`).
1276 /// A binary operation (e.g., `a + b`, `a * b`).
1277 Binary(BinOp, P<Expr>, P<Expr>),
1278 /// A unary operation (e.g., `!x`, `*x`).
1279 Unary(UnOp, P<Expr>),
1280 /// A literal (e.g., `1`, `"foo"`).
1282 /// A cast (e.g., `foo as f64`).
1283 Cast(P<Expr>, P<Ty>),
1284 /// A type ascription (e.g., `42: usize`).
1285 Type(P<Expr>, P<Ty>),
1286 /// A `let pat = expr` expression that is only semantically allowed in the condition
1287 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1288 Let(P<Pat>, P<Expr>),
1289 /// An `if` block, with an optional `else` block.
1291 /// `if expr { block } else { expr }`
1292 If(P<Expr>, P<Block>, Option<P<Expr>>),
1293 /// A while loop, with an optional label.
1295 /// `'label: while expr { block }`
1296 While(P<Expr>, P<Block>, Option<Label>),
1297 /// A `for` loop, with an optional label.
1299 /// `'label: for pat in expr { block }`
1301 /// This is desugared to a combination of `loop` and `match` expressions.
1302 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1303 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1305 /// `'label: loop { block }`
1306 Loop(P<Block>, Option<Label>),
1307 /// A `match` block.
1308 Match(P<Expr>, Vec<Arm>),
1309 /// A closure (e.g., `move |a, b, c| a + b + c`).
1311 /// The final span is the span of the argument block `|...|`.
1312 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1313 /// A block (`'label: { ... }`).
1314 Block(P<Block>, Option<Label>),
1315 /// An async block (`async move { ... }`).
1317 /// The `NodeId` is the `NodeId` for the closure that results from
1318 /// desugaring an async block, just like the NodeId field in the
1319 /// `Async::Yes` variant. This is necessary in order to create a def for the
1320 /// closure which can be used as a parent of any child defs. Defs
1321 /// created during lowering cannot be made the parent of any other
1322 /// preexisting defs.
1323 Async(CaptureBy, NodeId, P<Block>),
1324 /// An await expression (`my_future.await`).
1327 /// A try block (`try { ... }`).
1330 /// An assignment (`a = foo()`).
1331 /// The `Span` argument is the span of the `=` token.
1332 Assign(P<Expr>, P<Expr>, Span),
1333 /// An assignment with an operator.
1336 AssignOp(BinOp, P<Expr>, P<Expr>),
1337 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1338 Field(P<Expr>, Ident),
1339 /// An indexing operation (e.g., `foo[2]`).
1340 Index(P<Expr>, P<Expr>),
1341 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assingment).
1342 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1343 /// An underscore, used in destructuring assignment to ignore a value.
1346 /// Variable reference, possibly containing `::` and/or type
1347 /// parameters (e.g., `foo::bar::<baz>`).
1349 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1350 Path(Option<QSelf>, Path),
1352 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1353 AddrOf(BorrowKind, Mutability, P<Expr>),
1354 /// A `break`, with an optional label to break, and an optional expression.
1355 Break(Option<Label>, Option<P<Expr>>),
1356 /// A `continue`, with an optional label.
1357 Continue(Option<Label>),
1358 /// A `return`, with an optional value to be returned.
1359 Ret(Option<P<Expr>>),
1361 /// Output of the `asm!()` macro.
1362 InlineAsm(P<InlineAsm>),
1363 /// Output of the `llvm_asm!()` macro.
1364 LlvmInlineAsm(P<LlvmInlineAsm>),
1366 /// A macro invocation; pre-expansion.
1369 /// A struct literal expression.
1371 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1372 Struct(Path, Vec<Field>, StructRest),
1374 /// An array literal constructed from one repeated element.
1376 /// E.g., `[1; 5]`. The expression is the element to be
1377 /// repeated; the constant is the number of times to repeat it.
1378 Repeat(P<Expr>, AnonConst),
1380 /// No-op: used solely so we can pretty-print faithfully.
1383 /// A try expression (`expr?`).
1386 /// A `yield`, with an optional value to be yielded.
1387 Yield(Option<P<Expr>>),
1389 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1393 /// The explicit `Self` type in a "qualified path". The actual
1394 /// path, including the trait and the associated item, is stored
1395 /// separately. `position` represents the index of the associated
1396 /// item qualified with this `Self` type.
1398 /// ```ignore (only-for-syntax-highlight)
1399 /// <Vec<T> as a::b::Trait>::AssociatedItem
1400 /// ^~~~~ ~~~~~~~~~~~~~~^
1403 /// <Vec<T>>::AssociatedItem
1407 #[derive(Clone, Encodable, Decodable, Debug)]
1411 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1412 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1413 /// 0`, this is an empty span.
1414 pub path_span: Span,
1415 pub position: usize,
1418 /// A capture clause used in closures and `async` blocks.
1419 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1420 pub enum CaptureBy {
1421 /// `move |x| y + x`.
1423 /// `move` keyword was not specified.
1427 /// The movability of a generator / closure literal:
1428 /// whether a generator contains self-references, causing it to be `!Unpin`.
1429 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1430 #[derive(HashStable_Generic)]
1431 pub enum Movability {
1432 /// May contain self-references, `!Unpin`.
1434 /// Must not contain self-references, `Unpin`.
1438 /// Represents a macro invocation. The `path` indicates which macro
1439 /// is being invoked, and the `args` are arguments passed to it.
1440 #[derive(Clone, Encodable, Decodable, Debug)]
1441 pub struct MacCall {
1443 pub args: P<MacArgs>,
1444 pub prior_type_ascription: Option<(Span, bool)>,
1448 pub fn span(&self) -> Span {
1449 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1453 /// Arguments passed to an attribute or a function-like macro.
1454 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1456 /// No arguments - `#[attr]`.
1458 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1459 Delimited(DelimSpan, MacDelimiter, TokenStream),
1460 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1462 /// Span of the `=` token.
1464 /// "value" as a nonterminal token.
1470 pub fn delim(&self) -> DelimToken {
1472 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1473 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1477 pub fn span(&self) -> Option<Span> {
1479 MacArgs::Empty => None,
1480 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1481 MacArgs::Eq(eq_span, token) => Some(eq_span.to(token.span)),
1485 /// Tokens inside the delimiters or after `=`.
1486 /// Proc macros see these tokens, for example.
1487 pub fn inner_tokens(&self) -> TokenStream {
1489 MacArgs::Empty => TokenStream::default(),
1490 MacArgs::Delimited(.., tokens) => tokens.clone(),
1491 MacArgs::Eq(.., token) => TokenTree::Token(token.clone()).into(),
1495 /// Whether a macro with these arguments needs a semicolon
1496 /// when used as a standalone item or statement.
1497 pub fn need_semicolon(&self) -> bool {
1498 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1502 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1503 pub enum MacDelimiter {
1510 pub fn to_token(self) -> DelimToken {
1512 MacDelimiter::Parenthesis => DelimToken::Paren,
1513 MacDelimiter::Bracket => DelimToken::Bracket,
1514 MacDelimiter::Brace => DelimToken::Brace,
1518 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1520 token::Paren => Some(MacDelimiter::Parenthesis),
1521 token::Bracket => Some(MacDelimiter::Bracket),
1522 token::Brace => Some(MacDelimiter::Brace),
1523 token::NoDelim => None,
1528 /// Represents a macro definition.
1529 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1530 pub struct MacroDef {
1531 pub body: P<MacArgs>,
1532 /// `true` if macro was defined with `macro_rules`.
1533 pub macro_rules: bool,
1536 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1537 #[derive(HashStable_Generic)]
1539 /// A regular string, like `"foo"`.
1541 /// A raw string, like `r##"foo"##`.
1543 /// The value is the number of `#` symbols used.
1548 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1550 /// The original literal token as written in source code.
1551 pub token: token::Lit,
1552 /// The "semantic" representation of the literal lowered from the original tokens.
1553 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1554 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1559 /// Same as `Lit`, but restricted to string literals.
1560 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1562 /// The original literal token as written in source code.
1563 pub style: StrStyle,
1565 pub suffix: Option<Symbol>,
1567 /// The unescaped "semantic" representation of the literal lowered from the original token.
1568 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1569 pub symbol_unescaped: Symbol,
1573 pub fn as_lit(&self) -> Lit {
1574 let token_kind = match self.style {
1575 StrStyle::Cooked => token::Str,
1576 StrStyle::Raw(n) => token::StrRaw(n),
1579 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1581 kind: LitKind::Str(self.symbol_unescaped, self.style),
1586 /// Type of the integer literal based on provided suffix.
1587 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1588 #[derive(HashStable_Generic)]
1589 pub enum LitIntType {
1598 /// Type of the float literal based on provided suffix.
1599 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1600 #[derive(HashStable_Generic)]
1601 pub enum LitFloatType {
1602 /// A float literal with a suffix (`1f32` or `1E10f32`).
1604 /// A float literal without a suffix (`1.0 or 1.0E10`).
1610 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1611 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1613 /// A string literal (`"foo"`).
1614 Str(Symbol, StrStyle),
1615 /// A byte string (`b"foo"`).
1617 /// A byte char (`b'f'`).
1619 /// A character literal (`'a'`).
1621 /// An integer literal (`1`).
1622 Int(u128, LitIntType),
1623 /// A float literal (`1f64` or `1E10f64`).
1624 Float(Symbol, LitFloatType),
1625 /// A boolean literal.
1627 /// Placeholder for a literal that wasn't well-formed in some way.
1632 /// Returns `true` if this literal is a string.
1633 pub fn is_str(&self) -> bool {
1634 matches!(self, LitKind::Str(..))
1637 /// Returns `true` if this literal is byte literal string.
1638 pub fn is_bytestr(&self) -> bool {
1639 matches!(self, LitKind::ByteStr(_))
1642 /// Returns `true` if this is a numeric literal.
1643 pub fn is_numeric(&self) -> bool {
1644 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1647 /// Returns `true` if this literal has no suffix.
1648 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1649 pub fn is_unsuffixed(&self) -> bool {
1653 /// Returns `true` if this literal has a suffix.
1654 pub fn is_suffixed(&self) -> bool {
1656 // suffixed variants
1657 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1658 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1659 // unsuffixed variants
1661 | LitKind::ByteStr(..)
1664 | LitKind::Int(_, LitIntType::Unsuffixed)
1665 | LitKind::Float(_, LitFloatType::Unsuffixed)
1667 | LitKind::Err(..) => false,
1672 // N.B., If you change this, you'll probably want to change the corresponding
1673 // type structure in `middle/ty.rs` as well.
1674 #[derive(Clone, Encodable, Decodable, Debug)]
1677 pub mutbl: Mutability,
1680 /// Represents a function's signature in a trait declaration,
1681 /// trait implementation, or free function.
1682 #[derive(Clone, Encodable, Decodable, Debug)]
1684 pub header: FnHeader,
1685 pub decl: P<FnDecl>,
1689 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1690 #[derive(Encodable, Decodable, HashStable_Generic)]
1697 pub fn name_str(self) -> &'static str {
1699 FloatTy::F32 => "f32",
1700 FloatTy::F64 => "f64",
1704 pub fn name(self) -> Symbol {
1706 FloatTy::F32 => sym::f32,
1707 FloatTy::F64 => sym::f64,
1711 pub fn bit_width(self) -> u64 {
1719 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1720 #[derive(Encodable, Decodable, HashStable_Generic)]
1731 pub fn name_str(&self) -> &'static str {
1733 IntTy::Isize => "isize",
1735 IntTy::I16 => "i16",
1736 IntTy::I32 => "i32",
1737 IntTy::I64 => "i64",
1738 IntTy::I128 => "i128",
1742 pub fn name(&self) -> Symbol {
1744 IntTy::Isize => sym::isize,
1745 IntTy::I8 => sym::i8,
1746 IntTy::I16 => sym::i16,
1747 IntTy::I32 => sym::i32,
1748 IntTy::I64 => sym::i64,
1749 IntTy::I128 => sym::i128,
1753 pub fn bit_width(&self) -> Option<u64> {
1755 IntTy::Isize => return None,
1764 pub fn normalize(&self, target_width: u32) -> Self {
1766 IntTy::Isize => match target_width {
1770 _ => unreachable!(),
1777 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1778 #[derive(Encodable, Decodable, HashStable_Generic)]
1789 pub fn name_str(&self) -> &'static str {
1791 UintTy::Usize => "usize",
1793 UintTy::U16 => "u16",
1794 UintTy::U32 => "u32",
1795 UintTy::U64 => "u64",
1796 UintTy::U128 => "u128",
1800 pub fn name(&self) -> Symbol {
1802 UintTy::Usize => sym::usize,
1803 UintTy::U8 => sym::u8,
1804 UintTy::U16 => sym::u16,
1805 UintTy::U32 => sym::u32,
1806 UintTy::U64 => sym::u64,
1807 UintTy::U128 => sym::u128,
1811 pub fn bit_width(&self) -> Option<u64> {
1813 UintTy::Usize => return None,
1818 UintTy::U128 => 128,
1822 pub fn normalize(&self, target_width: u32) -> Self {
1824 UintTy::Usize => match target_width {
1828 _ => unreachable!(),
1835 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1836 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1837 #[derive(Clone, Encodable, Decodable, Debug)]
1838 pub struct AssocTyConstraint {
1841 pub gen_args: Option<GenericArgs>,
1842 pub kind: AssocTyConstraintKind,
1846 /// The kinds of an `AssocTyConstraint`.
1847 #[derive(Clone, Encodable, Decodable, Debug)]
1848 pub enum AssocTyConstraintKind {
1849 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1850 Equality { ty: P<Ty> },
1851 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1852 Bound { bounds: GenericBounds },
1855 #[derive(Encodable, Decodable, Debug)]
1860 pub tokens: Option<LazyTokenStream>,
1864 fn clone(&self) -> Self {
1865 ensure_sufficient_stack(|| Self {
1867 kind: self.kind.clone(),
1869 tokens: self.tokens.clone(),
1875 pub fn peel_refs(&self) -> &Self {
1876 let mut final_ty = self;
1877 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1884 #[derive(Clone, Encodable, Decodable, Debug)]
1885 pub struct BareFnTy {
1886 pub unsafety: Unsafe,
1888 pub generic_params: Vec<GenericParam>,
1889 pub decl: P<FnDecl>,
1892 /// The various kinds of type recognized by the compiler.
1893 #[derive(Clone, Encodable, Decodable, Debug)]
1895 /// A variable-length slice (`[T]`).
1897 /// A fixed length array (`[T; n]`).
1898 Array(P<Ty>, AnonConst),
1899 /// A raw pointer (`*const T` or `*mut T`).
1901 /// A reference (`&'a T` or `&'a mut T`).
1902 Rptr(Option<Lifetime>, MutTy),
1903 /// A bare function (e.g., `fn(usize) -> bool`).
1904 BareFn(P<BareFnTy>),
1905 /// The never type (`!`).
1907 /// A tuple (`(A, B, C, D,...)`).
1909 /// A path (`module::module::...::Type`), optionally
1910 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1912 /// Type parameters are stored in the `Path` itself.
1913 Path(Option<QSelf>, Path),
1914 /// A trait object type `Bound1 + Bound2 + Bound3`
1915 /// where `Bound` is a trait or a lifetime.
1916 TraitObject(GenericBounds, TraitObjectSyntax),
1917 /// An `impl Bound1 + Bound2 + Bound3` type
1918 /// where `Bound` is a trait or a lifetime.
1920 /// The `NodeId` exists to prevent lowering from having to
1921 /// generate `NodeId`s on the fly, which would complicate
1922 /// the generation of opaque `type Foo = impl Trait` items significantly.
1923 ImplTrait(NodeId, GenericBounds),
1924 /// No-op; kept solely so that we can pretty-print faithfully.
1928 /// This means the type should be inferred instead of it having been
1929 /// specified. This can appear anywhere in a type.
1931 /// Inferred type of a `self` or `&self` argument in a method.
1933 /// A macro in the type position.
1935 /// Placeholder for a kind that has failed to be defined.
1937 /// Placeholder for a `va_list`.
1942 pub fn is_implicit_self(&self) -> bool {
1943 matches!(self, TyKind::ImplicitSelf)
1946 pub fn is_unit(&self) -> bool {
1947 matches!(self, TyKind::Tup(tys) if tys.is_empty())
1951 /// Syntax used to declare a trait object.
1952 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1953 pub enum TraitObjectSyntax {
1958 /// Inline assembly operand explicit register or register class.
1960 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1961 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1962 pub enum InlineAsmRegOrRegClass {
1967 bitflags::bitflags! {
1968 #[derive(Encodable, Decodable, HashStable_Generic)]
1969 pub struct InlineAsmOptions: u8 {
1970 const PURE = 1 << 0;
1971 const NOMEM = 1 << 1;
1972 const READONLY = 1 << 2;
1973 const PRESERVES_FLAGS = 1 << 3;
1974 const NORETURN = 1 << 4;
1975 const NOSTACK = 1 << 5;
1976 const ATT_SYNTAX = 1 << 6;
1980 #[derive(Clone, PartialEq, PartialOrd, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
1981 pub enum InlineAsmTemplatePiece {
1983 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1986 impl fmt::Display for InlineAsmTemplatePiece {
1987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1989 Self::String(s) => {
1990 for c in s.chars() {
1992 '{' => f.write_str("{{")?,
1993 '}' => f.write_str("}}")?,
1999 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2000 write!(f, "{{{}:{}}}", operand_idx, modifier)
2002 Self::Placeholder { operand_idx, modifier: None, .. } => {
2003 write!(f, "{{{}}}", operand_idx)
2009 impl InlineAsmTemplatePiece {
2010 /// Rebuilds the asm template string from its pieces.
2011 pub fn to_string(s: &[Self]) -> String {
2013 let mut out = String::new();
2015 let _ = write!(out, "{}", p);
2021 /// Inline assembly operand.
2023 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2024 #[derive(Clone, Encodable, Decodable, Debug)]
2025 pub enum InlineAsmOperand {
2027 reg: InlineAsmRegOrRegClass,
2031 reg: InlineAsmRegOrRegClass,
2033 expr: Option<P<Expr>>,
2036 reg: InlineAsmRegOrRegClass,
2041 reg: InlineAsmRegOrRegClass,
2044 out_expr: Option<P<Expr>>,
2054 /// Inline assembly.
2056 /// E.g., `asm!("NOP");`.
2057 #[derive(Clone, Encodable, Decodable, Debug)]
2058 pub struct InlineAsm {
2059 pub template: Vec<InlineAsmTemplatePiece>,
2060 pub operands: Vec<(InlineAsmOperand, Span)>,
2061 pub options: InlineAsmOptions,
2062 pub line_spans: Vec<Span>,
2065 /// Inline assembly dialect.
2067 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2068 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Hash, HashStable_Generic)]
2069 pub enum LlvmAsmDialect {
2074 /// LLVM-style inline assembly.
2076 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2077 #[derive(Clone, Encodable, Decodable, Debug)]
2078 pub struct LlvmInlineAsmOutput {
2079 pub constraint: Symbol,
2082 pub is_indirect: bool,
2085 /// LLVM-style inline assembly.
2087 /// E.g., `llvm_asm!("NOP");`.
2088 #[derive(Clone, Encodable, Decodable, Debug)]
2089 pub struct LlvmInlineAsm {
2091 pub asm_str_style: StrStyle,
2092 pub outputs: Vec<LlvmInlineAsmOutput>,
2093 pub inputs: Vec<(Symbol, P<Expr>)>,
2094 pub clobbers: Vec<Symbol>,
2096 pub alignstack: bool,
2097 pub dialect: LlvmAsmDialect,
2100 /// A parameter in a function header.
2102 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2103 #[derive(Clone, Encodable, Decodable, Debug)]
2110 pub is_placeholder: bool,
2113 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2115 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2116 #[derive(Clone, Encodable, Decodable, Debug)]
2118 /// `self`, `mut self`
2120 /// `&'lt self`, `&'lt mut self`
2121 Region(Option<Lifetime>, Mutability),
2122 /// `self: TYPE`, `mut self: TYPE`
2123 Explicit(P<Ty>, Mutability),
2126 pub type ExplicitSelf = Spanned<SelfKind>;
2129 /// Attempts to cast parameter to `ExplicitSelf`.
2130 pub fn to_self(&self) -> Option<ExplicitSelf> {
2131 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2132 if ident.name == kw::SelfLower {
2133 return match self.ty.kind {
2134 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2135 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2136 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2139 self.pat.span.to(self.ty.span),
2140 SelfKind::Explicit(self.ty.clone(), mutbl),
2148 /// Returns `true` if parameter is `self`.
2149 pub fn is_self(&self) -> bool {
2150 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2151 ident.name == kw::SelfLower
2157 /// Builds a `Param` object from `ExplicitSelf`.
2158 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2159 let span = eself.span.to(eself_ident.span);
2160 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2161 let param = |mutbl, ty| Param {
2165 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2172 is_placeholder: false,
2175 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2176 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2177 SelfKind::Region(lt, mutbl) => param(
2181 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2190 /// A signature (not the body) of a function declaration.
2192 /// E.g., `fn foo(bar: baz)`.
2194 /// Please note that it's different from `FnHeader` structure
2195 /// which contains metadata about function safety, asyncness, constness and ABI.
2196 #[derive(Clone, Encodable, Decodable, Debug)]
2198 pub inputs: Vec<Param>,
2199 pub output: FnRetTy,
2203 pub fn get_self(&self) -> Option<ExplicitSelf> {
2204 self.inputs.get(0).and_then(Param::to_self)
2206 pub fn has_self(&self) -> bool {
2207 self.inputs.get(0).map_or(false, Param::is_self)
2209 pub fn c_variadic(&self) -> bool {
2210 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2214 /// Is the trait definition an auto trait?
2215 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2221 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2222 #[derive(HashStable_Generic)]
2228 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2230 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2235 pub fn is_async(self) -> bool {
2236 matches!(self, Async::Yes { .. })
2239 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2240 pub fn opt_return_id(self) -> Option<NodeId> {
2242 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2248 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2249 #[derive(HashStable_Generic)]
2255 /// Item defaultness.
2256 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2257 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2258 pub enum Defaultness {
2263 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2264 pub enum ImplPolarity {
2265 /// `impl Trait for Type`
2267 /// `impl !Trait for Type`
2271 impl fmt::Debug for ImplPolarity {
2272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2274 ImplPolarity::Positive => "positive".fmt(f),
2275 ImplPolarity::Negative(_) => "negative".fmt(f),
2280 #[derive(Clone, Encodable, Decodable, Debug)]
2282 /// Returns type is not specified.
2284 /// Functions default to `()` and closures default to inference.
2285 /// Span points to where return type would be inserted.
2287 /// Everything else.
2292 pub fn span(&self) -> Span {
2294 FnRetTy::Default(span) => span,
2295 FnRetTy::Ty(ref ty) => ty.span,
2300 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2306 /// Module item kind.
2307 #[derive(Clone, Encodable, Decodable, Debug)]
2309 /// Module with inlined definition `mod foo { ... }`,
2310 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2311 /// The inner span is from the first token past `{` to the last token until `}`,
2312 /// or from the first to the last token in the loaded file.
2313 Loaded(Vec<P<Item>>, Inline, Span),
2314 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2318 /// Foreign module declaration.
2320 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2321 #[derive(Clone, Encodable, Decodable, Debug)]
2322 pub struct ForeignMod {
2323 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2324 /// semantically by Rust.
2325 pub unsafety: Unsafe,
2326 pub abi: Option<StrLit>,
2327 pub items: Vec<P<ForeignItem>>,
2330 /// Global inline assembly.
2332 /// Also known as "module-level assembly" or "file-scoped assembly".
2333 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2334 pub struct GlobalAsm {
2338 #[derive(Clone, Encodable, Decodable, Debug)]
2339 pub struct EnumDef {
2340 pub variants: Vec<Variant>,
2343 #[derive(Clone, Encodable, Decodable, Debug)]
2344 pub struct Variant {
2345 /// Attributes of the variant.
2346 pub attrs: Vec<Attribute>,
2347 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2351 /// The visibility of the variant. Syntactically accepted but not semantically.
2352 pub vis: Visibility,
2353 /// Name of the variant.
2356 /// Fields and constructor id of the variant.
2357 pub data: VariantData,
2358 /// Explicit discriminant, e.g., `Foo = 1`.
2359 pub disr_expr: Option<AnonConst>,
2360 /// Is a macro placeholder
2361 pub is_placeholder: bool,
2364 /// Part of `use` item to the right of its prefix.
2365 #[derive(Clone, Encodable, Decodable, Debug)]
2366 pub enum UseTreeKind {
2367 /// `use prefix` or `use prefix as rename`
2369 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2371 Simple(Option<Ident>, NodeId, NodeId),
2372 /// `use prefix::{...}`
2373 Nested(Vec<(UseTree, NodeId)>),
2378 /// A tree of paths sharing common prefixes.
2379 /// Used in `use` items both at top-level and inside of braces in import groups.
2380 #[derive(Clone, Encodable, Decodable, Debug)]
2381 pub struct UseTree {
2383 pub kind: UseTreeKind,
2388 pub fn ident(&self) -> Ident {
2390 UseTreeKind::Simple(Some(rename), ..) => rename,
2391 UseTreeKind::Simple(None, ..) => {
2392 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2394 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2399 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2400 /// are contained as statements within items. These two cases need to be
2401 /// distinguished for pretty-printing.
2402 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2403 pub enum AttrStyle {
2408 rustc_index::newtype_index! {
2411 DEBUG_FORMAT = "AttrId({})"
2415 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2416 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2421 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2422 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2423 d.read_nil().map(|_| crate::attr::mk_attr_id())
2427 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2428 pub struct AttrItem {
2431 pub tokens: Option<LazyTokenStream>,
2434 /// A list of attributes.
2435 pub type AttrVec = ThinVec<Attribute>;
2437 /// Metadata associated with an item.
2438 #[derive(Clone, Encodable, Decodable, Debug)]
2439 pub struct Attribute {
2442 /// Denotes if the attribute decorates the following construct (outer)
2443 /// or the construct this attribute is contained within (inner).
2444 pub style: AttrStyle,
2448 #[derive(Clone, Encodable, Decodable, Debug)]
2450 /// A normal attribute.
2451 Normal(AttrItem, Option<LazyTokenStream>),
2453 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2454 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2455 /// variant (which is much less compact and thus more expensive).
2456 DocComment(CommentKind, Symbol),
2459 /// `TraitRef`s appear in impls.
2461 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2462 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2463 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2464 /// same as the impl's `NodeId`).
2465 #[derive(Clone, Encodable, Decodable, Debug)]
2466 pub struct TraitRef {
2471 #[derive(Clone, Encodable, Decodable, Debug)]
2472 pub struct PolyTraitRef {
2473 /// The `'a` in `<'a> Foo<&'a T>`.
2474 pub bound_generic_params: Vec<GenericParam>,
2476 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2477 pub trait_ref: TraitRef,
2483 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2485 bound_generic_params: generic_params,
2486 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2492 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2493 pub enum CrateSugar {
2494 /// Source is `pub(crate)`.
2497 /// Source is (just) `crate`.
2501 #[derive(Clone, Encodable, Decodable, Debug)]
2502 pub struct Visibility {
2503 pub kind: VisibilityKind,
2505 pub tokens: Option<LazyTokenStream>,
2508 #[derive(Clone, Encodable, Decodable, Debug)]
2509 pub enum VisibilityKind {
2512 Restricted { path: P<Path>, id: NodeId },
2516 impl VisibilityKind {
2517 pub fn is_pub(&self) -> bool {
2518 matches!(self, VisibilityKind::Public)
2522 /// Field of a struct.
2524 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2525 #[derive(Clone, Encodable, Decodable, Debug)]
2526 pub struct StructField {
2527 pub attrs: Vec<Attribute>,
2530 pub vis: Visibility,
2531 pub ident: Option<Ident>,
2534 pub is_placeholder: bool,
2537 /// Fields and constructor ids of enum variants and structs.
2538 #[derive(Clone, Encodable, Decodable, Debug)]
2539 pub enum VariantData {
2542 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2543 Struct(Vec<StructField>, bool),
2546 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2547 Tuple(Vec<StructField>, NodeId),
2550 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2555 /// Return the fields of this variant.
2556 pub fn fields(&self) -> &[StructField] {
2558 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2563 /// Return the `NodeId` of this variant's constructor, if it has one.
2564 pub fn ctor_id(&self) -> Option<NodeId> {
2566 VariantData::Struct(..) => None,
2567 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2572 /// An item definition.
2573 #[derive(Clone, Encodable, Decodable, Debug)]
2574 pub struct Item<K = ItemKind> {
2575 pub attrs: Vec<Attribute>,
2578 pub vis: Visibility,
2579 /// The name of the item.
2580 /// It might be a dummy name in case of anonymous items.
2585 /// Original tokens this item was parsed from. This isn't necessarily
2586 /// available for all items, although over time more and more items should
2587 /// have this be `Some`. Right now this is primarily used for procedural
2588 /// macros, notably custom attributes.
2590 /// Note that the tokens here do not include the outer attributes, but will
2591 /// include inner attributes.
2592 pub tokens: Option<LazyTokenStream>,
2596 /// Return the span that encompasses the attributes.
2597 pub fn span_with_attributes(&self) -> Span {
2598 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2602 impl<K: Into<ItemKind>> Item<K> {
2603 pub fn into_item(self) -> Item {
2604 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2605 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2609 /// `extern` qualifier on a function item or function type.
2610 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2618 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2619 abi.map_or(Extern::Implicit, Extern::Explicit)
2623 /// A function header.
2625 /// All the information between the visibility and the name of the function is
2626 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2627 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2628 pub struct FnHeader {
2629 pub unsafety: Unsafe,
2630 pub asyncness: Async,
2631 pub constness: Const,
2636 /// Does this function header have any qualifiers or is it empty?
2637 pub fn has_qualifiers(&self) -> bool {
2638 let Self { unsafety, asyncness, constness, ext } = self;
2639 matches!(unsafety, Unsafe::Yes(_))
2640 || asyncness.is_async()
2641 || matches!(constness, Const::Yes(_))
2642 || !matches!(ext, Extern::None)
2646 impl Default for FnHeader {
2647 fn default() -> FnHeader {
2649 unsafety: Unsafe::No,
2650 asyncness: Async::No,
2651 constness: Const::No,
2657 #[derive(Clone, Encodable, Decodable, Debug)]
2658 pub struct TraitKind(
2663 pub Vec<P<AssocItem>>,
2666 #[derive(Clone, Encodable, Decodable, Debug)]
2667 pub struct TyAliasKind(pub Defaultness, pub Generics, pub GenericBounds, pub Option<P<Ty>>);
2669 #[derive(Clone, Encodable, Decodable, Debug)]
2670 pub struct ImplKind {
2671 pub unsafety: Unsafe,
2672 pub polarity: ImplPolarity,
2673 pub defaultness: Defaultness,
2674 pub constness: Const,
2675 pub generics: Generics,
2677 /// The trait being implemented, if any.
2678 pub of_trait: Option<TraitRef>,
2681 pub items: Vec<P<AssocItem>>,
2684 #[derive(Clone, Encodable, Decodable, Debug)]
2685 pub struct FnKind(pub Defaultness, pub FnSig, pub Generics, pub Option<P<Block>>);
2687 #[derive(Clone, Encodable, Decodable, Debug)]
2689 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2691 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2692 ExternCrate(Option<Symbol>),
2693 /// A use declaration item (`use`).
2695 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2697 /// A static item (`static`).
2699 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2700 Static(P<Ty>, Mutability, Option<P<Expr>>),
2701 /// A constant item (`const`).
2703 /// E.g., `const FOO: i32 = 42;`.
2704 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2705 /// A function declaration (`fn`).
2707 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2709 /// A module declaration (`mod`).
2711 /// E.g., `mod foo;` or `mod foo { .. }`.
2712 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2713 /// semantically by Rust.
2714 Mod(Unsafe, ModKind),
2715 /// An external module (`extern`).
2717 /// E.g., `extern {}` or `extern "C" {}`.
2718 ForeignMod(ForeignMod),
2719 /// Module-level inline assembly (from `global_asm!()`).
2720 GlobalAsm(GlobalAsm),
2721 /// A type alias (`type`).
2723 /// E.g., `type Foo = Bar<u8>;`.
2724 TyAlias(Box<TyAliasKind>),
2725 /// An enum definition (`enum`).
2727 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2728 Enum(EnumDef, Generics),
2729 /// A struct definition (`struct`).
2731 /// E.g., `struct Foo<A> { x: A }`.
2732 Struct(VariantData, Generics),
2733 /// A union definition (`union`).
2735 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2736 Union(VariantData, Generics),
2737 /// A trait declaration (`trait`).
2739 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2740 Trait(Box<TraitKind>),
2743 /// E.g., `trait Foo = Bar + Quux;`.
2744 TraitAlias(Generics, GenericBounds),
2745 /// An implementation.
2747 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2748 Impl(Box<ImplKind>),
2749 /// A macro invocation.
2751 /// E.g., `foo!(..)`.
2754 /// A macro definition.
2758 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2759 rustc_data_structures::static_assert_size!(ItemKind, 112);
2762 pub fn article(&self) -> &str {
2765 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2766 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2767 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2771 pub fn descr(&self) -> &str {
2773 ItemKind::ExternCrate(..) => "extern crate",
2774 ItemKind::Use(..) => "`use` import",
2775 ItemKind::Static(..) => "static item",
2776 ItemKind::Const(..) => "constant item",
2777 ItemKind::Fn(..) => "function",
2778 ItemKind::Mod(..) => "module",
2779 ItemKind::ForeignMod(..) => "extern block",
2780 ItemKind::GlobalAsm(..) => "global asm item",
2781 ItemKind::TyAlias(..) => "type alias",
2782 ItemKind::Enum(..) => "enum",
2783 ItemKind::Struct(..) => "struct",
2784 ItemKind::Union(..) => "union",
2785 ItemKind::Trait(..) => "trait",
2786 ItemKind::TraitAlias(..) => "trait alias",
2787 ItemKind::MacCall(..) => "item macro invocation",
2788 ItemKind::MacroDef(..) => "macro definition",
2789 ItemKind::Impl { .. } => "implementation",
2793 pub fn generics(&self) -> Option<&Generics> {
2795 Self::Fn(box FnKind(_, _, generics, _))
2796 | Self::TyAlias(box TyAliasKind(_, generics, ..))
2797 | Self::Enum(_, generics)
2798 | Self::Struct(_, generics)
2799 | Self::Union(_, generics)
2800 | Self::Trait(box TraitKind(_, _, generics, ..))
2801 | Self::TraitAlias(generics, _)
2802 | Self::Impl(box ImplKind { generics, .. }) => Some(generics),
2808 /// Represents associated items.
2809 /// These include items in `impl` and `trait` definitions.
2810 pub type AssocItem = Item<AssocItemKind>;
2812 /// Represents associated item kinds.
2814 /// The term "provided" in the variants below refers to the item having a default
2815 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2816 /// In an implementation, all items must be provided.
2817 /// The `Option`s below denote the bodies, where `Some(_)`
2818 /// means "provided" and conversely `None` means "required".
2819 #[derive(Clone, Encodable, Decodable, Debug)]
2820 pub enum AssocItemKind {
2821 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2822 /// If `def` is parsed, then the constant is provided, and otherwise required.
2823 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2824 /// An associated function.
2826 /// An associated type.
2827 TyAlias(Box<TyAliasKind>),
2828 /// A macro expanding to associated items.
2832 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2833 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2835 impl AssocItemKind {
2836 pub fn defaultness(&self) -> Defaultness {
2838 Self::Const(def, ..)
2839 | Self::Fn(box FnKind(def, ..))
2840 | Self::TyAlias(box TyAliasKind(def, ..)) => def,
2841 Self::MacCall(..) => Defaultness::Final,
2846 impl From<AssocItemKind> for ItemKind {
2847 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2848 match assoc_item_kind {
2849 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2850 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2851 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2852 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2857 impl TryFrom<ItemKind> for AssocItemKind {
2858 type Error = ItemKind;
2860 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2861 Ok(match item_kind {
2862 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2863 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2864 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2865 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2866 _ => return Err(item_kind),
2871 /// An item in `extern` block.
2872 #[derive(Clone, Encodable, Decodable, Debug)]
2873 pub enum ForeignItemKind {
2874 /// A foreign static item (`static FOO: u8`).
2875 Static(P<Ty>, Mutability, Option<P<Expr>>),
2876 /// An foreign function.
2878 /// An foreign type.
2879 TyAlias(Box<TyAliasKind>),
2880 /// A macro expanding to foreign items.
2884 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2885 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
2887 impl From<ForeignItemKind> for ItemKind {
2888 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2889 match foreign_item_kind {
2890 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2891 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2892 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2893 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2898 impl TryFrom<ItemKind> for ForeignItemKind {
2899 type Error = ItemKind;
2901 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2902 Ok(match item_kind {
2903 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2904 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
2905 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
2906 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2907 _ => return Err(item_kind),
2912 pub type ForeignItem = Item<ForeignItemKind>;