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};
27 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable_Generic;
34 use rustc_serialize::{self, Decoder, Encoder};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
39 use std::cmp::Ordering;
40 use std::convert::TryFrom;
47 /// A "Label" is an identifier of some point in sources,
48 /// e.g. in the following code:
56 /// `'outer` is a label.
57 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
62 impl fmt::Debug for Label {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "label({:?})", self.ident)
68 /// A "Lifetime" is an annotation of the scope in which variable
69 /// can be used, e.g. `'a` in `&'a i32`.
70 #[derive(Clone, Encodable, Decodable, Copy)]
76 impl fmt::Debug for Lifetime {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "lifetime({}: {})", self.id, self)
82 impl fmt::Display for Lifetime {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 write!(f, "{}", self.ident.name)
88 /// A "Path" is essentially Rust's notion of a name.
90 /// It's represented as a sequence of identifiers,
91 /// along with a bunch of supporting information.
93 /// E.g., `std::cmp::PartialEq`.
94 #[derive(Clone, Encodable, Decodable, Debug)]
97 /// The segments in the path: the things separated by `::`.
98 /// Global paths begin with `kw::PathRoot`.
99 pub segments: Vec<PathSegment>,
100 pub tokens: Option<TokenStream>,
103 impl PartialEq<Symbol> for Path {
104 fn eq(&self, symbol: &Symbol) -> bool {
105 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
109 impl<CTX> HashStable<CTX> for Path {
110 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
111 self.segments.len().hash_stable(hcx, hasher);
112 for segment in &self.segments {
113 segment.ident.name.hash_stable(hcx, hasher);
119 // Convert a span and an identifier to the corresponding
121 pub fn from_ident(ident: Ident) -> Path {
122 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
125 pub fn is_global(&self) -> bool {
126 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
130 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
132 /// E.g., `std`, `String` or `Box<T>`.
133 #[derive(Clone, Encodable, Decodable, Debug)]
134 pub struct PathSegment {
135 /// The identifier portion of this path segment.
140 /// Type/lifetime parameters attached to this path. They come in
141 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
142 /// `None` means that no parameter list is supplied (`Path`),
143 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
144 /// but it can be empty (`Path<>`).
145 /// `P` is used as a size optimization for the common case with no parameters.
146 pub args: Option<P<GenericArgs>>,
150 pub fn from_ident(ident: Ident) -> Self {
151 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
153 pub fn path_root(span: Span) -> Self {
154 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
158 /// The arguments of a path segment.
160 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
161 #[derive(Clone, Encodable, Decodable, Debug)]
162 pub enum GenericArgs {
163 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
164 AngleBracketed(AngleBracketedArgs),
165 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
166 Parenthesized(ParenthesizedArgs),
170 pub fn is_parenthesized(&self) -> bool {
172 Parenthesized(..) => true,
177 pub fn is_angle_bracketed(&self) -> bool {
179 AngleBracketed(..) => true,
184 pub fn span(&self) -> Span {
186 AngleBracketed(ref data) => data.span,
187 Parenthesized(ref data) => data.span,
192 /// Concrete argument in the sequence of generic args.
193 #[derive(Clone, Encodable, Decodable, Debug)]
194 pub enum GenericArg {
195 /// `'a` in `Foo<'a>`
197 /// `Bar` in `Foo<Bar>`
204 pub fn span(&self) -> Span {
206 GenericArg::Lifetime(lt) => lt.ident.span,
207 GenericArg::Type(ty) => ty.span,
208 GenericArg::Const(ct) => ct.value.span,
213 /// A path like `Foo<'a, T>`.
214 #[derive(Clone, Encodable, Decodable, Debug, Default)]
215 pub struct AngleBracketedArgs {
216 /// The overall span.
218 /// The comma separated parts in the `<...>`.
219 pub args: Vec<AngleBracketedArg>,
222 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
223 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
224 #[derive(Clone, Encodable, Decodable, Debug)]
225 pub enum AngleBracketedArg {
226 /// Argument for a generic parameter.
228 /// Constraint for an associated item.
229 Constraint(AssocTyConstraint),
232 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
233 fn into(self) -> Option<P<GenericArgs>> {
234 Some(P(GenericArgs::AngleBracketed(self)))
238 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
239 fn into(self) -> Option<P<GenericArgs>> {
240 Some(P(GenericArgs::Parenthesized(self)))
244 /// A path like `Foo(A, B) -> C`.
245 #[derive(Clone, Encodable, Decodable, Debug)]
246 pub struct ParenthesizedArgs {
251 pub inputs: Vec<P<Ty>>,
257 impl ParenthesizedArgs {
258 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
263 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
265 AngleBracketedArgs { span: self.span, args }
269 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
271 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
273 /// Negative bounds should also be handled here.
274 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
275 pub enum TraitBoundModifier {
287 // This parses but will be rejected during AST validation.
291 /// The AST represents all type param bounds as types.
292 /// `typeck::collect::compute_bounds` matches these against
293 /// the "special" built-in traits (see `middle::lang_items`) and
294 /// detects `Copy`, `Send` and `Sync`.
295 #[derive(Clone, Encodable, Decodable, Debug)]
296 pub enum GenericBound {
297 Trait(PolyTraitRef, TraitBoundModifier),
302 pub fn span(&self) -> Span {
304 GenericBound::Trait(ref t, ..) => t.span,
305 GenericBound::Outlives(ref l) => l.ident.span,
310 pub type GenericBounds = Vec<GenericBound>;
312 /// Specifies the enforced ordering for generic parameters. In the future,
313 /// if we wanted to relax this order, we could override `PartialEq` and
314 /// `PartialOrd`, to allow the kinds to be unordered.
315 #[derive(Hash, Clone, Copy)]
316 pub enum ParamKindOrd {
319 // `unordered` is only `true` if `sess.has_features().const_generics`
320 // is active. Specifically, if it's only `min_const_generics`, it will still require
321 // ordering consts after types.
322 Const { unordered: bool },
325 impl Ord for ParamKindOrd {
326 fn cmp(&self, other: &Self) -> Ordering {
328 let to_int = |v| match v {
330 Type | Const { unordered: true } => 1,
331 // technically both consts should be ordered equally,
332 // but only one is ever encountered at a time, so this is
334 Const { unordered: false } => 2,
337 to_int(*self).cmp(&to_int(*other))
340 impl PartialOrd for ParamKindOrd {
341 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
342 Some(self.cmp(other))
345 impl PartialEq for ParamKindOrd {
346 fn eq(&self, other: &Self) -> bool {
347 self.cmp(other) == Ordering::Equal
350 impl Eq for ParamKindOrd {}
352 impl fmt::Display for ParamKindOrd {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355 ParamKindOrd::Lifetime => "lifetime".fmt(f),
356 ParamKindOrd::Type => "type".fmt(f),
357 ParamKindOrd::Const { .. } => "const".fmt(f),
362 #[derive(Clone, Encodable, Decodable, Debug)]
363 pub enum GenericParamKind {
364 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
367 default: Option<P<Ty>>,
371 /// Span of the `const` keyword.
376 #[derive(Clone, Encodable, Decodable, Debug)]
377 pub struct GenericParam {
381 pub bounds: GenericBounds,
382 pub is_placeholder: bool,
383 pub kind: GenericParamKind,
386 /// Represents lifetime, type and const parameters attached to a declaration of
387 /// a function, enum, trait, etc.
388 #[derive(Clone, Encodable, Decodable, Debug)]
389 pub struct Generics {
390 pub params: Vec<GenericParam>,
391 pub where_clause: WhereClause,
395 impl Default for Generics {
396 /// Creates an instance of `Generics`.
397 fn default() -> Generics {
400 where_clause: WhereClause {
401 has_where_token: false,
402 predicates: Vec::new(),
410 /// A where-clause in a definition.
411 #[derive(Clone, Encodable, Decodable, Debug)]
412 pub struct WhereClause {
413 /// `true` if we ate a `where` token: this can happen
414 /// if we parsed no predicates (e.g. `struct Foo where {}`).
415 /// This allows us to accurately pretty-print
416 /// in `nt_to_tokenstream`
417 pub has_where_token: bool,
418 pub predicates: Vec<WherePredicate>,
422 /// A single predicate in a where-clause.
423 #[derive(Clone, Encodable, Decodable, Debug)]
424 pub enum WherePredicate {
425 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
426 BoundPredicate(WhereBoundPredicate),
427 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
428 RegionPredicate(WhereRegionPredicate),
429 /// An equality predicate (unsupported).
430 EqPredicate(WhereEqPredicate),
433 impl WherePredicate {
434 pub fn span(&self) -> Span {
436 &WherePredicate::BoundPredicate(ref p) => p.span,
437 &WherePredicate::RegionPredicate(ref p) => p.span,
438 &WherePredicate::EqPredicate(ref p) => p.span,
445 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
446 #[derive(Clone, Encodable, Decodable, Debug)]
447 pub struct WhereBoundPredicate {
449 /// Any generics from a `for` binding.
450 pub bound_generic_params: Vec<GenericParam>,
451 /// The type being bounded.
452 pub bounded_ty: P<Ty>,
453 /// Trait and lifetime bounds (`Clone + Send + 'static`).
454 pub bounds: GenericBounds,
457 /// A lifetime predicate.
459 /// E.g., `'a: 'b + 'c`.
460 #[derive(Clone, Encodable, Decodable, Debug)]
461 pub struct WhereRegionPredicate {
463 pub lifetime: Lifetime,
464 pub bounds: GenericBounds,
467 /// An equality predicate (unsupported).
470 #[derive(Clone, Encodable, Decodable, Debug)]
471 pub struct WhereEqPredicate {
478 #[derive(Clone, Encodable, Decodable, Debug)]
481 pub attrs: Vec<Attribute>,
483 /// The order of items in the HIR is unrelated to the order of
484 /// items in the AST. However, we generate proc macro harnesses
485 /// based on the AST order, and later refer to these harnesses
486 /// from the HIR. This field keeps track of the order in which
487 /// we generated proc macros harnesses, so that we can map
488 /// HIR proc macros items back to their harness items.
489 pub proc_macros: Vec<NodeId>,
492 /// Possible values inside of compile-time attribute lists.
494 /// E.g., the '..' in `#[name(..)]`.
495 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
496 pub enum NestedMetaItem {
497 /// A full MetaItem, for recursive meta items.
501 /// E.g., `"foo"`, `64`, `true`.
505 /// A spanned compile-time attribute item.
507 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
508 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
509 pub struct MetaItem {
511 pub kind: MetaItemKind,
515 /// A compile-time attribute item.
517 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
518 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
519 pub enum MetaItemKind {
522 /// E.g., `test` as in `#[test]`.
526 /// E.g., `derive(..)` as in `#[derive(..)]`.
527 List(Vec<NestedMetaItem>),
528 /// Name value meta item.
530 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
534 /// A block (`{ .. }`).
536 /// E.g., `{ .. }` as in `fn foo() { .. }`.
537 #[derive(Clone, Encodable, Decodable, Debug)]
539 /// The statements in the block.
540 pub stmts: Vec<Stmt>,
542 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
543 pub rules: BlockCheckMode,
545 pub tokens: Option<TokenStream>,
550 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
551 #[derive(Clone, Encodable, Decodable, Debug)]
556 pub tokens: Option<TokenStream>,
560 /// Attempt reparsing the pattern as a type.
561 /// This is intended for use by diagnostics.
562 pub fn to_ty(&self) -> Option<P<Ty>> {
563 let kind = match &self.kind {
564 // In a type expression `_` is an inference variable.
565 PatKind::Wild => TyKind::Infer,
566 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
567 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
568 TyKind::Path(None, Path::from_ident(*ident))
570 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
571 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
572 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
573 PatKind::Ref(pat, mutbl) => {
574 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
576 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
577 // when `P` can be reparsed as a type `T`.
578 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
579 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
580 // assuming `T0` to `Tn` are all syntactically valid as types.
581 PatKind::Tuple(pats) => {
582 let mut tys = Vec::with_capacity(pats.len());
583 // FIXME(#48994) - could just be collected into an Option<Vec>
585 tys.push(pat.to_ty()?);
592 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
595 /// Walk top-down and call `it` in each place where a pattern occurs
596 /// starting with the root pattern `walk` is called on. If `it` returns
597 /// false then we will descend no further but siblings will be processed.
598 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
604 // Walk into the pattern associated with `Ident` (if any).
605 PatKind::Ident(_, _, Some(p)) => p.walk(it),
607 // Walk into each field of struct.
608 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
610 // Sequence of patterns.
611 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
612 s.iter().for_each(|p| p.walk(it))
615 // Trivial wrappers over inner patterns.
616 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
618 // These patterns do not contain subpatterns, skip.
625 | PatKind::MacCall(_) => {}
629 /// Is this a `..` pattern?
630 pub fn is_rest(&self) -> bool {
632 PatKind::Rest => true,
638 /// A single field in a struct pattern
640 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
641 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
642 /// except is_shorthand is true
643 #[derive(Clone, Encodable, Decodable, Debug)]
644 pub struct FieldPat {
645 /// The identifier for the field
647 /// The pattern the field is destructured to
649 pub is_shorthand: bool,
653 pub is_placeholder: bool,
656 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
657 pub enum BindingMode {
662 #[derive(Clone, Encodable, Decodable, Debug)]
664 Included(RangeSyntax),
668 #[derive(Clone, Encodable, Decodable, Debug)]
669 pub enum RangeSyntax {
676 #[derive(Clone, Encodable, Decodable, Debug)]
678 /// Represents a wildcard pattern (`_`).
681 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
682 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
683 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
684 /// during name resolution.
685 Ident(BindingMode, Ident, Option<P<Pat>>),
687 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
688 /// The `bool` is `true` in the presence of a `..`.
689 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
691 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
692 TupleStruct(Path, Vec<P<Pat>>),
694 /// An or-pattern `A | B | C`.
695 /// Invariant: `pats.len() >= 2`.
698 /// A possibly qualified path pattern.
699 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
700 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
701 /// only legally refer to associated constants.
702 Path(Option<QSelf>, Path),
704 /// A tuple pattern (`(a, b)`).
710 /// A reference pattern (e.g., `&mut (a, b)`).
711 Ref(P<Pat>, Mutability),
716 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
717 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
719 /// A slice pattern `[a, b, c]`.
722 /// A rest pattern `..`.
724 /// Syntactically it is valid anywhere.
726 /// Semantically however, it only has meaning immediately inside:
727 /// - a slice pattern: `[a, .., b]`,
728 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
729 /// - a tuple pattern: `(a, .., b)`,
730 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
732 /// In all of these cases, an additional restriction applies,
733 /// only one rest pattern may occur in the pattern sequences.
736 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
739 /// A macro pattern; pre-expansion.
743 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
744 #[derive(HashStable_Generic, Encodable, Decodable)]
745 pub enum Mutability {
751 /// Returns `MutMutable` only if both `self` and `other` are mutable.
752 pub fn and(self, other: Self) -> Self {
754 Mutability::Mut => other,
755 Mutability::Not => Mutability::Not,
759 pub fn invert(self) -> Self {
761 Mutability::Mut => Mutability::Not,
762 Mutability::Not => Mutability::Mut,
766 pub fn prefix_str(&self) -> &'static str {
768 Mutability::Mut => "mut ",
769 Mutability::Not => "",
774 /// The kind of borrow in an `AddrOf` expression,
775 /// e.g., `&place` or `&raw const place`.
776 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
777 #[derive(Encodable, Decodable, HashStable_Generic)]
778 pub enum BorrowKind {
779 /// A normal borrow, `&$expr` or `&mut $expr`.
780 /// The resulting type is either `&'a T` or `&'a mut T`
781 /// where `T = typeof($expr)` and `'a` is some lifetime.
783 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
784 /// The resulting type is either `*const T` or `*mut T`
785 /// where `T = typeof($expr)`.
789 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
791 /// The `+` operator (addition)
793 /// The `-` operator (subtraction)
795 /// The `*` operator (multiplication)
797 /// The `/` operator (division)
799 /// The `%` operator (modulus)
801 /// The `&&` operator (logical and)
803 /// The `||` operator (logical or)
805 /// The `^` operator (bitwise xor)
807 /// The `&` operator (bitwise and)
809 /// The `|` operator (bitwise or)
811 /// The `<<` operator (shift left)
813 /// The `>>` operator (shift right)
815 /// The `==` operator (equality)
817 /// The `<` operator (less than)
819 /// The `<=` operator (less than or equal to)
821 /// The `!=` operator (not equal to)
823 /// The `>=` operator (greater than or equal to)
825 /// The `>` operator (greater than)
830 pub fn to_string(&self) -> &'static str {
853 pub fn lazy(&self) -> bool {
855 BinOpKind::And | BinOpKind::Or => true,
860 pub fn is_shift(&self) -> bool {
862 BinOpKind::Shl | BinOpKind::Shr => true,
867 pub fn is_comparison(&self) -> bool {
869 // Note for developers: please keep this as is;
870 // we want compilation to fail if another variant is added.
872 Eq | Lt | Le | Ne | Gt | Ge => true,
873 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
877 /// Returns `true` if the binary operator takes its arguments by value
878 pub fn is_by_value(&self) -> bool {
879 !self.is_comparison()
883 pub type BinOp = Spanned<BinOpKind>;
887 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
888 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
890 /// The `*` operator for dereferencing
892 /// The `!` operator for logical inversion
894 /// The `-` operator for negation
899 /// Returns `true` if the unary operator takes its argument by value
900 pub fn is_by_value(u: UnOp) -> bool {
902 UnOp::Neg | UnOp::Not => true,
907 pub fn to_string(op: UnOp) -> &'static str {
917 #[derive(Clone, Encodable, Decodable, Debug)]
922 pub tokens: Option<TokenStream>,
926 pub fn add_trailing_semicolon(mut self) -> Self {
927 self.kind = match self.kind {
928 StmtKind::Expr(expr) => StmtKind::Semi(expr),
929 StmtKind::MacCall(mac) => {
930 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs }| MacCallStmt {
932 style: MacStmtStyle::Semicolon,
941 pub fn is_item(&self) -> bool {
943 StmtKind::Item(_) => true,
948 pub fn is_expr(&self) -> bool {
950 StmtKind::Expr(_) => true,
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,
979 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
980 pub enum MacStmtStyle {
981 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
982 /// `foo!(...);`, `foo![...];`).
984 /// The macro statement had braces (e.g., `foo! { ... }`).
986 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
987 /// `foo!(...)`). All of these will end up being converted into macro
992 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
993 #[derive(Clone, Encodable, Decodable, Debug)]
997 pub ty: Option<P<Ty>>,
998 /// Initializer expression to set the value, if any.
999 pub init: Option<P<Expr>>,
1004 /// An arm of a 'match'.
1006 /// E.g., `0..=10 => { println!("match!") }` as in
1010 /// 0..=10 => { println!("match!") },
1011 /// _ => { println!("no match!") },
1014 #[derive(Clone, Encodable, Decodable, Debug)]
1016 pub attrs: Vec<Attribute>,
1017 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1019 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1020 pub guard: Option<P<Expr>>,
1025 pub is_placeholder: bool,
1028 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1029 #[derive(Clone, Encodable, Decodable, Debug)]
1036 pub is_shorthand: bool,
1037 pub is_placeholder: bool,
1040 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1041 pub enum BlockCheckMode {
1043 Unsafe(UnsafeSource),
1046 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1047 pub enum UnsafeSource {
1052 /// A constant (expression) that's not an item or associated item,
1053 /// but needs its own `DefId` for type-checking, const-eval, etc.
1054 /// These are usually found nested inside types (e.g., array lengths)
1055 /// or expressions (e.g., repeat counts), and also used to define
1056 /// explicit discriminant values for enum variants.
1057 #[derive(Clone, Encodable, Decodable, Debug)]
1058 pub struct AnonConst {
1064 #[derive(Clone, Encodable, Decodable, Debug)]
1070 pub tokens: Option<TokenStream>,
1073 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1074 #[cfg(target_arch = "x86_64")]
1075 rustc_data_structures::static_assert_size!(Expr, 112);
1078 /// Returns `true` if this expression would be valid somewhere that expects a value;
1079 /// for example, an `if` condition.
1080 pub fn returns(&self) -> bool {
1081 if let ExprKind::Block(ref block, _) = self.kind {
1082 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1084 Some(&StmtKind::Expr(_)) => true,
1085 Some(&StmtKind::Semi(ref expr)) => {
1086 if let ExprKind::Ret(_) = expr.kind {
1087 // Last statement is explicit return.
1093 // This is a block that doesn't end in either an implicit or explicit return.
1097 // This is not a block, it is a value.
1102 /// Is this expr either `N`, or `{ N }`.
1104 /// If this is not the case, name resolution does not resolve `N` when using
1105 /// `feature(min_const_generics)` as more complex expressions are not supported.
1106 pub fn is_potential_trivial_const_param(&self) -> bool {
1107 let this = if let ExprKind::Block(ref block, None) = self.kind {
1108 if block.stmts.len() == 1 {
1109 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1117 if let ExprKind::Path(None, ref path) = this.kind {
1118 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1126 pub fn to_bound(&self) -> Option<GenericBound> {
1128 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1129 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1130 TraitBoundModifier::None,
1136 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1137 pub fn to_ty(&self) -> Option<P<Ty>> {
1138 let kind = match &self.kind {
1139 // Trivial conversions.
1140 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1141 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1143 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1145 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1146 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1149 ExprKind::Repeat(expr, expr_len) => {
1150 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1153 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1155 ExprKind::Tup(exprs) => {
1156 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1160 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1161 // then type of result is trait object.
1162 // Otherwise we don't assume the result type.
1163 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1164 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1165 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1171 // This expression doesn't look like a type syntactically.
1175 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1178 pub fn precedence(&self) -> ExprPrecedence {
1180 ExprKind::Box(_) => ExprPrecedence::Box,
1181 ExprKind::Array(_) => ExprPrecedence::Array,
1182 ExprKind::Call(..) => ExprPrecedence::Call,
1183 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1184 ExprKind::Tup(_) => ExprPrecedence::Tup,
1185 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1186 ExprKind::Unary(..) => ExprPrecedence::Unary,
1187 ExprKind::Lit(_) => ExprPrecedence::Lit,
1188 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1189 ExprKind::Let(..) => ExprPrecedence::Let,
1190 ExprKind::If(..) => ExprPrecedence::If,
1191 ExprKind::While(..) => ExprPrecedence::While,
1192 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1193 ExprKind::Loop(..) => ExprPrecedence::Loop,
1194 ExprKind::Match(..) => ExprPrecedence::Match,
1195 ExprKind::Closure(..) => ExprPrecedence::Closure,
1196 ExprKind::Block(..) => ExprPrecedence::Block,
1197 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1198 ExprKind::Async(..) => ExprPrecedence::Async,
1199 ExprKind::Await(..) => ExprPrecedence::Await,
1200 ExprKind::Assign(..) => ExprPrecedence::Assign,
1201 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1202 ExprKind::Field(..) => ExprPrecedence::Field,
1203 ExprKind::Index(..) => ExprPrecedence::Index,
1204 ExprKind::Range(..) => ExprPrecedence::Range,
1205 ExprKind::Path(..) => ExprPrecedence::Path,
1206 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1207 ExprKind::Break(..) => ExprPrecedence::Break,
1208 ExprKind::Continue(..) => ExprPrecedence::Continue,
1209 ExprKind::Ret(..) => ExprPrecedence::Ret,
1210 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1211 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1212 ExprKind::Struct(..) => ExprPrecedence::Struct,
1213 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1214 ExprKind::Paren(..) => ExprPrecedence::Paren,
1215 ExprKind::Try(..) => ExprPrecedence::Try,
1216 ExprKind::Yield(..) => ExprPrecedence::Yield,
1217 ExprKind::Err => ExprPrecedence::Err,
1222 /// Limit types of a range (inclusive or exclusive)
1223 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1224 pub enum RangeLimits {
1225 /// Inclusive at the beginning, exclusive at the end
1227 /// Inclusive at the beginning and end
1231 #[derive(Clone, Encodable, Decodable, Debug)]
1233 /// A `box x` expression.
1235 /// An array (`[a, b, c, d]`)
1236 Array(Vec<P<Expr>>),
1239 /// The first field resolves to the function itself,
1240 /// and the second field is the list of arguments.
1241 /// This also represents calling the constructor of
1242 /// tuple-like ADTs such as tuple structs and enum variants.
1243 Call(P<Expr>, Vec<P<Expr>>),
1244 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1246 /// The `PathSegment` represents the method name and its generic arguments
1247 /// (within the angle brackets).
1248 /// The first element of the vector of an `Expr` is the expression that evaluates
1249 /// to the object on which the method is being called on (the receiver),
1250 /// and the remaining elements are the rest of the arguments.
1251 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1252 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1253 /// This `Span` is the span of the function, without the dot and receiver
1254 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1255 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1256 /// A tuple (e.g., `(a, b, c, d)`).
1258 /// A binary operation (e.g., `a + b`, `a * b`).
1259 Binary(BinOp, P<Expr>, P<Expr>),
1260 /// A unary operation (e.g., `!x`, `*x`).
1261 Unary(UnOp, P<Expr>),
1262 /// A literal (e.g., `1`, `"foo"`).
1264 /// A cast (e.g., `foo as f64`).
1265 Cast(P<Expr>, P<Ty>),
1266 /// A type ascription (e.g., `42: usize`).
1267 Type(P<Expr>, P<Ty>),
1268 /// A `let pat = expr` expression that is only semantically allowed in the condition
1269 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1270 Let(P<Pat>, P<Expr>),
1271 /// An `if` block, with an optional `else` block.
1273 /// `if expr { block } else { expr }`
1274 If(P<Expr>, P<Block>, Option<P<Expr>>),
1275 /// A while loop, with an optional label.
1277 /// `'label: while expr { block }`
1278 While(P<Expr>, P<Block>, Option<Label>),
1279 /// A `for` loop, with an optional label.
1281 /// `'label: for pat in expr { block }`
1283 /// This is desugared to a combination of `loop` and `match` expressions.
1284 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1285 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1287 /// `'label: loop { block }`
1288 Loop(P<Block>, Option<Label>),
1289 /// A `match` block.
1290 Match(P<Expr>, Vec<Arm>),
1291 /// A closure (e.g., `move |a, b, c| a + b + c`).
1293 /// The final span is the span of the argument block `|...|`.
1294 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1295 /// A block (`'label: { ... }`).
1296 Block(P<Block>, Option<Label>),
1297 /// An async block (`async move { ... }`).
1299 /// The `NodeId` is the `NodeId` for the closure that results from
1300 /// desugaring an async block, just like the NodeId field in the
1301 /// `Async::Yes` variant. This is necessary in order to create a def for the
1302 /// closure which can be used as a parent of any child defs. Defs
1303 /// created during lowering cannot be made the parent of any other
1304 /// preexisting defs.
1305 Async(CaptureBy, NodeId, P<Block>),
1306 /// An await expression (`my_future.await`).
1309 /// A try block (`try { ... }`).
1312 /// An assignment (`a = foo()`).
1313 /// The `Span` argument is the span of the `=` token.
1314 Assign(P<Expr>, P<Expr>, Span),
1315 /// An assignment with an operator.
1318 AssignOp(BinOp, P<Expr>, P<Expr>),
1319 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1320 Field(P<Expr>, Ident),
1321 /// An indexing operation (e.g., `foo[2]`).
1322 Index(P<Expr>, P<Expr>),
1323 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1324 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1326 /// Variable reference, possibly containing `::` and/or type
1327 /// parameters (e.g., `foo::bar::<baz>`).
1329 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1330 Path(Option<QSelf>, Path),
1332 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1333 AddrOf(BorrowKind, Mutability, P<Expr>),
1334 /// A `break`, with an optional label to break, and an optional expression.
1335 Break(Option<Label>, Option<P<Expr>>),
1336 /// A `continue`, with an optional label.
1337 Continue(Option<Label>),
1338 /// A `return`, with an optional value to be returned.
1339 Ret(Option<P<Expr>>),
1341 /// Output of the `asm!()` macro.
1342 InlineAsm(P<InlineAsm>),
1343 /// Output of the `llvm_asm!()` macro.
1344 LlvmInlineAsm(P<LlvmInlineAsm>),
1346 /// A macro invocation; pre-expansion.
1349 /// A struct literal expression.
1351 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1352 /// where `base` is the `Option<Expr>`.
1353 Struct(Path, Vec<Field>, Option<P<Expr>>),
1355 /// An array literal constructed from one repeated element.
1357 /// E.g., `[1; 5]`. The expression is the element to be
1358 /// repeated; the constant is the number of times to repeat it.
1359 Repeat(P<Expr>, AnonConst),
1361 /// No-op: used solely so we can pretty-print faithfully.
1364 /// A try expression (`expr?`).
1367 /// A `yield`, with an optional value to be yielded.
1368 Yield(Option<P<Expr>>),
1370 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1374 /// The explicit `Self` type in a "qualified path". The actual
1375 /// path, including the trait and the associated item, is stored
1376 /// separately. `position` represents the index of the associated
1377 /// item qualified with this `Self` type.
1379 /// ```ignore (only-for-syntax-highlight)
1380 /// <Vec<T> as a::b::Trait>::AssociatedItem
1381 /// ^~~~~ ~~~~~~~~~~~~~~^
1384 /// <Vec<T>>::AssociatedItem
1388 #[derive(Clone, Encodable, Decodable, Debug)]
1392 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1393 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1394 /// 0`, this is an empty span.
1395 pub path_span: Span,
1396 pub position: usize,
1399 /// A capture clause used in closures and `async` blocks.
1400 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1401 pub enum CaptureBy {
1402 /// `move |x| y + x`.
1404 /// `move` keyword was not specified.
1408 /// The movability of a generator / closure literal:
1409 /// whether a generator contains self-references, causing it to be `!Unpin`.
1410 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1411 #[derive(HashStable_Generic)]
1412 pub enum Movability {
1413 /// May contain self-references, `!Unpin`.
1415 /// Must not contain self-references, `Unpin`.
1419 /// Represents a macro invocation. The `path` indicates which macro
1420 /// is being invoked, and the `args` are arguments passed to it.
1421 #[derive(Clone, Encodable, Decodable, Debug)]
1422 pub struct MacCall {
1424 pub args: P<MacArgs>,
1425 pub prior_type_ascription: Option<(Span, bool)>,
1429 pub fn span(&self) -> Span {
1430 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1434 /// Arguments passed to an attribute or a function-like macro.
1435 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1437 /// No arguments - `#[attr]`.
1439 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1440 Delimited(DelimSpan, MacDelimiter, TokenStream),
1441 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1443 /// Span of the `=` token.
1445 /// Token stream of the "value".
1451 pub fn delim(&self) -> DelimToken {
1453 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1454 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1458 pub fn span(&self) -> Option<Span> {
1460 MacArgs::Empty => None,
1461 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1462 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1466 /// Tokens inside the delimiters or after `=`.
1467 /// Proc macros see these tokens, for example.
1468 pub fn inner_tokens(&self) -> TokenStream {
1470 MacArgs::Empty => TokenStream::default(),
1471 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1475 /// Tokens together with the delimiters or `=`.
1476 /// Use of this method generally means that something suboptimal or hacky is happening.
1477 pub fn outer_tokens(&self) -> TokenStream {
1479 MacArgs::Empty => TokenStream::default(),
1480 MacArgs::Delimited(dspan, delim, ref tokens) => {
1481 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1483 MacArgs::Eq(eq_span, ref tokens) => {
1484 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1489 /// Whether a macro with these arguments needs a semicolon
1490 /// when used as a standalone item or statement.
1491 pub fn need_semicolon(&self) -> bool {
1492 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1496 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1497 pub enum MacDelimiter {
1504 pub fn to_token(self) -> DelimToken {
1506 MacDelimiter::Parenthesis => DelimToken::Paren,
1507 MacDelimiter::Bracket => DelimToken::Bracket,
1508 MacDelimiter::Brace => DelimToken::Brace,
1512 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1514 token::Paren => Some(MacDelimiter::Parenthesis),
1515 token::Bracket => Some(MacDelimiter::Bracket),
1516 token::Brace => Some(MacDelimiter::Brace),
1517 token::NoDelim => None,
1522 /// Represents a macro definition.
1523 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1524 pub struct MacroDef {
1525 pub body: P<MacArgs>,
1526 /// `true` if macro was defined with `macro_rules`.
1527 pub macro_rules: bool,
1530 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1531 #[derive(HashStable_Generic)]
1533 /// A regular string, like `"foo"`.
1535 /// A raw string, like `r##"foo"##`.
1537 /// The value is the number of `#` symbols used.
1542 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1544 /// The original literal token as written in source code.
1545 pub token: token::Lit,
1546 /// The "semantic" representation of the literal lowered from the original tokens.
1547 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1548 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1553 /// Same as `Lit`, but restricted to string literals.
1554 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1556 /// The original literal token as written in source code.
1557 pub style: StrStyle,
1559 pub suffix: Option<Symbol>,
1561 /// The unescaped "semantic" representation of the literal lowered from the original token.
1562 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1563 pub symbol_unescaped: Symbol,
1567 pub fn as_lit(&self) -> Lit {
1568 let token_kind = match self.style {
1569 StrStyle::Cooked => token::Str,
1570 StrStyle::Raw(n) => token::StrRaw(n),
1573 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1575 kind: LitKind::Str(self.symbol_unescaped, self.style),
1580 /// Type of the integer literal based on provided suffix.
1581 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1582 #[derive(HashStable_Generic)]
1583 pub enum LitIntType {
1592 /// Type of the float literal based on provided suffix.
1593 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1594 #[derive(HashStable_Generic)]
1595 pub enum LitFloatType {
1596 /// A float literal with a suffix (`1f32` or `1E10f32`).
1598 /// A float literal without a suffix (`1.0 or 1.0E10`).
1604 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1605 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1607 /// A string literal (`"foo"`).
1608 Str(Symbol, StrStyle),
1609 /// A byte string (`b"foo"`).
1611 /// A byte char (`b'f'`).
1613 /// A character literal (`'a'`).
1615 /// An integer literal (`1`).
1616 Int(u128, LitIntType),
1617 /// A float literal (`1f64` or `1E10f64`).
1618 Float(Symbol, LitFloatType),
1619 /// A boolean literal.
1621 /// Placeholder for a literal that wasn't well-formed in some way.
1626 /// Returns `true` if this literal is a string.
1627 pub fn is_str(&self) -> bool {
1629 LitKind::Str(..) => true,
1634 /// Returns `true` if this literal is byte literal string.
1635 pub fn is_bytestr(&self) -> bool {
1637 LitKind::ByteStr(_) => true,
1642 /// Returns `true` if this is a numeric literal.
1643 pub fn is_numeric(&self) -> bool {
1645 LitKind::Int(..) | LitKind::Float(..) => true,
1650 /// Returns `true` if this literal has no suffix.
1651 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1652 pub fn is_unsuffixed(&self) -> bool {
1656 /// Returns `true` if this literal has a suffix.
1657 pub fn is_suffixed(&self) -> bool {
1659 // suffixed variants
1660 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1661 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1662 // unsuffixed variants
1664 | LitKind::ByteStr(..)
1667 | LitKind::Int(_, LitIntType::Unsuffixed)
1668 | LitKind::Float(_, LitFloatType::Unsuffixed)
1670 | LitKind::Err(..) => false,
1675 // N.B., If you change this, you'll probably want to change the corresponding
1676 // type structure in `middle/ty.rs` as well.
1677 #[derive(Clone, Encodable, Decodable, Debug)]
1680 pub mutbl: Mutability,
1683 /// Represents a function's signature in a trait declaration,
1684 /// trait implementation, or free function.
1685 #[derive(Clone, Encodable, Decodable, Debug)]
1687 pub header: FnHeader,
1688 pub decl: P<FnDecl>,
1692 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1693 #[derive(Encodable, Decodable, HashStable_Generic)]
1700 pub fn name_str(self) -> &'static str {
1702 FloatTy::F32 => "f32",
1703 FloatTy::F64 => "f64",
1707 pub fn name(self) -> Symbol {
1709 FloatTy::F32 => sym::f32,
1710 FloatTy::F64 => sym::f64,
1714 pub fn bit_width(self) -> u64 {
1722 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1723 #[derive(Encodable, Decodable, HashStable_Generic)]
1734 pub fn name_str(&self) -> &'static str {
1736 IntTy::Isize => "isize",
1738 IntTy::I16 => "i16",
1739 IntTy::I32 => "i32",
1740 IntTy::I64 => "i64",
1741 IntTy::I128 => "i128",
1745 pub fn name(&self) -> Symbol {
1747 IntTy::Isize => sym::isize,
1748 IntTy::I8 => sym::i8,
1749 IntTy::I16 => sym::i16,
1750 IntTy::I32 => sym::i32,
1751 IntTy::I64 => sym::i64,
1752 IntTy::I128 => sym::i128,
1756 pub fn val_to_string(&self, val: i128) -> String {
1757 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1758 // are parsed as `u128`, so we wouldn't want to print an extra negative
1760 format!("{}{}", val as u128, self.name_str())
1763 pub fn bit_width(&self) -> Option<u64> {
1765 IntTy::Isize => return None,
1774 pub fn normalize(&self, target_width: u32) -> Self {
1776 IntTy::Isize => match target_width {
1780 _ => unreachable!(),
1787 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1788 #[derive(Encodable, Decodable, HashStable_Generic)]
1799 pub fn name_str(&self) -> &'static str {
1801 UintTy::Usize => "usize",
1803 UintTy::U16 => "u16",
1804 UintTy::U32 => "u32",
1805 UintTy::U64 => "u64",
1806 UintTy::U128 => "u128",
1810 pub fn name(&self) -> Symbol {
1812 UintTy::Usize => sym::usize,
1813 UintTy::U8 => sym::u8,
1814 UintTy::U16 => sym::u16,
1815 UintTy::U32 => sym::u32,
1816 UintTy::U64 => sym::u64,
1817 UintTy::U128 => sym::u128,
1821 pub fn val_to_string(&self, val: u128) -> String {
1822 format!("{}{}", val, self.name_str())
1825 pub fn bit_width(&self) -> Option<u64> {
1827 UintTy::Usize => return None,
1832 UintTy::U128 => 128,
1836 pub fn normalize(&self, target_width: u32) -> Self {
1838 UintTy::Usize => match target_width {
1842 _ => unreachable!(),
1849 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1850 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1851 #[derive(Clone, Encodable, Decodable, Debug)]
1852 pub struct AssocTyConstraint {
1855 pub kind: AssocTyConstraintKind,
1859 /// The kinds of an `AssocTyConstraint`.
1860 #[derive(Clone, Encodable, Decodable, Debug)]
1861 pub enum AssocTyConstraintKind {
1862 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1863 Equality { ty: P<Ty> },
1864 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1865 Bound { bounds: GenericBounds },
1868 #[derive(Encodable, Decodable, Debug)]
1873 pub tokens: Option<TokenStream>,
1877 fn clone(&self) -> Self {
1878 ensure_sufficient_stack(|| Self {
1880 kind: self.kind.clone(),
1882 tokens: self.tokens.clone(),
1888 pub fn peel_refs(&self) -> &Self {
1889 let mut final_ty = self;
1890 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1897 #[derive(Clone, Encodable, Decodable, Debug)]
1898 pub struct BareFnTy {
1899 pub unsafety: Unsafe,
1901 pub generic_params: Vec<GenericParam>,
1902 pub decl: P<FnDecl>,
1905 /// The various kinds of type recognized by the compiler.
1906 #[derive(Clone, Encodable, Decodable, Debug)]
1908 /// A variable-length slice (`[T]`).
1910 /// A fixed length array (`[T; n]`).
1911 Array(P<Ty>, AnonConst),
1912 /// A raw pointer (`*const T` or `*mut T`).
1914 /// A reference (`&'a T` or `&'a mut T`).
1915 Rptr(Option<Lifetime>, MutTy),
1916 /// A bare function (e.g., `fn(usize) -> bool`).
1917 BareFn(P<BareFnTy>),
1918 /// The never type (`!`).
1920 /// A tuple (`(A, B, C, D,...)`).
1922 /// A path (`module::module::...::Type`), optionally
1923 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1925 /// Type parameters are stored in the `Path` itself.
1926 Path(Option<QSelf>, Path),
1927 /// A trait object type `Bound1 + Bound2 + Bound3`
1928 /// where `Bound` is a trait or a lifetime.
1929 TraitObject(GenericBounds, TraitObjectSyntax),
1930 /// An `impl Bound1 + Bound2 + Bound3` type
1931 /// where `Bound` is a trait or a lifetime.
1933 /// The `NodeId` exists to prevent lowering from having to
1934 /// generate `NodeId`s on the fly, which would complicate
1935 /// the generation of opaque `type Foo = impl Trait` items significantly.
1936 ImplTrait(NodeId, GenericBounds),
1937 /// No-op; kept solely so that we can pretty-print faithfully.
1941 /// This means the type should be inferred instead of it having been
1942 /// specified. This can appear anywhere in a type.
1944 /// Inferred type of a `self` or `&self` argument in a method.
1946 /// A macro in the type position.
1948 /// Placeholder for a kind that has failed to be defined.
1950 /// Placeholder for a `va_list`.
1955 pub fn is_implicit_self(&self) -> bool {
1956 matches!(self, TyKind::ImplicitSelf)
1959 pub fn is_unit(&self) -> bool {
1960 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1964 /// Syntax used to declare a trait object.
1965 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1966 pub enum TraitObjectSyntax {
1971 /// Inline assembly operand explicit register or register class.
1973 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1974 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1975 pub enum InlineAsmRegOrRegClass {
1980 bitflags::bitflags! {
1981 #[derive(Encodable, Decodable, HashStable_Generic)]
1982 pub struct InlineAsmOptions: u8 {
1983 const PURE = 1 << 0;
1984 const NOMEM = 1 << 1;
1985 const READONLY = 1 << 2;
1986 const PRESERVES_FLAGS = 1 << 3;
1987 const NORETURN = 1 << 4;
1988 const NOSTACK = 1 << 5;
1989 const ATT_SYNTAX = 1 << 6;
1993 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1994 pub enum InlineAsmTemplatePiece {
1996 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1999 impl fmt::Display for InlineAsmTemplatePiece {
2000 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2002 Self::String(s) => {
2003 for c in s.chars() {
2005 '{' => f.write_str("{{")?,
2006 '}' => f.write_str("}}")?,
2012 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2013 write!(f, "{{{}:{}}}", operand_idx, modifier)
2015 Self::Placeholder { operand_idx, modifier: None, .. } => {
2016 write!(f, "{{{}}}", operand_idx)
2022 impl InlineAsmTemplatePiece {
2023 /// Rebuilds the asm template string from its pieces.
2024 pub fn to_string(s: &[Self]) -> String {
2026 let mut out = String::new();
2028 let _ = write!(out, "{}", p);
2034 /// Inline assembly operand.
2036 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2037 #[derive(Clone, Encodable, Decodable, Debug)]
2038 pub enum InlineAsmOperand {
2040 reg: InlineAsmRegOrRegClass,
2044 reg: InlineAsmRegOrRegClass,
2046 expr: Option<P<Expr>>,
2049 reg: InlineAsmRegOrRegClass,
2054 reg: InlineAsmRegOrRegClass,
2057 out_expr: Option<P<Expr>>,
2067 /// Inline assembly.
2069 /// E.g., `asm!("NOP");`.
2070 #[derive(Clone, Encodable, Decodable, Debug)]
2071 pub struct InlineAsm {
2072 pub template: Vec<InlineAsmTemplatePiece>,
2073 pub operands: Vec<(InlineAsmOperand, Span)>,
2074 pub options: InlineAsmOptions,
2075 pub line_spans: Vec<Span>,
2078 /// Inline assembly dialect.
2080 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2081 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2082 pub enum LlvmAsmDialect {
2087 /// LLVM-style inline assembly.
2089 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2090 #[derive(Clone, Encodable, Decodable, Debug)]
2091 pub struct LlvmInlineAsmOutput {
2092 pub constraint: Symbol,
2095 pub is_indirect: bool,
2098 /// LLVM-style inline assembly.
2100 /// E.g., `llvm_asm!("NOP");`.
2101 #[derive(Clone, Encodable, Decodable, Debug)]
2102 pub struct LlvmInlineAsm {
2104 pub asm_str_style: StrStyle,
2105 pub outputs: Vec<LlvmInlineAsmOutput>,
2106 pub inputs: Vec<(Symbol, P<Expr>)>,
2107 pub clobbers: Vec<Symbol>,
2109 pub alignstack: bool,
2110 pub dialect: LlvmAsmDialect,
2113 /// A parameter in a function header.
2115 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2116 #[derive(Clone, Encodable, Decodable, Debug)]
2123 pub is_placeholder: bool,
2126 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2128 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2129 #[derive(Clone, Encodable, Decodable, Debug)]
2131 /// `self`, `mut self`
2133 /// `&'lt self`, `&'lt mut self`
2134 Region(Option<Lifetime>, Mutability),
2135 /// `self: TYPE`, `mut self: TYPE`
2136 Explicit(P<Ty>, Mutability),
2139 pub type ExplicitSelf = Spanned<SelfKind>;
2142 /// Attempts to cast parameter to `ExplicitSelf`.
2143 pub fn to_self(&self) -> Option<ExplicitSelf> {
2144 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2145 if ident.name == kw::SelfLower {
2146 return match self.ty.kind {
2147 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2148 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2149 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2152 self.pat.span.to(self.ty.span),
2153 SelfKind::Explicit(self.ty.clone(), mutbl),
2161 /// Returns `true` if parameter is `self`.
2162 pub fn is_self(&self) -> bool {
2163 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2164 ident.name == kw::SelfLower
2170 /// Builds a `Param` object from `ExplicitSelf`.
2171 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2172 let span = eself.span.to(eself_ident.span);
2173 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2174 let param = |mutbl, ty| Param {
2178 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2185 is_placeholder: false,
2188 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2189 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2190 SelfKind::Region(lt, mutbl) => param(
2194 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2203 /// A signature (not the body) of a function declaration.
2205 /// E.g., `fn foo(bar: baz)`.
2207 /// Please note that it's different from `FnHeader` structure
2208 /// which contains metadata about function safety, asyncness, constness and ABI.
2209 #[derive(Clone, Encodable, Decodable, Debug)]
2211 pub inputs: Vec<Param>,
2212 pub output: FnRetTy,
2216 pub fn get_self(&self) -> Option<ExplicitSelf> {
2217 self.inputs.get(0).and_then(Param::to_self)
2219 pub fn has_self(&self) -> bool {
2220 self.inputs.get(0).map_or(false, Param::is_self)
2222 pub fn c_variadic(&self) -> bool {
2223 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2224 TyKind::CVarArgs => true,
2230 /// Is the trait definition an auto trait?
2231 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2237 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2238 #[derive(HashStable_Generic)]
2244 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2246 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2251 pub fn is_async(self) -> bool {
2252 matches!(self, Async::Yes { .. })
2255 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2256 pub fn opt_return_id(self) -> Option<NodeId> {
2258 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2264 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2265 #[derive(HashStable_Generic)]
2271 /// Item defaultness.
2272 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2273 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2274 pub enum Defaultness {
2279 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2280 pub enum ImplPolarity {
2281 /// `impl Trait for Type`
2283 /// `impl !Trait for Type`
2287 impl fmt::Debug for ImplPolarity {
2288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2290 ImplPolarity::Positive => "positive".fmt(f),
2291 ImplPolarity::Negative(_) => "negative".fmt(f),
2296 #[derive(Clone, Encodable, Decodable, Debug)]
2298 /// Returns type is not specified.
2300 /// Functions default to `()` and closures default to inference.
2301 /// Span points to where return type would be inserted.
2303 /// Everything else.
2308 pub fn span(&self) -> Span {
2310 FnRetTy::Default(span) => span,
2311 FnRetTy::Ty(ref ty) => ty.span,
2316 /// Module declaration.
2318 /// E.g., `mod foo;` or `mod foo { .. }`.
2319 #[derive(Clone, Encodable, Decodable, Debug)]
2321 /// A span from the first token past `{` to the last token until `}`.
2322 /// For `mod foo;`, the inner span ranges from the first token
2323 /// to the last token in the external file.
2325 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2326 /// semantically by Rust.
2327 pub unsafety: Unsafe,
2328 pub items: Vec<P<Item>>,
2329 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2333 /// Foreign module declaration.
2335 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2336 #[derive(Clone, Encodable, Decodable, Debug)]
2337 pub struct ForeignMod {
2338 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2339 /// semantically by Rust.
2340 pub unsafety: Unsafe,
2341 pub abi: Option<StrLit>,
2342 pub items: Vec<P<ForeignItem>>,
2345 /// Global inline assembly.
2347 /// Also known as "module-level assembly" or "file-scoped assembly".
2348 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2349 pub struct GlobalAsm {
2353 #[derive(Clone, Encodable, Decodable, Debug)]
2354 pub struct EnumDef {
2355 pub variants: Vec<Variant>,
2358 #[derive(Clone, Encodable, Decodable, Debug)]
2359 pub struct Variant {
2360 /// Attributes of the variant.
2361 pub attrs: Vec<Attribute>,
2362 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2366 /// The visibility of the variant. Syntactically accepted but not semantically.
2367 pub vis: Visibility,
2368 /// Name of the variant.
2371 /// Fields and constructor id of the variant.
2372 pub data: VariantData,
2373 /// Explicit discriminant, e.g., `Foo = 1`.
2374 pub disr_expr: Option<AnonConst>,
2375 /// Is a macro placeholder
2376 pub is_placeholder: bool,
2379 /// Part of `use` item to the right of its prefix.
2380 #[derive(Clone, Encodable, Decodable, Debug)]
2381 pub enum UseTreeKind {
2382 /// `use prefix` or `use prefix as rename`
2384 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2386 Simple(Option<Ident>, NodeId, NodeId),
2387 /// `use prefix::{...}`
2388 Nested(Vec<(UseTree, NodeId)>),
2393 /// A tree of paths sharing common prefixes.
2394 /// Used in `use` items both at top-level and inside of braces in import groups.
2395 #[derive(Clone, Encodable, Decodable, Debug)]
2396 pub struct UseTree {
2398 pub kind: UseTreeKind,
2403 pub fn ident(&self) -> Ident {
2405 UseTreeKind::Simple(Some(rename), ..) => rename,
2406 UseTreeKind::Simple(None, ..) => {
2407 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2409 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2414 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2415 /// are contained as statements within items. These two cases need to be
2416 /// distinguished for pretty-printing.
2417 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2418 pub enum AttrStyle {
2423 rustc_index::newtype_index! {
2426 DEBUG_FORMAT = "AttrId({})"
2430 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2431 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2436 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2437 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2438 d.read_nil().map(|_| crate::attr::mk_attr_id())
2442 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2443 pub struct AttrItem {
2446 pub tokens: Option<TokenStream>,
2449 /// A list of attributes.
2450 pub type AttrVec = ThinVec<Attribute>;
2452 /// Metadata associated with an item.
2453 #[derive(Clone, Encodable, Decodable, Debug)]
2454 pub struct Attribute {
2457 /// Denotes if the attribute decorates the following construct (outer)
2458 /// or the construct this attribute is contained within (inner).
2459 pub style: AttrStyle,
2463 #[derive(Clone, Encodable, Decodable, Debug)]
2465 /// A normal attribute.
2468 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2469 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2470 /// variant (which is much less compact and thus more expensive).
2471 DocComment(CommentKind, Symbol),
2474 /// `TraitRef`s appear in impls.
2476 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2477 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2478 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2479 /// same as the impl's `NodeId`).
2480 #[derive(Clone, Encodable, Decodable, Debug)]
2481 pub struct TraitRef {
2486 #[derive(Clone, Encodable, Decodable, Debug)]
2487 pub struct PolyTraitRef {
2488 /// The `'a` in `<'a> Foo<&'a T>`.
2489 pub bound_generic_params: Vec<GenericParam>,
2491 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2492 pub trait_ref: TraitRef,
2498 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2500 bound_generic_params: generic_params,
2501 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2507 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2508 pub enum CrateSugar {
2509 /// Source is `pub(crate)`.
2512 /// Source is (just) `crate`.
2516 #[derive(Clone, Encodable, Decodable, Debug)]
2517 pub struct Visibility {
2518 pub kind: VisibilityKind,
2520 pub tokens: Option<TokenStream>,
2523 #[derive(Clone, Encodable, Decodable, Debug)]
2524 pub enum VisibilityKind {
2527 Restricted { path: P<Path>, id: NodeId },
2531 impl VisibilityKind {
2532 pub fn is_pub(&self) -> bool {
2533 matches!(self, VisibilityKind::Public)
2537 /// Field of a struct.
2539 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2540 #[derive(Clone, Encodable, Decodable, Debug)]
2541 pub struct StructField {
2542 pub attrs: Vec<Attribute>,
2545 pub vis: Visibility,
2546 pub ident: Option<Ident>,
2549 pub is_placeholder: bool,
2552 /// Fields and constructor ids of enum variants and structs.
2553 #[derive(Clone, Encodable, Decodable, Debug)]
2554 pub enum VariantData {
2557 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2558 Struct(Vec<StructField>, bool),
2561 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2562 Tuple(Vec<StructField>, NodeId),
2565 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2570 /// Return the fields of this variant.
2571 pub fn fields(&self) -> &[StructField] {
2573 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2578 /// Return the `NodeId` of this variant's constructor, if it has one.
2579 pub fn ctor_id(&self) -> Option<NodeId> {
2581 VariantData::Struct(..) => None,
2582 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2587 /// An item definition.
2588 #[derive(Clone, Encodable, Decodable, Debug)]
2589 pub struct Item<K = ItemKind> {
2590 pub attrs: Vec<Attribute>,
2593 pub vis: Visibility,
2594 /// The name of the item.
2595 /// It might be a dummy name in case of anonymous items.
2600 /// Original tokens this item was parsed from. This isn't necessarily
2601 /// available for all items, although over time more and more items should
2602 /// have this be `Some`. Right now this is primarily used for procedural
2603 /// macros, notably custom attributes.
2605 /// Note that the tokens here do not include the outer attributes, but will
2606 /// include inner attributes.
2607 pub tokens: Option<TokenStream>,
2611 /// Return the span that encompasses the attributes.
2612 pub fn span_with_attributes(&self) -> Span {
2613 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2617 impl<K: Into<ItemKind>> Item<K> {
2618 pub fn into_item(self) -> Item {
2619 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2620 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2624 /// `extern` qualifier on a function item or function type.
2625 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2633 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2634 abi.map_or(Extern::Implicit, Extern::Explicit)
2638 /// A function header.
2640 /// All the information between the visibility and the name of the function is
2641 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2642 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2643 pub struct FnHeader {
2644 pub unsafety: Unsafe,
2645 pub asyncness: Async,
2646 pub constness: Const,
2651 /// Does this function header have any qualifiers or is it empty?
2652 pub fn has_qualifiers(&self) -> bool {
2653 let Self { unsafety, asyncness, constness, ext } = self;
2654 matches!(unsafety, Unsafe::Yes(_))
2655 || asyncness.is_async()
2656 || matches!(constness, Const::Yes(_))
2657 || !matches!(ext, Extern::None)
2661 impl Default for FnHeader {
2662 fn default() -> FnHeader {
2664 unsafety: Unsafe::No,
2665 asyncness: Async::No,
2666 constness: Const::No,
2672 #[derive(Clone, Encodable, Decodable, Debug)]
2674 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2676 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2677 ExternCrate(Option<Symbol>),
2678 /// A use declaration item (`use`).
2680 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2682 /// A static item (`static`).
2684 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2685 Static(P<Ty>, Mutability, Option<P<Expr>>),
2686 /// A constant item (`const`).
2688 /// E.g., `const FOO: i32 = 42;`.
2689 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2690 /// A function declaration (`fn`).
2692 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2693 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2694 /// A module declaration (`mod`).
2696 /// E.g., `mod foo;` or `mod foo { .. }`.
2698 /// An external module (`extern`).
2700 /// E.g., `extern {}` or `extern "C" {}`.
2701 ForeignMod(ForeignMod),
2702 /// Module-level inline assembly (from `global_asm!()`).
2703 GlobalAsm(P<GlobalAsm>),
2704 /// A type alias (`type`).
2706 /// E.g., `type Foo = Bar<u8>;`.
2707 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2708 /// An enum definition (`enum`).
2710 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2711 Enum(EnumDef, Generics),
2712 /// A struct definition (`struct`).
2714 /// E.g., `struct Foo<A> { x: A }`.
2715 Struct(VariantData, Generics),
2716 /// A union definition (`union`).
2718 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2719 Union(VariantData, Generics),
2720 /// A trait declaration (`trait`).
2722 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2723 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2726 /// E.g., `trait Foo = Bar + Quux;`.
2727 TraitAlias(Generics, GenericBounds),
2728 /// An implementation.
2730 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2733 polarity: ImplPolarity,
2734 defaultness: Defaultness,
2738 /// The trait being implemented, if any.
2739 of_trait: Option<TraitRef>,
2742 items: Vec<P<AssocItem>>,
2744 /// A macro invocation.
2746 /// E.g., `foo!(..)`.
2749 /// A macro definition.
2754 pub fn article(&self) -> &str {
2757 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2758 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2759 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2763 pub fn descr(&self) -> &str {
2765 ItemKind::ExternCrate(..) => "extern crate",
2766 ItemKind::Use(..) => "`use` import",
2767 ItemKind::Static(..) => "static item",
2768 ItemKind::Const(..) => "constant item",
2769 ItemKind::Fn(..) => "function",
2770 ItemKind::Mod(..) => "module",
2771 ItemKind::ForeignMod(..) => "extern block",
2772 ItemKind::GlobalAsm(..) => "global asm item",
2773 ItemKind::TyAlias(..) => "type alias",
2774 ItemKind::Enum(..) => "enum",
2775 ItemKind::Struct(..) => "struct",
2776 ItemKind::Union(..) => "union",
2777 ItemKind::Trait(..) => "trait",
2778 ItemKind::TraitAlias(..) => "trait alias",
2779 ItemKind::MacCall(..) => "item macro invocation",
2780 ItemKind::MacroDef(..) => "macro definition",
2781 ItemKind::Impl { .. } => "implementation",
2785 pub fn generics(&self) -> Option<&Generics> {
2787 Self::Fn(_, _, generics, _)
2788 | Self::TyAlias(_, generics, ..)
2789 | Self::Enum(_, generics)
2790 | Self::Struct(_, generics)
2791 | Self::Union(_, generics)
2792 | Self::Trait(_, _, generics, ..)
2793 | Self::TraitAlias(generics, _)
2794 | Self::Impl { generics, .. } => Some(generics),
2800 /// Represents associated items.
2801 /// These include items in `impl` and `trait` definitions.
2802 pub type AssocItem = Item<AssocItemKind>;
2804 /// Represents associated item kinds.
2806 /// The term "provided" in the variants below refers to the item having a default
2807 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2808 /// In an implementation, all items must be provided.
2809 /// The `Option`s below denote the bodies, where `Some(_)`
2810 /// means "provided" and conversely `None` means "required".
2811 #[derive(Clone, Encodable, Decodable, Debug)]
2812 pub enum AssocItemKind {
2813 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2814 /// If `def` is parsed, then the constant is provided, and otherwise required.
2815 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2816 /// An associated function.
2817 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2818 /// An associated type.
2819 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2820 /// A macro expanding to associated items.
2824 impl AssocItemKind {
2825 pub fn defaultness(&self) -> Defaultness {
2827 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2828 Self::MacCall(..) => Defaultness::Final,
2833 impl From<AssocItemKind> for ItemKind {
2834 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2835 match assoc_item_kind {
2836 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2837 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2838 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2839 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2844 impl TryFrom<ItemKind> for AssocItemKind {
2845 type Error = ItemKind;
2847 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2848 Ok(match item_kind {
2849 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2850 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2851 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2852 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2853 _ => return Err(item_kind),
2858 /// An item in `extern` block.
2859 #[derive(Clone, Encodable, Decodable, Debug)]
2860 pub enum ForeignItemKind {
2861 /// A foreign static item (`static FOO: u8`).
2862 Static(P<Ty>, Mutability, Option<P<Expr>>),
2863 /// A foreign function.
2864 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2866 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2867 /// A macro expanding to foreign items.
2871 impl From<ForeignItemKind> for ItemKind {
2872 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2873 match foreign_item_kind {
2874 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2875 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2876 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2877 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2882 impl TryFrom<ItemKind> for ForeignItemKind {
2883 type Error = ItemKind;
2885 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2886 Ok(match item_kind {
2887 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2888 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2889 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2890 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2891 _ => return Err(item_kind),
2896 pub type ForeignItem = Item<ForeignItemKind>;