1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
26 use crate::token::{self, CommentKind, DelimToken};
27 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::sync::Lrc;
31 use rustc_data_structures::thin_vec::ThinVec;
32 use rustc_macros::HashStable_Generic;
33 use rustc_serialize::{self, Decoder, Encoder};
34 use rustc_span::source_map::{respan, Spanned};
35 use rustc_span::symbol::{kw, sym, Ident, Symbol};
36 use rustc_span::{Span, DUMMY_SP};
38 use std::cmp::Ordering;
39 use std::convert::TryFrom;
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
55 /// `'outer` is a label.
56 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
61 impl fmt::Debug for Label {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "label({:?})", self.ident)
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, Encodable, Decodable, Copy)]
75 impl fmt::Debug for Lifetime {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "lifetime({}: {})", self.id, self)
81 impl fmt::Display for Lifetime {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "{}", self.ident.name)
87 /// A "Path" is essentially Rust's notion of a name.
89 /// It's represented as a sequence of identifiers,
90 /// along with a bunch of supporting information.
92 /// E.g., `std::cmp::PartialEq`.
93 #[derive(Clone, Encodable, Decodable, Debug)]
96 /// The segments in the path: the things separated by `::`.
97 /// Global paths begin with `kw::PathRoot`.
98 pub segments: Vec<PathSegment>,
101 impl PartialEq<Symbol> for Path {
102 fn eq(&self, symbol: &Symbol) -> bool {
103 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
107 impl<CTX> HashStable<CTX> for Path {
108 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
109 self.segments.len().hash_stable(hcx, hasher);
110 for segment in &self.segments {
111 segment.ident.name.hash_stable(hcx, hasher);
117 // Convert a span and an identifier to the corresponding
119 pub fn from_ident(ident: Ident) -> Path {
120 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
123 pub fn is_global(&self) -> bool {
124 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
128 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
130 /// E.g., `std`, `String` or `Box<T>`.
131 #[derive(Clone, Encodable, Decodable, Debug)]
132 pub struct PathSegment {
133 /// The identifier portion of this path segment.
138 /// Type/lifetime parameters attached to this path. They come in
139 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
140 /// `None` means that no parameter list is supplied (`Path`),
141 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
142 /// but it can be empty (`Path<>`).
143 /// `P` is used as a size optimization for the common case with no parameters.
144 pub args: Option<P<GenericArgs>>,
148 pub fn from_ident(ident: Ident) -> Self {
149 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
151 pub fn path_root(span: Span) -> Self {
152 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
156 /// The arguments of a path segment.
158 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
159 #[derive(Clone, Encodable, Decodable, Debug)]
160 pub enum GenericArgs {
161 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
162 AngleBracketed(AngleBracketedArgs),
163 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
164 Parenthesized(ParenthesizedArgs),
168 pub fn is_parenthesized(&self) -> bool {
170 Parenthesized(..) => true,
175 pub fn is_angle_bracketed(&self) -> bool {
177 AngleBracketed(..) => true,
182 pub fn span(&self) -> Span {
184 AngleBracketed(ref data) => data.span,
185 Parenthesized(ref data) => data.span,
190 /// Concrete argument in the sequence of generic args.
191 #[derive(Clone, Encodable, Decodable, Debug)]
192 pub enum GenericArg {
193 /// `'a` in `Foo<'a>`
195 /// `Bar` in `Foo<Bar>`
202 pub fn span(&self) -> Span {
204 GenericArg::Lifetime(lt) => lt.ident.span,
205 GenericArg::Type(ty) => ty.span,
206 GenericArg::Const(ct) => ct.value.span,
211 /// A path like `Foo<'a, T>`.
212 #[derive(Clone, Encodable, Decodable, Debug, Default)]
213 pub struct AngleBracketedArgs {
214 /// The overall span.
216 /// The comma separated parts in the `<...>`.
217 pub args: Vec<AngleBracketedArg>,
220 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
221 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
222 #[derive(Clone, Encodable, Decodable, Debug)]
223 pub enum AngleBracketedArg {
224 /// Argument for a generic parameter.
226 /// Constraint for an associated item.
227 Constraint(AssocTyConstraint),
230 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
231 fn into(self) -> Option<P<GenericArgs>> {
232 Some(P(GenericArgs::AngleBracketed(self)))
236 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
237 fn into(self) -> Option<P<GenericArgs>> {
238 Some(P(GenericArgs::Parenthesized(self)))
242 /// A path like `Foo(A, B) -> C`.
243 #[derive(Clone, Encodable, Decodable, Debug)]
244 pub struct ParenthesizedArgs {
249 pub inputs: Vec<P<Ty>>,
255 impl ParenthesizedArgs {
256 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
261 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
263 AngleBracketedArgs { span: self.span, args }
267 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
269 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
271 /// Negative bounds should also be handled here.
272 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
273 pub enum TraitBoundModifier {
285 // This parses but will be rejected during AST validation.
289 /// The AST represents all type param bounds as types.
290 /// `typeck::collect::compute_bounds` matches these against
291 /// the "special" built-in traits (see `middle::lang_items`) and
292 /// detects `Copy`, `Send` and `Sync`.
293 #[derive(Clone, Encodable, Decodable, Debug)]
294 pub enum GenericBound {
295 Trait(PolyTraitRef, TraitBoundModifier),
300 pub fn span(&self) -> Span {
302 GenericBound::Trait(ref t, ..) => t.span,
303 GenericBound::Outlives(ref l) => l.ident.span,
308 pub type GenericBounds = Vec<GenericBound>;
310 /// Specifies the enforced ordering for generic parameters. In the future,
311 /// if we wanted to relax this order, we could override `PartialEq` and
312 /// `PartialOrd`, to allow the kinds to be unordered.
313 #[derive(Hash, Clone, Copy)]
314 pub enum ParamKindOrd {
317 // `unordered` is only `true` if `sess.has_features().const_generics`
318 // is active. Specifically, if it's only `min_const_generics`, it will still require
319 // ordering consts after types.
320 Const { unordered: bool },
323 impl Ord for ParamKindOrd {
324 fn cmp(&self, other: &Self) -> Ordering {
326 let to_int = |v| match v {
328 Type | Const { unordered: true } => 1,
329 // technically both consts should be ordered equally,
330 // but only one is ever encountered at a time, so this is
332 Const { unordered: false } => 2,
335 to_int(*self).cmp(&to_int(*other))
338 impl PartialOrd for ParamKindOrd {
339 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
340 Some(self.cmp(other))
343 impl PartialEq for ParamKindOrd {
344 fn eq(&self, other: &Self) -> bool {
345 self.cmp(other) == Ordering::Equal
348 impl Eq for ParamKindOrd {}
350 impl fmt::Display for ParamKindOrd {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353 ParamKindOrd::Lifetime => "lifetime".fmt(f),
354 ParamKindOrd::Type => "type".fmt(f),
355 ParamKindOrd::Const { .. } => "const".fmt(f),
360 #[derive(Clone, Encodable, Decodable, Debug)]
361 pub enum GenericParamKind {
362 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
365 default: Option<P<Ty>>,
369 /// Span of the `const` keyword.
374 #[derive(Clone, Encodable, Decodable, Debug)]
375 pub struct GenericParam {
379 pub bounds: GenericBounds,
380 pub is_placeholder: bool,
381 pub kind: GenericParamKind,
384 /// Represents lifetime, type and const parameters attached to a declaration of
385 /// a function, enum, trait, etc.
386 #[derive(Clone, Encodable, Decodable, Debug)]
387 pub struct Generics {
388 pub params: Vec<GenericParam>,
389 pub where_clause: WhereClause,
393 impl Default for Generics {
394 /// Creates an instance of `Generics`.
395 fn default() -> Generics {
398 where_clause: WhereClause {
399 has_where_token: false,
400 predicates: Vec::new(),
408 /// A where-clause in a definition.
409 #[derive(Clone, Encodable, Decodable, Debug)]
410 pub struct WhereClause {
411 /// `true` if we ate a `where` token: this can happen
412 /// if we parsed no predicates (e.g. `struct Foo where {}`).
413 /// This allows us to accurately pretty-print
414 /// in `nt_to_tokenstream`
415 pub has_where_token: bool,
416 pub predicates: Vec<WherePredicate>,
420 /// A single predicate in a where-clause.
421 #[derive(Clone, Encodable, Decodable, Debug)]
422 pub enum WherePredicate {
423 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
424 BoundPredicate(WhereBoundPredicate),
425 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
426 RegionPredicate(WhereRegionPredicate),
427 /// An equality predicate (unsupported).
428 EqPredicate(WhereEqPredicate),
431 impl WherePredicate {
432 pub fn span(&self) -> Span {
434 &WherePredicate::BoundPredicate(ref p) => p.span,
435 &WherePredicate::RegionPredicate(ref p) => p.span,
436 &WherePredicate::EqPredicate(ref p) => p.span,
443 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
444 #[derive(Clone, Encodable, Decodable, Debug)]
445 pub struct WhereBoundPredicate {
447 /// Any generics from a `for` binding.
448 pub bound_generic_params: Vec<GenericParam>,
449 /// The type being bounded.
450 pub bounded_ty: P<Ty>,
451 /// Trait and lifetime bounds (`Clone + Send + 'static`).
452 pub bounds: GenericBounds,
455 /// A lifetime predicate.
457 /// E.g., `'a: 'b + 'c`.
458 #[derive(Clone, Encodable, Decodable, Debug)]
459 pub struct WhereRegionPredicate {
461 pub lifetime: Lifetime,
462 pub bounds: GenericBounds,
465 /// An equality predicate (unsupported).
468 #[derive(Clone, Encodable, Decodable, Debug)]
469 pub struct WhereEqPredicate {
476 #[derive(Clone, Encodable, Decodable, Debug)]
479 pub attrs: Vec<Attribute>,
481 /// The order of items in the HIR is unrelated to the order of
482 /// items in the AST. However, we generate proc macro harnesses
483 /// based on the AST order, and later refer to these harnesses
484 /// from the HIR. This field keeps track of the order in which
485 /// we generated proc macros harnesses, so that we can map
486 /// HIR proc macros items back to their harness items.
487 pub proc_macros: Vec<NodeId>,
490 /// Possible values inside of compile-time attribute lists.
492 /// E.g., the '..' in `#[name(..)]`.
493 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
494 pub enum NestedMetaItem {
495 /// A full MetaItem, for recursive meta items.
499 /// E.g., `"foo"`, `64`, `true`.
503 /// A spanned compile-time attribute item.
505 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
506 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
507 pub struct MetaItem {
509 pub kind: MetaItemKind,
513 /// A compile-time attribute item.
515 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
516 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
517 pub enum MetaItemKind {
520 /// E.g., `test` as in `#[test]`.
524 /// E.g., `derive(..)` as in `#[derive(..)]`.
525 List(Vec<NestedMetaItem>),
526 /// Name value meta item.
528 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
532 /// A block (`{ .. }`).
534 /// E.g., `{ .. }` as in `fn foo() { .. }`.
535 #[derive(Clone, Encodable, Decodable, Debug)]
537 /// The statements in the block.
538 pub stmts: Vec<Stmt>,
540 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
541 pub rules: BlockCheckMode,
547 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
548 #[derive(Clone, Encodable, Decodable, Debug)]
556 /// Attempt reparsing the pattern as a type.
557 /// This is intended for use by diagnostics.
558 pub fn to_ty(&self) -> Option<P<Ty>> {
559 let kind = match &self.kind {
560 // In a type expression `_` is an inference variable.
561 PatKind::Wild => TyKind::Infer,
562 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
563 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
564 TyKind::Path(None, Path::from_ident(*ident))
566 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
567 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
568 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
569 PatKind::Ref(pat, mutbl) => {
570 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
572 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
573 // when `P` can be reparsed as a type `T`.
574 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
575 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
576 // assuming `T0` to `Tn` are all syntactically valid as types.
577 PatKind::Tuple(pats) => {
578 let mut tys = Vec::with_capacity(pats.len());
579 // FIXME(#48994) - could just be collected into an Option<Vec>
581 tys.push(pat.to_ty()?);
588 Some(P(Ty { kind, id: self.id, span: self.span }))
591 /// Walk top-down and call `it` in each place where a pattern occurs
592 /// starting with the root pattern `walk` is called on. If `it` returns
593 /// false then we will descend no further but siblings will be processed.
594 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
600 // Walk into the pattern associated with `Ident` (if any).
601 PatKind::Ident(_, _, Some(p)) => p.walk(it),
603 // Walk into each field of struct.
604 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
606 // Sequence of patterns.
607 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
608 s.iter().for_each(|p| p.walk(it))
611 // Trivial wrappers over inner patterns.
612 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
614 // These patterns do not contain subpatterns, skip.
621 | PatKind::MacCall(_) => {}
625 /// Is this a `..` pattern?
626 pub fn is_rest(&self) -> bool {
628 PatKind::Rest => true,
634 /// A single field in a struct pattern
636 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
637 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
638 /// except is_shorthand is true
639 #[derive(Clone, Encodable, Decodable, Debug)]
640 pub struct FieldPat {
641 /// The identifier for the field
643 /// The pattern the field is destructured to
645 pub is_shorthand: bool,
649 pub is_placeholder: bool,
652 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
653 pub enum BindingMode {
658 #[derive(Clone, Encodable, Decodable, Debug)]
660 Included(RangeSyntax),
664 #[derive(Clone, Encodable, Decodable, Debug)]
665 pub enum RangeSyntax {
672 #[derive(Clone, Encodable, Decodable, Debug)]
674 /// Represents a wildcard pattern (`_`).
677 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
678 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
679 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
680 /// during name resolution.
681 Ident(BindingMode, Ident, Option<P<Pat>>),
683 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
684 /// The `bool` is `true` in the presence of a `..`.
685 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
687 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
688 TupleStruct(Path, Vec<P<Pat>>),
690 /// An or-pattern `A | B | C`.
691 /// Invariant: `pats.len() >= 2`.
694 /// A possibly qualified path pattern.
695 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
696 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
697 /// only legally refer to associated constants.
698 Path(Option<QSelf>, Path),
700 /// A tuple pattern (`(a, b)`).
706 /// A reference pattern (e.g., `&mut (a, b)`).
707 Ref(P<Pat>, Mutability),
712 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
713 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
715 /// A slice pattern `[a, b, c]`.
718 /// A rest pattern `..`.
720 /// Syntactically it is valid anywhere.
722 /// Semantically however, it only has meaning immediately inside:
723 /// - a slice pattern: `[a, .., b]`,
724 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
725 /// - a tuple pattern: `(a, .., b)`,
726 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
728 /// In all of these cases, an additional restriction applies,
729 /// only one rest pattern may occur in the pattern sequences.
732 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
735 /// A macro pattern; pre-expansion.
739 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
740 #[derive(HashStable_Generic, Encodable, Decodable)]
741 pub enum Mutability {
747 /// Returns `MutMutable` only if both `self` and `other` are mutable.
748 pub fn and(self, other: Self) -> Self {
750 Mutability::Mut => other,
751 Mutability::Not => Mutability::Not,
755 pub fn invert(self) -> Self {
757 Mutability::Mut => Mutability::Not,
758 Mutability::Not => Mutability::Mut,
762 pub fn prefix_str(&self) -> &'static str {
764 Mutability::Mut => "mut ",
765 Mutability::Not => "",
770 /// The kind of borrow in an `AddrOf` expression,
771 /// e.g., `&place` or `&raw const place`.
772 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
773 #[derive(Encodable, Decodable, HashStable_Generic)]
774 pub enum BorrowKind {
775 /// A normal borrow, `&$expr` or `&mut $expr`.
776 /// The resulting type is either `&'a T` or `&'a mut T`
777 /// where `T = typeof($expr)` and `'a` is some lifetime.
779 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
780 /// The resulting type is either `*const T` or `*mut T`
781 /// where `T = typeof($expr)`.
785 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
787 /// The `+` operator (addition)
789 /// The `-` operator (subtraction)
791 /// The `*` operator (multiplication)
793 /// The `/` operator (division)
795 /// The `%` operator (modulus)
797 /// The `&&` operator (logical and)
799 /// The `||` operator (logical or)
801 /// The `^` operator (bitwise xor)
803 /// The `&` operator (bitwise and)
805 /// The `|` operator (bitwise or)
807 /// The `<<` operator (shift left)
809 /// The `>>` operator (shift right)
811 /// The `==` operator (equality)
813 /// The `<` operator (less than)
815 /// The `<=` operator (less than or equal to)
817 /// The `!=` operator (not equal to)
819 /// The `>=` operator (greater than or equal to)
821 /// The `>` operator (greater than)
826 pub fn to_string(&self) -> &'static str {
849 pub fn lazy(&self) -> bool {
851 BinOpKind::And | BinOpKind::Or => true,
856 pub fn is_shift(&self) -> bool {
858 BinOpKind::Shl | BinOpKind::Shr => true,
863 pub fn is_comparison(&self) -> bool {
865 // Note for developers: please keep this as is;
866 // we want compilation to fail if another variant is added.
868 Eq | Lt | Le | Ne | Gt | Ge => true,
869 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
873 /// Returns `true` if the binary operator takes its arguments by value
874 pub fn is_by_value(&self) -> bool {
875 !self.is_comparison()
879 pub type BinOp = Spanned<BinOpKind>;
883 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
884 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
886 /// The `*` operator for dereferencing
888 /// The `!` operator for logical inversion
890 /// The `-` operator for negation
895 /// Returns `true` if the unary operator takes its argument by value
896 pub fn is_by_value(u: UnOp) -> bool {
898 UnOp::Neg | UnOp::Not => true,
903 pub fn to_string(op: UnOp) -> &'static str {
913 #[derive(Clone, Encodable, Decodable, Debug)]
921 pub fn add_trailing_semicolon(mut self) -> Self {
922 self.kind = match self.kind {
923 StmtKind::Expr(expr) => StmtKind::Semi(expr),
924 StmtKind::MacCall(mac) => StmtKind::MacCall(
925 mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)),
932 pub fn is_item(&self) -> bool {
934 StmtKind::Item(_) => true,
939 pub fn is_expr(&self) -> bool {
941 StmtKind::Expr(_) => true,
947 #[derive(Clone, Encodable, Decodable, Debug)]
949 /// A local (let) binding.
951 /// An item definition.
953 /// Expr without trailing semi-colon.
955 /// Expr with a trailing semi-colon.
957 /// Just a trailing semi-colon.
960 MacCall(P<(MacCall, MacStmtStyle, AttrVec)>),
963 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
964 pub enum MacStmtStyle {
965 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
966 /// `foo!(...);`, `foo![...];`).
968 /// The macro statement had braces (e.g., `foo! { ... }`).
970 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
971 /// `foo!(...)`). All of these will end up being converted into macro
976 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
977 #[derive(Clone, Encodable, Decodable, Debug)]
981 pub ty: Option<P<Ty>>,
982 /// Initializer expression to set the value, if any.
983 pub init: Option<P<Expr>>,
988 /// An arm of a 'match'.
990 /// E.g., `0..=10 => { println!("match!") }` as in
994 /// 0..=10 => { println!("match!") },
995 /// _ => { println!("no match!") },
998 #[derive(Clone, Encodable, Decodable, Debug)]
1000 pub attrs: Vec<Attribute>,
1001 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1003 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1004 pub guard: Option<P<Expr>>,
1009 pub is_placeholder: bool,
1012 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1013 #[derive(Clone, Encodable, Decodable, Debug)]
1020 pub is_shorthand: bool,
1021 pub is_placeholder: bool,
1024 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1025 pub enum BlockCheckMode {
1027 Unsafe(UnsafeSource),
1030 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1031 pub enum UnsafeSource {
1036 /// A constant (expression) that's not an item or associated item,
1037 /// but needs its own `DefId` for type-checking, const-eval, etc.
1038 /// These are usually found nested inside types (e.g., array lengths)
1039 /// or expressions (e.g., repeat counts), and also used to define
1040 /// explicit discriminant values for enum variants.
1041 #[derive(Clone, Encodable, Decodable, Debug)]
1042 pub struct AnonConst {
1048 #[derive(Clone, Encodable, Decodable, Debug)]
1054 pub tokens: Option<TokenStream>,
1057 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1058 #[cfg(target_arch = "x86_64")]
1059 rustc_data_structures::static_assert_size!(Expr, 104);
1062 /// Returns `true` if this expression would be valid somewhere that expects a value;
1063 /// for example, an `if` condition.
1064 pub fn returns(&self) -> bool {
1065 if let ExprKind::Block(ref block, _) = self.kind {
1066 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1068 Some(&StmtKind::Expr(_)) => true,
1069 Some(&StmtKind::Semi(ref expr)) => {
1070 if let ExprKind::Ret(_) = expr.kind {
1071 // Last statement is explicit return.
1077 // This is a block that doesn't end in either an implicit or explicit return.
1081 // This is not a block, it is a value.
1086 /// Is this expr either `N`, or `{ N }`.
1088 /// If this is not the case, name resolution does not resolve `N` when using
1089 /// `feature(min_const_generics)` as more complex expressions are not supported.
1090 pub fn is_potential_trivial_const_param(&self) -> bool {
1091 let this = if let ExprKind::Block(ref block, None) = self.kind {
1092 if block.stmts.len() == 1 {
1093 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1101 if let ExprKind::Path(None, ref path) = this.kind {
1102 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1110 pub fn to_bound(&self) -> Option<GenericBound> {
1112 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1113 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1114 TraitBoundModifier::None,
1120 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1121 pub fn to_ty(&self) -> Option<P<Ty>> {
1122 let kind = match &self.kind {
1123 // Trivial conversions.
1124 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1125 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1127 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1129 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1130 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1133 ExprKind::Repeat(expr, expr_len) => {
1134 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1137 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1139 ExprKind::Tup(exprs) => {
1140 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1144 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1145 // then type of result is trait object.
1146 // Otherwise we don't assume the result type.
1147 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1148 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1149 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1155 // This expression doesn't look like a type syntactically.
1159 Some(P(Ty { kind, id: self.id, span: self.span }))
1162 pub fn precedence(&self) -> ExprPrecedence {
1164 ExprKind::Box(_) => ExprPrecedence::Box,
1165 ExprKind::Array(_) => ExprPrecedence::Array,
1166 ExprKind::Call(..) => ExprPrecedence::Call,
1167 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1168 ExprKind::Tup(_) => ExprPrecedence::Tup,
1169 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1170 ExprKind::Unary(..) => ExprPrecedence::Unary,
1171 ExprKind::Lit(_) => ExprPrecedence::Lit,
1172 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1173 ExprKind::Let(..) => ExprPrecedence::Let,
1174 ExprKind::If(..) => ExprPrecedence::If,
1175 ExprKind::While(..) => ExprPrecedence::While,
1176 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1177 ExprKind::Loop(..) => ExprPrecedence::Loop,
1178 ExprKind::Match(..) => ExprPrecedence::Match,
1179 ExprKind::Closure(..) => ExprPrecedence::Closure,
1180 ExprKind::Block(..) => ExprPrecedence::Block,
1181 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1182 ExprKind::Async(..) => ExprPrecedence::Async,
1183 ExprKind::Await(..) => ExprPrecedence::Await,
1184 ExprKind::Assign(..) => ExprPrecedence::Assign,
1185 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1186 ExprKind::Field(..) => ExprPrecedence::Field,
1187 ExprKind::Index(..) => ExprPrecedence::Index,
1188 ExprKind::Range(..) => ExprPrecedence::Range,
1189 ExprKind::Path(..) => ExprPrecedence::Path,
1190 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1191 ExprKind::Break(..) => ExprPrecedence::Break,
1192 ExprKind::Continue(..) => ExprPrecedence::Continue,
1193 ExprKind::Ret(..) => ExprPrecedence::Ret,
1194 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1195 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1196 ExprKind::Struct(..) => ExprPrecedence::Struct,
1197 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1198 ExprKind::Paren(..) => ExprPrecedence::Paren,
1199 ExprKind::Try(..) => ExprPrecedence::Try,
1200 ExprKind::Yield(..) => ExprPrecedence::Yield,
1201 ExprKind::Err => ExprPrecedence::Err,
1206 /// Limit types of a range (inclusive or exclusive)
1207 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1208 pub enum RangeLimits {
1209 /// Inclusive at the beginning, exclusive at the end
1211 /// Inclusive at the beginning and end
1215 #[derive(Clone, Encodable, Decodable, Debug)]
1217 /// A `box x` expression.
1219 /// An array (`[a, b, c, d]`)
1220 Array(Vec<P<Expr>>),
1223 /// The first field resolves to the function itself,
1224 /// and the second field is the list of arguments.
1225 /// This also represents calling the constructor of
1226 /// tuple-like ADTs such as tuple structs and enum variants.
1227 Call(P<Expr>, Vec<P<Expr>>),
1228 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1230 /// The `PathSegment` represents the method name and its generic arguments
1231 /// (within the angle brackets).
1232 /// The first element of the vector of an `Expr` is the expression that evaluates
1233 /// to the object on which the method is being called on (the receiver),
1234 /// and the remaining elements are the rest of the arguments.
1235 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1236 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1237 /// This `Span` is the span of the function, without the dot and receiver
1238 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1239 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1240 /// A tuple (e.g., `(a, b, c, d)`).
1242 /// A binary operation (e.g., `a + b`, `a * b`).
1243 Binary(BinOp, P<Expr>, P<Expr>),
1244 /// A unary operation (e.g., `!x`, `*x`).
1245 Unary(UnOp, P<Expr>),
1246 /// A literal (e.g., `1`, `"foo"`).
1248 /// A cast (e.g., `foo as f64`).
1249 Cast(P<Expr>, P<Ty>),
1250 /// A type ascription (e.g., `42: usize`).
1251 Type(P<Expr>, P<Ty>),
1252 /// A `let pat = expr` expression that is only semantically allowed in the condition
1253 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1254 Let(P<Pat>, P<Expr>),
1255 /// An `if` block, with an optional `else` block.
1257 /// `if expr { block } else { expr }`
1258 If(P<Expr>, P<Block>, Option<P<Expr>>),
1259 /// A while loop, with an optional label.
1261 /// `'label: while expr { block }`
1262 While(P<Expr>, P<Block>, Option<Label>),
1263 /// A `for` loop, with an optional label.
1265 /// `'label: for pat in expr { block }`
1267 /// This is desugared to a combination of `loop` and `match` expressions.
1268 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1269 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1271 /// `'label: loop { block }`
1272 Loop(P<Block>, Option<Label>),
1273 /// A `match` block.
1274 Match(P<Expr>, Vec<Arm>),
1275 /// A closure (e.g., `move |a, b, c| a + b + c`).
1277 /// The final span is the span of the argument block `|...|`.
1278 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1279 /// A block (`'label: { ... }`).
1280 Block(P<Block>, Option<Label>),
1281 /// An async block (`async move { ... }`).
1283 /// The `NodeId` is the `NodeId` for the closure that results from
1284 /// desugaring an async block, just like the NodeId field in the
1285 /// `Async::Yes` variant. This is necessary in order to create a def for the
1286 /// closure which can be used as a parent of any child defs. Defs
1287 /// created during lowering cannot be made the parent of any other
1288 /// preexisting defs.
1289 Async(CaptureBy, NodeId, P<Block>),
1290 /// An await expression (`my_future.await`).
1293 /// A try block (`try { ... }`).
1296 /// An assignment (`a = foo()`).
1297 /// The `Span` argument is the span of the `=` token.
1298 Assign(P<Expr>, P<Expr>, Span),
1299 /// An assignment with an operator.
1302 AssignOp(BinOp, P<Expr>, P<Expr>),
1303 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1304 Field(P<Expr>, Ident),
1305 /// An indexing operation (e.g., `foo[2]`).
1306 Index(P<Expr>, P<Expr>),
1307 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1308 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1310 /// Variable reference, possibly containing `::` and/or type
1311 /// parameters (e.g., `foo::bar::<baz>`).
1313 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1314 Path(Option<QSelf>, Path),
1316 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1317 AddrOf(BorrowKind, Mutability, P<Expr>),
1318 /// A `break`, with an optional label to break, and an optional expression.
1319 Break(Option<Label>, Option<P<Expr>>),
1320 /// A `continue`, with an optional label.
1321 Continue(Option<Label>),
1322 /// A `return`, with an optional value to be returned.
1323 Ret(Option<P<Expr>>),
1325 /// Output of the `asm!()` macro.
1326 InlineAsm(P<InlineAsm>),
1327 /// Output of the `llvm_asm!()` macro.
1328 LlvmInlineAsm(P<LlvmInlineAsm>),
1330 /// A macro invocation; pre-expansion.
1333 /// A struct literal expression.
1335 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1336 /// where `base` is the `Option<Expr>`.
1337 Struct(Path, Vec<Field>, Option<P<Expr>>),
1339 /// An array literal constructed from one repeated element.
1341 /// E.g., `[1; 5]`. The expression is the element to be
1342 /// repeated; the constant is the number of times to repeat it.
1343 Repeat(P<Expr>, AnonConst),
1345 /// No-op: used solely so we can pretty-print faithfully.
1348 /// A try expression (`expr?`).
1351 /// A `yield`, with an optional value to be yielded.
1352 Yield(Option<P<Expr>>),
1354 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1358 /// The explicit `Self` type in a "qualified path". The actual
1359 /// path, including the trait and the associated item, is stored
1360 /// separately. `position` represents the index of the associated
1361 /// item qualified with this `Self` type.
1363 /// ```ignore (only-for-syntax-highlight)
1364 /// <Vec<T> as a::b::Trait>::AssociatedItem
1365 /// ^~~~~ ~~~~~~~~~~~~~~^
1368 /// <Vec<T>>::AssociatedItem
1372 #[derive(Clone, Encodable, Decodable, Debug)]
1376 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1377 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1378 /// 0`, this is an empty span.
1379 pub path_span: Span,
1380 pub position: usize,
1383 /// A capture clause used in closures and `async` blocks.
1384 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1385 pub enum CaptureBy {
1386 /// `move |x| y + x`.
1388 /// `move` keyword was not specified.
1392 /// The movability of a generator / closure literal:
1393 /// whether a generator contains self-references, causing it to be `!Unpin`.
1394 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1395 #[derive(HashStable_Generic)]
1396 pub enum Movability {
1397 /// May contain self-references, `!Unpin`.
1399 /// Must not contain self-references, `Unpin`.
1403 /// Represents a macro invocation. The `path` indicates which macro
1404 /// is being invoked, and the `args` are arguments passed to it.
1405 #[derive(Clone, Encodable, Decodable, Debug)]
1406 pub struct MacCall {
1408 pub args: P<MacArgs>,
1409 pub prior_type_ascription: Option<(Span, bool)>,
1413 pub fn span(&self) -> Span {
1414 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1418 /// Arguments passed to an attribute or a function-like macro.
1419 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1421 /// No arguments - `#[attr]`.
1423 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1424 Delimited(DelimSpan, MacDelimiter, TokenStream),
1425 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1427 /// Span of the `=` token.
1429 /// Token stream of the "value".
1435 pub fn delim(&self) -> DelimToken {
1437 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1438 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1442 pub fn span(&self) -> Option<Span> {
1444 MacArgs::Empty => None,
1445 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1446 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1450 /// Tokens inside the delimiters or after `=`.
1451 /// Proc macros see these tokens, for example.
1452 pub fn inner_tokens(&self) -> TokenStream {
1454 MacArgs::Empty => TokenStream::default(),
1455 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1459 /// Tokens together with the delimiters or `=`.
1460 /// Use of this method generally means that something suboptimal or hacky is happening.
1461 pub fn outer_tokens(&self) -> TokenStream {
1463 MacArgs::Empty => TokenStream::default(),
1464 MacArgs::Delimited(dspan, delim, ref tokens) => {
1465 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1467 MacArgs::Eq(eq_span, ref tokens) => {
1468 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1473 /// Whether a macro with these arguments needs a semicolon
1474 /// when used as a standalone item or statement.
1475 pub fn need_semicolon(&self) -> bool {
1476 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1480 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1481 pub enum MacDelimiter {
1488 pub fn to_token(self) -> DelimToken {
1490 MacDelimiter::Parenthesis => DelimToken::Paren,
1491 MacDelimiter::Bracket => DelimToken::Bracket,
1492 MacDelimiter::Brace => DelimToken::Brace,
1496 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1498 token::Paren => Some(MacDelimiter::Parenthesis),
1499 token::Bracket => Some(MacDelimiter::Bracket),
1500 token::Brace => Some(MacDelimiter::Brace),
1501 token::NoDelim => None,
1506 /// Represents a macro definition.
1507 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1508 pub struct MacroDef {
1509 pub body: P<MacArgs>,
1510 /// `true` if macro was defined with `macro_rules`.
1511 pub macro_rules: bool,
1514 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1515 #[derive(HashStable_Generic)]
1517 /// A regular string, like `"foo"`.
1519 /// A raw string, like `r##"foo"##`.
1521 /// The value is the number of `#` symbols used.
1526 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1528 /// The original literal token as written in source code.
1529 pub token: token::Lit,
1530 /// The "semantic" representation of the literal lowered from the original tokens.
1531 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1532 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1537 /// Same as `Lit`, but restricted to string literals.
1538 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1540 /// The original literal token as written in source code.
1541 pub style: StrStyle,
1543 pub suffix: Option<Symbol>,
1545 /// The unescaped "semantic" representation of the literal lowered from the original token.
1546 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1547 pub symbol_unescaped: Symbol,
1551 pub fn as_lit(&self) -> Lit {
1552 let token_kind = match self.style {
1553 StrStyle::Cooked => token::Str,
1554 StrStyle::Raw(n) => token::StrRaw(n),
1557 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1559 kind: LitKind::Str(self.symbol_unescaped, self.style),
1564 /// Type of the integer literal based on provided suffix.
1565 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1566 #[derive(HashStable_Generic)]
1567 pub enum LitIntType {
1576 /// Type of the float literal based on provided suffix.
1577 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1578 #[derive(HashStable_Generic)]
1579 pub enum LitFloatType {
1580 /// A float literal with a suffix (`1f32` or `1E10f32`).
1582 /// A float literal without a suffix (`1.0 or 1.0E10`).
1588 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1589 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1591 /// A string literal (`"foo"`).
1592 Str(Symbol, StrStyle),
1593 /// A byte string (`b"foo"`).
1594 ByteStr(Lrc<Vec<u8>>),
1595 /// A byte char (`b'f'`).
1597 /// A character literal (`'a'`).
1599 /// An integer literal (`1`).
1600 Int(u128, LitIntType),
1601 /// A float literal (`1f64` or `1E10f64`).
1602 Float(Symbol, LitFloatType),
1603 /// A boolean literal.
1605 /// Placeholder for a literal that wasn't well-formed in some way.
1610 /// Returns `true` if this literal is a string.
1611 pub fn is_str(&self) -> bool {
1613 LitKind::Str(..) => true,
1618 /// Returns `true` if this literal is byte literal string.
1619 pub fn is_bytestr(&self) -> bool {
1621 LitKind::ByteStr(_) => true,
1626 /// Returns `true` if this is a numeric literal.
1627 pub fn is_numeric(&self) -> bool {
1629 LitKind::Int(..) | LitKind::Float(..) => true,
1634 /// Returns `true` if this literal has no suffix.
1635 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1636 pub fn is_unsuffixed(&self) -> bool {
1640 /// Returns `true` if this literal has a suffix.
1641 pub fn is_suffixed(&self) -> bool {
1643 // suffixed variants
1644 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1645 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1646 // unsuffixed variants
1648 | LitKind::ByteStr(..)
1651 | LitKind::Int(_, LitIntType::Unsuffixed)
1652 | LitKind::Float(_, LitFloatType::Unsuffixed)
1654 | LitKind::Err(..) => false,
1659 // N.B., If you change this, you'll probably want to change the corresponding
1660 // type structure in `middle/ty.rs` as well.
1661 #[derive(Clone, Encodable, Decodable, Debug)]
1664 pub mutbl: Mutability,
1667 /// Represents a function's signature in a trait declaration,
1668 /// trait implementation, or free function.
1669 #[derive(Clone, Encodable, Decodable, Debug)]
1671 pub header: FnHeader,
1672 pub decl: P<FnDecl>,
1675 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1676 #[derive(Encodable, Decodable, HashStable_Generic)]
1683 pub fn name_str(self) -> &'static str {
1685 FloatTy::F32 => "f32",
1686 FloatTy::F64 => "f64",
1690 pub fn name(self) -> Symbol {
1692 FloatTy::F32 => sym::f32,
1693 FloatTy::F64 => sym::f64,
1697 pub fn bit_width(self) -> u64 {
1705 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1706 #[derive(Encodable, Decodable, HashStable_Generic)]
1717 pub fn name_str(&self) -> &'static str {
1719 IntTy::Isize => "isize",
1721 IntTy::I16 => "i16",
1722 IntTy::I32 => "i32",
1723 IntTy::I64 => "i64",
1724 IntTy::I128 => "i128",
1728 pub fn name(&self) -> Symbol {
1730 IntTy::Isize => sym::isize,
1731 IntTy::I8 => sym::i8,
1732 IntTy::I16 => sym::i16,
1733 IntTy::I32 => sym::i32,
1734 IntTy::I64 => sym::i64,
1735 IntTy::I128 => sym::i128,
1739 pub fn val_to_string(&self, val: i128) -> String {
1740 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1741 // are parsed as `u128`, so we wouldn't want to print an extra negative
1743 format!("{}{}", val as u128, self.name_str())
1746 pub fn bit_width(&self) -> Option<u64> {
1748 IntTy::Isize => return None,
1757 pub fn normalize(&self, target_width: u32) -> Self {
1759 IntTy::Isize => match target_width {
1763 _ => unreachable!(),
1770 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1771 #[derive(Encodable, Decodable, HashStable_Generic)]
1782 pub fn name_str(&self) -> &'static str {
1784 UintTy::Usize => "usize",
1786 UintTy::U16 => "u16",
1787 UintTy::U32 => "u32",
1788 UintTy::U64 => "u64",
1789 UintTy::U128 => "u128",
1793 pub fn name(&self) -> Symbol {
1795 UintTy::Usize => sym::usize,
1796 UintTy::U8 => sym::u8,
1797 UintTy::U16 => sym::u16,
1798 UintTy::U32 => sym::u32,
1799 UintTy::U64 => sym::u64,
1800 UintTy::U128 => sym::u128,
1804 pub fn val_to_string(&self, val: u128) -> String {
1805 format!("{}{}", val, self.name_str())
1808 pub fn bit_width(&self) -> Option<u64> {
1810 UintTy::Usize => return None,
1815 UintTy::U128 => 128,
1819 pub fn normalize(&self, target_width: u32) -> Self {
1821 UintTy::Usize => match target_width {
1825 _ => unreachable!(),
1832 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1833 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1834 #[derive(Clone, Encodable, Decodable, Debug)]
1835 pub struct AssocTyConstraint {
1838 pub kind: AssocTyConstraintKind,
1842 /// The kinds of an `AssocTyConstraint`.
1843 #[derive(Clone, Encodable, Decodable, Debug)]
1844 pub enum AssocTyConstraintKind {
1845 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1846 Equality { ty: P<Ty> },
1847 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1848 Bound { bounds: GenericBounds },
1851 #[derive(Clone, Encodable, Decodable, Debug)]
1858 #[derive(Clone, Encodable, Decodable, Debug)]
1859 pub struct BareFnTy {
1860 pub unsafety: Unsafe,
1862 pub generic_params: Vec<GenericParam>,
1863 pub decl: P<FnDecl>,
1866 /// The various kinds of type recognized by the compiler.
1867 #[derive(Clone, Encodable, Decodable, Debug)]
1869 /// A variable-length slice (`[T]`).
1871 /// A fixed length array (`[T; n]`).
1872 Array(P<Ty>, AnonConst),
1873 /// A raw pointer (`*const T` or `*mut T`).
1875 /// A reference (`&'a T` or `&'a mut T`).
1876 Rptr(Option<Lifetime>, MutTy),
1877 /// A bare function (e.g., `fn(usize) -> bool`).
1878 BareFn(P<BareFnTy>),
1879 /// The never type (`!`).
1881 /// A tuple (`(A, B, C, D,...)`).
1883 /// A path (`module::module::...::Type`), optionally
1884 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1886 /// Type parameters are stored in the `Path` itself.
1887 Path(Option<QSelf>, Path),
1888 /// A trait object type `Bound1 + Bound2 + Bound3`
1889 /// where `Bound` is a trait or a lifetime.
1890 TraitObject(GenericBounds, TraitObjectSyntax),
1891 /// An `impl Bound1 + Bound2 + Bound3` type
1892 /// where `Bound` is a trait or a lifetime.
1894 /// The `NodeId` exists to prevent lowering from having to
1895 /// generate `NodeId`s on the fly, which would complicate
1896 /// the generation of opaque `type Foo = impl Trait` items significantly.
1897 ImplTrait(NodeId, GenericBounds),
1898 /// No-op; kept solely so that we can pretty-print faithfully.
1902 /// This means the type should be inferred instead of it having been
1903 /// specified. This can appear anywhere in a type.
1905 /// Inferred type of a `self` or `&self` argument in a method.
1907 /// A macro in the type position.
1909 /// Placeholder for a kind that has failed to be defined.
1911 /// Placeholder for a `va_list`.
1916 pub fn is_implicit_self(&self) -> bool {
1917 if let TyKind::ImplicitSelf = *self { true } else { false }
1920 pub fn is_unit(&self) -> bool {
1921 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1925 /// Syntax used to declare a trait object.
1926 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1927 pub enum TraitObjectSyntax {
1932 /// Inline assembly operand explicit register or register class.
1934 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1935 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1936 pub enum InlineAsmRegOrRegClass {
1941 bitflags::bitflags! {
1942 #[derive(Encodable, Decodable, HashStable_Generic)]
1943 pub struct InlineAsmOptions: u8 {
1944 const PURE = 1 << 0;
1945 const NOMEM = 1 << 1;
1946 const READONLY = 1 << 2;
1947 const PRESERVES_FLAGS = 1 << 3;
1948 const NORETURN = 1 << 4;
1949 const NOSTACK = 1 << 5;
1950 const ATT_SYNTAX = 1 << 6;
1954 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1955 pub enum InlineAsmTemplatePiece {
1957 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1960 impl fmt::Display for InlineAsmTemplatePiece {
1961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1963 Self::String(s) => {
1964 for c in s.chars() {
1966 '{' => f.write_str("{{")?,
1967 '}' => f.write_str("}}")?,
1973 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1974 write!(f, "{{{}:{}}}", operand_idx, modifier)
1976 Self::Placeholder { operand_idx, modifier: None, .. } => {
1977 write!(f, "{{{}}}", operand_idx)
1983 impl InlineAsmTemplatePiece {
1984 /// Rebuilds the asm template string from its pieces.
1985 pub fn to_string(s: &[Self]) -> String {
1987 let mut out = String::new();
1989 let _ = write!(out, "{}", p);
1995 /// Inline assembly operand.
1997 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
1998 #[derive(Clone, Encodable, Decodable, Debug)]
1999 pub enum InlineAsmOperand {
2001 reg: InlineAsmRegOrRegClass,
2005 reg: InlineAsmRegOrRegClass,
2007 expr: Option<P<Expr>>,
2010 reg: InlineAsmRegOrRegClass,
2015 reg: InlineAsmRegOrRegClass,
2018 out_expr: Option<P<Expr>>,
2028 /// Inline assembly.
2030 /// E.g., `asm!("NOP");`.
2031 #[derive(Clone, Encodable, Decodable, Debug)]
2032 pub struct InlineAsm {
2033 pub template: Vec<InlineAsmTemplatePiece>,
2034 pub operands: Vec<(InlineAsmOperand, Span)>,
2035 pub options: InlineAsmOptions,
2036 pub line_spans: Vec<Span>,
2039 /// Inline assembly dialect.
2041 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2042 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2043 pub enum LlvmAsmDialect {
2048 /// LLVM-style inline assembly.
2050 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2051 #[derive(Clone, Encodable, Decodable, Debug)]
2052 pub struct LlvmInlineAsmOutput {
2053 pub constraint: Symbol,
2056 pub is_indirect: bool,
2059 /// LLVM-style inline assembly.
2061 /// E.g., `llvm_asm!("NOP");`.
2062 #[derive(Clone, Encodable, Decodable, Debug)]
2063 pub struct LlvmInlineAsm {
2065 pub asm_str_style: StrStyle,
2066 pub outputs: Vec<LlvmInlineAsmOutput>,
2067 pub inputs: Vec<(Symbol, P<Expr>)>,
2068 pub clobbers: Vec<Symbol>,
2070 pub alignstack: bool,
2071 pub dialect: LlvmAsmDialect,
2074 /// A parameter in a function header.
2076 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2077 #[derive(Clone, Encodable, Decodable, Debug)]
2084 pub is_placeholder: bool,
2087 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2089 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2090 #[derive(Clone, Encodable, Decodable, Debug)]
2092 /// `self`, `mut self`
2094 /// `&'lt self`, `&'lt mut self`
2095 Region(Option<Lifetime>, Mutability),
2096 /// `self: TYPE`, `mut self: TYPE`
2097 Explicit(P<Ty>, Mutability),
2100 pub type ExplicitSelf = Spanned<SelfKind>;
2103 /// Attempts to cast parameter to `ExplicitSelf`.
2104 pub fn to_self(&self) -> Option<ExplicitSelf> {
2105 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2106 if ident.name == kw::SelfLower {
2107 return match self.ty.kind {
2108 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2109 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2110 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2113 self.pat.span.to(self.ty.span),
2114 SelfKind::Explicit(self.ty.clone(), mutbl),
2122 /// Returns `true` if parameter is `self`.
2123 pub fn is_self(&self) -> bool {
2124 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2125 ident.name == kw::SelfLower
2131 /// Builds a `Param` object from `ExplicitSelf`.
2132 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2133 let span = eself.span.to(eself_ident.span);
2134 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2135 let param = |mutbl, ty| Param {
2139 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2145 is_placeholder: false,
2148 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2149 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2150 SelfKind::Region(lt, mutbl) => param(
2154 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2162 /// A signature (not the body) of a function declaration.
2164 /// E.g., `fn foo(bar: baz)`.
2166 /// Please note that it's different from `FnHeader` structure
2167 /// which contains metadata about function safety, asyncness, constness and ABI.
2168 #[derive(Clone, Encodable, Decodable, Debug)]
2170 pub inputs: Vec<Param>,
2171 pub output: FnRetTy,
2175 pub fn get_self(&self) -> Option<ExplicitSelf> {
2176 self.inputs.get(0).and_then(Param::to_self)
2178 pub fn has_self(&self) -> bool {
2179 self.inputs.get(0).map_or(false, Param::is_self)
2181 pub fn c_variadic(&self) -> bool {
2182 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2183 TyKind::CVarArgs => true,
2189 /// Is the trait definition an auto trait?
2190 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2196 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2197 #[derive(HashStable_Generic)]
2203 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2205 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2210 pub fn is_async(self) -> bool {
2211 if let Async::Yes { .. } = self { true } else { false }
2214 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2215 pub fn opt_return_id(self) -> Option<NodeId> {
2217 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2223 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2224 #[derive(HashStable_Generic)]
2230 /// Item defaultness.
2231 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2232 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2233 pub enum Defaultness {
2238 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2239 pub enum ImplPolarity {
2240 /// `impl Trait for Type`
2242 /// `impl !Trait for Type`
2246 impl fmt::Debug for ImplPolarity {
2247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2249 ImplPolarity::Positive => "positive".fmt(f),
2250 ImplPolarity::Negative(_) => "negative".fmt(f),
2255 #[derive(Clone, Encodable, Decodable, Debug)]
2257 /// Returns type is not specified.
2259 /// Functions default to `()` and closures default to inference.
2260 /// Span points to where return type would be inserted.
2262 /// Everything else.
2267 pub fn span(&self) -> Span {
2269 FnRetTy::Default(span) => span,
2270 FnRetTy::Ty(ref ty) => ty.span,
2275 /// Module declaration.
2277 /// E.g., `mod foo;` or `mod foo { .. }`.
2278 #[derive(Clone, Encodable, Decodable, Debug, Default)]
2280 /// A span from the first token past `{` to the last token until `}`.
2281 /// For `mod foo;`, the inner span ranges from the first token
2282 /// to the last token in the external file.
2284 pub items: Vec<P<Item>>,
2285 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2289 /// Foreign module declaration.
2291 /// E.g., `extern { .. }` or `extern C { .. }`.
2292 #[derive(Clone, Encodable, Decodable, Debug)]
2293 pub struct ForeignMod {
2294 pub abi: Option<StrLit>,
2295 pub items: Vec<P<ForeignItem>>,
2298 /// Global inline assembly.
2300 /// Also known as "module-level assembly" or "file-scoped assembly".
2301 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2302 pub struct GlobalAsm {
2306 #[derive(Clone, Encodable, Decodable, Debug)]
2307 pub struct EnumDef {
2308 pub variants: Vec<Variant>,
2311 #[derive(Clone, Encodable, Decodable, Debug)]
2312 pub struct Variant {
2313 /// Attributes of the variant.
2314 pub attrs: Vec<Attribute>,
2315 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2319 /// The visibility of the variant. Syntactically accepted but not semantically.
2320 pub vis: Visibility,
2321 /// Name of the variant.
2324 /// Fields and constructor id of the variant.
2325 pub data: VariantData,
2326 /// Explicit discriminant, e.g., `Foo = 1`.
2327 pub disr_expr: Option<AnonConst>,
2328 /// Is a macro placeholder
2329 pub is_placeholder: bool,
2332 /// Part of `use` item to the right of its prefix.
2333 #[derive(Clone, Encodable, Decodable, Debug)]
2334 pub enum UseTreeKind {
2335 /// `use prefix` or `use prefix as rename`
2337 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2339 Simple(Option<Ident>, NodeId, NodeId),
2340 /// `use prefix::{...}`
2341 Nested(Vec<(UseTree, NodeId)>),
2346 /// A tree of paths sharing common prefixes.
2347 /// Used in `use` items both at top-level and inside of braces in import groups.
2348 #[derive(Clone, Encodable, Decodable, Debug)]
2349 pub struct UseTree {
2351 pub kind: UseTreeKind,
2356 pub fn ident(&self) -> Ident {
2358 UseTreeKind::Simple(Some(rename), ..) => rename,
2359 UseTreeKind::Simple(None, ..) => {
2360 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2362 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2367 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2368 /// are contained as statements within items. These two cases need to be
2369 /// distinguished for pretty-printing.
2370 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2371 pub enum AttrStyle {
2376 rustc_index::newtype_index! {
2379 DEBUG_FORMAT = "AttrId({})"
2383 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2384 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2389 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2390 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2391 d.read_nil().map(|_| crate::attr::mk_attr_id())
2395 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2396 pub struct AttrItem {
2401 /// A list of attributes.
2402 pub type AttrVec = ThinVec<Attribute>;
2404 /// Metadata associated with an item.
2405 #[derive(Clone, Encodable, Decodable, Debug)]
2406 pub struct Attribute {
2409 /// Denotes if the attribute decorates the following construct (outer)
2410 /// or the construct this attribute is contained within (inner).
2411 pub style: AttrStyle,
2415 #[derive(Clone, Encodable, Decodable, Debug)]
2417 /// A normal attribute.
2420 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2421 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2422 /// variant (which is much less compact and thus more expensive).
2423 DocComment(CommentKind, Symbol),
2426 /// `TraitRef`s appear in impls.
2428 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2429 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2430 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2431 /// same as the impl's `NodeId`).
2432 #[derive(Clone, Encodable, Decodable, Debug)]
2433 pub struct TraitRef {
2438 #[derive(Clone, Encodable, Decodable, Debug)]
2439 pub struct PolyTraitRef {
2440 /// The `'a` in `<'a> Foo<&'a T>`.
2441 pub bound_generic_params: Vec<GenericParam>,
2443 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2444 pub trait_ref: TraitRef,
2450 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2452 bound_generic_params: generic_params,
2453 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2459 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2460 pub enum CrateSugar {
2461 /// Source is `pub(crate)`.
2464 /// Source is (just) `crate`.
2468 pub type Visibility = Spanned<VisibilityKind>;
2470 #[derive(Clone, Encodable, Decodable, Debug)]
2471 pub enum VisibilityKind {
2474 Restricted { path: P<Path>, id: NodeId },
2478 impl VisibilityKind {
2479 pub fn is_pub(&self) -> bool {
2480 if let VisibilityKind::Public = *self { true } else { false }
2484 /// Field of a struct.
2486 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2487 #[derive(Clone, Encodable, Decodable, Debug)]
2488 pub struct StructField {
2489 pub attrs: Vec<Attribute>,
2492 pub vis: Visibility,
2493 pub ident: Option<Ident>,
2496 pub is_placeholder: bool,
2499 /// Fields and constructor ids of enum variants and structs.
2500 #[derive(Clone, Encodable, Decodable, Debug)]
2501 pub enum VariantData {
2504 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2505 Struct(Vec<StructField>, bool),
2508 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2509 Tuple(Vec<StructField>, NodeId),
2512 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2517 /// Return the fields of this variant.
2518 pub fn fields(&self) -> &[StructField] {
2520 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2525 /// Return the `NodeId` of this variant's constructor, if it has one.
2526 pub fn ctor_id(&self) -> Option<NodeId> {
2528 VariantData::Struct(..) => None,
2529 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2534 /// An item definition.
2535 #[derive(Clone, Encodable, Decodable, Debug)]
2536 pub struct Item<K = ItemKind> {
2537 pub attrs: Vec<Attribute>,
2540 pub vis: Visibility,
2541 /// The name of the item.
2542 /// It might be a dummy name in case of anonymous items.
2547 /// Original tokens this item was parsed from. This isn't necessarily
2548 /// available for all items, although over time more and more items should
2549 /// have this be `Some`. Right now this is primarily used for procedural
2550 /// macros, notably custom attributes.
2552 /// Note that the tokens here do not include the outer attributes, but will
2553 /// include inner attributes.
2554 pub tokens: Option<TokenStream>,
2558 /// Return the span that encompasses the attributes.
2559 pub fn span_with_attributes(&self) -> Span {
2560 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2564 impl<K: Into<ItemKind>> Item<K> {
2565 pub fn into_item(self) -> Item {
2566 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2567 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2571 /// `extern` qualifier on a function item or function type.
2572 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2580 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2581 abi.map_or(Extern::Implicit, Extern::Explicit)
2585 /// A function header.
2587 /// All the information between the visibility and the name of the function is
2588 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2589 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2590 pub struct FnHeader {
2591 pub unsafety: Unsafe,
2592 pub asyncness: Async,
2593 pub constness: Const,
2598 /// Does this function header have any qualifiers or is it empty?
2599 pub fn has_qualifiers(&self) -> bool {
2600 let Self { unsafety, asyncness, constness, ext } = self;
2601 matches!(unsafety, Unsafe::Yes(_))
2602 || asyncness.is_async()
2603 || matches!(constness, Const::Yes(_))
2604 || !matches!(ext, Extern::None)
2608 impl Default for FnHeader {
2609 fn default() -> FnHeader {
2611 unsafety: Unsafe::No,
2612 asyncness: Async::No,
2613 constness: Const::No,
2619 #[derive(Clone, Encodable, Decodable, Debug)]
2621 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2623 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2624 ExternCrate(Option<Symbol>),
2625 /// A use declaration item (`use`).
2627 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2629 /// A static item (`static`).
2631 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2632 Static(P<Ty>, Mutability, Option<P<Expr>>),
2633 /// A constant item (`const`).
2635 /// E.g., `const FOO: i32 = 42;`.
2636 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2637 /// A function declaration (`fn`).
2639 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2640 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2641 /// A module declaration (`mod`).
2643 /// E.g., `mod foo;` or `mod foo { .. }`.
2645 /// An external module (`extern`).
2647 /// E.g., `extern {}` or `extern "C" {}`.
2648 ForeignMod(ForeignMod),
2649 /// Module-level inline assembly (from `global_asm!()`).
2650 GlobalAsm(P<GlobalAsm>),
2651 /// A type alias (`type`).
2653 /// E.g., `type Foo = Bar<u8>;`.
2654 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2655 /// An enum definition (`enum`).
2657 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2658 Enum(EnumDef, Generics),
2659 /// A struct definition (`struct`).
2661 /// E.g., `struct Foo<A> { x: A }`.
2662 Struct(VariantData, Generics),
2663 /// A union definition (`union`).
2665 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2666 Union(VariantData, Generics),
2667 /// A trait declaration (`trait`).
2669 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2670 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2673 /// E.g., `trait Foo = Bar + Quux;`.
2674 TraitAlias(Generics, GenericBounds),
2675 /// An implementation.
2677 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2680 polarity: ImplPolarity,
2681 defaultness: Defaultness,
2685 /// The trait being implemented, if any.
2686 of_trait: Option<TraitRef>,
2689 items: Vec<P<AssocItem>>,
2691 /// A macro invocation.
2693 /// E.g., `foo!(..)`.
2696 /// A macro definition.
2701 pub fn article(&self) -> &str {
2704 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2705 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2706 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2710 pub fn descr(&self) -> &str {
2712 ItemKind::ExternCrate(..) => "extern crate",
2713 ItemKind::Use(..) => "`use` import",
2714 ItemKind::Static(..) => "static item",
2715 ItemKind::Const(..) => "constant item",
2716 ItemKind::Fn(..) => "function",
2717 ItemKind::Mod(..) => "module",
2718 ItemKind::ForeignMod(..) => "extern block",
2719 ItemKind::GlobalAsm(..) => "global asm item",
2720 ItemKind::TyAlias(..) => "type alias",
2721 ItemKind::Enum(..) => "enum",
2722 ItemKind::Struct(..) => "struct",
2723 ItemKind::Union(..) => "union",
2724 ItemKind::Trait(..) => "trait",
2725 ItemKind::TraitAlias(..) => "trait alias",
2726 ItemKind::MacCall(..) => "item macro invocation",
2727 ItemKind::MacroDef(..) => "macro definition",
2728 ItemKind::Impl { .. } => "implementation",
2732 pub fn generics(&self) -> Option<&Generics> {
2734 Self::Fn(_, _, generics, _)
2735 | Self::TyAlias(_, generics, ..)
2736 | Self::Enum(_, generics)
2737 | Self::Struct(_, generics)
2738 | Self::Union(_, generics)
2739 | Self::Trait(_, _, generics, ..)
2740 | Self::TraitAlias(generics, _)
2741 | Self::Impl { generics, .. } => Some(generics),
2747 /// Represents associated items.
2748 /// These include items in `impl` and `trait` definitions.
2749 pub type AssocItem = Item<AssocItemKind>;
2751 /// Represents associated item kinds.
2753 /// The term "provided" in the variants below refers to the item having a default
2754 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2755 /// In an implementation, all items must be provided.
2756 /// The `Option`s below denote the bodies, where `Some(_)`
2757 /// means "provided" and conversely `None` means "required".
2758 #[derive(Clone, Encodable, Decodable, Debug)]
2759 pub enum AssocItemKind {
2760 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2761 /// If `def` is parsed, then the constant is provided, and otherwise required.
2762 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2763 /// An associated function.
2764 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2765 /// An associated type.
2766 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2767 /// A macro expanding to associated items.
2771 impl AssocItemKind {
2772 pub fn defaultness(&self) -> Defaultness {
2774 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2775 Self::MacCall(..) => Defaultness::Final,
2780 impl From<AssocItemKind> for ItemKind {
2781 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2782 match assoc_item_kind {
2783 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2784 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2785 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2786 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2791 impl TryFrom<ItemKind> for AssocItemKind {
2792 type Error = ItemKind;
2794 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2795 Ok(match item_kind {
2796 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2797 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2798 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2799 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2800 _ => return Err(item_kind),
2805 /// An item in `extern` block.
2806 #[derive(Clone, Encodable, Decodable, Debug)]
2807 pub enum ForeignItemKind {
2808 /// A foreign static item (`static FOO: u8`).
2809 Static(P<Ty>, Mutability, Option<P<Expr>>),
2810 /// A foreign function.
2811 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2813 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2814 /// A macro expanding to foreign items.
2818 impl From<ForeignItemKind> for ItemKind {
2819 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2820 match foreign_item_kind {
2821 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2822 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2823 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2824 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2829 impl TryFrom<ItemKind> for ForeignItemKind {
2830 type Error = ItemKind;
2832 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2833 Ok(match item_kind {
2834 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2835 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2836 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2837 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2838 _ => return Err(item_kind),
2843 pub type ForeignItem = Item<ForeignItemKind>;