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::sync::Lrc;
31 use rustc_data_structures::thin_vec::ThinVec;
32 use rustc_macros::HashStable_Generic;
33 use rustc_serialize::{self, Decoder, Encoder};
34 use rustc_span::source_map::{respan, Spanned};
35 use rustc_span::symbol::{kw, sym, Ident, Symbol};
36 use rustc_span::{Span, DUMMY_SP};
38 use std::cmp::Ordering;
39 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<TokenStream>,
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_parenthesized(&self) -> bool {
171 Parenthesized(..) => true,
176 pub fn is_angle_bracketed(&self) -> bool {
178 AngleBracketed(..) => true,
183 pub fn span(&self) -> Span {
185 AngleBracketed(ref data) => data.span,
186 Parenthesized(ref data) => data.span,
191 /// Concrete argument in the sequence of generic args.
192 #[derive(Clone, Encodable, Decodable, Debug)]
193 pub enum GenericArg {
194 /// `'a` in `Foo<'a>`
196 /// `Bar` in `Foo<Bar>`
203 pub fn span(&self) -> Span {
205 GenericArg::Lifetime(lt) => lt.ident.span,
206 GenericArg::Type(ty) => ty.span,
207 GenericArg::Const(ct) => ct.value.span,
212 /// A path like `Foo<'a, T>`.
213 #[derive(Clone, Encodable, Decodable, Debug, Default)]
214 pub struct AngleBracketedArgs {
215 /// The overall span.
217 /// The comma separated parts in the `<...>`.
218 pub args: Vec<AngleBracketedArg>,
221 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
222 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
223 #[derive(Clone, Encodable, Decodable, Debug)]
224 pub enum AngleBracketedArg {
225 /// Argument for a generic parameter.
227 /// Constraint for an associated item.
228 Constraint(AssocTyConstraint),
231 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
232 fn into(self) -> Option<P<GenericArgs>> {
233 Some(P(GenericArgs::AngleBracketed(self)))
237 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
238 fn into(self) -> Option<P<GenericArgs>> {
239 Some(P(GenericArgs::Parenthesized(self)))
243 /// A path like `Foo(A, B) -> C`.
244 #[derive(Clone, Encodable, Decodable, Debug)]
245 pub struct ParenthesizedArgs {
250 pub inputs: Vec<P<Ty>>,
256 impl ParenthesizedArgs {
257 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
262 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
264 AngleBracketedArgs { span: self.span, args }
268 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
270 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
272 /// Negative bounds should also be handled here.
273 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
274 pub enum TraitBoundModifier {
286 // This parses but will be rejected during AST validation.
290 /// The AST represents all type param bounds as types.
291 /// `typeck::collect::compute_bounds` matches these against
292 /// the "special" built-in traits (see `middle::lang_items`) and
293 /// detects `Copy`, `Send` and `Sync`.
294 #[derive(Clone, Encodable, Decodable, Debug)]
295 pub enum GenericBound {
296 Trait(PolyTraitRef, TraitBoundModifier),
301 pub fn span(&self) -> Span {
303 GenericBound::Trait(ref t, ..) => t.span,
304 GenericBound::Outlives(ref l) => l.ident.span,
309 pub type GenericBounds = Vec<GenericBound>;
311 /// Specifies the enforced ordering for generic parameters. In the future,
312 /// if we wanted to relax this order, we could override `PartialEq` and
313 /// `PartialOrd`, to allow the kinds to be unordered.
314 #[derive(Hash, Clone, Copy)]
315 pub enum ParamKindOrd {
318 // `unordered` is only `true` if `sess.has_features().const_generics`
319 // is active. Specifically, if it's only `min_const_generics`, it will still require
320 // ordering consts after types.
321 Const { unordered: bool },
324 impl Ord for ParamKindOrd {
325 fn cmp(&self, other: &Self) -> Ordering {
327 let to_int = |v| match v {
329 Type | Const { unordered: true } => 1,
330 // technically both consts should be ordered equally,
331 // but only one is ever encountered at a time, so this is
333 Const { unordered: false } => 2,
336 to_int(*self).cmp(&to_int(*other))
339 impl PartialOrd for ParamKindOrd {
340 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
341 Some(self.cmp(other))
344 impl PartialEq for ParamKindOrd {
345 fn eq(&self, other: &Self) -> bool {
346 self.cmp(other) == Ordering::Equal
349 impl Eq for ParamKindOrd {}
351 impl fmt::Display for ParamKindOrd {
352 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 ParamKindOrd::Lifetime => "lifetime".fmt(f),
355 ParamKindOrd::Type => "type".fmt(f),
356 ParamKindOrd::Const { .. } => "const".fmt(f),
361 #[derive(Clone, Encodable, Decodable, Debug)]
362 pub enum GenericParamKind {
363 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
366 default: Option<P<Ty>>,
370 /// Span of the `const` keyword.
375 #[derive(Clone, Encodable, Decodable, Debug)]
376 pub struct GenericParam {
380 pub bounds: GenericBounds,
381 pub is_placeholder: bool,
382 pub kind: GenericParamKind,
385 /// Represents lifetime, type and const parameters attached to a declaration of
386 /// a function, enum, trait, etc.
387 #[derive(Clone, Encodable, Decodable, Debug)]
388 pub struct Generics {
389 pub params: Vec<GenericParam>,
390 pub where_clause: WhereClause,
394 impl Default for Generics {
395 /// Creates an instance of `Generics`.
396 fn default() -> Generics {
399 where_clause: WhereClause {
400 has_where_token: false,
401 predicates: Vec::new(),
409 /// A where-clause in a definition.
410 #[derive(Clone, Encodable, Decodable, Debug)]
411 pub struct WhereClause {
412 /// `true` if we ate a `where` token: this can happen
413 /// if we parsed no predicates (e.g. `struct Foo where {}`).
414 /// This allows us to accurately pretty-print
415 /// in `nt_to_tokenstream`
416 pub has_where_token: bool,
417 pub predicates: Vec<WherePredicate>,
421 /// A single predicate in a where-clause.
422 #[derive(Clone, Encodable, Decodable, Debug)]
423 pub enum WherePredicate {
424 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
425 BoundPredicate(WhereBoundPredicate),
426 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
427 RegionPredicate(WhereRegionPredicate),
428 /// An equality predicate (unsupported).
429 EqPredicate(WhereEqPredicate),
432 impl WherePredicate {
433 pub fn span(&self) -> Span {
435 &WherePredicate::BoundPredicate(ref p) => p.span,
436 &WherePredicate::RegionPredicate(ref p) => p.span,
437 &WherePredicate::EqPredicate(ref p) => p.span,
444 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
445 #[derive(Clone, Encodable, Decodable, Debug)]
446 pub struct WhereBoundPredicate {
448 /// Any generics from a `for` binding.
449 pub bound_generic_params: Vec<GenericParam>,
450 /// The type being bounded.
451 pub bounded_ty: P<Ty>,
452 /// Trait and lifetime bounds (`Clone + Send + 'static`).
453 pub bounds: GenericBounds,
456 /// A lifetime predicate.
458 /// E.g., `'a: 'b + 'c`.
459 #[derive(Clone, Encodable, Decodable, Debug)]
460 pub struct WhereRegionPredicate {
462 pub lifetime: Lifetime,
463 pub bounds: GenericBounds,
466 /// An equality predicate (unsupported).
469 #[derive(Clone, Encodable, Decodable, Debug)]
470 pub struct WhereEqPredicate {
477 #[derive(Clone, Encodable, Decodable, Debug)]
480 pub attrs: Vec<Attribute>,
482 /// The order of items in the HIR is unrelated to the order of
483 /// items in the AST. However, we generate proc macro harnesses
484 /// based on the AST order, and later refer to these harnesses
485 /// from the HIR. This field keeps track of the order in which
486 /// we generated proc macros harnesses, so that we can map
487 /// HIR proc macros items back to their harness items.
488 pub proc_macros: Vec<NodeId>,
491 /// Possible values inside of compile-time attribute lists.
493 /// E.g., the '..' in `#[name(..)]`.
494 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
495 pub enum NestedMetaItem {
496 /// A full MetaItem, for recursive meta items.
500 /// E.g., `"foo"`, `64`, `true`.
504 /// A spanned compile-time attribute item.
506 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
507 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
508 pub struct MetaItem {
510 pub kind: MetaItemKind,
514 /// A compile-time attribute item.
516 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
517 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
518 pub enum MetaItemKind {
521 /// E.g., `test` as in `#[test]`.
525 /// E.g., `derive(..)` as in `#[derive(..)]`.
526 List(Vec<NestedMetaItem>),
527 /// Name value meta item.
529 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
533 /// A block (`{ .. }`).
535 /// E.g., `{ .. }` as in `fn foo() { .. }`.
536 #[derive(Clone, Encodable, Decodable, Debug)]
538 /// The statements in the block.
539 pub stmts: Vec<Stmt>,
541 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
542 pub rules: BlockCheckMode,
544 pub tokens: Option<TokenStream>,
549 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
550 #[derive(Clone, Encodable, Decodable, Debug)]
555 pub tokens: Option<TokenStream>,
559 /// Attempt reparsing the pattern as a type.
560 /// This is intended for use by diagnostics.
561 pub fn to_ty(&self) -> Option<P<Ty>> {
562 let kind = match &self.kind {
563 // In a type expression `_` is an inference variable.
564 PatKind::Wild => TyKind::Infer,
565 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
566 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
567 TyKind::Path(None, Path::from_ident(*ident))
569 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
570 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
571 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
572 PatKind::Ref(pat, mutbl) => {
573 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
575 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
576 // when `P` can be reparsed as a type `T`.
577 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
578 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
579 // assuming `T0` to `Tn` are all syntactically valid as types.
580 PatKind::Tuple(pats) => {
581 let mut tys = Vec::with_capacity(pats.len());
582 // FIXME(#48994) - could just be collected into an Option<Vec>
584 tys.push(pat.to_ty()?);
591 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
594 /// Walk top-down and call `it` in each place where a pattern occurs
595 /// starting with the root pattern `walk` is called on. If `it` returns
596 /// false then we will descend no further but siblings will be processed.
597 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
603 // Walk into the pattern associated with `Ident` (if any).
604 PatKind::Ident(_, _, Some(p)) => p.walk(it),
606 // Walk into each field of struct.
607 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
609 // Sequence of patterns.
610 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
611 s.iter().for_each(|p| p.walk(it))
614 // Trivial wrappers over inner patterns.
615 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
617 // These patterns do not contain subpatterns, skip.
624 | PatKind::MacCall(_) => {}
628 /// Is this a `..` pattern?
629 pub fn is_rest(&self) -> bool {
631 PatKind::Rest => true,
637 /// A single field in a struct pattern
639 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
640 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
641 /// except is_shorthand is true
642 #[derive(Clone, Encodable, Decodable, Debug)]
643 pub struct FieldPat {
644 /// The identifier for the field
646 /// The pattern the field is destructured to
648 pub is_shorthand: bool,
652 pub is_placeholder: bool,
655 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
656 pub enum BindingMode {
661 #[derive(Clone, Encodable, Decodable, Debug)]
663 Included(RangeSyntax),
667 #[derive(Clone, Encodable, Decodable, Debug)]
668 pub enum RangeSyntax {
675 #[derive(Clone, Encodable, Decodable, Debug)]
677 /// Represents a wildcard pattern (`_`).
680 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
681 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
682 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
683 /// during name resolution.
684 Ident(BindingMode, Ident, Option<P<Pat>>),
686 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
687 /// The `bool` is `true` in the presence of a `..`.
688 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
690 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
691 TupleStruct(Path, Vec<P<Pat>>),
693 /// An or-pattern `A | B | C`.
694 /// Invariant: `pats.len() >= 2`.
697 /// A possibly qualified path pattern.
698 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
699 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
700 /// only legally refer to associated constants.
701 Path(Option<QSelf>, Path),
703 /// A tuple pattern (`(a, b)`).
709 /// A reference pattern (e.g., `&mut (a, b)`).
710 Ref(P<Pat>, Mutability),
715 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
716 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
718 /// A slice pattern `[a, b, c]`.
721 /// A rest pattern `..`.
723 /// Syntactically it is valid anywhere.
725 /// Semantically however, it only has meaning immediately inside:
726 /// - a slice pattern: `[a, .., b]`,
727 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
728 /// - a tuple pattern: `(a, .., b)`,
729 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
731 /// In all of these cases, an additional restriction applies,
732 /// only one rest pattern may occur in the pattern sequences.
735 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
738 /// A macro pattern; pre-expansion.
742 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
743 #[derive(HashStable_Generic, Encodable, Decodable)]
744 pub enum Mutability {
750 /// Returns `MutMutable` only if both `self` and `other` are mutable.
751 pub fn and(self, other: Self) -> Self {
753 Mutability::Mut => other,
754 Mutability::Not => Mutability::Not,
758 pub fn invert(self) -> Self {
760 Mutability::Mut => Mutability::Not,
761 Mutability::Not => Mutability::Mut,
765 pub fn prefix_str(&self) -> &'static str {
767 Mutability::Mut => "mut ",
768 Mutability::Not => "",
773 /// The kind of borrow in an `AddrOf` expression,
774 /// e.g., `&place` or `&raw const place`.
775 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
776 #[derive(Encodable, Decodable, HashStable_Generic)]
777 pub enum BorrowKind {
778 /// A normal borrow, `&$expr` or `&mut $expr`.
779 /// The resulting type is either `&'a T` or `&'a mut T`
780 /// where `T = typeof($expr)` and `'a` is some lifetime.
782 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
783 /// The resulting type is either `*const T` or `*mut T`
784 /// where `T = typeof($expr)`.
788 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
790 /// The `+` operator (addition)
792 /// The `-` operator (subtraction)
794 /// The `*` operator (multiplication)
796 /// The `/` operator (division)
798 /// The `%` operator (modulus)
800 /// The `&&` operator (logical and)
802 /// The `||` operator (logical or)
804 /// The `^` operator (bitwise xor)
806 /// The `&` operator (bitwise and)
808 /// The `|` operator (bitwise or)
810 /// The `<<` operator (shift left)
812 /// The `>>` operator (shift right)
814 /// The `==` operator (equality)
816 /// The `<` operator (less than)
818 /// The `<=` operator (less than or equal to)
820 /// The `!=` operator (not equal to)
822 /// The `>=` operator (greater than or equal to)
824 /// The `>` operator (greater than)
829 pub fn to_string(&self) -> &'static str {
852 pub fn lazy(&self) -> bool {
854 BinOpKind::And | BinOpKind::Or => true,
859 pub fn is_shift(&self) -> bool {
861 BinOpKind::Shl | BinOpKind::Shr => true,
866 pub fn is_comparison(&self) -> bool {
868 // Note for developers: please keep this as is;
869 // we want compilation to fail if another variant is added.
871 Eq | Lt | Le | Ne | Gt | Ge => true,
872 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
876 /// Returns `true` if the binary operator takes its arguments by value
877 pub fn is_by_value(&self) -> bool {
878 !self.is_comparison()
882 pub type BinOp = Spanned<BinOpKind>;
886 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
887 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
889 /// The `*` operator for dereferencing
891 /// The `!` operator for logical inversion
893 /// The `-` operator for negation
898 /// Returns `true` if the unary operator takes its argument by value
899 pub fn is_by_value(u: UnOp) -> bool {
901 UnOp::Neg | UnOp::Not => true,
906 pub fn to_string(op: UnOp) -> &'static str {
916 #[derive(Clone, Encodable, Decodable, Debug)]
921 pub tokens: Option<TokenStream>,
925 pub fn add_trailing_semicolon(mut self) -> Self {
926 self.kind = match self.kind {
927 StmtKind::Expr(expr) => StmtKind::Semi(expr),
928 StmtKind::MacCall(mac) => {
929 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs }| MacCallStmt {
931 style: MacStmtStyle::Semicolon,
940 pub fn is_item(&self) -> bool {
942 StmtKind::Item(_) => true,
947 pub fn is_expr(&self) -> bool {
949 StmtKind::Expr(_) => true,
955 #[derive(Clone, Encodable, Decodable, Debug)]
957 /// A local (let) binding.
959 /// An item definition.
961 /// Expr without trailing semi-colon.
963 /// Expr with a trailing semi-colon.
965 /// Just a trailing semi-colon.
968 MacCall(P<MacCallStmt>),
971 #[derive(Clone, Encodable, Decodable, Debug)]
972 pub struct MacCallStmt {
974 pub style: MacStmtStyle,
978 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
979 pub enum MacStmtStyle {
980 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
981 /// `foo!(...);`, `foo![...];`).
983 /// The macro statement had braces (e.g., `foo! { ... }`).
985 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
986 /// `foo!(...)`). All of these will end up being converted into macro
991 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
992 #[derive(Clone, Encodable, Decodable, Debug)]
996 pub ty: Option<P<Ty>>,
997 /// Initializer expression to set the value, if any.
998 pub init: Option<P<Expr>>,
1003 /// An arm of a 'match'.
1005 /// E.g., `0..=10 => { println!("match!") }` as in
1009 /// 0..=10 => { println!("match!") },
1010 /// _ => { println!("no match!") },
1013 #[derive(Clone, Encodable, Decodable, Debug)]
1015 pub attrs: Vec<Attribute>,
1016 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1018 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1019 pub guard: Option<P<Expr>>,
1024 pub is_placeholder: bool,
1027 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1028 #[derive(Clone, Encodable, Decodable, Debug)]
1035 pub is_shorthand: bool,
1036 pub is_placeholder: bool,
1039 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1040 pub enum BlockCheckMode {
1042 Unsafe(UnsafeSource),
1045 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1046 pub enum UnsafeSource {
1051 /// A constant (expression) that's not an item or associated item,
1052 /// but needs its own `DefId` for type-checking, const-eval, etc.
1053 /// These are usually found nested inside types (e.g., array lengths)
1054 /// or expressions (e.g., repeat counts), and also used to define
1055 /// explicit discriminant values for enum variants.
1056 #[derive(Clone, Encodable, Decodable, Debug)]
1057 pub struct AnonConst {
1063 #[derive(Clone, Encodable, Decodable, Debug)]
1069 pub tokens: Option<TokenStream>,
1072 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1073 #[cfg(target_arch = "x86_64")]
1074 rustc_data_structures::static_assert_size!(Expr, 112);
1077 /// Returns `true` if this expression would be valid somewhere that expects a value;
1078 /// for example, an `if` condition.
1079 pub fn returns(&self) -> bool {
1080 if let ExprKind::Block(ref block, _) = self.kind {
1081 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1083 Some(&StmtKind::Expr(_)) => true,
1084 Some(&StmtKind::Semi(ref expr)) => {
1085 if let ExprKind::Ret(_) = expr.kind {
1086 // Last statement is explicit return.
1092 // This is a block that doesn't end in either an implicit or explicit return.
1096 // This is not a block, it is a value.
1101 /// Is this expr either `N`, or `{ N }`.
1103 /// If this is not the case, name resolution does not resolve `N` when using
1104 /// `feature(min_const_generics)` as more complex expressions are not supported.
1105 pub fn is_potential_trivial_const_param(&self) -> bool {
1106 let this = if let ExprKind::Block(ref block, None) = self.kind {
1107 if block.stmts.len() == 1 {
1108 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1116 if let ExprKind::Path(None, ref path) = this.kind {
1117 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1125 pub fn to_bound(&self) -> Option<GenericBound> {
1127 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1128 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1129 TraitBoundModifier::None,
1135 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1136 pub fn to_ty(&self) -> Option<P<Ty>> {
1137 let kind = match &self.kind {
1138 // Trivial conversions.
1139 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1140 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1142 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1144 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1145 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1148 ExprKind::Repeat(expr, expr_len) => {
1149 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1152 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1154 ExprKind::Tup(exprs) => {
1155 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1159 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1160 // then type of result is trait object.
1161 // Otherwise we don't assume the result type.
1162 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1163 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1164 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1170 // This expression doesn't look like a type syntactically.
1174 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1177 pub fn precedence(&self) -> ExprPrecedence {
1179 ExprKind::Box(_) => ExprPrecedence::Box,
1180 ExprKind::Array(_) => ExprPrecedence::Array,
1181 ExprKind::Call(..) => ExprPrecedence::Call,
1182 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1183 ExprKind::Tup(_) => ExprPrecedence::Tup,
1184 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1185 ExprKind::Unary(..) => ExprPrecedence::Unary,
1186 ExprKind::Lit(_) => ExprPrecedence::Lit,
1187 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1188 ExprKind::Let(..) => ExprPrecedence::Let,
1189 ExprKind::If(..) => ExprPrecedence::If,
1190 ExprKind::While(..) => ExprPrecedence::While,
1191 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1192 ExprKind::Loop(..) => ExprPrecedence::Loop,
1193 ExprKind::Match(..) => ExprPrecedence::Match,
1194 ExprKind::Closure(..) => ExprPrecedence::Closure,
1195 ExprKind::Block(..) => ExprPrecedence::Block,
1196 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1197 ExprKind::Async(..) => ExprPrecedence::Async,
1198 ExprKind::Await(..) => ExprPrecedence::Await,
1199 ExprKind::Assign(..) => ExprPrecedence::Assign,
1200 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1201 ExprKind::Field(..) => ExprPrecedence::Field,
1202 ExprKind::Index(..) => ExprPrecedence::Index,
1203 ExprKind::Range(..) => ExprPrecedence::Range,
1204 ExprKind::Path(..) => ExprPrecedence::Path,
1205 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1206 ExprKind::Break(..) => ExprPrecedence::Break,
1207 ExprKind::Continue(..) => ExprPrecedence::Continue,
1208 ExprKind::Ret(..) => ExprPrecedence::Ret,
1209 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1210 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1211 ExprKind::Struct(..) => ExprPrecedence::Struct,
1212 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1213 ExprKind::Paren(..) => ExprPrecedence::Paren,
1214 ExprKind::Try(..) => ExprPrecedence::Try,
1215 ExprKind::Yield(..) => ExprPrecedence::Yield,
1216 ExprKind::Err => ExprPrecedence::Err,
1221 /// Limit types of a range (inclusive or exclusive)
1222 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1223 pub enum RangeLimits {
1224 /// Inclusive at the beginning, exclusive at the end
1226 /// Inclusive at the beginning and end
1230 #[derive(Clone, Encodable, Decodable, Debug)]
1232 /// A `box x` expression.
1234 /// An array (`[a, b, c, d]`)
1235 Array(Vec<P<Expr>>),
1238 /// The first field resolves to the function itself,
1239 /// and the second field is the list of arguments.
1240 /// This also represents calling the constructor of
1241 /// tuple-like ADTs such as tuple structs and enum variants.
1242 Call(P<Expr>, Vec<P<Expr>>),
1243 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1245 /// The `PathSegment` represents the method name and its generic arguments
1246 /// (within the angle brackets).
1247 /// The first element of the vector of an `Expr` is the expression that evaluates
1248 /// to the object on which the method is being called on (the receiver),
1249 /// and the remaining elements are the rest of the arguments.
1250 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1251 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1252 /// This `Span` is the span of the function, without the dot and receiver
1253 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1254 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1255 /// A tuple (e.g., `(a, b, c, d)`).
1257 /// A binary operation (e.g., `a + b`, `a * b`).
1258 Binary(BinOp, P<Expr>, P<Expr>),
1259 /// A unary operation (e.g., `!x`, `*x`).
1260 Unary(UnOp, P<Expr>),
1261 /// A literal (e.g., `1`, `"foo"`).
1263 /// A cast (e.g., `foo as f64`).
1264 Cast(P<Expr>, P<Ty>),
1265 /// A type ascription (e.g., `42: usize`).
1266 Type(P<Expr>, P<Ty>),
1267 /// A `let pat = expr` expression that is only semantically allowed in the condition
1268 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1269 Let(P<Pat>, P<Expr>),
1270 /// An `if` block, with an optional `else` block.
1272 /// `if expr { block } else { expr }`
1273 If(P<Expr>, P<Block>, Option<P<Expr>>),
1274 /// A while loop, with an optional label.
1276 /// `'label: while expr { block }`
1277 While(P<Expr>, P<Block>, Option<Label>),
1278 /// A `for` loop, with an optional label.
1280 /// `'label: for pat in expr { block }`
1282 /// This is desugared to a combination of `loop` and `match` expressions.
1283 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1284 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1286 /// `'label: loop { block }`
1287 Loop(P<Block>, Option<Label>),
1288 /// A `match` block.
1289 Match(P<Expr>, Vec<Arm>),
1290 /// A closure (e.g., `move |a, b, c| a + b + c`).
1292 /// The final span is the span of the argument block `|...|`.
1293 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1294 /// A block (`'label: { ... }`).
1295 Block(P<Block>, Option<Label>),
1296 /// An async block (`async move { ... }`).
1298 /// The `NodeId` is the `NodeId` for the closure that results from
1299 /// desugaring an async block, just like the NodeId field in the
1300 /// `Async::Yes` variant. This is necessary in order to create a def for the
1301 /// closure which can be used as a parent of any child defs. Defs
1302 /// created during lowering cannot be made the parent of any other
1303 /// preexisting defs.
1304 Async(CaptureBy, NodeId, P<Block>),
1305 /// An await expression (`my_future.await`).
1308 /// A try block (`try { ... }`).
1311 /// An assignment (`a = foo()`).
1312 /// The `Span` argument is the span of the `=` token.
1313 Assign(P<Expr>, P<Expr>, Span),
1314 /// An assignment with an operator.
1317 AssignOp(BinOp, P<Expr>, P<Expr>),
1318 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1319 Field(P<Expr>, Ident),
1320 /// An indexing operation (e.g., `foo[2]`).
1321 Index(P<Expr>, P<Expr>),
1322 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1323 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1325 /// Variable reference, possibly containing `::` and/or type
1326 /// parameters (e.g., `foo::bar::<baz>`).
1328 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1329 Path(Option<QSelf>, Path),
1331 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1332 AddrOf(BorrowKind, Mutability, P<Expr>),
1333 /// A `break`, with an optional label to break, and an optional expression.
1334 Break(Option<Label>, Option<P<Expr>>),
1335 /// A `continue`, with an optional label.
1336 Continue(Option<Label>),
1337 /// A `return`, with an optional value to be returned.
1338 Ret(Option<P<Expr>>),
1340 /// Output of the `asm!()` macro.
1341 InlineAsm(P<InlineAsm>),
1342 /// Output of the `llvm_asm!()` macro.
1343 LlvmInlineAsm(P<LlvmInlineAsm>),
1345 /// A macro invocation; pre-expansion.
1348 /// A struct literal expression.
1350 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1351 /// where `base` is the `Option<Expr>`.
1352 Struct(Path, Vec<Field>, Option<P<Expr>>),
1354 /// An array literal constructed from one repeated element.
1356 /// E.g., `[1; 5]`. The expression is the element to be
1357 /// repeated; the constant is the number of times to repeat it.
1358 Repeat(P<Expr>, AnonConst),
1360 /// No-op: used solely so we can pretty-print faithfully.
1363 /// A try expression (`expr?`).
1366 /// A `yield`, with an optional value to be yielded.
1367 Yield(Option<P<Expr>>),
1369 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1373 /// The explicit `Self` type in a "qualified path". The actual
1374 /// path, including the trait and the associated item, is stored
1375 /// separately. `position` represents the index of the associated
1376 /// item qualified with this `Self` type.
1378 /// ```ignore (only-for-syntax-highlight)
1379 /// <Vec<T> as a::b::Trait>::AssociatedItem
1380 /// ^~~~~ ~~~~~~~~~~~~~~^
1383 /// <Vec<T>>::AssociatedItem
1387 #[derive(Clone, Encodable, Decodable, Debug)]
1391 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1392 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1393 /// 0`, this is an empty span.
1394 pub path_span: Span,
1395 pub position: usize,
1398 /// A capture clause used in closures and `async` blocks.
1399 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1400 pub enum CaptureBy {
1401 /// `move |x| y + x`.
1403 /// `move` keyword was not specified.
1407 /// The movability of a generator / closure literal:
1408 /// whether a generator contains self-references, causing it to be `!Unpin`.
1409 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1410 #[derive(HashStable_Generic)]
1411 pub enum Movability {
1412 /// May contain self-references, `!Unpin`.
1414 /// Must not contain self-references, `Unpin`.
1418 /// Represents a macro invocation. The `path` indicates which macro
1419 /// is being invoked, and the `args` are arguments passed to it.
1420 #[derive(Clone, Encodable, Decodable, Debug)]
1421 pub struct MacCall {
1423 pub args: P<MacArgs>,
1424 pub prior_type_ascription: Option<(Span, bool)>,
1428 pub fn span(&self) -> Span {
1429 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1433 /// Arguments passed to an attribute or a function-like macro.
1434 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1436 /// No arguments - `#[attr]`.
1438 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1439 Delimited(DelimSpan, MacDelimiter, TokenStream),
1440 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1442 /// Span of the `=` token.
1444 /// Token stream of the "value".
1450 pub fn delim(&self) -> DelimToken {
1452 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1453 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1457 pub fn span(&self) -> Option<Span> {
1459 MacArgs::Empty => None,
1460 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1461 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1465 /// Tokens inside the delimiters or after `=`.
1466 /// Proc macros see these tokens, for example.
1467 pub fn inner_tokens(&self) -> TokenStream {
1469 MacArgs::Empty => TokenStream::default(),
1470 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1474 /// Tokens together with the delimiters or `=`.
1475 /// Use of this method generally means that something suboptimal or hacky is happening.
1476 pub fn outer_tokens(&self) -> TokenStream {
1478 MacArgs::Empty => TokenStream::default(),
1479 MacArgs::Delimited(dspan, delim, ref tokens) => {
1480 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1482 MacArgs::Eq(eq_span, ref tokens) => {
1483 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1488 /// Whether a macro with these arguments needs a semicolon
1489 /// when used as a standalone item or statement.
1490 pub fn need_semicolon(&self) -> bool {
1491 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1495 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1496 pub enum MacDelimiter {
1503 pub fn to_token(self) -> DelimToken {
1505 MacDelimiter::Parenthesis => DelimToken::Paren,
1506 MacDelimiter::Bracket => DelimToken::Bracket,
1507 MacDelimiter::Brace => DelimToken::Brace,
1511 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1513 token::Paren => Some(MacDelimiter::Parenthesis),
1514 token::Bracket => Some(MacDelimiter::Bracket),
1515 token::Brace => Some(MacDelimiter::Brace),
1516 token::NoDelim => None,
1521 /// Represents a macro definition.
1522 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1523 pub struct MacroDef {
1524 pub body: P<MacArgs>,
1525 /// `true` if macro was defined with `macro_rules`.
1526 pub macro_rules: bool,
1529 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1530 #[derive(HashStable_Generic)]
1532 /// A regular string, like `"foo"`.
1534 /// A raw string, like `r##"foo"##`.
1536 /// The value is the number of `#` symbols used.
1541 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1543 /// The original literal token as written in source code.
1544 pub token: token::Lit,
1545 /// The "semantic" representation of the literal lowered from the original tokens.
1546 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1547 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1552 /// Same as `Lit`, but restricted to string literals.
1553 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1555 /// The original literal token as written in source code.
1556 pub style: StrStyle,
1558 pub suffix: Option<Symbol>,
1560 /// The unescaped "semantic" representation of the literal lowered from the original token.
1561 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1562 pub symbol_unescaped: Symbol,
1566 pub fn as_lit(&self) -> Lit {
1567 let token_kind = match self.style {
1568 StrStyle::Cooked => token::Str,
1569 StrStyle::Raw(n) => token::StrRaw(n),
1572 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1574 kind: LitKind::Str(self.symbol_unescaped, self.style),
1579 /// Type of the integer literal based on provided suffix.
1580 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1581 #[derive(HashStable_Generic)]
1582 pub enum LitIntType {
1591 /// Type of the float literal based on provided suffix.
1592 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1593 #[derive(HashStable_Generic)]
1594 pub enum LitFloatType {
1595 /// A float literal with a suffix (`1f32` or `1E10f32`).
1597 /// A float literal without a suffix (`1.0 or 1.0E10`).
1603 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1604 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1606 /// A string literal (`"foo"`).
1607 Str(Symbol, StrStyle),
1608 /// A byte string (`b"foo"`).
1609 ByteStr(Lrc<Vec<u8>>),
1610 /// A byte char (`b'f'`).
1612 /// A character literal (`'a'`).
1614 /// An integer literal (`1`).
1615 Int(u128, LitIntType),
1616 /// A float literal (`1f64` or `1E10f64`).
1617 Float(Symbol, LitFloatType),
1618 /// A boolean literal.
1620 /// Placeholder for a literal that wasn't well-formed in some way.
1625 /// Returns `true` if this literal is a string.
1626 pub fn is_str(&self) -> bool {
1628 LitKind::Str(..) => true,
1633 /// Returns `true` if this literal is byte literal string.
1634 pub fn is_bytestr(&self) -> bool {
1636 LitKind::ByteStr(_) => true,
1641 /// Returns `true` if this is a numeric literal.
1642 pub fn is_numeric(&self) -> bool {
1644 LitKind::Int(..) | LitKind::Float(..) => true,
1649 /// Returns `true` if this literal has no suffix.
1650 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1651 pub fn is_unsuffixed(&self) -> bool {
1655 /// Returns `true` if this literal has a suffix.
1656 pub fn is_suffixed(&self) -> bool {
1658 // suffixed variants
1659 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1660 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1661 // unsuffixed variants
1663 | LitKind::ByteStr(..)
1666 | LitKind::Int(_, LitIntType::Unsuffixed)
1667 | LitKind::Float(_, LitFloatType::Unsuffixed)
1669 | LitKind::Err(..) => false,
1674 // N.B., If you change this, you'll probably want to change the corresponding
1675 // type structure in `middle/ty.rs` as well.
1676 #[derive(Clone, Encodable, Decodable, Debug)]
1679 pub mutbl: Mutability,
1682 /// Represents a function's signature in a trait declaration,
1683 /// trait implementation, or free function.
1684 #[derive(Clone, Encodable, Decodable, Debug)]
1686 pub header: FnHeader,
1687 pub decl: P<FnDecl>,
1691 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1692 #[derive(Encodable, Decodable, HashStable_Generic)]
1699 pub fn name_str(self) -> &'static str {
1701 FloatTy::F32 => "f32",
1702 FloatTy::F64 => "f64",
1706 pub fn name(self) -> Symbol {
1708 FloatTy::F32 => sym::f32,
1709 FloatTy::F64 => sym::f64,
1713 pub fn bit_width(self) -> u64 {
1721 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1722 #[derive(Encodable, Decodable, HashStable_Generic)]
1733 pub fn name_str(&self) -> &'static str {
1735 IntTy::Isize => "isize",
1737 IntTy::I16 => "i16",
1738 IntTy::I32 => "i32",
1739 IntTy::I64 => "i64",
1740 IntTy::I128 => "i128",
1744 pub fn name(&self) -> Symbol {
1746 IntTy::Isize => sym::isize,
1747 IntTy::I8 => sym::i8,
1748 IntTy::I16 => sym::i16,
1749 IntTy::I32 => sym::i32,
1750 IntTy::I64 => sym::i64,
1751 IntTy::I128 => sym::i128,
1755 pub fn val_to_string(&self, val: i128) -> String {
1756 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1757 // are parsed as `u128`, so we wouldn't want to print an extra negative
1759 format!("{}{}", val as u128, self.name_str())
1762 pub fn bit_width(&self) -> Option<u64> {
1764 IntTy::Isize => return None,
1773 pub fn normalize(&self, target_width: u32) -> Self {
1775 IntTy::Isize => match target_width {
1779 _ => unreachable!(),
1786 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1787 #[derive(Encodable, Decodable, HashStable_Generic)]
1798 pub fn name_str(&self) -> &'static str {
1800 UintTy::Usize => "usize",
1802 UintTy::U16 => "u16",
1803 UintTy::U32 => "u32",
1804 UintTy::U64 => "u64",
1805 UintTy::U128 => "u128",
1809 pub fn name(&self) -> Symbol {
1811 UintTy::Usize => sym::usize,
1812 UintTy::U8 => sym::u8,
1813 UintTy::U16 => sym::u16,
1814 UintTy::U32 => sym::u32,
1815 UintTy::U64 => sym::u64,
1816 UintTy::U128 => sym::u128,
1820 pub fn val_to_string(&self, val: u128) -> String {
1821 format!("{}{}", val, self.name_str())
1824 pub fn bit_width(&self) -> Option<u64> {
1826 UintTy::Usize => return None,
1831 UintTy::U128 => 128,
1835 pub fn normalize(&self, target_width: u32) -> Self {
1837 UintTy::Usize => match target_width {
1841 _ => unreachable!(),
1848 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1849 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1850 #[derive(Clone, Encodable, Decodable, Debug)]
1851 pub struct AssocTyConstraint {
1854 pub kind: AssocTyConstraintKind,
1858 /// The kinds of an `AssocTyConstraint`.
1859 #[derive(Clone, Encodable, Decodable, Debug)]
1860 pub enum AssocTyConstraintKind {
1861 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1862 Equality { ty: P<Ty> },
1863 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1864 Bound { bounds: GenericBounds },
1867 #[derive(Clone, Encodable, Decodable, Debug)]
1872 pub tokens: Option<TokenStream>,
1875 #[derive(Clone, Encodable, Decodable, Debug)]
1876 pub struct BareFnTy {
1877 pub unsafety: Unsafe,
1879 pub generic_params: Vec<GenericParam>,
1880 pub decl: P<FnDecl>,
1883 /// The various kinds of type recognized by the compiler.
1884 #[derive(Clone, Encodable, Decodable, Debug)]
1886 /// A variable-length slice (`[T]`).
1888 /// A fixed length array (`[T; n]`).
1889 Array(P<Ty>, AnonConst),
1890 /// A raw pointer (`*const T` or `*mut T`).
1892 /// A reference (`&'a T` or `&'a mut T`).
1893 Rptr(Option<Lifetime>, MutTy),
1894 /// A bare function (e.g., `fn(usize) -> bool`).
1895 BareFn(P<BareFnTy>),
1896 /// The never type (`!`).
1898 /// A tuple (`(A, B, C, D,...)`).
1900 /// A path (`module::module::...::Type`), optionally
1901 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1903 /// Type parameters are stored in the `Path` itself.
1904 Path(Option<QSelf>, Path),
1905 /// A trait object type `Bound1 + Bound2 + Bound3`
1906 /// where `Bound` is a trait or a lifetime.
1907 TraitObject(GenericBounds, TraitObjectSyntax),
1908 /// An `impl Bound1 + Bound2 + Bound3` type
1909 /// where `Bound` is a trait or a lifetime.
1911 /// The `NodeId` exists to prevent lowering from having to
1912 /// generate `NodeId`s on the fly, which would complicate
1913 /// the generation of opaque `type Foo = impl Trait` items significantly.
1914 ImplTrait(NodeId, GenericBounds),
1915 /// No-op; kept solely so that we can pretty-print faithfully.
1919 /// This means the type should be inferred instead of it having been
1920 /// specified. This can appear anywhere in a type.
1922 /// Inferred type of a `self` or `&self` argument in a method.
1924 /// A macro in the type position.
1926 /// Placeholder for a kind that has failed to be defined.
1928 /// Placeholder for a `va_list`.
1933 pub fn is_implicit_self(&self) -> bool {
1934 if let TyKind::ImplicitSelf = *self { true } else { false }
1937 pub fn is_unit(&self) -> bool {
1938 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1942 /// Syntax used to declare a trait object.
1943 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1944 pub enum TraitObjectSyntax {
1949 /// Inline assembly operand explicit register or register class.
1951 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1952 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1953 pub enum InlineAsmRegOrRegClass {
1958 bitflags::bitflags! {
1959 #[derive(Encodable, Decodable, HashStable_Generic)]
1960 pub struct InlineAsmOptions: u8 {
1961 const PURE = 1 << 0;
1962 const NOMEM = 1 << 1;
1963 const READONLY = 1 << 2;
1964 const PRESERVES_FLAGS = 1 << 3;
1965 const NORETURN = 1 << 4;
1966 const NOSTACK = 1 << 5;
1967 const ATT_SYNTAX = 1 << 6;
1971 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1972 pub enum InlineAsmTemplatePiece {
1974 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1977 impl fmt::Display for InlineAsmTemplatePiece {
1978 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1980 Self::String(s) => {
1981 for c in s.chars() {
1983 '{' => f.write_str("{{")?,
1984 '}' => f.write_str("}}")?,
1990 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1991 write!(f, "{{{}:{}}}", operand_idx, modifier)
1993 Self::Placeholder { operand_idx, modifier: None, .. } => {
1994 write!(f, "{{{}}}", operand_idx)
2000 impl InlineAsmTemplatePiece {
2001 /// Rebuilds the asm template string from its pieces.
2002 pub fn to_string(s: &[Self]) -> String {
2004 let mut out = String::new();
2006 let _ = write!(out, "{}", p);
2012 /// Inline assembly operand.
2014 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2015 #[derive(Clone, Encodable, Decodable, Debug)]
2016 pub enum InlineAsmOperand {
2018 reg: InlineAsmRegOrRegClass,
2022 reg: InlineAsmRegOrRegClass,
2024 expr: Option<P<Expr>>,
2027 reg: InlineAsmRegOrRegClass,
2032 reg: InlineAsmRegOrRegClass,
2035 out_expr: Option<P<Expr>>,
2045 /// Inline assembly.
2047 /// E.g., `asm!("NOP");`.
2048 #[derive(Clone, Encodable, Decodable, Debug)]
2049 pub struct InlineAsm {
2050 pub template: Vec<InlineAsmTemplatePiece>,
2051 pub operands: Vec<(InlineAsmOperand, Span)>,
2052 pub options: InlineAsmOptions,
2053 pub line_spans: Vec<Span>,
2056 /// Inline assembly dialect.
2058 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2059 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2060 pub enum LlvmAsmDialect {
2065 /// LLVM-style inline assembly.
2067 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2068 #[derive(Clone, Encodable, Decodable, Debug)]
2069 pub struct LlvmInlineAsmOutput {
2070 pub constraint: Symbol,
2073 pub is_indirect: bool,
2076 /// LLVM-style inline assembly.
2078 /// E.g., `llvm_asm!("NOP");`.
2079 #[derive(Clone, Encodable, Decodable, Debug)]
2080 pub struct LlvmInlineAsm {
2082 pub asm_str_style: StrStyle,
2083 pub outputs: Vec<LlvmInlineAsmOutput>,
2084 pub inputs: Vec<(Symbol, P<Expr>)>,
2085 pub clobbers: Vec<Symbol>,
2087 pub alignstack: bool,
2088 pub dialect: LlvmAsmDialect,
2091 /// A parameter in a function header.
2093 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2094 #[derive(Clone, Encodable, Decodable, Debug)]
2101 pub is_placeholder: bool,
2104 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2106 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2107 #[derive(Clone, Encodable, Decodable, Debug)]
2109 /// `self`, `mut self`
2111 /// `&'lt self`, `&'lt mut self`
2112 Region(Option<Lifetime>, Mutability),
2113 /// `self: TYPE`, `mut self: TYPE`
2114 Explicit(P<Ty>, Mutability),
2117 pub type ExplicitSelf = Spanned<SelfKind>;
2120 /// Attempts to cast parameter to `ExplicitSelf`.
2121 pub fn to_self(&self) -> Option<ExplicitSelf> {
2122 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2123 if ident.name == kw::SelfLower {
2124 return match self.ty.kind {
2125 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2126 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2127 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2130 self.pat.span.to(self.ty.span),
2131 SelfKind::Explicit(self.ty.clone(), mutbl),
2139 /// Returns `true` if parameter is `self`.
2140 pub fn is_self(&self) -> bool {
2141 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2142 ident.name == kw::SelfLower
2148 /// Builds a `Param` object from `ExplicitSelf`.
2149 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2150 let span = eself.span.to(eself_ident.span);
2151 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2152 let param = |mutbl, ty| Param {
2156 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2163 is_placeholder: false,
2166 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2167 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2168 SelfKind::Region(lt, mutbl) => param(
2172 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2181 /// A signature (not the body) of a function declaration.
2183 /// E.g., `fn foo(bar: baz)`.
2185 /// Please note that it's different from `FnHeader` structure
2186 /// which contains metadata about function safety, asyncness, constness and ABI.
2187 #[derive(Clone, Encodable, Decodable, Debug)]
2189 pub inputs: Vec<Param>,
2190 pub output: FnRetTy,
2194 pub fn get_self(&self) -> Option<ExplicitSelf> {
2195 self.inputs.get(0).and_then(Param::to_self)
2197 pub fn has_self(&self) -> bool {
2198 self.inputs.get(0).map_or(false, Param::is_self)
2200 pub fn c_variadic(&self) -> bool {
2201 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2202 TyKind::CVarArgs => true,
2208 /// Is the trait definition an auto trait?
2209 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2215 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2216 #[derive(HashStable_Generic)]
2222 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2224 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2229 pub fn is_async(self) -> bool {
2230 if let Async::Yes { .. } = self { true } else { false }
2233 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2234 pub fn opt_return_id(self) -> Option<NodeId> {
2236 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2242 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2243 #[derive(HashStable_Generic)]
2249 /// Item defaultness.
2250 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2251 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2252 pub enum Defaultness {
2257 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2258 pub enum ImplPolarity {
2259 /// `impl Trait for Type`
2261 /// `impl !Trait for Type`
2265 impl fmt::Debug for ImplPolarity {
2266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2268 ImplPolarity::Positive => "positive".fmt(f),
2269 ImplPolarity::Negative(_) => "negative".fmt(f),
2274 #[derive(Clone, Encodable, Decodable, Debug)]
2276 /// Returns type is not specified.
2278 /// Functions default to `()` and closures default to inference.
2279 /// Span points to where return type would be inserted.
2281 /// Everything else.
2286 pub fn span(&self) -> Span {
2288 FnRetTy::Default(span) => span,
2289 FnRetTy::Ty(ref ty) => ty.span,
2294 /// Module declaration.
2296 /// E.g., `mod foo;` or `mod foo { .. }`.
2297 #[derive(Clone, Encodable, Decodable, Debug)]
2299 /// A span from the first token past `{` to the last token until `}`.
2300 /// For `mod foo;`, the inner span ranges from the first token
2301 /// to the last token in the external file.
2303 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2304 /// semantically by Rust.
2305 pub unsafety: Unsafe,
2306 pub items: Vec<P<Item>>,
2307 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2311 /// Foreign module declaration.
2313 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2314 #[derive(Clone, Encodable, Decodable, Debug)]
2315 pub struct ForeignMod {
2316 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2317 /// semantically by Rust.
2318 pub unsafety: Unsafe,
2319 pub abi: Option<StrLit>,
2320 pub items: Vec<P<ForeignItem>>,
2323 /// Global inline assembly.
2325 /// Also known as "module-level assembly" or "file-scoped assembly".
2326 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2327 pub struct GlobalAsm {
2331 #[derive(Clone, Encodable, Decodable, Debug)]
2332 pub struct EnumDef {
2333 pub variants: Vec<Variant>,
2336 #[derive(Clone, Encodable, Decodable, Debug)]
2337 pub struct Variant {
2338 /// Attributes of the variant.
2339 pub attrs: Vec<Attribute>,
2340 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2344 /// The visibility of the variant. Syntactically accepted but not semantically.
2345 pub vis: Visibility,
2346 /// Name of the variant.
2349 /// Fields and constructor id of the variant.
2350 pub data: VariantData,
2351 /// Explicit discriminant, e.g., `Foo = 1`.
2352 pub disr_expr: Option<AnonConst>,
2353 /// Is a macro placeholder
2354 pub is_placeholder: bool,
2357 /// Part of `use` item to the right of its prefix.
2358 #[derive(Clone, Encodable, Decodable, Debug)]
2359 pub enum UseTreeKind {
2360 /// `use prefix` or `use prefix as rename`
2362 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2364 Simple(Option<Ident>, NodeId, NodeId),
2365 /// `use prefix::{...}`
2366 Nested(Vec<(UseTree, NodeId)>),
2371 /// A tree of paths sharing common prefixes.
2372 /// Used in `use` items both at top-level and inside of braces in import groups.
2373 #[derive(Clone, Encodable, Decodable, Debug)]
2374 pub struct UseTree {
2376 pub kind: UseTreeKind,
2381 pub fn ident(&self) -> Ident {
2383 UseTreeKind::Simple(Some(rename), ..) => rename,
2384 UseTreeKind::Simple(None, ..) => {
2385 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2387 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2392 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2393 /// are contained as statements within items. These two cases need to be
2394 /// distinguished for pretty-printing.
2395 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2396 pub enum AttrStyle {
2401 rustc_index::newtype_index! {
2404 DEBUG_FORMAT = "AttrId({})"
2408 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2409 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2414 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2415 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2416 d.read_nil().map(|_| crate::attr::mk_attr_id())
2420 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2421 pub struct AttrItem {
2424 pub tokens: Option<TokenStream>,
2427 /// A list of attributes.
2428 pub type AttrVec = ThinVec<Attribute>;
2430 /// Metadata associated with an item.
2431 #[derive(Clone, Encodable, Decodable, Debug)]
2432 pub struct Attribute {
2435 /// Denotes if the attribute decorates the following construct (outer)
2436 /// or the construct this attribute is contained within (inner).
2437 pub style: AttrStyle,
2441 #[derive(Clone, Encodable, Decodable, Debug)]
2443 /// A normal attribute.
2446 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2447 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2448 /// variant (which is much less compact and thus more expensive).
2449 DocComment(CommentKind, Symbol),
2452 /// `TraitRef`s appear in impls.
2454 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2455 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2456 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2457 /// same as the impl's `NodeId`).
2458 #[derive(Clone, Encodable, Decodable, Debug)]
2459 pub struct TraitRef {
2464 #[derive(Clone, Encodable, Decodable, Debug)]
2465 pub struct PolyTraitRef {
2466 /// The `'a` in `<'a> Foo<&'a T>`.
2467 pub bound_generic_params: Vec<GenericParam>,
2469 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2470 pub trait_ref: TraitRef,
2476 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2478 bound_generic_params: generic_params,
2479 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2485 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2486 pub enum CrateSugar {
2487 /// Source is `pub(crate)`.
2490 /// Source is (just) `crate`.
2494 #[derive(Clone, Encodable, Decodable, Debug)]
2495 pub struct Visibility {
2496 pub kind: VisibilityKind,
2498 pub tokens: Option<TokenStream>,
2501 #[derive(Clone, Encodable, Decodable, Debug)]
2502 pub enum VisibilityKind {
2505 Restricted { path: P<Path>, id: NodeId },
2509 impl VisibilityKind {
2510 pub fn is_pub(&self) -> bool {
2511 if let VisibilityKind::Public = *self { true } else { false }
2515 /// Field of a struct.
2517 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2518 #[derive(Clone, Encodable, Decodable, Debug)]
2519 pub struct StructField {
2520 pub attrs: Vec<Attribute>,
2523 pub vis: Visibility,
2524 pub ident: Option<Ident>,
2527 pub is_placeholder: bool,
2530 /// Fields and constructor ids of enum variants and structs.
2531 #[derive(Clone, Encodable, Decodable, Debug)]
2532 pub enum VariantData {
2535 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2536 Struct(Vec<StructField>, bool),
2539 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2540 Tuple(Vec<StructField>, NodeId),
2543 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2548 /// Return the fields of this variant.
2549 pub fn fields(&self) -> &[StructField] {
2551 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2556 /// Return the `NodeId` of this variant's constructor, if it has one.
2557 pub fn ctor_id(&self) -> Option<NodeId> {
2559 VariantData::Struct(..) => None,
2560 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2565 /// An item definition.
2566 #[derive(Clone, Encodable, Decodable, Debug)]
2567 pub struct Item<K = ItemKind> {
2568 pub attrs: Vec<Attribute>,
2571 pub vis: Visibility,
2572 /// The name of the item.
2573 /// It might be a dummy name in case of anonymous items.
2578 /// Original tokens this item was parsed from. This isn't necessarily
2579 /// available for all items, although over time more and more items should
2580 /// have this be `Some`. Right now this is primarily used for procedural
2581 /// macros, notably custom attributes.
2583 /// Note that the tokens here do not include the outer attributes, but will
2584 /// include inner attributes.
2585 pub tokens: Option<TokenStream>,
2589 /// Return the span that encompasses the attributes.
2590 pub fn span_with_attributes(&self) -> Span {
2591 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2595 impl<K: Into<ItemKind>> Item<K> {
2596 pub fn into_item(self) -> Item {
2597 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2598 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2602 /// `extern` qualifier on a function item or function type.
2603 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2611 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2612 abi.map_or(Extern::Implicit, Extern::Explicit)
2616 /// A function header.
2618 /// All the information between the visibility and the name of the function is
2619 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2620 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2621 pub struct FnHeader {
2622 pub unsafety: Unsafe,
2623 pub asyncness: Async,
2624 pub constness: Const,
2629 /// Does this function header have any qualifiers or is it empty?
2630 pub fn has_qualifiers(&self) -> bool {
2631 let Self { unsafety, asyncness, constness, ext } = self;
2632 matches!(unsafety, Unsafe::Yes(_))
2633 || asyncness.is_async()
2634 || matches!(constness, Const::Yes(_))
2635 || !matches!(ext, Extern::None)
2639 impl Default for FnHeader {
2640 fn default() -> FnHeader {
2642 unsafety: Unsafe::No,
2643 asyncness: Async::No,
2644 constness: Const::No,
2650 #[derive(Clone, Encodable, Decodable, Debug)]
2652 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2654 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2655 ExternCrate(Option<Symbol>),
2656 /// A use declaration item (`use`).
2658 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2660 /// A static item (`static`).
2662 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2663 Static(P<Ty>, Mutability, Option<P<Expr>>),
2664 /// A constant item (`const`).
2666 /// E.g., `const FOO: i32 = 42;`.
2667 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2668 /// A function declaration (`fn`).
2670 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2671 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2672 /// A module declaration (`mod`).
2674 /// E.g., `mod foo;` or `mod foo { .. }`.
2676 /// An external module (`extern`).
2678 /// E.g., `extern {}` or `extern "C" {}`.
2679 ForeignMod(ForeignMod),
2680 /// Module-level inline assembly (from `global_asm!()`).
2681 GlobalAsm(P<GlobalAsm>),
2682 /// A type alias (`type`).
2684 /// E.g., `type Foo = Bar<u8>;`.
2685 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2686 /// An enum definition (`enum`).
2688 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2689 Enum(EnumDef, Generics),
2690 /// A struct definition (`struct`).
2692 /// E.g., `struct Foo<A> { x: A }`.
2693 Struct(VariantData, Generics),
2694 /// A union definition (`union`).
2696 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2697 Union(VariantData, Generics),
2698 /// A trait declaration (`trait`).
2700 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2701 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2704 /// E.g., `trait Foo = Bar + Quux;`.
2705 TraitAlias(Generics, GenericBounds),
2706 /// An implementation.
2708 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2711 polarity: ImplPolarity,
2712 defaultness: Defaultness,
2716 /// The trait being implemented, if any.
2717 of_trait: Option<TraitRef>,
2720 items: Vec<P<AssocItem>>,
2722 /// A macro invocation.
2724 /// E.g., `foo!(..)`.
2727 /// A macro definition.
2732 pub fn article(&self) -> &str {
2735 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2736 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2737 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2741 pub fn descr(&self) -> &str {
2743 ItemKind::ExternCrate(..) => "extern crate",
2744 ItemKind::Use(..) => "`use` import",
2745 ItemKind::Static(..) => "static item",
2746 ItemKind::Const(..) => "constant item",
2747 ItemKind::Fn(..) => "function",
2748 ItemKind::Mod(..) => "module",
2749 ItemKind::ForeignMod(..) => "extern block",
2750 ItemKind::GlobalAsm(..) => "global asm item",
2751 ItemKind::TyAlias(..) => "type alias",
2752 ItemKind::Enum(..) => "enum",
2753 ItemKind::Struct(..) => "struct",
2754 ItemKind::Union(..) => "union",
2755 ItemKind::Trait(..) => "trait",
2756 ItemKind::TraitAlias(..) => "trait alias",
2757 ItemKind::MacCall(..) => "item macro invocation",
2758 ItemKind::MacroDef(..) => "macro definition",
2759 ItemKind::Impl { .. } => "implementation",
2763 pub fn generics(&self) -> Option<&Generics> {
2765 Self::Fn(_, _, generics, _)
2766 | Self::TyAlias(_, generics, ..)
2767 | Self::Enum(_, generics)
2768 | Self::Struct(_, generics)
2769 | Self::Union(_, generics)
2770 | Self::Trait(_, _, generics, ..)
2771 | Self::TraitAlias(generics, _)
2772 | Self::Impl { generics, .. } => Some(generics),
2778 /// Represents associated items.
2779 /// These include items in `impl` and `trait` definitions.
2780 pub type AssocItem = Item<AssocItemKind>;
2782 /// Represents associated item kinds.
2784 /// The term "provided" in the variants below refers to the item having a default
2785 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2786 /// In an implementation, all items must be provided.
2787 /// The `Option`s below denote the bodies, where `Some(_)`
2788 /// means "provided" and conversely `None` means "required".
2789 #[derive(Clone, Encodable, Decodable, Debug)]
2790 pub enum AssocItemKind {
2791 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2792 /// If `def` is parsed, then the constant is provided, and otherwise required.
2793 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2794 /// An associated function.
2795 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2796 /// An associated type.
2797 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2798 /// A macro expanding to associated items.
2802 impl AssocItemKind {
2803 pub fn defaultness(&self) -> Defaultness {
2805 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2806 Self::MacCall(..) => Defaultness::Final,
2811 impl From<AssocItemKind> for ItemKind {
2812 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2813 match assoc_item_kind {
2814 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2815 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2816 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2817 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2822 impl TryFrom<ItemKind> for AssocItemKind {
2823 type Error = ItemKind;
2825 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2826 Ok(match item_kind {
2827 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2828 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2829 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2830 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2831 _ => return Err(item_kind),
2836 /// An item in `extern` block.
2837 #[derive(Clone, Encodable, Decodable, Debug)]
2838 pub enum ForeignItemKind {
2839 /// A foreign static item (`static FOO: u8`).
2840 Static(P<Ty>, Mutability, Option<P<Expr>>),
2841 /// A foreign function.
2842 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2844 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2845 /// A macro expanding to foreign items.
2849 impl From<ForeignItemKind> for ItemKind {
2850 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2851 match foreign_item_kind {
2852 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2853 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2854 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2855 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2860 impl TryFrom<ItemKind> for ForeignItemKind {
2861 type Error = ItemKind;
2863 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2864 Ok(match item_kind {
2865 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2866 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2867 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2868 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2869 _ => return Err(item_kind),
2874 pub type ForeignItem = Item<ForeignItemKind>;