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::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 /// Is this expr either `N`, or `{ N }`.
1057 /// If this is not the case, name resolution does not resolve `N` when using
1058 /// `feature(min_const_generics)` as more complex expressions are not supported.
1059 pub fn is_potential_trivial_const_param(&self) -> bool {
1060 let this = if let ExprKind::Block(ref block, None) = self.kind {
1061 if block.stmts.len() == 1 {
1062 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1070 if let ExprKind::Path(None, ref path) = this.kind {
1071 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1079 pub fn to_bound(&self) -> Option<GenericBound> {
1081 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1082 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1083 TraitBoundModifier::None,
1089 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1090 pub fn to_ty(&self) -> Option<P<Ty>> {
1091 let kind = match &self.kind {
1092 // Trivial conversions.
1093 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1094 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1096 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1098 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1099 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1102 ExprKind::Repeat(expr, expr_len) => {
1103 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1106 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1108 ExprKind::Tup(exprs) => {
1109 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1113 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1114 // then type of result is trait object.
1115 // Otherwise we don't assume the result type.
1116 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1117 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1118 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1124 // This expression doesn't look like a type syntactically.
1128 Some(P(Ty { kind, id: self.id, span: self.span }))
1131 pub fn precedence(&self) -> ExprPrecedence {
1133 ExprKind::Box(_) => ExprPrecedence::Box,
1134 ExprKind::Array(_) => ExprPrecedence::Array,
1135 ExprKind::Call(..) => ExprPrecedence::Call,
1136 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1137 ExprKind::Tup(_) => ExprPrecedence::Tup,
1138 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1139 ExprKind::Unary(..) => ExprPrecedence::Unary,
1140 ExprKind::Lit(_) => ExprPrecedence::Lit,
1141 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1142 ExprKind::Let(..) => ExprPrecedence::Let,
1143 ExprKind::If(..) => ExprPrecedence::If,
1144 ExprKind::While(..) => ExprPrecedence::While,
1145 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1146 ExprKind::Loop(..) => ExprPrecedence::Loop,
1147 ExprKind::Match(..) => ExprPrecedence::Match,
1148 ExprKind::Closure(..) => ExprPrecedence::Closure,
1149 ExprKind::Block(..) => ExprPrecedence::Block,
1150 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1151 ExprKind::Async(..) => ExprPrecedence::Async,
1152 ExprKind::Await(..) => ExprPrecedence::Await,
1153 ExprKind::Assign(..) => ExprPrecedence::Assign,
1154 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1155 ExprKind::Field(..) => ExprPrecedence::Field,
1156 ExprKind::Index(..) => ExprPrecedence::Index,
1157 ExprKind::Range(..) => ExprPrecedence::Range,
1158 ExprKind::Path(..) => ExprPrecedence::Path,
1159 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1160 ExprKind::Break(..) => ExprPrecedence::Break,
1161 ExprKind::Continue(..) => ExprPrecedence::Continue,
1162 ExprKind::Ret(..) => ExprPrecedence::Ret,
1163 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1164 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1165 ExprKind::Struct(..) => ExprPrecedence::Struct,
1166 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1167 ExprKind::Paren(..) => ExprPrecedence::Paren,
1168 ExprKind::Try(..) => ExprPrecedence::Try,
1169 ExprKind::Yield(..) => ExprPrecedence::Yield,
1170 ExprKind::Err => ExprPrecedence::Err,
1175 /// Limit types of a range (inclusive or exclusive)
1176 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1177 pub enum RangeLimits {
1178 /// Inclusive at the beginning, exclusive at the end
1180 /// Inclusive at the beginning and end
1184 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1186 /// A `box x` expression.
1188 /// An array (`[a, b, c, d]`)
1189 Array(Vec<P<Expr>>),
1192 /// The first field resolves to the function itself,
1193 /// and the second field is the list of arguments.
1194 /// This also represents calling the constructor of
1195 /// tuple-like ADTs such as tuple structs and enum variants.
1196 Call(P<Expr>, Vec<P<Expr>>),
1197 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1199 /// The `PathSegment` represents the method name and its generic arguments
1200 /// (within the angle brackets).
1201 /// The first element of the vector of an `Expr` is the expression that evaluates
1202 /// to the object on which the method is being called on (the receiver),
1203 /// and the remaining elements are the rest of the arguments.
1204 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1205 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1206 /// This `Span` is the span of the function, without the dot and receiver
1207 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1208 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1209 /// A tuple (e.g., `(a, b, c, d)`).
1211 /// A binary operation (e.g., `a + b`, `a * b`).
1212 Binary(BinOp, P<Expr>, P<Expr>),
1213 /// A unary operation (e.g., `!x`, `*x`).
1214 Unary(UnOp, P<Expr>),
1215 /// A literal (e.g., `1`, `"foo"`).
1217 /// A cast (e.g., `foo as f64`).
1218 Cast(P<Expr>, P<Ty>),
1219 /// A type ascription (e.g., `42: usize`).
1220 Type(P<Expr>, P<Ty>),
1221 /// A `let pat = expr` expression that is only semantically allowed in the condition
1222 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1223 Let(P<Pat>, P<Expr>),
1224 /// An `if` block, with an optional `else` block.
1226 /// `if expr { block } else { expr }`
1227 If(P<Expr>, P<Block>, Option<P<Expr>>),
1228 /// A while loop, with an optional label.
1230 /// `'label: while expr { block }`
1231 While(P<Expr>, P<Block>, Option<Label>),
1232 /// A `for` loop, with an optional label.
1234 /// `'label: for pat in expr { block }`
1236 /// This is desugared to a combination of `loop` and `match` expressions.
1237 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1238 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1240 /// `'label: loop { block }`
1241 Loop(P<Block>, Option<Label>),
1242 /// A `match` block.
1243 Match(P<Expr>, Vec<Arm>),
1244 /// A closure (e.g., `move |a, b, c| a + b + c`).
1246 /// The final span is the span of the argument block `|...|`.
1247 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1248 /// A block (`'label: { ... }`).
1249 Block(P<Block>, Option<Label>),
1250 /// An async block (`async move { ... }`).
1252 /// The `NodeId` is the `NodeId` for the closure that results from
1253 /// desugaring an async block, just like the NodeId field in the
1254 /// `Async::Yes` variant. This is necessary in order to create a def for the
1255 /// closure which can be used as a parent of any child defs. Defs
1256 /// created during lowering cannot be made the parent of any other
1257 /// preexisting defs.
1258 Async(CaptureBy, NodeId, P<Block>),
1259 /// An await expression (`my_future.await`).
1262 /// A try block (`try { ... }`).
1265 /// An assignment (`a = foo()`).
1266 /// The `Span` argument is the span of the `=` token.
1267 Assign(P<Expr>, P<Expr>, Span),
1268 /// An assignment with an operator.
1271 AssignOp(BinOp, P<Expr>, P<Expr>),
1272 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1273 Field(P<Expr>, Ident),
1274 /// An indexing operation (e.g., `foo[2]`).
1275 Index(P<Expr>, P<Expr>),
1276 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1277 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1279 /// Variable reference, possibly containing `::` and/or type
1280 /// parameters (e.g., `foo::bar::<baz>`).
1282 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1283 Path(Option<QSelf>, Path),
1285 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1286 AddrOf(BorrowKind, Mutability, P<Expr>),
1287 /// A `break`, with an optional label to break, and an optional expression.
1288 Break(Option<Label>, Option<P<Expr>>),
1289 /// A `continue`, with an optional label.
1290 Continue(Option<Label>),
1291 /// A `return`, with an optional value to be returned.
1292 Ret(Option<P<Expr>>),
1294 /// Output of the `asm!()` macro.
1295 InlineAsm(P<InlineAsm>),
1296 /// Output of the `llvm_asm!()` macro.
1297 LlvmInlineAsm(P<LlvmInlineAsm>),
1299 /// A macro invocation; pre-expansion.
1302 /// A struct literal expression.
1304 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1305 /// where `base` is the `Option<Expr>`.
1306 Struct(Path, Vec<Field>, Option<P<Expr>>),
1308 /// An array literal constructed from one repeated element.
1310 /// E.g., `[1; 5]`. The expression is the element to be
1311 /// repeated; the constant is the number of times to repeat it.
1312 Repeat(P<Expr>, AnonConst),
1314 /// No-op: used solely so we can pretty-print faithfully.
1317 /// A try expression (`expr?`).
1320 /// A `yield`, with an optional value to be yielded.
1321 Yield(Option<P<Expr>>),
1323 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1327 /// The explicit `Self` type in a "qualified path". The actual
1328 /// path, including the trait and the associated item, is stored
1329 /// separately. `position` represents the index of the associated
1330 /// item qualified with this `Self` type.
1332 /// ```ignore (only-for-syntax-highlight)
1333 /// <Vec<T> as a::b::Trait>::AssociatedItem
1334 /// ^~~~~ ~~~~~~~~~~~~~~^
1337 /// <Vec<T>>::AssociatedItem
1341 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1345 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1346 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1347 /// 0`, this is an empty span.
1348 pub path_span: Span,
1349 pub position: usize,
1352 /// A capture clause used in closures and `async` blocks.
1353 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1354 pub enum CaptureBy {
1355 /// `move |x| y + x`.
1357 /// `move` keyword was not specified.
1361 /// The movability of a generator / closure literal:
1362 /// whether a generator contains self-references, causing it to be `!Unpin`.
1363 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
1364 #[derive(HashStable_Generic)]
1365 pub enum Movability {
1366 /// May contain self-references, `!Unpin`.
1368 /// Must not contain self-references, `Unpin`.
1372 /// Represents a macro invocation. The `path` indicates which macro
1373 /// is being invoked, and the `args` are arguments passed to it.
1374 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1375 pub struct MacCall {
1377 pub args: P<MacArgs>,
1378 pub prior_type_ascription: Option<(Span, bool)>,
1382 pub fn span(&self) -> Span {
1383 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1387 /// Arguments passed to an attribute or a function-like macro.
1388 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1390 /// No arguments - `#[attr]`.
1392 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1393 Delimited(DelimSpan, MacDelimiter, TokenStream),
1394 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1396 /// Span of the `=` token.
1398 /// Token stream of the "value".
1404 pub fn delim(&self) -> DelimToken {
1406 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1407 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1411 pub fn span(&self) -> Option<Span> {
1413 MacArgs::Empty => None,
1414 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1415 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1419 /// Tokens inside the delimiters or after `=`.
1420 /// Proc macros see these tokens, for example.
1421 pub fn inner_tokens(&self) -> TokenStream {
1423 MacArgs::Empty => TokenStream::default(),
1424 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1428 /// Tokens together with the delimiters or `=`.
1429 /// Use of this method generally means that something suboptimal or hacky is happening.
1430 pub fn outer_tokens(&self) -> TokenStream {
1432 MacArgs::Empty => TokenStream::default(),
1433 MacArgs::Delimited(dspan, delim, ref tokens) => {
1434 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1436 MacArgs::Eq(eq_span, ref tokens) => {
1437 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1442 /// Whether a macro with these arguments needs a semicolon
1443 /// when used as a standalone item or statement.
1444 pub fn need_semicolon(&self) -> bool {
1445 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1449 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1450 pub enum MacDelimiter {
1457 pub fn to_token(self) -> DelimToken {
1459 MacDelimiter::Parenthesis => DelimToken::Paren,
1460 MacDelimiter::Bracket => DelimToken::Bracket,
1461 MacDelimiter::Brace => DelimToken::Brace,
1465 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1467 token::Paren => Some(MacDelimiter::Parenthesis),
1468 token::Bracket => Some(MacDelimiter::Bracket),
1469 token::Brace => Some(MacDelimiter::Brace),
1470 token::NoDelim => None,
1475 /// Represents a macro definition.
1476 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1477 pub struct MacroDef {
1478 pub body: P<MacArgs>,
1479 /// `true` if macro was defined with `macro_rules`.
1480 pub macro_rules: bool,
1483 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, Eq, PartialEq)]
1484 #[derive(HashStable_Generic)]
1486 /// A regular string, like `"foo"`.
1488 /// A raw string, like `r##"foo"##`.
1490 /// The value is the number of `#` symbols used.
1495 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1497 /// The original literal token as written in source code.
1498 pub token: token::Lit,
1499 /// The "semantic" representation of the literal lowered from the original tokens.
1500 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1501 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1506 /// Same as `Lit`, but restricted to string literals.
1507 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1509 /// The original literal token as written in source code.
1510 pub style: StrStyle,
1512 pub suffix: Option<Symbol>,
1514 /// The unescaped "semantic" representation of the literal lowered from the original token.
1515 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1516 pub symbol_unescaped: Symbol,
1520 pub fn as_lit(&self) -> Lit {
1521 let token_kind = match self.style {
1522 StrStyle::Cooked => token::Str,
1523 StrStyle::Raw(n) => token::StrRaw(n),
1526 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1528 kind: LitKind::Str(self.symbol_unescaped, self.style),
1533 /// Type of the integer literal based on provided suffix.
1534 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1535 #[derive(HashStable_Generic)]
1536 pub enum LitIntType {
1545 /// Type of the float literal based on provided suffix.
1546 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1547 #[derive(HashStable_Generic)]
1548 pub enum LitFloatType {
1549 /// A float literal with a suffix (`1f32` or `1E10f32`).
1551 /// A float literal without a suffix (`1.0 or 1.0E10`).
1557 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1558 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1560 /// A string literal (`"foo"`).
1561 Str(Symbol, StrStyle),
1562 /// A byte string (`b"foo"`).
1563 ByteStr(Lrc<Vec<u8>>),
1564 /// A byte char (`b'f'`).
1566 /// A character literal (`'a'`).
1568 /// An integer literal (`1`).
1569 Int(u128, LitIntType),
1570 /// A float literal (`1f64` or `1E10f64`).
1571 Float(Symbol, LitFloatType),
1572 /// A boolean literal.
1574 /// Placeholder for a literal that wasn't well-formed in some way.
1579 /// Returns `true` if this literal is a string.
1580 pub fn is_str(&self) -> bool {
1582 LitKind::Str(..) => true,
1587 /// Returns `true` if this literal is byte literal string.
1588 pub fn is_bytestr(&self) -> bool {
1590 LitKind::ByteStr(_) => true,
1595 /// Returns `true` if this is a numeric literal.
1596 pub fn is_numeric(&self) -> bool {
1598 LitKind::Int(..) | LitKind::Float(..) => true,
1603 /// Returns `true` if this literal has no suffix.
1604 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1605 pub fn is_unsuffixed(&self) -> bool {
1609 /// Returns `true` if this literal has a suffix.
1610 pub fn is_suffixed(&self) -> bool {
1612 // suffixed variants
1613 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1614 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1615 // unsuffixed variants
1617 | LitKind::ByteStr(..)
1620 | LitKind::Int(_, LitIntType::Unsuffixed)
1621 | LitKind::Float(_, LitFloatType::Unsuffixed)
1623 | LitKind::Err(..) => false,
1628 // N.B., If you change this, you'll probably want to change the corresponding
1629 // type structure in `middle/ty.rs` as well.
1630 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1633 pub mutbl: Mutability,
1636 /// Represents a function's signature in a trait declaration,
1637 /// trait implementation, or free function.
1638 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1640 pub header: FnHeader,
1641 pub decl: P<FnDecl>,
1644 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
1645 #[derive(HashStable_Generic)]
1652 pub fn name_str(self) -> &'static str {
1654 FloatTy::F32 => "f32",
1655 FloatTy::F64 => "f64",
1659 pub fn name(self) -> Symbol {
1661 FloatTy::F32 => sym::f32,
1662 FloatTy::F64 => sym::f64,
1666 pub fn bit_width(self) -> u64 {
1674 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
1675 #[derive(HashStable_Generic)]
1686 pub fn name_str(&self) -> &'static str {
1688 IntTy::Isize => "isize",
1690 IntTy::I16 => "i16",
1691 IntTy::I32 => "i32",
1692 IntTy::I64 => "i64",
1693 IntTy::I128 => "i128",
1697 pub fn name(&self) -> Symbol {
1699 IntTy::Isize => sym::isize,
1700 IntTy::I8 => sym::i8,
1701 IntTy::I16 => sym::i16,
1702 IntTy::I32 => sym::i32,
1703 IntTy::I64 => sym::i64,
1704 IntTy::I128 => sym::i128,
1708 pub fn val_to_string(&self, val: i128) -> String {
1709 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1710 // are parsed as `u128`, so we wouldn't want to print an extra negative
1712 format!("{}{}", val as u128, self.name_str())
1715 pub fn bit_width(&self) -> Option<u64> {
1717 IntTy::Isize => return None,
1726 pub fn normalize(&self, target_width: u32) -> Self {
1728 IntTy::Isize => match target_width {
1732 _ => unreachable!(),
1739 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy, Debug)]
1740 #[derive(HashStable_Generic)]
1751 pub fn name_str(&self) -> &'static str {
1753 UintTy::Usize => "usize",
1755 UintTy::U16 => "u16",
1756 UintTy::U32 => "u32",
1757 UintTy::U64 => "u64",
1758 UintTy::U128 => "u128",
1762 pub fn name(&self) -> Symbol {
1764 UintTy::Usize => sym::usize,
1765 UintTy::U8 => sym::u8,
1766 UintTy::U16 => sym::u16,
1767 UintTy::U32 => sym::u32,
1768 UintTy::U64 => sym::u64,
1769 UintTy::U128 => sym::u128,
1773 pub fn val_to_string(&self, val: u128) -> String {
1774 format!("{}{}", val, self.name_str())
1777 pub fn bit_width(&self) -> Option<u64> {
1779 UintTy::Usize => return None,
1784 UintTy::U128 => 128,
1788 pub fn normalize(&self, target_width: u32) -> Self {
1790 UintTy::Usize => match target_width {
1794 _ => unreachable!(),
1801 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1802 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1803 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1804 pub struct AssocTyConstraint {
1807 pub kind: AssocTyConstraintKind,
1811 /// The kinds of an `AssocTyConstraint`.
1812 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1813 pub enum AssocTyConstraintKind {
1814 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1815 Equality { ty: P<Ty> },
1816 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1817 Bound { bounds: GenericBounds },
1820 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1827 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1828 pub struct BareFnTy {
1829 pub unsafety: Unsafe,
1831 pub generic_params: Vec<GenericParam>,
1832 pub decl: P<FnDecl>,
1835 /// The various kinds of type recognized by the compiler.
1836 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1838 /// A variable-length slice (`[T]`).
1840 /// A fixed length array (`[T; n]`).
1841 Array(P<Ty>, AnonConst),
1842 /// A raw pointer (`*const T` or `*mut T`).
1844 /// A reference (`&'a T` or `&'a mut T`).
1845 Rptr(Option<Lifetime>, MutTy),
1846 /// A bare function (e.g., `fn(usize) -> bool`).
1847 BareFn(P<BareFnTy>),
1848 /// The never type (`!`).
1850 /// A tuple (`(A, B, C, D,...)`).
1852 /// A path (`module::module::...::Type`), optionally
1853 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1855 /// Type parameters are stored in the `Path` itself.
1856 Path(Option<QSelf>, Path),
1857 /// A trait object type `Bound1 + Bound2 + Bound3`
1858 /// where `Bound` is a trait or a lifetime.
1859 TraitObject(GenericBounds, TraitObjectSyntax),
1860 /// An `impl Bound1 + Bound2 + Bound3` type
1861 /// where `Bound` is a trait or a lifetime.
1863 /// The `NodeId` exists to prevent lowering from having to
1864 /// generate `NodeId`s on the fly, which would complicate
1865 /// the generation of opaque `type Foo = impl Trait` items significantly.
1866 ImplTrait(NodeId, GenericBounds),
1867 /// No-op; kept solely so that we can pretty-print faithfully.
1871 /// This means the type should be inferred instead of it having been
1872 /// specified. This can appear anywhere in a type.
1874 /// Inferred type of a `self` or `&self` argument in a method.
1876 /// A macro in the type position.
1878 /// Placeholder for a kind that has failed to be defined.
1880 /// Placeholder for a `va_list`.
1885 pub fn is_implicit_self(&self) -> bool {
1886 if let TyKind::ImplicitSelf = *self { true } else { false }
1889 pub fn is_unit(&self) -> bool {
1890 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1894 /// Syntax used to declare a trait object.
1895 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1896 pub enum TraitObjectSyntax {
1901 /// Inline assembly operand explicit register or register class.
1903 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1904 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1905 pub enum InlineAsmRegOrRegClass {
1910 bitflags::bitflags! {
1911 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1912 pub struct InlineAsmOptions: u8 {
1913 const PURE = 1 << 0;
1914 const NOMEM = 1 << 1;
1915 const READONLY = 1 << 2;
1916 const PRESERVES_FLAGS = 1 << 3;
1917 const NORETURN = 1 << 4;
1918 const NOSTACK = 1 << 5;
1919 const ATT_SYNTAX = 1 << 6;
1923 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1924 pub enum InlineAsmTemplatePiece {
1926 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1929 impl fmt::Display for InlineAsmTemplatePiece {
1930 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1932 Self::String(s) => {
1933 for c in s.chars() {
1935 '{' => f.write_str("{{")?,
1936 '}' => f.write_str("}}")?,
1942 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1943 write!(f, "{{{}:{}}}", operand_idx, modifier)
1945 Self::Placeholder { operand_idx, modifier: None, .. } => {
1946 write!(f, "{{{}}}", operand_idx)
1952 impl InlineAsmTemplatePiece {
1953 /// Rebuilds the asm template string from its pieces.
1954 pub fn to_string(s: &[Self]) -> String {
1956 let mut out = String::new();
1958 let _ = write!(out, "{}", p);
1964 /// Inline assembly operand.
1966 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
1967 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1968 pub enum InlineAsmOperand {
1970 reg: InlineAsmRegOrRegClass,
1974 reg: InlineAsmRegOrRegClass,
1976 expr: Option<P<Expr>>,
1979 reg: InlineAsmRegOrRegClass,
1984 reg: InlineAsmRegOrRegClass,
1987 out_expr: Option<P<Expr>>,
1997 /// Inline assembly.
1999 /// E.g., `asm!("NOP");`.
2000 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2001 pub struct InlineAsm {
2002 pub template: Vec<InlineAsmTemplatePiece>,
2003 pub operands: Vec<(InlineAsmOperand, Span)>,
2004 pub options: InlineAsmOptions,
2005 pub line_spans: Vec<Span>,
2008 /// Inline assembly dialect.
2010 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2011 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2012 pub enum LlvmAsmDialect {
2017 /// LLVM-style inline assembly.
2019 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2020 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2021 pub struct LlvmInlineAsmOutput {
2022 pub constraint: Symbol,
2025 pub is_indirect: bool,
2028 /// LLVM-style inline assembly.
2030 /// E.g., `llvm_asm!("NOP");`.
2031 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2032 pub struct LlvmInlineAsm {
2034 pub asm_str_style: StrStyle,
2035 pub outputs: Vec<LlvmInlineAsmOutput>,
2036 pub inputs: Vec<(Symbol, P<Expr>)>,
2037 pub clobbers: Vec<Symbol>,
2039 pub alignstack: bool,
2040 pub dialect: LlvmAsmDialect,
2043 /// A parameter in a function header.
2045 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2046 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2053 pub is_placeholder: bool,
2056 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2058 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2059 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2061 /// `self`, `mut self`
2063 /// `&'lt self`, `&'lt mut self`
2064 Region(Option<Lifetime>, Mutability),
2065 /// `self: TYPE`, `mut self: TYPE`
2066 Explicit(P<Ty>, Mutability),
2069 pub type ExplicitSelf = Spanned<SelfKind>;
2072 /// Attempts to cast parameter to `ExplicitSelf`.
2073 pub fn to_self(&self) -> Option<ExplicitSelf> {
2074 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2075 if ident.name == kw::SelfLower {
2076 return match self.ty.kind {
2077 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2078 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2079 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2082 self.pat.span.to(self.ty.span),
2083 SelfKind::Explicit(self.ty.clone(), mutbl),
2091 /// Returns `true` if parameter is `self`.
2092 pub fn is_self(&self) -> bool {
2093 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2094 ident.name == kw::SelfLower
2100 /// Builds a `Param` object from `ExplicitSelf`.
2101 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2102 let span = eself.span.to(eself_ident.span);
2103 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2104 let param = |mutbl, ty| Param {
2108 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2114 is_placeholder: false,
2117 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2118 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2119 SelfKind::Region(lt, mutbl) => param(
2123 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2131 /// A signature (not the body) of a function declaration.
2133 /// E.g., `fn foo(bar: baz)`.
2135 /// Please note that it's different from `FnHeader` structure
2136 /// which contains metadata about function safety, asyncness, constness and ABI.
2137 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2139 pub inputs: Vec<Param>,
2140 pub output: FnRetTy,
2144 pub fn get_self(&self) -> Option<ExplicitSelf> {
2145 self.inputs.get(0).and_then(Param::to_self)
2147 pub fn has_self(&self) -> bool {
2148 self.inputs.get(0).map_or(false, Param::is_self)
2150 pub fn c_variadic(&self) -> bool {
2151 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2152 TyKind::CVarArgs => true,
2158 /// Is the trait definition an auto trait?
2159 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2165 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
2166 #[derive(HashStable_Generic)]
2172 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2174 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2179 pub fn is_async(self) -> bool {
2180 if let Async::Yes { .. } = self { true } else { false }
2183 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2184 pub fn opt_return_id(self) -> Option<NodeId> {
2186 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2192 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
2193 #[derive(HashStable_Generic)]
2199 /// Item defaultness.
2200 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2201 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2202 pub enum Defaultness {
2207 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2208 pub enum ImplPolarity {
2209 /// `impl Trait for Type`
2211 /// `impl !Trait for Type`
2215 impl fmt::Debug for ImplPolarity {
2216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2218 ImplPolarity::Positive => "positive".fmt(f),
2219 ImplPolarity::Negative(_) => "negative".fmt(f),
2224 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2226 /// Returns type is not specified.
2228 /// Functions default to `()` and closures default to inference.
2229 /// Span points to where return type would be inserted.
2231 /// Everything else.
2236 pub fn span(&self) -> Span {
2238 FnRetTy::Default(span) => span,
2239 FnRetTy::Ty(ref ty) => ty.span,
2244 /// Module declaration.
2246 /// E.g., `mod foo;` or `mod foo { .. }`.
2247 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
2249 /// A span from the first token past `{` to the last token until `}`.
2250 /// For `mod foo;`, the inner span ranges from the first token
2251 /// to the last token in the external file.
2253 pub items: Vec<P<Item>>,
2254 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2258 /// Foreign module declaration.
2260 /// E.g., `extern { .. }` or `extern C { .. }`.
2261 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2262 pub struct ForeignMod {
2263 pub abi: Option<StrLit>,
2264 pub items: Vec<P<ForeignItem>>,
2267 /// Global inline assembly.
2269 /// Also known as "module-level assembly" or "file-scoped assembly".
2270 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2271 pub struct GlobalAsm {
2275 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2276 pub struct EnumDef {
2277 pub variants: Vec<Variant>,
2280 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2281 pub struct Variant {
2282 /// Attributes of the variant.
2283 pub attrs: Vec<Attribute>,
2284 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2288 /// The visibility of the variant. Syntactically accepted but not semantically.
2289 pub vis: Visibility,
2290 /// Name of the variant.
2293 /// Fields and constructor id of the variant.
2294 pub data: VariantData,
2295 /// Explicit discriminant, e.g., `Foo = 1`.
2296 pub disr_expr: Option<AnonConst>,
2297 /// Is a macro placeholder
2298 pub is_placeholder: bool,
2301 /// Part of `use` item to the right of its prefix.
2302 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2303 pub enum UseTreeKind {
2304 /// `use prefix` or `use prefix as rename`
2306 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2308 Simple(Option<Ident>, NodeId, NodeId),
2309 /// `use prefix::{...}`
2310 Nested(Vec<(UseTree, NodeId)>),
2315 /// A tree of paths sharing common prefixes.
2316 /// Used in `use` items both at top-level and inside of braces in import groups.
2317 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2318 pub struct UseTree {
2320 pub kind: UseTreeKind,
2325 pub fn ident(&self) -> Ident {
2327 UseTreeKind::Simple(Some(rename), ..) => rename,
2328 UseTreeKind::Simple(None, ..) => {
2329 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2331 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2336 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2337 /// are contained as statements within items. These two cases need to be
2338 /// distinguished for pretty-printing.
2339 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2340 pub enum AttrStyle {
2345 rustc_index::newtype_index! {
2348 DEBUG_FORMAT = "AttrId({})"
2352 impl rustc_serialize::Encodable for AttrId {
2353 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2358 impl rustc_serialize::Decodable for AttrId {
2359 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2360 d.read_nil().map(|_| crate::attr::mk_attr_id())
2364 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2365 pub struct AttrItem {
2370 /// A list of attributes.
2371 pub type AttrVec = ThinVec<Attribute>;
2373 /// Metadata associated with an item.
2374 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2375 pub struct Attribute {
2378 /// Denotes if the attribute decorates the following construct (outer)
2379 /// or the construct this attribute is contained within (inner).
2380 pub style: AttrStyle,
2384 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2386 /// A normal attribute.
2389 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2390 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2391 /// variant (which is much less compact and thus more expensive).
2392 DocComment(CommentKind, Symbol),
2395 /// `TraitRef`s appear in impls.
2397 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2398 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2399 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2400 /// same as the impl's `NodeId`).
2401 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2402 pub struct TraitRef {
2407 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2408 pub struct PolyTraitRef {
2409 /// The `'a` in `<'a> Foo<&'a T>`.
2410 pub bound_generic_params: Vec<GenericParam>,
2412 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2413 pub trait_ref: TraitRef,
2419 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2421 bound_generic_params: generic_params,
2422 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2428 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2429 pub enum CrateSugar {
2430 /// Source is `pub(crate)`.
2433 /// Source is (just) `crate`.
2437 pub type Visibility = Spanned<VisibilityKind>;
2439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2440 pub enum VisibilityKind {
2443 Restricted { path: P<Path>, id: NodeId },
2447 impl VisibilityKind {
2448 pub fn is_pub(&self) -> bool {
2449 if let VisibilityKind::Public = *self { true } else { false }
2453 /// Field of a struct.
2455 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2457 pub struct StructField {
2458 pub attrs: Vec<Attribute>,
2461 pub vis: Visibility,
2462 pub ident: Option<Ident>,
2465 pub is_placeholder: bool,
2468 /// Fields and constructor ids of enum variants and structs.
2469 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2470 pub enum VariantData {
2473 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2474 Struct(Vec<StructField>, bool),
2477 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2478 Tuple(Vec<StructField>, NodeId),
2481 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2486 /// Return the fields of this variant.
2487 pub fn fields(&self) -> &[StructField] {
2489 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2494 /// Return the `NodeId` of this variant's constructor, if it has one.
2495 pub fn ctor_id(&self) -> Option<NodeId> {
2497 VariantData::Struct(..) => None,
2498 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2503 /// An item definition.
2504 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2505 pub struct Item<K = ItemKind> {
2506 pub attrs: Vec<Attribute>,
2509 pub vis: Visibility,
2510 /// The name of the item.
2511 /// It might be a dummy name in case of anonymous items.
2516 /// Original tokens this item was parsed from. This isn't necessarily
2517 /// available for all items, although over time more and more items should
2518 /// have this be `Some`. Right now this is primarily used for procedural
2519 /// macros, notably custom attributes.
2521 /// Note that the tokens here do not include the outer attributes, but will
2522 /// include inner attributes.
2523 pub tokens: Option<TokenStream>,
2527 /// Return the span that encompasses the attributes.
2528 pub fn span_with_attributes(&self) -> Span {
2529 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2533 impl<K: Into<ItemKind>> Item<K> {
2534 pub fn into_item(self) -> Item {
2535 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2536 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2540 /// `extern` qualifier on a function item or function type.
2541 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2549 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2550 abi.map_or(Extern::Implicit, Extern::Explicit)
2554 /// A function header.
2556 /// All the information between the visibility and the name of the function is
2557 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2558 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2559 pub struct FnHeader {
2560 pub unsafety: Unsafe,
2561 pub asyncness: Async,
2562 pub constness: Const,
2567 /// Does this function header have any qualifiers or is it empty?
2568 pub fn has_qualifiers(&self) -> bool {
2569 let Self { unsafety, asyncness, constness, ext } = self;
2570 matches!(unsafety, Unsafe::Yes(_))
2571 || asyncness.is_async()
2572 || matches!(constness, Const::Yes(_))
2573 || !matches!(ext, Extern::None)
2577 impl Default for FnHeader {
2578 fn default() -> FnHeader {
2580 unsafety: Unsafe::No,
2581 asyncness: Async::No,
2582 constness: Const::No,
2588 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2590 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2592 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2593 ExternCrate(Option<Symbol>),
2594 /// A use declaration item (`use`).
2596 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2598 /// A static item (`static`).
2600 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2601 Static(P<Ty>, Mutability, Option<P<Expr>>),
2602 /// A constant item (`const`).
2604 /// E.g., `const FOO: i32 = 42;`.
2605 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2606 /// A function declaration (`fn`).
2608 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2609 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2610 /// A module declaration (`mod`).
2612 /// E.g., `mod foo;` or `mod foo { .. }`.
2614 /// An external module (`extern`).
2616 /// E.g., `extern {}` or `extern "C" {}`.
2617 ForeignMod(ForeignMod),
2618 /// Module-level inline assembly (from `global_asm!()`).
2619 GlobalAsm(P<GlobalAsm>),
2620 /// A type alias (`type`).
2622 /// E.g., `type Foo = Bar<u8>;`.
2623 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2624 /// An enum definition (`enum`).
2626 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2627 Enum(EnumDef, Generics),
2628 /// A struct definition (`struct`).
2630 /// E.g., `struct Foo<A> { x: A }`.
2631 Struct(VariantData, Generics),
2632 /// A union definition (`union`).
2634 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2635 Union(VariantData, Generics),
2636 /// A trait declaration (`trait`).
2638 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2639 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2642 /// E.g., `trait Foo = Bar + Quux;`.
2643 TraitAlias(Generics, GenericBounds),
2644 /// An implementation.
2646 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2649 polarity: ImplPolarity,
2650 defaultness: Defaultness,
2654 /// The trait being implemented, if any.
2655 of_trait: Option<TraitRef>,
2658 items: Vec<P<AssocItem>>,
2660 /// A macro invocation.
2662 /// E.g., `foo!(..)`.
2665 /// A macro definition.
2670 pub fn article(&self) -> &str {
2673 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2674 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2675 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2679 pub fn descr(&self) -> &str {
2681 ItemKind::ExternCrate(..) => "extern crate",
2682 ItemKind::Use(..) => "`use` import",
2683 ItemKind::Static(..) => "static item",
2684 ItemKind::Const(..) => "constant item",
2685 ItemKind::Fn(..) => "function",
2686 ItemKind::Mod(..) => "module",
2687 ItemKind::ForeignMod(..) => "extern block",
2688 ItemKind::GlobalAsm(..) => "global asm item",
2689 ItemKind::TyAlias(..) => "type alias",
2690 ItemKind::Enum(..) => "enum",
2691 ItemKind::Struct(..) => "struct",
2692 ItemKind::Union(..) => "union",
2693 ItemKind::Trait(..) => "trait",
2694 ItemKind::TraitAlias(..) => "trait alias",
2695 ItemKind::MacCall(..) => "item macro invocation",
2696 ItemKind::MacroDef(..) => "macro definition",
2697 ItemKind::Impl { .. } => "implementation",
2701 pub fn generics(&self) -> Option<&Generics> {
2703 Self::Fn(_, _, generics, _)
2704 | Self::TyAlias(_, generics, ..)
2705 | Self::Enum(_, generics)
2706 | Self::Struct(_, generics)
2707 | Self::Union(_, generics)
2708 | Self::Trait(_, _, generics, ..)
2709 | Self::TraitAlias(generics, _)
2710 | Self::Impl { generics, .. } => Some(generics),
2716 /// Represents associated items.
2717 /// These include items in `impl` and `trait` definitions.
2718 pub type AssocItem = Item<AssocItemKind>;
2720 /// Represents associated item kinds.
2722 /// The term "provided" in the variants below refers to the item having a default
2723 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2724 /// In an implementation, all items must be provided.
2725 /// The `Option`s below denote the bodies, where `Some(_)`
2726 /// means "provided" and conversely `None` means "required".
2727 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2728 pub enum AssocItemKind {
2729 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2730 /// If `def` is parsed, then the constant is provided, and otherwise required.
2731 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2732 /// An associated function.
2733 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2734 /// An associated type.
2735 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2736 /// A macro expanding to associated items.
2740 impl AssocItemKind {
2741 pub fn defaultness(&self) -> Defaultness {
2743 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2744 Self::MacCall(..) => Defaultness::Final,
2749 impl From<AssocItemKind> for ItemKind {
2750 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2751 match assoc_item_kind {
2752 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2753 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2754 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2755 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2760 impl TryFrom<ItemKind> for AssocItemKind {
2761 type Error = ItemKind;
2763 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2764 Ok(match item_kind {
2765 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2766 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2767 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2768 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2769 _ => return Err(item_kind),
2774 /// An item in `extern` block.
2775 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2776 pub enum ForeignItemKind {
2777 /// A foreign static item (`static FOO: u8`).
2778 Static(P<Ty>, Mutability, Option<P<Expr>>),
2779 /// A foreign function.
2780 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2782 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2783 /// A macro expanding to foreign items.
2787 impl From<ForeignItemKind> for ItemKind {
2788 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2789 match foreign_item_kind {
2790 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2791 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2792 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2793 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2798 impl TryFrom<ItemKind> for ForeignItemKind {
2799 type Error = ItemKind;
2801 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2802 Ok(match item_kind {
2803 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2804 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2805 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2806 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2807 _ => return Err(item_kind),
2812 pub type ForeignItem = Item<ForeignItemKind>;