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, 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::convert::TryFrom;
45 /// A "Label" is an identifier of some point in sources,
46 /// e.g. in the following code:
54 /// `'outer` is a label.
55 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable_Generic)]
60 impl fmt::Debug for Label {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 write!(f, "label({:?})", self.ident)
66 /// A "Lifetime" is an annotation of the scope in which variable
67 /// can be used, e.g. `'a` in `&'a i32`.
68 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
74 impl fmt::Debug for Lifetime {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 write!(f, "lifetime({}: {})", self.id, self)
80 impl fmt::Display for Lifetime {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 write!(f, "{}", self.ident.name)
86 /// A "Path" is essentially Rust's notion of a name.
88 /// It's represented as a sequence of identifiers,
89 /// along with a bunch of supporting information.
91 /// E.g., `std::cmp::PartialEq`.
92 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
95 /// The segments in the path: the things separated by `::`.
96 /// Global paths begin with `kw::PathRoot`.
97 pub segments: Vec<PathSegment>,
100 impl PartialEq<Symbol> for Path {
101 fn eq(&self, symbol: &Symbol) -> bool {
102 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
106 impl<CTX> HashStable<CTX> for Path {
107 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
108 self.segments.len().hash_stable(hcx, hasher);
109 for segment in &self.segments {
110 segment.ident.name.hash_stable(hcx, hasher);
116 // Convert a span and an identifier to the corresponding
118 pub fn from_ident(ident: Ident) -> Path {
119 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
122 pub fn is_global(&self) -> bool {
123 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
127 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
129 /// E.g., `std`, `String` or `Box<T>`.
130 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
131 pub struct PathSegment {
132 /// The identifier portion of this path segment.
137 /// Type/lifetime parameters attached to this path. They come in
138 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
139 /// `None` means that no parameter list is supplied (`Path`),
140 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
141 /// but it can be empty (`Path<>`).
142 /// `P` is used as a size optimization for the common case with no parameters.
143 pub args: Option<P<GenericArgs>>,
147 pub fn from_ident(ident: Ident) -> Self {
148 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
150 pub fn path_root(span: Span) -> Self {
151 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
155 /// The arguments of a path segment.
157 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
158 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
159 pub enum GenericArgs {
160 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
161 AngleBracketed(AngleBracketedArgs),
162 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
163 Parenthesized(ParenthesizedArgs),
167 pub fn is_parenthesized(&self) -> bool {
169 Parenthesized(..) => true,
174 pub fn is_angle_bracketed(&self) -> bool {
176 AngleBracketed(..) => true,
181 pub fn span(&self) -> Span {
183 AngleBracketed(ref data) => data.span,
184 Parenthesized(ref data) => data.span,
189 /// Concrete argument in the sequence of generic args.
190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
191 pub enum GenericArg {
192 /// `'a` in `Foo<'a>`
194 /// `Bar` in `Foo<Bar>`
201 pub fn span(&self) -> Span {
203 GenericArg::Lifetime(lt) => lt.ident.span,
204 GenericArg::Type(ty) => ty.span,
205 GenericArg::Const(ct) => ct.value.span,
210 /// A path like `Foo<'a, T>`.
211 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
212 pub struct AngleBracketedArgs {
213 /// The overall span.
215 /// The comma separated parts in the `<...>`.
216 pub args: Vec<AngleBracketedArg>,
219 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
220 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
221 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
222 pub enum AngleBracketedArg {
223 /// Argument for a generic parameter.
225 /// Constraint for an associated item.
226 Constraint(AssocTyConstraint),
229 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
230 fn into(self) -> Option<P<GenericArgs>> {
231 Some(P(GenericArgs::AngleBracketed(self)))
235 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
236 fn into(self) -> Option<P<GenericArgs>> {
237 Some(P(GenericArgs::Parenthesized(self)))
241 /// A path like `Foo(A, B) -> C`.
242 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
243 pub struct ParenthesizedArgs {
248 pub inputs: Vec<P<Ty>>,
254 impl ParenthesizedArgs {
255 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
260 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
262 AngleBracketedArgs { span: self.span, args }
266 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
268 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
270 /// Negative bounds should also be handled here.
271 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
272 pub enum TraitBoundModifier {
284 // This parses but will be rejected during AST validation.
288 /// The AST represents all type param bounds as types.
289 /// `typeck::collect::compute_bounds` matches these against
290 /// the "special" built-in traits (see `middle::lang_items`) and
291 /// detects `Copy`, `Send` and `Sync`.
292 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
293 pub enum GenericBound {
294 Trait(PolyTraitRef, TraitBoundModifier),
299 pub fn span(&self) -> Span {
301 GenericBound::Trait(ref t, ..) => t.span,
302 GenericBound::Outlives(ref l) => l.ident.span,
307 pub type GenericBounds = Vec<GenericBound>;
309 /// Specifies the enforced ordering for generic parameters. In the future,
310 /// if we wanted to relax this order, we could override `PartialEq` and
311 /// `PartialOrd`, to allow the kinds to be unordered.
312 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
313 pub enum ParamKindOrd {
319 impl fmt::Display for ParamKindOrd {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 ParamKindOrd::Lifetime => "lifetime".fmt(f),
323 ParamKindOrd::Type => "type".fmt(f),
324 ParamKindOrd::Const => "const".fmt(f),
329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
330 pub enum GenericParamKind {
331 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
334 default: Option<P<Ty>>,
338 /// Span of the `const` keyword.
343 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
344 pub struct GenericParam {
348 pub bounds: GenericBounds,
349 pub is_placeholder: bool,
350 pub kind: GenericParamKind,
353 /// Represents lifetime, type and const parameters attached to a declaration of
354 /// a function, enum, trait, etc.
355 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
356 pub struct Generics {
357 pub params: Vec<GenericParam>,
358 pub where_clause: WhereClause,
362 impl Default for Generics {
363 /// Creates an instance of `Generics`.
364 fn default() -> Generics {
367 where_clause: WhereClause {
368 has_where_token: false,
369 predicates: Vec::new(),
377 /// A where-clause in a definition.
378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
379 pub struct WhereClause {
380 /// `true` if we ate a `where` token: this can happen
381 /// if we parsed no predicates (e.g. `struct Foo where {}
382 /// This allows us to accurately pretty-print
383 /// in `nt_to_tokenstream`
384 pub has_where_token: bool,
385 pub predicates: Vec<WherePredicate>,
389 /// A single predicate in a where-clause.
390 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
391 pub enum WherePredicate {
392 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
393 BoundPredicate(WhereBoundPredicate),
394 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
395 RegionPredicate(WhereRegionPredicate),
396 /// An equality predicate (unsupported).
397 EqPredicate(WhereEqPredicate),
400 impl WherePredicate {
401 pub fn span(&self) -> Span {
403 &WherePredicate::BoundPredicate(ref p) => p.span,
404 &WherePredicate::RegionPredicate(ref p) => p.span,
405 &WherePredicate::EqPredicate(ref p) => p.span,
412 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
413 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
414 pub struct WhereBoundPredicate {
416 /// Any generics from a `for` binding.
417 pub bound_generic_params: Vec<GenericParam>,
418 /// The type being bounded.
419 pub bounded_ty: P<Ty>,
420 /// Trait and lifetime bounds (`Clone + Send + 'static`).
421 pub bounds: GenericBounds,
424 /// A lifetime predicate.
426 /// E.g., `'a: 'b + 'c`.
427 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
428 pub struct WhereRegionPredicate {
430 pub lifetime: Lifetime,
431 pub bounds: GenericBounds,
434 /// An equality predicate (unsupported).
437 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
438 pub struct WhereEqPredicate {
445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
448 pub attrs: Vec<Attribute>,
450 /// The order of items in the HIR is unrelated to the order of
451 /// items in the AST. However, we generate proc macro harnesses
452 /// based on the AST order, and later refer to these harnesses
453 /// from the HIR. This field keeps track of the order in which
454 /// we generated proc macros harnesses, so that we can map
455 /// HIR proc macros items back to their harness items.
456 pub proc_macros: Vec<NodeId>,
459 /// Possible values inside of compile-time attribute lists.
461 /// E.g., the '..' in `#[name(..)]`.
462 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
463 pub enum NestedMetaItem {
464 /// A full MetaItem, for recursive meta items.
468 /// E.g., `"foo"`, `64`, `true`.
472 /// A spanned compile-time attribute item.
474 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
475 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
476 pub struct MetaItem {
478 pub kind: MetaItemKind,
482 /// A compile-time attribute item.
484 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
485 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
486 pub enum MetaItemKind {
489 /// E.g., `test` as in `#[test]`.
493 /// E.g., `derive(..)` as in `#[derive(..)]`.
494 List(Vec<NestedMetaItem>),
495 /// Name value meta item.
497 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
501 /// A block (`{ .. }`).
503 /// E.g., `{ .. }` as in `fn foo() { .. }`.
504 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
506 /// The statements in the block.
507 pub stmts: Vec<Stmt>,
509 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
510 pub rules: BlockCheckMode,
516 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
517 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
525 /// Attempt reparsing the pattern as a type.
526 /// This is intended for use by diagnostics.
527 pub fn to_ty(&self) -> Option<P<Ty>> {
528 let kind = match &self.kind {
529 // In a type expression `_` is an inference variable.
530 PatKind::Wild => TyKind::Infer,
531 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
532 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
533 TyKind::Path(None, Path::from_ident(*ident))
535 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
536 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
537 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
538 PatKind::Ref(pat, mutbl) => {
539 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
541 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
542 // when `P` can be reparsed as a type `T`.
543 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
544 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
545 // assuming `T0` to `Tn` are all syntactically valid as types.
546 PatKind::Tuple(pats) => {
547 let mut tys = Vec::with_capacity(pats.len());
548 // FIXME(#48994) - could just be collected into an Option<Vec>
550 tys.push(pat.to_ty()?);
557 Some(P(Ty { kind, id: self.id, span: self.span }))
560 /// Walk top-down and call `it` in each place where a pattern occurs
561 /// starting with the root pattern `walk` is called on. If `it` returns
562 /// false then we will descend no further but siblings will be processed.
563 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
569 // Walk into the pattern associated with `Ident` (if any).
570 PatKind::Ident(_, _, Some(p)) => p.walk(it),
572 // Walk into each field of struct.
573 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
575 // Sequence of patterns.
576 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
577 s.iter().for_each(|p| p.walk(it))
580 // Trivial wrappers over inner patterns.
581 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
583 // These patterns do not contain subpatterns, skip.
590 | PatKind::MacCall(_) => {}
594 /// Is this a `..` pattern?
595 pub fn is_rest(&self) -> bool {
597 PatKind::Rest => true,
603 /// A single field in a struct pattern
605 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
606 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
607 /// except is_shorthand is true
608 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
609 pub struct FieldPat {
610 /// The identifier for the field
612 /// The pattern the field is destructured to
614 pub is_shorthand: bool,
618 pub is_placeholder: bool,
621 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
622 pub enum BindingMode {
627 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
629 Included(RangeSyntax),
633 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
634 pub enum RangeSyntax {
641 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
643 /// Represents a wildcard pattern (`_`).
646 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
647 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
648 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
649 /// during name resolution.
650 Ident(BindingMode, Ident, Option<P<Pat>>),
652 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
653 /// The `bool` is `true` in the presence of a `..`.
654 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
656 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
657 TupleStruct(Path, Vec<P<Pat>>),
659 /// An or-pattern `A | B | C`.
660 /// Invariant: `pats.len() >= 2`.
663 /// A possibly qualified path pattern.
664 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
665 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
666 /// only legally refer to associated constants.
667 Path(Option<QSelf>, Path),
669 /// A tuple pattern (`(a, b)`).
675 /// A reference pattern (e.g., `&mut (a, b)`).
676 Ref(P<Pat>, Mutability),
681 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
682 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
684 /// A slice pattern `[a, b, c]`.
687 /// A rest pattern `..`.
689 /// Syntactically it is valid anywhere.
691 /// Semantically however, it only has meaning immediately inside:
692 /// - a slice pattern: `[a, .., b]`,
693 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
694 /// - a tuple pattern: `(a, .., b)`,
695 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
697 /// In all of these cases, an additional restriction applies,
698 /// only one rest pattern may occur in the pattern sequences.
701 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
704 /// A macro pattern; pre-expansion.
708 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
709 #[derive(HashStable_Generic)]
710 pub enum Mutability {
716 /// Returns `MutMutable` only if both `self` and `other` are mutable.
717 pub fn and(self, other: Self) -> Self {
719 Mutability::Mut => other,
720 Mutability::Not => Mutability::Not,
724 pub fn invert(self) -> Self {
726 Mutability::Mut => Mutability::Not,
727 Mutability::Not => Mutability::Mut,
731 pub fn prefix_str(&self) -> &'static str {
733 Mutability::Mut => "mut ",
734 Mutability::Not => "",
739 /// The kind of borrow in an `AddrOf` expression,
740 /// e.g., `&place` or `&raw const place`.
741 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
742 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
743 pub enum BorrowKind {
744 /// A normal borrow, `&$expr` or `&mut $expr`.
745 /// The resulting type is either `&'a T` or `&'a mut T`
746 /// where `T = typeof($expr)` and `'a` is some lifetime.
748 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
749 /// The resulting type is either `*const T` or `*mut T`
750 /// where `T = typeof($expr)`.
754 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
756 /// The `+` operator (addition)
758 /// The `-` operator (subtraction)
760 /// The `*` operator (multiplication)
762 /// The `/` operator (division)
764 /// The `%` operator (modulus)
766 /// The `&&` operator (logical and)
768 /// The `||` operator (logical or)
770 /// The `^` operator (bitwise xor)
772 /// The `&` operator (bitwise and)
774 /// The `|` operator (bitwise or)
776 /// The `<<` operator (shift left)
778 /// The `>>` operator (shift right)
780 /// The `==` operator (equality)
782 /// The `<` operator (less than)
784 /// The `<=` operator (less than or equal to)
786 /// The `!=` operator (not equal to)
788 /// The `>=` operator (greater than or equal to)
790 /// The `>` operator (greater than)
795 pub fn to_string(&self) -> &'static str {
818 pub fn lazy(&self) -> bool {
820 BinOpKind::And | BinOpKind::Or => true,
825 pub fn is_shift(&self) -> bool {
827 BinOpKind::Shl | BinOpKind::Shr => true,
832 pub fn is_comparison(&self) -> bool {
834 // Note for developers: please keep this as is;
835 // we want compilation to fail if another variant is added.
837 Eq | Lt | Le | Ne | Gt | Ge => true,
838 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
842 /// Returns `true` if the binary operator takes its arguments by value
843 pub fn is_by_value(&self) -> bool {
844 !self.is_comparison()
848 pub type BinOp = Spanned<BinOpKind>;
852 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
853 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
855 /// The `*` operator for dereferencing
857 /// The `!` operator for logical inversion
859 /// The `-` operator for negation
864 /// Returns `true` if the unary operator takes its argument by value
865 pub fn is_by_value(u: UnOp) -> bool {
867 UnOp::Neg | UnOp::Not => true,
872 pub fn to_string(op: UnOp) -> &'static str {
882 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
890 pub fn add_trailing_semicolon(mut self) -> Self {
891 self.kind = match self.kind {
892 StmtKind::Expr(expr) => StmtKind::Semi(expr),
893 StmtKind::MacCall(mac) => StmtKind::MacCall(
894 mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)),
901 pub fn is_item(&self) -> bool {
903 StmtKind::Item(_) => true,
908 pub fn is_expr(&self) -> bool {
910 StmtKind::Expr(_) => true,
916 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
918 /// A local (let) binding.
920 /// An item definition.
922 /// Expr without trailing semi-colon.
924 /// Expr with a trailing semi-colon.
926 /// Just a trailing semi-colon.
929 MacCall(P<(MacCall, MacStmtStyle, AttrVec)>),
932 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
933 pub enum MacStmtStyle {
934 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
935 /// `foo!(...);`, `foo![...];`).
937 /// The macro statement had braces (e.g., `foo! { ... }`).
939 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
940 /// `foo!(...)`). All of these will end up being converted into macro
945 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
946 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
950 pub ty: Option<P<Ty>>,
951 /// Initializer expression to set the value, if any.
952 pub init: Option<P<Expr>>,
957 /// An arm of a 'match'.
959 /// E.g., `0..=10 => { println!("match!") }` as in
963 /// 0..=10 => { println!("match!") },
964 /// _ => { println!("no match!") },
967 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
969 pub attrs: Vec<Attribute>,
970 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
972 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
973 pub guard: Option<P<Expr>>,
978 pub is_placeholder: bool,
981 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
982 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
989 pub is_shorthand: bool,
990 pub is_placeholder: bool,
993 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
994 pub enum BlockCheckMode {
996 Unsafe(UnsafeSource),
999 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1000 pub enum UnsafeSource {
1005 /// A constant (expression) that's not an item or associated item,
1006 /// but needs its own `DefId` for type-checking, const-eval, etc.
1007 /// These are usually found nested inside types (e.g., array lengths)
1008 /// or expressions (e.g., repeat counts), and also used to define
1009 /// explicit discriminant values for enum variants.
1010 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1011 pub struct AnonConst {
1017 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1023 pub tokens: Option<TokenStream>,
1026 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1027 #[cfg(target_arch = "x86_64")]
1028 rustc_data_structures::static_assert_size!(Expr, 104);
1031 /// Returns `true` if this expression would be valid somewhere that expects a value;
1032 /// for example, an `if` condition.
1033 pub fn returns(&self) -> bool {
1034 if let ExprKind::Block(ref block, _) = self.kind {
1035 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1037 Some(&StmtKind::Expr(_)) => true,
1038 Some(&StmtKind::Semi(ref expr)) => {
1039 if let ExprKind::Ret(_) = expr.kind {
1040 // Last statement is explicit return.
1046 // This is a block that doesn't end in either an implicit or explicit return.
1050 // This is not a block, it is a value.
1055 pub fn to_bound(&self) -> Option<GenericBound> {
1057 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1058 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1059 TraitBoundModifier::None,
1065 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1066 pub fn to_ty(&self) -> Option<P<Ty>> {
1067 let kind = match &self.kind {
1068 // Trivial conversions.
1069 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1070 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1072 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1074 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1075 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1078 ExprKind::Repeat(expr, expr_len) => {
1079 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1082 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1084 ExprKind::Tup(exprs) => {
1085 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1089 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1090 // then type of result is trait object.
1091 // Otherwise we don't assume the result type.
1092 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1093 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1094 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1100 // This expression doesn't look like a type syntactically.
1104 Some(P(Ty { kind, id: self.id, span: self.span }))
1107 pub fn precedence(&self) -> ExprPrecedence {
1109 ExprKind::Box(_) => ExprPrecedence::Box,
1110 ExprKind::Array(_) => ExprPrecedence::Array,
1111 ExprKind::Call(..) => ExprPrecedence::Call,
1112 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1113 ExprKind::Tup(_) => ExprPrecedence::Tup,
1114 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1115 ExprKind::Unary(..) => ExprPrecedence::Unary,
1116 ExprKind::Lit(_) => ExprPrecedence::Lit,
1117 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1118 ExprKind::Let(..) => ExprPrecedence::Let,
1119 ExprKind::If(..) => ExprPrecedence::If,
1120 ExprKind::While(..) => ExprPrecedence::While,
1121 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1122 ExprKind::Loop(..) => ExprPrecedence::Loop,
1123 ExprKind::Match(..) => ExprPrecedence::Match,
1124 ExprKind::Closure(..) => ExprPrecedence::Closure,
1125 ExprKind::Block(..) => ExprPrecedence::Block,
1126 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1127 ExprKind::Async(..) => ExprPrecedence::Async,
1128 ExprKind::Await(..) => ExprPrecedence::Await,
1129 ExprKind::Assign(..) => ExprPrecedence::Assign,
1130 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1131 ExprKind::Field(..) => ExprPrecedence::Field,
1132 ExprKind::Index(..) => ExprPrecedence::Index,
1133 ExprKind::Range(..) => ExprPrecedence::Range,
1134 ExprKind::Path(..) => ExprPrecedence::Path,
1135 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1136 ExprKind::Break(..) => ExprPrecedence::Break,
1137 ExprKind::Continue(..) => ExprPrecedence::Continue,
1138 ExprKind::Ret(..) => ExprPrecedence::Ret,
1139 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1140 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1141 ExprKind::Struct(..) => ExprPrecedence::Struct,
1142 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1143 ExprKind::Paren(..) => ExprPrecedence::Paren,
1144 ExprKind::Try(..) => ExprPrecedence::Try,
1145 ExprKind::Yield(..) => ExprPrecedence::Yield,
1146 ExprKind::Err => ExprPrecedence::Err,
1151 /// Limit types of a range (inclusive or exclusive)
1152 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1153 pub enum RangeLimits {
1154 /// Inclusive at the beginning, exclusive at the end
1156 /// Inclusive at the beginning and end
1160 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1162 /// A `box x` expression.
1164 /// An array (`[a, b, c, d]`)
1165 Array(Vec<P<Expr>>),
1168 /// The first field resolves to the function itself,
1169 /// and the second field is the list of arguments.
1170 /// This also represents calling the constructor of
1171 /// tuple-like ADTs such as tuple structs and enum variants.
1172 Call(P<Expr>, Vec<P<Expr>>),
1173 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1175 /// The `PathSegment` represents the method name and its generic arguments
1176 /// (within the angle brackets).
1177 /// The first element of the vector of an `Expr` is the expression that evaluates
1178 /// to the object on which the method is being called on (the receiver),
1179 /// and the remaining elements are the rest of the arguments.
1180 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1181 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1182 /// This `Span` is the span of the function, without the dot and receiver
1183 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1184 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1185 /// A tuple (e.g., `(a, b, c, d)`).
1187 /// A binary operation (e.g., `a + b`, `a * b`).
1188 Binary(BinOp, P<Expr>, P<Expr>),
1189 /// A unary operation (e.g., `!x`, `*x`).
1190 Unary(UnOp, P<Expr>),
1191 /// A literal (e.g., `1`, `"foo"`).
1193 /// A cast (e.g., `foo as f64`).
1194 Cast(P<Expr>, P<Ty>),
1195 /// A type ascription (e.g., `42: usize`).
1196 Type(P<Expr>, P<Ty>),
1197 /// A `let pat = expr` expression that is only semantically allowed in the condition
1198 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1199 Let(P<Pat>, P<Expr>),
1200 /// An `if` block, with an optional `else` block.
1202 /// `if expr { block } else { expr }`
1203 If(P<Expr>, P<Block>, Option<P<Expr>>),
1204 /// A while loop, with an optional label.
1206 /// `'label: while expr { block }`
1207 While(P<Expr>, P<Block>, Option<Label>),
1208 /// A `for` loop, with an optional label.
1210 /// `'label: for pat in expr { block }`
1212 /// This is desugared to a combination of `loop` and `match` expressions.
1213 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1214 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1216 /// `'label: loop { block }`
1217 Loop(P<Block>, Option<Label>),
1218 /// A `match` block.
1219 Match(P<Expr>, Vec<Arm>),
1220 /// A closure (e.g., `move |a, b, c| a + b + c`).
1222 /// The final span is the span of the argument block `|...|`.
1223 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1224 /// A block (`'label: { ... }`).
1225 Block(P<Block>, Option<Label>),
1226 /// An async block (`async move { ... }`).
1228 /// The `NodeId` is the `NodeId` for the closure that results from
1229 /// desugaring an async block, just like the NodeId field in the
1230 /// `Async::Yes` variant. This is necessary in order to create a def for the
1231 /// closure which can be used as a parent of any child defs. Defs
1232 /// created during lowering cannot be made the parent of any other
1233 /// preexisting defs.
1234 Async(CaptureBy, NodeId, P<Block>),
1235 /// An await expression (`my_future.await`).
1238 /// A try block (`try { ... }`).
1241 /// An assignment (`a = foo()`).
1242 /// The `Span` argument is the span of the `=` token.
1243 Assign(P<Expr>, P<Expr>, Span),
1244 /// An assignment with an operator.
1247 AssignOp(BinOp, P<Expr>, P<Expr>),
1248 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1249 Field(P<Expr>, Ident),
1250 /// An indexing operation (e.g., `foo[2]`).
1251 Index(P<Expr>, P<Expr>),
1252 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1253 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1255 /// Variable reference, possibly containing `::` and/or type
1256 /// parameters (e.g., `foo::bar::<baz>`).
1258 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1259 Path(Option<QSelf>, Path),
1261 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1262 AddrOf(BorrowKind, Mutability, P<Expr>),
1263 /// A `break`, with an optional label to break, and an optional expression.
1264 Break(Option<Label>, Option<P<Expr>>),
1265 /// A `continue`, with an optional label.
1266 Continue(Option<Label>),
1267 /// A `return`, with an optional value to be returned.
1268 Ret(Option<P<Expr>>),
1270 /// Output of the `asm!()` macro.
1271 InlineAsm(P<InlineAsm>),
1272 /// Output of the `llvm_asm!()` macro.
1273 LlvmInlineAsm(P<LlvmInlineAsm>),
1275 /// A macro invocation; pre-expansion.
1278 /// A struct literal expression.
1280 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1281 /// where `base` is the `Option<Expr>`.
1282 Struct(Path, Vec<Field>, Option<P<Expr>>),
1284 /// An array literal constructed from one repeated element.
1286 /// E.g., `[1; 5]`. The expression is the element to be
1287 /// repeated; the constant is the number of times to repeat it.
1288 Repeat(P<Expr>, AnonConst),
1290 /// No-op: used solely so we can pretty-print faithfully.
1293 /// A try expression (`expr?`).
1296 /// A `yield`, with an optional value to be yielded.
1297 Yield(Option<P<Expr>>),
1299 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1303 /// The explicit `Self` type in a "qualified path". The actual
1304 /// path, including the trait and the associated item, is stored
1305 /// separately. `position` represents the index of the associated
1306 /// item qualified with this `Self` type.
1308 /// ```ignore (only-for-syntax-highlight)
1309 /// <Vec<T> as a::b::Trait>::AssociatedItem
1310 /// ^~~~~ ~~~~~~~~~~~~~~^
1313 /// <Vec<T>>::AssociatedItem
1317 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1321 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1322 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1323 /// 0`, this is an empty span.
1324 pub path_span: Span,
1325 pub position: usize,
1328 /// A capture clause used in closures and `async` blocks.
1329 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1330 pub enum CaptureBy {
1331 /// `move |x| y + x`.
1333 /// `move` keyword was not specified.
1337 /// The movability of a generator / closure literal:
1338 /// whether a generator contains self-references, causing it to be `!Unpin`.
1339 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1340 #[derive(HashStable_Generic)]
1341 pub enum Movability {
1342 /// May contain self-references, `!Unpin`.
1344 /// Must not contain self-references, `Unpin`.
1348 /// Represents a macro invocation. The `path` indicates which macro
1349 /// is being invoked, and the `args` are arguments passed to it.
1350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1351 pub struct MacCall {
1353 pub args: P<MacArgs>,
1354 pub prior_type_ascription: Option<(Span, bool)>,
1358 pub fn span(&self) -> Span {
1359 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1363 /// Arguments passed to an attribute or a function-like macro.
1364 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1366 /// No arguments - `#[attr]`.
1368 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1369 Delimited(DelimSpan, MacDelimiter, TokenStream),
1370 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1372 /// Span of the `=` token.
1374 /// Token stream of the "value".
1380 pub fn delim(&self) -> DelimToken {
1382 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1383 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1387 pub fn span(&self) -> Option<Span> {
1389 MacArgs::Empty => None,
1390 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1391 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1395 /// Tokens inside the delimiters or after `=`.
1396 /// Proc macros see these tokens, for example.
1397 pub fn inner_tokens(&self) -> TokenStream {
1399 MacArgs::Empty => TokenStream::default(),
1400 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1404 /// Tokens together with the delimiters or `=`.
1405 /// Use of this method generally means that something suboptimal or hacky is happening.
1406 pub fn outer_tokens(&self) -> TokenStream {
1408 MacArgs::Empty => TokenStream::default(),
1409 MacArgs::Delimited(dspan, delim, ref tokens) => {
1410 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1412 MacArgs::Eq(eq_span, ref tokens) => {
1413 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1418 /// Whether a macro with these arguments needs a semicolon
1419 /// when used as a standalone item or statement.
1420 pub fn need_semicolon(&self) -> bool {
1421 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1425 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1426 pub enum MacDelimiter {
1433 pub fn to_token(self) -> DelimToken {
1435 MacDelimiter::Parenthesis => DelimToken::Paren,
1436 MacDelimiter::Bracket => DelimToken::Bracket,
1437 MacDelimiter::Brace => DelimToken::Brace,
1441 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1443 token::Paren => Some(MacDelimiter::Parenthesis),
1444 token::Bracket => Some(MacDelimiter::Bracket),
1445 token::Brace => Some(MacDelimiter::Brace),
1446 token::NoDelim => None,
1451 /// Represents a macro definition.
1452 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1453 pub struct MacroDef {
1454 pub body: P<MacArgs>,
1455 /// `true` if macro was defined with `macro_rules`.
1456 pub macro_rules: bool,
1459 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, Eq, PartialEq)]
1460 #[derive(HashStable_Generic)]
1462 /// A regular string, like `"foo"`.
1464 /// A raw string, like `r##"foo"##`.
1466 /// The value is the number of `#` symbols used.
1471 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1473 /// The original literal token as written in source code.
1474 pub token: token::Lit,
1475 /// The "semantic" representation of the literal lowered from the original tokens.
1476 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1477 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1482 /// Same as `Lit`, but restricted to string literals.
1483 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1485 /// The original literal token as written in source code.
1486 pub style: StrStyle,
1488 pub suffix: Option<Symbol>,
1490 /// The unescaped "semantic" representation of the literal lowered from the original token.
1491 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1492 pub symbol_unescaped: Symbol,
1496 pub fn as_lit(&self) -> Lit {
1497 let token_kind = match self.style {
1498 StrStyle::Cooked => token::Str,
1499 StrStyle::Raw(n) => token::StrRaw(n),
1502 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1504 kind: LitKind::Str(self.symbol_unescaped, self.style),
1509 /// Type of the integer literal based on provided suffix.
1510 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1511 #[derive(HashStable_Generic)]
1512 pub enum LitIntType {
1521 /// Type of the float literal based on provided suffix.
1522 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1523 #[derive(HashStable_Generic)]
1524 pub enum LitFloatType {
1525 /// A float literal with a suffix (`1f32` or `1E10f32`).
1527 /// A float literal without a suffix (`1.0 or 1.0E10`).
1533 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1534 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1536 /// A string literal (`"foo"`).
1537 Str(Symbol, StrStyle),
1538 /// A byte string (`b"foo"`).
1539 ByteStr(Lrc<Vec<u8>>),
1540 /// A byte char (`b'f'`).
1542 /// A character literal (`'a'`).
1544 /// An integer literal (`1`).
1545 Int(u128, LitIntType),
1546 /// A float literal (`1f64` or `1E10f64`).
1547 Float(Symbol, LitFloatType),
1548 /// A boolean literal.
1550 /// Placeholder for a literal that wasn't well-formed in some way.
1555 /// Returns `true` if this literal is a string.
1556 pub fn is_str(&self) -> bool {
1558 LitKind::Str(..) => true,
1563 /// Returns `true` if this literal is byte literal string.
1564 pub fn is_bytestr(&self) -> bool {
1566 LitKind::ByteStr(_) => true,
1571 /// Returns `true` if this is a numeric literal.
1572 pub fn is_numeric(&self) -> bool {
1574 LitKind::Int(..) | LitKind::Float(..) => true,
1579 /// Returns `true` if this literal has no suffix.
1580 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1581 pub fn is_unsuffixed(&self) -> bool {
1585 /// Returns `true` if this literal has a suffix.
1586 pub fn is_suffixed(&self) -> bool {
1588 // suffixed variants
1589 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1590 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1591 // unsuffixed variants
1593 | LitKind::ByteStr(..)
1596 | LitKind::Int(_, LitIntType::Unsuffixed)
1597 | LitKind::Float(_, LitFloatType::Unsuffixed)
1599 | LitKind::Err(..) => false,
1604 // N.B., If you change this, you'll probably want to change the corresponding
1605 // type structure in `middle/ty.rs` as well.
1606 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1609 pub mutbl: Mutability,
1612 /// Represents a function's signature in a trait declaration,
1613 /// trait implementation, or free function.
1614 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1616 pub header: FnHeader,
1617 pub decl: P<FnDecl>,
1620 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
1621 #[derive(HashStable_Generic)]
1628 pub fn name_str(self) -> &'static str {
1630 FloatTy::F32 => "f32",
1631 FloatTy::F64 => "f64",
1635 pub fn name(self) -> Symbol {
1637 FloatTy::F32 => sym::f32,
1638 FloatTy::F64 => sym::f64,
1642 pub fn bit_width(self) -> u64 {
1650 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
1651 #[derive(HashStable_Generic)]
1662 pub fn name_str(&self) -> &'static str {
1664 IntTy::Isize => "isize",
1666 IntTy::I16 => "i16",
1667 IntTy::I32 => "i32",
1668 IntTy::I64 => "i64",
1669 IntTy::I128 => "i128",
1673 pub fn name(&self) -> Symbol {
1675 IntTy::Isize => sym::isize,
1676 IntTy::I8 => sym::i8,
1677 IntTy::I16 => sym::i16,
1678 IntTy::I32 => sym::i32,
1679 IntTy::I64 => sym::i64,
1680 IntTy::I128 => sym::i128,
1684 pub fn val_to_string(&self, val: i128) -> String {
1685 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1686 // are parsed as `u128`, so we wouldn't want to print an extra negative
1688 format!("{}{}", val as u128, self.name_str())
1691 pub fn bit_width(&self) -> Option<u64> {
1693 IntTy::Isize => return None,
1702 pub fn normalize(&self, target_width: u32) -> Self {
1704 IntTy::Isize => match target_width {
1708 _ => unreachable!(),
1715 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy, Debug)]
1716 #[derive(HashStable_Generic)]
1727 pub fn name_str(&self) -> &'static str {
1729 UintTy::Usize => "usize",
1731 UintTy::U16 => "u16",
1732 UintTy::U32 => "u32",
1733 UintTy::U64 => "u64",
1734 UintTy::U128 => "u128",
1738 pub fn name(&self) -> Symbol {
1740 UintTy::Usize => sym::usize,
1741 UintTy::U8 => sym::u8,
1742 UintTy::U16 => sym::u16,
1743 UintTy::U32 => sym::u32,
1744 UintTy::U64 => sym::u64,
1745 UintTy::U128 => sym::u128,
1749 pub fn val_to_string(&self, val: u128) -> String {
1750 format!("{}{}", val, self.name_str())
1753 pub fn bit_width(&self) -> Option<u64> {
1755 UintTy::Usize => return None,
1760 UintTy::U128 => 128,
1764 pub fn normalize(&self, target_width: u32) -> Self {
1766 UintTy::Usize => match target_width {
1770 _ => unreachable!(),
1777 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1778 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1779 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1780 pub struct AssocTyConstraint {
1783 pub kind: AssocTyConstraintKind,
1787 /// The kinds of an `AssocTyConstraint`.
1788 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1789 pub enum AssocTyConstraintKind {
1790 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1791 Equality { ty: P<Ty> },
1792 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1793 Bound { bounds: GenericBounds },
1796 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1803 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1804 pub struct BareFnTy {
1805 pub unsafety: Unsafe,
1807 pub generic_params: Vec<GenericParam>,
1808 pub decl: P<FnDecl>,
1811 /// The various kinds of type recognized by the compiler.
1812 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1814 /// A variable-length slice (`[T]`).
1816 /// A fixed length array (`[T; n]`).
1817 Array(P<Ty>, AnonConst),
1818 /// A raw pointer (`*const T` or `*mut T`).
1820 /// A reference (`&'a T` or `&'a mut T`).
1821 Rptr(Option<Lifetime>, MutTy),
1822 /// A bare function (e.g., `fn(usize) -> bool`).
1823 BareFn(P<BareFnTy>),
1824 /// The never type (`!`).
1826 /// A tuple (`(A, B, C, D,...)`).
1828 /// A path (`module::module::...::Type`), optionally
1829 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1831 /// Type parameters are stored in the `Path` itself.
1832 Path(Option<QSelf>, Path),
1833 /// A trait object type `Bound1 + Bound2 + Bound3`
1834 /// where `Bound` is a trait or a lifetime.
1835 TraitObject(GenericBounds, TraitObjectSyntax),
1836 /// An `impl Bound1 + Bound2 + Bound3` type
1837 /// where `Bound` is a trait or a lifetime.
1839 /// The `NodeId` exists to prevent lowering from having to
1840 /// generate `NodeId`s on the fly, which would complicate
1841 /// the generation of opaque `type Foo = impl Trait` items significantly.
1842 ImplTrait(NodeId, GenericBounds),
1843 /// No-op; kept solely so that we can pretty-print faithfully.
1847 /// This means the type should be inferred instead of it having been
1848 /// specified. This can appear anywhere in a type.
1850 /// Inferred type of a `self` or `&self` argument in a method.
1852 /// A macro in the type position.
1854 /// Placeholder for a kind that has failed to be defined.
1856 /// Placeholder for a `va_list`.
1861 pub fn is_implicit_self(&self) -> bool {
1862 if let TyKind::ImplicitSelf = *self { true } else { false }
1865 pub fn is_unit(&self) -> bool {
1866 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1870 /// Syntax used to declare a trait object.
1871 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1872 pub enum TraitObjectSyntax {
1877 /// Inline assembly operand explicit register or register class.
1879 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1880 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1881 pub enum InlineAsmRegOrRegClass {
1886 bitflags::bitflags! {
1887 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1888 pub struct InlineAsmOptions: u8 {
1889 const PURE = 1 << 0;
1890 const NOMEM = 1 << 1;
1891 const READONLY = 1 << 2;
1892 const PRESERVES_FLAGS = 1 << 3;
1893 const NORETURN = 1 << 4;
1894 const NOSTACK = 1 << 5;
1895 const ATT_SYNTAX = 1 << 6;
1899 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1900 pub enum InlineAsmTemplatePiece {
1902 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1905 impl fmt::Display for InlineAsmTemplatePiece {
1906 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1908 Self::String(s) => {
1909 for c in s.chars() {
1911 '{' => f.write_str("{{")?,
1912 '}' => f.write_str("}}")?,
1918 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1919 write!(f, "{{{}:{}}}", operand_idx, modifier)
1921 Self::Placeholder { operand_idx, modifier: None, .. } => {
1922 write!(f, "{{{}}}", operand_idx)
1928 impl InlineAsmTemplatePiece {
1929 /// Rebuilds the asm template string from its pieces.
1930 pub fn to_string(s: &[Self]) -> String {
1932 let mut out = String::new();
1934 let _ = write!(out, "{}", p);
1940 /// Inline assembly operand.
1942 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
1943 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1944 pub enum InlineAsmOperand {
1946 reg: InlineAsmRegOrRegClass,
1950 reg: InlineAsmRegOrRegClass,
1952 expr: Option<P<Expr>>,
1955 reg: InlineAsmRegOrRegClass,
1960 reg: InlineAsmRegOrRegClass,
1963 out_expr: Option<P<Expr>>,
1973 /// Inline assembly.
1975 /// E.g., `asm!("NOP");`.
1976 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1977 pub struct InlineAsm {
1978 pub template: Vec<InlineAsmTemplatePiece>,
1979 pub operands: Vec<(InlineAsmOperand, Span)>,
1980 pub options: InlineAsmOptions,
1981 pub line_spans: Vec<Span>,
1984 /// Inline assembly dialect.
1986 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1987 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1988 pub enum LlvmAsmDialect {
1993 /// LLVM-style inline assembly.
1995 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1996 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1997 pub struct LlvmInlineAsmOutput {
1998 pub constraint: Symbol,
2001 pub is_indirect: bool,
2004 /// LLVM-style inline assembly.
2006 /// E.g., `llvm_asm!("NOP");`.
2007 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2008 pub struct LlvmInlineAsm {
2010 pub asm_str_style: StrStyle,
2011 pub outputs: Vec<LlvmInlineAsmOutput>,
2012 pub inputs: Vec<(Symbol, P<Expr>)>,
2013 pub clobbers: Vec<Symbol>,
2015 pub alignstack: bool,
2016 pub dialect: LlvmAsmDialect,
2019 /// A parameter in a function header.
2021 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2022 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2029 pub is_placeholder: bool,
2032 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2034 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2035 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2037 /// `self`, `mut self`
2039 /// `&'lt self`, `&'lt mut self`
2040 Region(Option<Lifetime>, Mutability),
2041 /// `self: TYPE`, `mut self: TYPE`
2042 Explicit(P<Ty>, Mutability),
2045 pub type ExplicitSelf = Spanned<SelfKind>;
2048 /// Attempts to cast parameter to `ExplicitSelf`.
2049 pub fn to_self(&self) -> Option<ExplicitSelf> {
2050 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2051 if ident.name == kw::SelfLower {
2052 return match self.ty.kind {
2053 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2054 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2055 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2058 self.pat.span.to(self.ty.span),
2059 SelfKind::Explicit(self.ty.clone(), mutbl),
2067 /// Returns `true` if parameter is `self`.
2068 pub fn is_self(&self) -> bool {
2069 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2070 ident.name == kw::SelfLower
2076 /// Builds a `Param` object from `ExplicitSelf`.
2077 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2078 let span = eself.span.to(eself_ident.span);
2079 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2080 let param = |mutbl, ty| Param {
2084 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2090 is_placeholder: false,
2093 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2094 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2095 SelfKind::Region(lt, mutbl) => param(
2099 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2107 /// A signature (not the body) of a function declaration.
2109 /// E.g., `fn foo(bar: baz)`.
2111 /// Please note that it's different from `FnHeader` structure
2112 /// which contains metadata about function safety, asyncness, constness and ABI.
2113 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2115 pub inputs: Vec<Param>,
2116 pub output: FnRetTy,
2120 pub fn get_self(&self) -> Option<ExplicitSelf> {
2121 self.inputs.get(0).and_then(Param::to_self)
2123 pub fn has_self(&self) -> bool {
2124 self.inputs.get(0).map_or(false, Param::is_self)
2126 pub fn c_variadic(&self) -> bool {
2127 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2128 TyKind::CVarArgs => true,
2134 /// Is the trait definition an auto trait?
2135 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2141 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
2142 #[derive(HashStable_Generic)]
2148 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2150 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2155 pub fn is_async(self) -> bool {
2156 if let Async::Yes { .. } = self { true } else { false }
2159 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2160 pub fn opt_return_id(self) -> Option<NodeId> {
2162 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2168 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
2169 #[derive(HashStable_Generic)]
2175 /// Item defaultness.
2176 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2177 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2178 pub enum Defaultness {
2183 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2184 pub enum ImplPolarity {
2185 /// `impl Trait for Type`
2187 /// `impl !Trait for Type`
2191 impl fmt::Debug for ImplPolarity {
2192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2194 ImplPolarity::Positive => "positive".fmt(f),
2195 ImplPolarity::Negative(_) => "negative".fmt(f),
2200 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2202 /// Returns type is not specified.
2204 /// Functions default to `()` and closures default to inference.
2205 /// Span points to where return type would be inserted.
2207 /// Everything else.
2212 pub fn span(&self) -> Span {
2214 FnRetTy::Default(span) => span,
2215 FnRetTy::Ty(ref ty) => ty.span,
2220 /// Module declaration.
2222 /// E.g., `mod foo;` or `mod foo { .. }`.
2223 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
2225 /// A span from the first token past `{` to the last token until `}`.
2226 /// For `mod foo;`, the inner span ranges from the first token
2227 /// to the last token in the external file.
2229 pub items: Vec<P<Item>>,
2230 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2234 /// Foreign module declaration.
2236 /// E.g., `extern { .. }` or `extern C { .. }`.
2237 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2238 pub struct ForeignMod {
2239 pub abi: Option<StrLit>,
2240 pub items: Vec<P<ForeignItem>>,
2243 /// Global inline assembly.
2245 /// Also known as "module-level assembly" or "file-scoped assembly".
2246 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2247 pub struct GlobalAsm {
2251 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2252 pub struct EnumDef {
2253 pub variants: Vec<Variant>,
2256 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2257 pub struct Variant {
2258 /// Attributes of the variant.
2259 pub attrs: Vec<Attribute>,
2260 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2264 /// The visibility of the variant. Syntactically accepted but not semantically.
2265 pub vis: Visibility,
2266 /// Name of the variant.
2269 /// Fields and constructor id of the variant.
2270 pub data: VariantData,
2271 /// Explicit discriminant, e.g., `Foo = 1`.
2272 pub disr_expr: Option<AnonConst>,
2273 /// Is a macro placeholder
2274 pub is_placeholder: bool,
2277 /// Part of `use` item to the right of its prefix.
2278 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2279 pub enum UseTreeKind {
2280 /// `use prefix` or `use prefix as rename`
2282 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2284 Simple(Option<Ident>, NodeId, NodeId),
2285 /// `use prefix::{...}`
2286 Nested(Vec<(UseTree, NodeId)>),
2291 /// A tree of paths sharing common prefixes.
2292 /// Used in `use` items both at top-level and inside of braces in import groups.
2293 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2294 pub struct UseTree {
2296 pub kind: UseTreeKind,
2301 pub fn ident(&self) -> Ident {
2303 UseTreeKind::Simple(Some(rename), ..) => rename,
2304 UseTreeKind::Simple(None, ..) => {
2305 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2307 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2312 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2313 /// are contained as statements within items. These two cases need to be
2314 /// distinguished for pretty-printing.
2315 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2316 pub enum AttrStyle {
2321 rustc_index::newtype_index! {
2324 DEBUG_FORMAT = "AttrId({})"
2328 impl rustc_serialize::Encodable for AttrId {
2329 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2334 impl rustc_serialize::Decodable for AttrId {
2335 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2336 d.read_nil().map(|_| crate::attr::mk_attr_id())
2340 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2341 pub struct AttrItem {
2346 /// A list of attributes.
2347 pub type AttrVec = ThinVec<Attribute>;
2349 /// Metadata associated with an item.
2350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2351 pub struct Attribute {
2354 /// Denotes if the attribute decorates the following construct (outer)
2355 /// or the construct this attribute is contained within (inner).
2356 pub style: AttrStyle,
2360 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2362 /// A normal attribute.
2365 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2366 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2367 /// variant (which is much less compact and thus more expensive).
2371 /// `TraitRef`s appear in impls.
2373 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2374 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2375 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2376 /// same as the impl's `NodeId`).
2377 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2378 pub struct TraitRef {
2383 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2384 pub struct PolyTraitRef {
2385 /// The `'a` in `<'a> Foo<&'a T>`.
2386 pub bound_generic_params: Vec<GenericParam>,
2388 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2389 pub trait_ref: TraitRef,
2395 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2397 bound_generic_params: generic_params,
2398 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2404 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2405 pub enum CrateSugar {
2406 /// Source is `pub(crate)`.
2409 /// Source is (just) `crate`.
2413 pub type Visibility = Spanned<VisibilityKind>;
2415 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2416 pub enum VisibilityKind {
2419 Restricted { path: P<Path>, id: NodeId },
2423 impl VisibilityKind {
2424 pub fn is_pub(&self) -> bool {
2425 if let VisibilityKind::Public = *self { true } else { false }
2429 /// Field of a struct.
2431 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2432 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2433 pub struct StructField {
2434 pub attrs: Vec<Attribute>,
2437 pub vis: Visibility,
2438 pub ident: Option<Ident>,
2441 pub is_placeholder: bool,
2444 /// Fields and constructor ids of enum variants and structs.
2445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2446 pub enum VariantData {
2449 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2450 Struct(Vec<StructField>, bool),
2453 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2454 Tuple(Vec<StructField>, NodeId),
2457 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2462 /// Return the fields of this variant.
2463 pub fn fields(&self) -> &[StructField] {
2465 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2470 /// Return the `NodeId` of this variant's constructor, if it has one.
2471 pub fn ctor_id(&self) -> Option<NodeId> {
2473 VariantData::Struct(..) => None,
2474 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2479 /// An item definition.
2480 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2481 pub struct Item<K = ItemKind> {
2482 pub attrs: Vec<Attribute>,
2485 pub vis: Visibility,
2486 /// The name of the item.
2487 /// It might be a dummy name in case of anonymous items.
2492 /// Original tokens this item was parsed from. This isn't necessarily
2493 /// available for all items, although over time more and more items should
2494 /// have this be `Some`. Right now this is primarily used for procedural
2495 /// macros, notably custom attributes.
2497 /// Note that the tokens here do not include the outer attributes, but will
2498 /// include inner attributes.
2499 pub tokens: Option<TokenStream>,
2503 /// Return the span that encompasses the attributes.
2504 pub fn span_with_attributes(&self) -> Span {
2505 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2509 impl<K: Into<ItemKind>> Item<K> {
2510 pub fn into_item(self) -> Item {
2511 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2512 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2516 /// `extern` qualifier on a function item or function type.
2517 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2525 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2526 abi.map_or(Extern::Implicit, Extern::Explicit)
2530 /// A function header.
2532 /// All the information between the visibility and the name of the function is
2533 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2534 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2535 pub struct FnHeader {
2536 pub unsafety: Unsafe,
2537 pub asyncness: Async,
2538 pub constness: Const,
2543 /// Does this function header have any qualifiers or is it empty?
2544 pub fn has_qualifiers(&self) -> bool {
2545 let Self { unsafety, asyncness, constness, ext } = self;
2546 matches!(unsafety, Unsafe::Yes(_))
2547 || asyncness.is_async()
2548 || matches!(constness, Const::Yes(_))
2549 || !matches!(ext, Extern::None)
2553 impl Default for FnHeader {
2554 fn default() -> FnHeader {
2556 unsafety: Unsafe::No,
2557 asyncness: Async::No,
2558 constness: Const::No,
2564 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2566 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2568 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2569 ExternCrate(Option<Symbol>),
2570 /// A use declaration item (`use`).
2572 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2574 /// A static item (`static`).
2576 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2577 Static(P<Ty>, Mutability, Option<P<Expr>>),
2578 /// A constant item (`const`).
2580 /// E.g., `const FOO: i32 = 42;`.
2581 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2582 /// A function declaration (`fn`).
2584 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2585 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2586 /// A module declaration (`mod`).
2588 /// E.g., `mod foo;` or `mod foo { .. }`.
2590 /// An external module (`extern`).
2592 /// E.g., `extern {}` or `extern "C" {}`.
2593 ForeignMod(ForeignMod),
2594 /// Module-level inline assembly (from `global_asm!()`).
2595 GlobalAsm(P<GlobalAsm>),
2596 /// A type alias (`type`).
2598 /// E.g., `type Foo = Bar<u8>;`.
2599 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2600 /// An enum definition (`enum`).
2602 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2603 Enum(EnumDef, Generics),
2604 /// A struct definition (`struct`).
2606 /// E.g., `struct Foo<A> { x: A }`.
2607 Struct(VariantData, Generics),
2608 /// A union definition (`union`).
2610 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2611 Union(VariantData, Generics),
2612 /// A trait declaration (`trait`).
2614 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2615 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2618 /// E.g., `trait Foo = Bar + Quux;`.
2619 TraitAlias(Generics, GenericBounds),
2620 /// An implementation.
2622 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2625 polarity: ImplPolarity,
2626 defaultness: Defaultness,
2630 /// The trait being implemented, if any.
2631 of_trait: Option<TraitRef>,
2634 items: Vec<P<AssocItem>>,
2636 /// A macro invocation.
2638 /// E.g., `foo!(..)`.
2641 /// A macro definition.
2646 pub fn article(&self) -> &str {
2649 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2650 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2651 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2655 pub fn descr(&self) -> &str {
2657 ItemKind::ExternCrate(..) => "extern crate",
2658 ItemKind::Use(..) => "`use` import",
2659 ItemKind::Static(..) => "static item",
2660 ItemKind::Const(..) => "constant item",
2661 ItemKind::Fn(..) => "function",
2662 ItemKind::Mod(..) => "module",
2663 ItemKind::ForeignMod(..) => "extern block",
2664 ItemKind::GlobalAsm(..) => "global asm item",
2665 ItemKind::TyAlias(..) => "type alias",
2666 ItemKind::Enum(..) => "enum",
2667 ItemKind::Struct(..) => "struct",
2668 ItemKind::Union(..) => "union",
2669 ItemKind::Trait(..) => "trait",
2670 ItemKind::TraitAlias(..) => "trait alias",
2671 ItemKind::MacCall(..) => "item macro invocation",
2672 ItemKind::MacroDef(..) => "macro definition",
2673 ItemKind::Impl { .. } => "implementation",
2677 pub fn generics(&self) -> Option<&Generics> {
2679 Self::Fn(_, _, generics, _)
2680 | Self::TyAlias(_, generics, ..)
2681 | Self::Enum(_, generics)
2682 | Self::Struct(_, generics)
2683 | Self::Union(_, generics)
2684 | Self::Trait(_, _, generics, ..)
2685 | Self::TraitAlias(generics, _)
2686 | Self::Impl { generics, .. } => Some(generics),
2692 /// Represents associated items.
2693 /// These include items in `impl` and `trait` definitions.
2694 pub type AssocItem = Item<AssocItemKind>;
2696 /// Represents associated item kinds.
2698 /// The term "provided" in the variants below refers to the item having a default
2699 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2700 /// In an implementation, all items must be provided.
2701 /// The `Option`s below denote the bodies, where `Some(_)`
2702 /// means "provided" and conversely `None` means "required".
2703 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2704 pub enum AssocItemKind {
2705 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2706 /// If `def` is parsed, then the constant is provided, and otherwise required.
2707 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2708 /// An associated function.
2709 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2710 /// An associated type.
2711 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2712 /// A macro expanding to associated items.
2716 impl AssocItemKind {
2717 pub fn defaultness(&self) -> Defaultness {
2719 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2720 Self::MacCall(..) => Defaultness::Final,
2725 impl From<AssocItemKind> for ItemKind {
2726 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2727 match assoc_item_kind {
2728 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2729 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2730 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2731 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2736 impl TryFrom<ItemKind> for AssocItemKind {
2737 type Error = ItemKind;
2739 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2740 Ok(match item_kind {
2741 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2742 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2743 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2744 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2745 _ => return Err(item_kind),
2750 /// An item in `extern` block.
2751 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2752 pub enum ForeignItemKind {
2753 /// A foreign static item (`static FOO: u8`).
2754 Static(P<Ty>, Mutability, Option<P<Expr>>),
2755 /// A foreign function.
2756 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2758 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2759 /// A macro expanding to foreign items.
2763 impl From<ForeignItemKind> for ItemKind {
2764 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2765 match foreign_item_kind {
2766 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2767 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2768 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2769 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2774 impl TryFrom<ItemKind> for ForeignItemKind {
2775 type Error = ItemKind;
2777 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2778 Ok(match item_kind {
2779 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2780 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2781 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2782 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2783 _ => return Err(item_kind),
2788 pub type ForeignItem = Item<ForeignItemKind>;