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,
543 pub tokens: Option<TokenStream>,
548 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
549 #[derive(Clone, Encodable, Decodable, Debug)]
554 pub tokens: Option<TokenStream>,
558 /// Attempt reparsing the pattern as a type.
559 /// This is intended for use by diagnostics.
560 pub fn to_ty(&self) -> Option<P<Ty>> {
561 let kind = match &self.kind {
562 // In a type expression `_` is an inference variable.
563 PatKind::Wild => TyKind::Infer,
564 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
565 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
566 TyKind::Path(None, Path::from_ident(*ident))
568 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
569 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
570 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
571 PatKind::Ref(pat, mutbl) => {
572 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
574 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
575 // when `P` can be reparsed as a type `T`.
576 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
577 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
578 // assuming `T0` to `Tn` are all syntactically valid as types.
579 PatKind::Tuple(pats) => {
580 let mut tys = Vec::with_capacity(pats.len());
581 // FIXME(#48994) - could just be collected into an Option<Vec>
583 tys.push(pat.to_ty()?);
590 Some(P(Ty { kind, id: self.id, span: self.span }))
593 /// Walk top-down and call `it` in each place where a pattern occurs
594 /// starting with the root pattern `walk` is called on. If `it` returns
595 /// false then we will descend no further but siblings will be processed.
596 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
602 // Walk into the pattern associated with `Ident` (if any).
603 PatKind::Ident(_, _, Some(p)) => p.walk(it),
605 // Walk into each field of struct.
606 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
608 // Sequence of patterns.
609 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
610 s.iter().for_each(|p| p.walk(it))
613 // Trivial wrappers over inner patterns.
614 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
616 // These patterns do not contain subpatterns, skip.
623 | PatKind::MacCall(_) => {}
627 /// Is this a `..` pattern?
628 pub fn is_rest(&self) -> bool {
630 PatKind::Rest => true,
636 /// A single field in a struct pattern
638 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
639 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
640 /// except is_shorthand is true
641 #[derive(Clone, Encodable, Decodable, Debug)]
642 pub struct FieldPat {
643 /// The identifier for the field
645 /// The pattern the field is destructured to
647 pub is_shorthand: bool,
651 pub is_placeholder: bool,
654 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
655 pub enum BindingMode {
660 #[derive(Clone, Encodable, Decodable, Debug)]
662 Included(RangeSyntax),
666 #[derive(Clone, Encodable, Decodable, Debug)]
667 pub enum RangeSyntax {
674 #[derive(Clone, Encodable, Decodable, Debug)]
676 /// Represents a wildcard pattern (`_`).
679 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
680 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
681 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
682 /// during name resolution.
683 Ident(BindingMode, Ident, Option<P<Pat>>),
685 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
686 /// The `bool` is `true` in the presence of a `..`.
687 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
689 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
690 TupleStruct(Path, Vec<P<Pat>>),
692 /// An or-pattern `A | B | C`.
693 /// Invariant: `pats.len() >= 2`.
696 /// A possibly qualified path pattern.
697 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
698 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
699 /// only legally refer to associated constants.
700 Path(Option<QSelf>, Path),
702 /// A tuple pattern (`(a, b)`).
708 /// A reference pattern (e.g., `&mut (a, b)`).
709 Ref(P<Pat>, Mutability),
714 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
715 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
717 /// A slice pattern `[a, b, c]`.
720 /// A rest pattern `..`.
722 /// Syntactically it is valid anywhere.
724 /// Semantically however, it only has meaning immediately inside:
725 /// - a slice pattern: `[a, .., b]`,
726 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
727 /// - a tuple pattern: `(a, .., b)`,
728 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
730 /// In all of these cases, an additional restriction applies,
731 /// only one rest pattern may occur in the pattern sequences.
734 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
737 /// A macro pattern; pre-expansion.
741 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
742 #[derive(HashStable_Generic, Encodable, Decodable)]
743 pub enum Mutability {
749 /// Returns `MutMutable` only if both `self` and `other` are mutable.
750 pub fn and(self, other: Self) -> Self {
752 Mutability::Mut => other,
753 Mutability::Not => Mutability::Not,
757 pub fn invert(self) -> Self {
759 Mutability::Mut => Mutability::Not,
760 Mutability::Not => Mutability::Mut,
764 pub fn prefix_str(&self) -> &'static str {
766 Mutability::Mut => "mut ",
767 Mutability::Not => "",
772 /// The kind of borrow in an `AddrOf` expression,
773 /// e.g., `&place` or `&raw const place`.
774 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
775 #[derive(Encodable, Decodable, HashStable_Generic)]
776 pub enum BorrowKind {
777 /// A normal borrow, `&$expr` or `&mut $expr`.
778 /// The resulting type is either `&'a T` or `&'a mut T`
779 /// where `T = typeof($expr)` and `'a` is some lifetime.
781 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
782 /// The resulting type is either `*const T` or `*mut T`
783 /// where `T = typeof($expr)`.
787 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
789 /// The `+` operator (addition)
791 /// The `-` operator (subtraction)
793 /// The `*` operator (multiplication)
795 /// The `/` operator (division)
797 /// The `%` operator (modulus)
799 /// The `&&` operator (logical and)
801 /// The `||` operator (logical or)
803 /// The `^` operator (bitwise xor)
805 /// The `&` operator (bitwise and)
807 /// The `|` operator (bitwise or)
809 /// The `<<` operator (shift left)
811 /// The `>>` operator (shift right)
813 /// The `==` operator (equality)
815 /// The `<` operator (less than)
817 /// The `<=` operator (less than or equal to)
819 /// The `!=` operator (not equal to)
821 /// The `>=` operator (greater than or equal to)
823 /// The `>` operator (greater than)
828 pub fn to_string(&self) -> &'static str {
851 pub fn lazy(&self) -> bool {
853 BinOpKind::And | BinOpKind::Or => true,
858 pub fn is_shift(&self) -> bool {
860 BinOpKind::Shl | BinOpKind::Shr => true,
865 pub fn is_comparison(&self) -> bool {
867 // Note for developers: please keep this as is;
868 // we want compilation to fail if another variant is added.
870 Eq | Lt | Le | Ne | Gt | Ge => true,
871 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
875 /// Returns `true` if the binary operator takes its arguments by value
876 pub fn is_by_value(&self) -> bool {
877 !self.is_comparison()
881 pub type BinOp = Spanned<BinOpKind>;
885 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
886 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
888 /// The `*` operator for dereferencing
890 /// The `!` operator for logical inversion
892 /// The `-` operator for negation
897 /// Returns `true` if the unary operator takes its argument by value
898 pub fn is_by_value(u: UnOp) -> bool {
900 UnOp::Neg | UnOp::Not => true,
905 pub fn to_string(op: UnOp) -> &'static str {
915 #[derive(Clone, Encodable, Decodable, Debug)]
923 pub fn add_trailing_semicolon(mut self) -> Self {
924 self.kind = match self.kind {
925 StmtKind::Expr(expr) => StmtKind::Semi(expr),
926 StmtKind::MacCall(mac) => {
927 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs }| MacCallStmt {
929 style: MacStmtStyle::Semicolon,
938 pub fn is_item(&self) -> bool {
940 StmtKind::Item(_) => true,
945 pub fn is_expr(&self) -> bool {
947 StmtKind::Expr(_) => true,
953 #[derive(Clone, Encodable, Decodable, Debug)]
955 /// A local (let) binding.
957 /// An item definition.
959 /// Expr without trailing semi-colon.
961 /// Expr with a trailing semi-colon.
963 /// Just a trailing semi-colon.
966 MacCall(P<MacCallStmt>),
969 #[derive(Clone, Encodable, Decodable, Debug)]
970 pub struct MacCallStmt {
972 pub style: MacStmtStyle,
976 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
977 pub enum MacStmtStyle {
978 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
979 /// `foo!(...);`, `foo![...];`).
981 /// The macro statement had braces (e.g., `foo! { ... }`).
983 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
984 /// `foo!(...)`). All of these will end up being converted into macro
989 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
990 #[derive(Clone, Encodable, Decodable, Debug)]
994 pub ty: Option<P<Ty>>,
995 /// Initializer expression to set the value, if any.
996 pub init: Option<P<Expr>>,
1001 /// An arm of a 'match'.
1003 /// E.g., `0..=10 => { println!("match!") }` as in
1007 /// 0..=10 => { println!("match!") },
1008 /// _ => { println!("no match!") },
1011 #[derive(Clone, Encodable, Decodable, Debug)]
1013 pub attrs: Vec<Attribute>,
1014 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1016 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1017 pub guard: Option<P<Expr>>,
1022 pub is_placeholder: bool,
1025 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1026 #[derive(Clone, Encodable, Decodable, Debug)]
1033 pub is_shorthand: bool,
1034 pub is_placeholder: bool,
1037 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1038 pub enum BlockCheckMode {
1040 Unsafe(UnsafeSource),
1043 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1044 pub enum UnsafeSource {
1049 /// A constant (expression) that's not an item or associated item,
1050 /// but needs its own `DefId` for type-checking, const-eval, etc.
1051 /// These are usually found nested inside types (e.g., array lengths)
1052 /// or expressions (e.g., repeat counts), and also used to define
1053 /// explicit discriminant values for enum variants.
1054 #[derive(Clone, Encodable, Decodable, Debug)]
1055 pub struct AnonConst {
1061 #[derive(Clone, Encodable, Decodable, Debug)]
1067 pub tokens: Option<TokenStream>,
1070 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1071 #[cfg(target_arch = "x86_64")]
1072 rustc_data_structures::static_assert_size!(Expr, 104);
1075 /// Returns `true` if this expression would be valid somewhere that expects a value;
1076 /// for example, an `if` condition.
1077 pub fn returns(&self) -> bool {
1078 if let ExprKind::Block(ref block, _) = self.kind {
1079 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1081 Some(&StmtKind::Expr(_)) => true,
1082 Some(&StmtKind::Semi(ref expr)) => {
1083 if let ExprKind::Ret(_) = expr.kind {
1084 // Last statement is explicit return.
1090 // This is a block that doesn't end in either an implicit or explicit return.
1094 // This is not a block, it is a value.
1099 /// Is this expr either `N`, or `{ N }`.
1101 /// If this is not the case, name resolution does not resolve `N` when using
1102 /// `feature(min_const_generics)` as more complex expressions are not supported.
1103 pub fn is_potential_trivial_const_param(&self) -> bool {
1104 let this = if let ExprKind::Block(ref block, None) = self.kind {
1105 if block.stmts.len() == 1 {
1106 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1114 if let ExprKind::Path(None, ref path) = this.kind {
1115 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1123 pub fn to_bound(&self) -> Option<GenericBound> {
1125 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1126 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1127 TraitBoundModifier::None,
1133 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1134 pub fn to_ty(&self) -> Option<P<Ty>> {
1135 let kind = match &self.kind {
1136 // Trivial conversions.
1137 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1138 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1140 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1142 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1143 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1146 ExprKind::Repeat(expr, expr_len) => {
1147 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1150 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1152 ExprKind::Tup(exprs) => {
1153 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1157 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1158 // then type of result is trait object.
1159 // Otherwise we don't assume the result type.
1160 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1161 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1162 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1168 // This expression doesn't look like a type syntactically.
1172 Some(P(Ty { kind, id: self.id, span: self.span }))
1175 pub fn precedence(&self) -> ExprPrecedence {
1177 ExprKind::Box(_) => ExprPrecedence::Box,
1178 ExprKind::Array(_) => ExprPrecedence::Array,
1179 ExprKind::Call(..) => ExprPrecedence::Call,
1180 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1181 ExprKind::Tup(_) => ExprPrecedence::Tup,
1182 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1183 ExprKind::Unary(..) => ExprPrecedence::Unary,
1184 ExprKind::Lit(_) => ExprPrecedence::Lit,
1185 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1186 ExprKind::Let(..) => ExprPrecedence::Let,
1187 ExprKind::If(..) => ExprPrecedence::If,
1188 ExprKind::While(..) => ExprPrecedence::While,
1189 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1190 ExprKind::Loop(..) => ExprPrecedence::Loop,
1191 ExprKind::Match(..) => ExprPrecedence::Match,
1192 ExprKind::Closure(..) => ExprPrecedence::Closure,
1193 ExprKind::Block(..) => ExprPrecedence::Block,
1194 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1195 ExprKind::Async(..) => ExprPrecedence::Async,
1196 ExprKind::Await(..) => ExprPrecedence::Await,
1197 ExprKind::Assign(..) => ExprPrecedence::Assign,
1198 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1199 ExprKind::Field(..) => ExprPrecedence::Field,
1200 ExprKind::Index(..) => ExprPrecedence::Index,
1201 ExprKind::Range(..) => ExprPrecedence::Range,
1202 ExprKind::Path(..) => ExprPrecedence::Path,
1203 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1204 ExprKind::Break(..) => ExprPrecedence::Break,
1205 ExprKind::Continue(..) => ExprPrecedence::Continue,
1206 ExprKind::Ret(..) => ExprPrecedence::Ret,
1207 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1208 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1209 ExprKind::Struct(..) => ExprPrecedence::Struct,
1210 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1211 ExprKind::Paren(..) => ExprPrecedence::Paren,
1212 ExprKind::Try(..) => ExprPrecedence::Try,
1213 ExprKind::Yield(..) => ExprPrecedence::Yield,
1214 ExprKind::Err => ExprPrecedence::Err,
1219 /// Limit types of a range (inclusive or exclusive)
1220 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1221 pub enum RangeLimits {
1222 /// Inclusive at the beginning, exclusive at the end
1224 /// Inclusive at the beginning and end
1228 #[derive(Clone, Encodable, Decodable, Debug)]
1230 /// A `box x` expression.
1232 /// An array (`[a, b, c, d]`)
1233 Array(Vec<P<Expr>>),
1236 /// The first field resolves to the function itself,
1237 /// and the second field is the list of arguments.
1238 /// This also represents calling the constructor of
1239 /// tuple-like ADTs such as tuple structs and enum variants.
1240 Call(P<Expr>, Vec<P<Expr>>),
1241 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1243 /// The `PathSegment` represents the method name and its generic arguments
1244 /// (within the angle brackets).
1245 /// The first element of the vector of an `Expr` is the expression that evaluates
1246 /// to the object on which the method is being called on (the receiver),
1247 /// and the remaining elements are the rest of the arguments.
1248 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1249 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1250 /// This `Span` is the span of the function, without the dot and receiver
1251 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1252 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1253 /// A tuple (e.g., `(a, b, c, d)`).
1255 /// A binary operation (e.g., `a + b`, `a * b`).
1256 Binary(BinOp, P<Expr>, P<Expr>),
1257 /// A unary operation (e.g., `!x`, `*x`).
1258 Unary(UnOp, P<Expr>),
1259 /// A literal (e.g., `1`, `"foo"`).
1261 /// A cast (e.g., `foo as f64`).
1262 Cast(P<Expr>, P<Ty>),
1263 /// A type ascription (e.g., `42: usize`).
1264 Type(P<Expr>, P<Ty>),
1265 /// A `let pat = expr` expression that is only semantically allowed in the condition
1266 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1267 Let(P<Pat>, P<Expr>),
1268 /// An `if` block, with an optional `else` block.
1270 /// `if expr { block } else { expr }`
1271 If(P<Expr>, P<Block>, Option<P<Expr>>),
1272 /// A while loop, with an optional label.
1274 /// `'label: while expr { block }`
1275 While(P<Expr>, P<Block>, Option<Label>),
1276 /// A `for` loop, with an optional label.
1278 /// `'label: for pat in expr { block }`
1280 /// This is desugared to a combination of `loop` and `match` expressions.
1281 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1282 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1284 /// `'label: loop { block }`
1285 Loop(P<Block>, Option<Label>),
1286 /// A `match` block.
1287 Match(P<Expr>, Vec<Arm>),
1288 /// A closure (e.g., `move |a, b, c| a + b + c`).
1290 /// The final span is the span of the argument block `|...|`.
1291 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1292 /// A block (`'label: { ... }`).
1293 Block(P<Block>, Option<Label>),
1294 /// An async block (`async move { ... }`).
1296 /// The `NodeId` is the `NodeId` for the closure that results from
1297 /// desugaring an async block, just like the NodeId field in the
1298 /// `Async::Yes` variant. This is necessary in order to create a def for the
1299 /// closure which can be used as a parent of any child defs. Defs
1300 /// created during lowering cannot be made the parent of any other
1301 /// preexisting defs.
1302 Async(CaptureBy, NodeId, P<Block>),
1303 /// An await expression (`my_future.await`).
1306 /// A try block (`try { ... }`).
1309 /// An assignment (`a = foo()`).
1310 /// The `Span` argument is the span of the `=` token.
1311 Assign(P<Expr>, P<Expr>, Span),
1312 /// An assignment with an operator.
1315 AssignOp(BinOp, P<Expr>, P<Expr>),
1316 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1317 Field(P<Expr>, Ident),
1318 /// An indexing operation (e.g., `foo[2]`).
1319 Index(P<Expr>, P<Expr>),
1320 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1321 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1323 /// Variable reference, possibly containing `::` and/or type
1324 /// parameters (e.g., `foo::bar::<baz>`).
1326 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1327 Path(Option<QSelf>, Path),
1329 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1330 AddrOf(BorrowKind, Mutability, P<Expr>),
1331 /// A `break`, with an optional label to break, and an optional expression.
1332 Break(Option<Label>, Option<P<Expr>>),
1333 /// A `continue`, with an optional label.
1334 Continue(Option<Label>),
1335 /// A `return`, with an optional value to be returned.
1336 Ret(Option<P<Expr>>),
1338 /// Output of the `asm!()` macro.
1339 InlineAsm(P<InlineAsm>),
1340 /// Output of the `llvm_asm!()` macro.
1341 LlvmInlineAsm(P<LlvmInlineAsm>),
1343 /// A macro invocation; pre-expansion.
1346 /// A struct literal expression.
1348 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1349 /// where `base` is the `Option<Expr>`.
1350 Struct(Path, Vec<Field>, Option<P<Expr>>),
1352 /// An array literal constructed from one repeated element.
1354 /// E.g., `[1; 5]`. The expression is the element to be
1355 /// repeated; the constant is the number of times to repeat it.
1356 Repeat(P<Expr>, AnonConst),
1358 /// No-op: used solely so we can pretty-print faithfully.
1361 /// A try expression (`expr?`).
1364 /// A `yield`, with an optional value to be yielded.
1365 Yield(Option<P<Expr>>),
1367 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1371 /// The explicit `Self` type in a "qualified path". The actual
1372 /// path, including the trait and the associated item, is stored
1373 /// separately. `position` represents the index of the associated
1374 /// item qualified with this `Self` type.
1376 /// ```ignore (only-for-syntax-highlight)
1377 /// <Vec<T> as a::b::Trait>::AssociatedItem
1378 /// ^~~~~ ~~~~~~~~~~~~~~^
1381 /// <Vec<T>>::AssociatedItem
1385 #[derive(Clone, Encodable, Decodable, Debug)]
1389 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1390 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1391 /// 0`, this is an empty span.
1392 pub path_span: Span,
1393 pub position: usize,
1396 /// A capture clause used in closures and `async` blocks.
1397 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1398 pub enum CaptureBy {
1399 /// `move |x| y + x`.
1401 /// `move` keyword was not specified.
1405 /// The movability of a generator / closure literal:
1406 /// whether a generator contains self-references, causing it to be `!Unpin`.
1407 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1408 #[derive(HashStable_Generic)]
1409 pub enum Movability {
1410 /// May contain self-references, `!Unpin`.
1412 /// Must not contain self-references, `Unpin`.
1416 /// Represents a macro invocation. The `path` indicates which macro
1417 /// is being invoked, and the `args` are arguments passed to it.
1418 #[derive(Clone, Encodable, Decodable, Debug)]
1419 pub struct MacCall {
1421 pub args: P<MacArgs>,
1422 pub prior_type_ascription: Option<(Span, bool)>,
1426 pub fn span(&self) -> Span {
1427 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1431 /// Arguments passed to an attribute or a function-like macro.
1432 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1434 /// No arguments - `#[attr]`.
1436 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1437 Delimited(DelimSpan, MacDelimiter, TokenStream),
1438 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1440 /// Span of the `=` token.
1442 /// Token stream of the "value".
1448 pub fn delim(&self) -> DelimToken {
1450 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1451 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1455 pub fn span(&self) -> Option<Span> {
1457 MacArgs::Empty => None,
1458 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1459 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1463 /// Tokens inside the delimiters or after `=`.
1464 /// Proc macros see these tokens, for example.
1465 pub fn inner_tokens(&self) -> TokenStream {
1467 MacArgs::Empty => TokenStream::default(),
1468 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1472 /// Tokens together with the delimiters or `=`.
1473 /// Use of this method generally means that something suboptimal or hacky is happening.
1474 pub fn outer_tokens(&self) -> TokenStream {
1476 MacArgs::Empty => TokenStream::default(),
1477 MacArgs::Delimited(dspan, delim, ref tokens) => {
1478 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1480 MacArgs::Eq(eq_span, ref tokens) => {
1481 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1486 /// Whether a macro with these arguments needs a semicolon
1487 /// when used as a standalone item or statement.
1488 pub fn need_semicolon(&self) -> bool {
1489 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1493 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1494 pub enum MacDelimiter {
1501 pub fn to_token(self) -> DelimToken {
1503 MacDelimiter::Parenthesis => DelimToken::Paren,
1504 MacDelimiter::Bracket => DelimToken::Bracket,
1505 MacDelimiter::Brace => DelimToken::Brace,
1509 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1511 token::Paren => Some(MacDelimiter::Parenthesis),
1512 token::Bracket => Some(MacDelimiter::Bracket),
1513 token::Brace => Some(MacDelimiter::Brace),
1514 token::NoDelim => None,
1519 /// Represents a macro definition.
1520 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1521 pub struct MacroDef {
1522 pub body: P<MacArgs>,
1523 /// `true` if macro was defined with `macro_rules`.
1524 pub macro_rules: bool,
1527 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1528 #[derive(HashStable_Generic)]
1530 /// A regular string, like `"foo"`.
1532 /// A raw string, like `r##"foo"##`.
1534 /// The value is the number of `#` symbols used.
1539 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1541 /// The original literal token as written in source code.
1542 pub token: token::Lit,
1543 /// The "semantic" representation of the literal lowered from the original tokens.
1544 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1545 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1550 /// Same as `Lit`, but restricted to string literals.
1551 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1553 /// The original literal token as written in source code.
1554 pub style: StrStyle,
1556 pub suffix: Option<Symbol>,
1558 /// The unescaped "semantic" representation of the literal lowered from the original token.
1559 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1560 pub symbol_unescaped: Symbol,
1564 pub fn as_lit(&self) -> Lit {
1565 let token_kind = match self.style {
1566 StrStyle::Cooked => token::Str,
1567 StrStyle::Raw(n) => token::StrRaw(n),
1570 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1572 kind: LitKind::Str(self.symbol_unescaped, self.style),
1577 /// Type of the integer literal based on provided suffix.
1578 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1579 #[derive(HashStable_Generic)]
1580 pub enum LitIntType {
1589 /// Type of the float literal based on provided suffix.
1590 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1591 #[derive(HashStable_Generic)]
1592 pub enum LitFloatType {
1593 /// A float literal with a suffix (`1f32` or `1E10f32`).
1595 /// A float literal without a suffix (`1.0 or 1.0E10`).
1601 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1602 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1604 /// A string literal (`"foo"`).
1605 Str(Symbol, StrStyle),
1606 /// A byte string (`b"foo"`).
1607 ByteStr(Lrc<Vec<u8>>),
1608 /// A byte char (`b'f'`).
1610 /// A character literal (`'a'`).
1612 /// An integer literal (`1`).
1613 Int(u128, LitIntType),
1614 /// A float literal (`1f64` or `1E10f64`).
1615 Float(Symbol, LitFloatType),
1616 /// A boolean literal.
1618 /// Placeholder for a literal that wasn't well-formed in some way.
1623 /// Returns `true` if this literal is a string.
1624 pub fn is_str(&self) -> bool {
1626 LitKind::Str(..) => true,
1631 /// Returns `true` if this literal is byte literal string.
1632 pub fn is_bytestr(&self) -> bool {
1634 LitKind::ByteStr(_) => true,
1639 /// Returns `true` if this is a numeric literal.
1640 pub fn is_numeric(&self) -> bool {
1642 LitKind::Int(..) | LitKind::Float(..) => true,
1647 /// Returns `true` if this literal has no suffix.
1648 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1649 pub fn is_unsuffixed(&self) -> bool {
1653 /// Returns `true` if this literal has a suffix.
1654 pub fn is_suffixed(&self) -> bool {
1656 // suffixed variants
1657 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1658 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1659 // unsuffixed variants
1661 | LitKind::ByteStr(..)
1664 | LitKind::Int(_, LitIntType::Unsuffixed)
1665 | LitKind::Float(_, LitFloatType::Unsuffixed)
1667 | LitKind::Err(..) => false,
1672 // N.B., If you change this, you'll probably want to change the corresponding
1673 // type structure in `middle/ty.rs` as well.
1674 #[derive(Clone, Encodable, Decodable, Debug)]
1677 pub mutbl: Mutability,
1680 /// Represents a function's signature in a trait declaration,
1681 /// trait implementation, or free function.
1682 #[derive(Clone, Encodable, Decodable, Debug)]
1684 pub header: FnHeader,
1685 pub decl: P<FnDecl>,
1689 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1690 #[derive(Encodable, Decodable, HashStable_Generic)]
1697 pub fn name_str(self) -> &'static str {
1699 FloatTy::F32 => "f32",
1700 FloatTy::F64 => "f64",
1704 pub fn name(self) -> Symbol {
1706 FloatTy::F32 => sym::f32,
1707 FloatTy::F64 => sym::f64,
1711 pub fn bit_width(self) -> u64 {
1719 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1720 #[derive(Encodable, Decodable, HashStable_Generic)]
1731 pub fn name_str(&self) -> &'static str {
1733 IntTy::Isize => "isize",
1735 IntTy::I16 => "i16",
1736 IntTy::I32 => "i32",
1737 IntTy::I64 => "i64",
1738 IntTy::I128 => "i128",
1742 pub fn name(&self) -> Symbol {
1744 IntTy::Isize => sym::isize,
1745 IntTy::I8 => sym::i8,
1746 IntTy::I16 => sym::i16,
1747 IntTy::I32 => sym::i32,
1748 IntTy::I64 => sym::i64,
1749 IntTy::I128 => sym::i128,
1753 pub fn val_to_string(&self, val: i128) -> String {
1754 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1755 // are parsed as `u128`, so we wouldn't want to print an extra negative
1757 format!("{}{}", val as u128, self.name_str())
1760 pub fn bit_width(&self) -> Option<u64> {
1762 IntTy::Isize => return None,
1771 pub fn normalize(&self, target_width: u32) -> Self {
1773 IntTy::Isize => match target_width {
1777 _ => unreachable!(),
1784 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1785 #[derive(Encodable, Decodable, HashStable_Generic)]
1796 pub fn name_str(&self) -> &'static str {
1798 UintTy::Usize => "usize",
1800 UintTy::U16 => "u16",
1801 UintTy::U32 => "u32",
1802 UintTy::U64 => "u64",
1803 UintTy::U128 => "u128",
1807 pub fn name(&self) -> Symbol {
1809 UintTy::Usize => sym::usize,
1810 UintTy::U8 => sym::u8,
1811 UintTy::U16 => sym::u16,
1812 UintTy::U32 => sym::u32,
1813 UintTy::U64 => sym::u64,
1814 UintTy::U128 => sym::u128,
1818 pub fn val_to_string(&self, val: u128) -> String {
1819 format!("{}{}", val, self.name_str())
1822 pub fn bit_width(&self) -> Option<u64> {
1824 UintTy::Usize => return None,
1829 UintTy::U128 => 128,
1833 pub fn normalize(&self, target_width: u32) -> Self {
1835 UintTy::Usize => match target_width {
1839 _ => unreachable!(),
1846 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1847 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1848 #[derive(Clone, Encodable, Decodable, Debug)]
1849 pub struct AssocTyConstraint {
1852 pub kind: AssocTyConstraintKind,
1856 /// The kinds of an `AssocTyConstraint`.
1857 #[derive(Clone, Encodable, Decodable, Debug)]
1858 pub enum AssocTyConstraintKind {
1859 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1860 Equality { ty: P<Ty> },
1861 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1862 Bound { bounds: GenericBounds },
1865 #[derive(Clone, Encodable, Decodable, Debug)]
1872 #[derive(Clone, Encodable, Decodable, Debug)]
1873 pub struct BareFnTy {
1874 pub unsafety: Unsafe,
1876 pub generic_params: Vec<GenericParam>,
1877 pub decl: P<FnDecl>,
1880 /// The various kinds of type recognized by the compiler.
1881 #[derive(Clone, Encodable, Decodable, Debug)]
1883 /// A variable-length slice (`[T]`).
1885 /// A fixed length array (`[T; n]`).
1886 Array(P<Ty>, AnonConst),
1887 /// A raw pointer (`*const T` or `*mut T`).
1889 /// A reference (`&'a T` or `&'a mut T`).
1890 Rptr(Option<Lifetime>, MutTy),
1891 /// A bare function (e.g., `fn(usize) -> bool`).
1892 BareFn(P<BareFnTy>),
1893 /// The never type (`!`).
1895 /// A tuple (`(A, B, C, D,...)`).
1897 /// A path (`module::module::...::Type`), optionally
1898 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1900 /// Type parameters are stored in the `Path` itself.
1901 Path(Option<QSelf>, Path),
1902 /// A trait object type `Bound1 + Bound2 + Bound3`
1903 /// where `Bound` is a trait or a lifetime.
1904 TraitObject(GenericBounds, TraitObjectSyntax),
1905 /// An `impl Bound1 + Bound2 + Bound3` type
1906 /// where `Bound` is a trait or a lifetime.
1908 /// The `NodeId` exists to prevent lowering from having to
1909 /// generate `NodeId`s on the fly, which would complicate
1910 /// the generation of opaque `type Foo = impl Trait` items significantly.
1911 ImplTrait(NodeId, GenericBounds),
1912 /// No-op; kept solely so that we can pretty-print faithfully.
1916 /// This means the type should be inferred instead of it having been
1917 /// specified. This can appear anywhere in a type.
1919 /// Inferred type of a `self` or `&self` argument in a method.
1921 /// A macro in the type position.
1923 /// Placeholder for a kind that has failed to be defined.
1925 /// Placeholder for a `va_list`.
1930 pub fn is_implicit_self(&self) -> bool {
1931 if let TyKind::ImplicitSelf = *self { true } else { false }
1934 pub fn is_unit(&self) -> bool {
1935 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1939 /// Syntax used to declare a trait object.
1940 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1941 pub enum TraitObjectSyntax {
1946 /// Inline assembly operand explicit register or register class.
1948 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1949 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1950 pub enum InlineAsmRegOrRegClass {
1955 bitflags::bitflags! {
1956 #[derive(Encodable, Decodable, HashStable_Generic)]
1957 pub struct InlineAsmOptions: u8 {
1958 const PURE = 1 << 0;
1959 const NOMEM = 1 << 1;
1960 const READONLY = 1 << 2;
1961 const PRESERVES_FLAGS = 1 << 3;
1962 const NORETURN = 1 << 4;
1963 const NOSTACK = 1 << 5;
1964 const ATT_SYNTAX = 1 << 6;
1968 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1969 pub enum InlineAsmTemplatePiece {
1971 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1974 impl fmt::Display for InlineAsmTemplatePiece {
1975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1977 Self::String(s) => {
1978 for c in s.chars() {
1980 '{' => f.write_str("{{")?,
1981 '}' => f.write_str("}}")?,
1987 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1988 write!(f, "{{{}:{}}}", operand_idx, modifier)
1990 Self::Placeholder { operand_idx, modifier: None, .. } => {
1991 write!(f, "{{{}}}", operand_idx)
1997 impl InlineAsmTemplatePiece {
1998 /// Rebuilds the asm template string from its pieces.
1999 pub fn to_string(s: &[Self]) -> String {
2001 let mut out = String::new();
2003 let _ = write!(out, "{}", p);
2009 /// Inline assembly operand.
2011 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2012 #[derive(Clone, Encodable, Decodable, Debug)]
2013 pub enum InlineAsmOperand {
2015 reg: InlineAsmRegOrRegClass,
2019 reg: InlineAsmRegOrRegClass,
2021 expr: Option<P<Expr>>,
2024 reg: InlineAsmRegOrRegClass,
2029 reg: InlineAsmRegOrRegClass,
2032 out_expr: Option<P<Expr>>,
2042 /// Inline assembly.
2044 /// E.g., `asm!("NOP");`.
2045 #[derive(Clone, Encodable, Decodable, Debug)]
2046 pub struct InlineAsm {
2047 pub template: Vec<InlineAsmTemplatePiece>,
2048 pub operands: Vec<(InlineAsmOperand, Span)>,
2049 pub options: InlineAsmOptions,
2050 pub line_spans: Vec<Span>,
2053 /// Inline assembly dialect.
2055 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2056 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2057 pub enum LlvmAsmDialect {
2062 /// LLVM-style inline assembly.
2064 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2065 #[derive(Clone, Encodable, Decodable, Debug)]
2066 pub struct LlvmInlineAsmOutput {
2067 pub constraint: Symbol,
2070 pub is_indirect: bool,
2073 /// LLVM-style inline assembly.
2075 /// E.g., `llvm_asm!("NOP");`.
2076 #[derive(Clone, Encodable, Decodable, Debug)]
2077 pub struct LlvmInlineAsm {
2079 pub asm_str_style: StrStyle,
2080 pub outputs: Vec<LlvmInlineAsmOutput>,
2081 pub inputs: Vec<(Symbol, P<Expr>)>,
2082 pub clobbers: Vec<Symbol>,
2084 pub alignstack: bool,
2085 pub dialect: LlvmAsmDialect,
2088 /// A parameter in a function header.
2090 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2091 #[derive(Clone, Encodable, Decodable, Debug)]
2098 pub is_placeholder: bool,
2101 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2103 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2104 #[derive(Clone, Encodable, Decodable, Debug)]
2106 /// `self`, `mut self`
2108 /// `&'lt self`, `&'lt mut self`
2109 Region(Option<Lifetime>, Mutability),
2110 /// `self: TYPE`, `mut self: TYPE`
2111 Explicit(P<Ty>, Mutability),
2114 pub type ExplicitSelf = Spanned<SelfKind>;
2117 /// Attempts to cast parameter to `ExplicitSelf`.
2118 pub fn to_self(&self) -> Option<ExplicitSelf> {
2119 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2120 if ident.name == kw::SelfLower {
2121 return match self.ty.kind {
2122 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2123 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2124 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2127 self.pat.span.to(self.ty.span),
2128 SelfKind::Explicit(self.ty.clone(), mutbl),
2136 /// Returns `true` if parameter is `self`.
2137 pub fn is_self(&self) -> bool {
2138 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2139 ident.name == kw::SelfLower
2145 /// Builds a `Param` object from `ExplicitSelf`.
2146 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2147 let span = eself.span.to(eself_ident.span);
2148 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2149 let param = |mutbl, ty| Param {
2153 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2160 is_placeholder: false,
2163 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2164 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2165 SelfKind::Region(lt, mutbl) => param(
2169 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2177 /// A signature (not the body) of a function declaration.
2179 /// E.g., `fn foo(bar: baz)`.
2181 /// Please note that it's different from `FnHeader` structure
2182 /// which contains metadata about function safety, asyncness, constness and ABI.
2183 #[derive(Clone, Encodable, Decodable, Debug)]
2185 pub inputs: Vec<Param>,
2186 pub output: FnRetTy,
2190 pub fn get_self(&self) -> Option<ExplicitSelf> {
2191 self.inputs.get(0).and_then(Param::to_self)
2193 pub fn has_self(&self) -> bool {
2194 self.inputs.get(0).map_or(false, Param::is_self)
2196 pub fn c_variadic(&self) -> bool {
2197 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2198 TyKind::CVarArgs => true,
2204 /// Is the trait definition an auto trait?
2205 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2211 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2212 #[derive(HashStable_Generic)]
2218 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2220 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2225 pub fn is_async(self) -> bool {
2226 if let Async::Yes { .. } = self { true } else { false }
2229 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2230 pub fn opt_return_id(self) -> Option<NodeId> {
2232 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2238 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2239 #[derive(HashStable_Generic)]
2245 /// Item defaultness.
2246 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2247 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2248 pub enum Defaultness {
2253 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2254 pub enum ImplPolarity {
2255 /// `impl Trait for Type`
2257 /// `impl !Trait for Type`
2261 impl fmt::Debug for ImplPolarity {
2262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2264 ImplPolarity::Positive => "positive".fmt(f),
2265 ImplPolarity::Negative(_) => "negative".fmt(f),
2270 #[derive(Clone, Encodable, Decodable, Debug)]
2272 /// Returns type is not specified.
2274 /// Functions default to `()` and closures default to inference.
2275 /// Span points to where return type would be inserted.
2277 /// Everything else.
2282 pub fn span(&self) -> Span {
2284 FnRetTy::Default(span) => span,
2285 FnRetTy::Ty(ref ty) => ty.span,
2290 /// Module declaration.
2292 /// E.g., `mod foo;` or `mod foo { .. }`.
2293 #[derive(Clone, Encodable, Decodable, Debug)]
2295 /// A span from the first token past `{` to the last token until `}`.
2296 /// For `mod foo;`, the inner span ranges from the first token
2297 /// to the last token in the external file.
2299 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2300 /// semantically by Rust.
2301 pub unsafety: Unsafe,
2302 pub items: Vec<P<Item>>,
2303 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2307 /// Foreign module declaration.
2309 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2310 #[derive(Clone, Encodable, Decodable, Debug)]
2311 pub struct ForeignMod {
2312 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2313 /// semantically by Rust.
2314 pub unsafety: Unsafe,
2315 pub abi: Option<StrLit>,
2316 pub items: Vec<P<ForeignItem>>,
2319 /// Global inline assembly.
2321 /// Also known as "module-level assembly" or "file-scoped assembly".
2322 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2323 pub struct GlobalAsm {
2327 #[derive(Clone, Encodable, Decodable, Debug)]
2328 pub struct EnumDef {
2329 pub variants: Vec<Variant>,
2332 #[derive(Clone, Encodable, Decodable, Debug)]
2333 pub struct Variant {
2334 /// Attributes of the variant.
2335 pub attrs: Vec<Attribute>,
2336 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2340 /// The visibility of the variant. Syntactically accepted but not semantically.
2341 pub vis: Visibility,
2342 /// Name of the variant.
2345 /// Fields and constructor id of the variant.
2346 pub data: VariantData,
2347 /// Explicit discriminant, e.g., `Foo = 1`.
2348 pub disr_expr: Option<AnonConst>,
2349 /// Is a macro placeholder
2350 pub is_placeholder: bool,
2353 /// Part of `use` item to the right of its prefix.
2354 #[derive(Clone, Encodable, Decodable, Debug)]
2355 pub enum UseTreeKind {
2356 /// `use prefix` or `use prefix as rename`
2358 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2360 Simple(Option<Ident>, NodeId, NodeId),
2361 /// `use prefix::{...}`
2362 Nested(Vec<(UseTree, NodeId)>),
2367 /// A tree of paths sharing common prefixes.
2368 /// Used in `use` items both at top-level and inside of braces in import groups.
2369 #[derive(Clone, Encodable, Decodable, Debug)]
2370 pub struct UseTree {
2372 pub kind: UseTreeKind,
2377 pub fn ident(&self) -> Ident {
2379 UseTreeKind::Simple(Some(rename), ..) => rename,
2380 UseTreeKind::Simple(None, ..) => {
2381 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2383 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2388 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2389 /// are contained as statements within items. These two cases need to be
2390 /// distinguished for pretty-printing.
2391 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2392 pub enum AttrStyle {
2397 rustc_index::newtype_index! {
2400 DEBUG_FORMAT = "AttrId({})"
2404 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2405 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2410 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2411 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2412 d.read_nil().map(|_| crate::attr::mk_attr_id())
2416 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2417 pub struct AttrItem {
2422 /// A list of attributes.
2423 pub type AttrVec = ThinVec<Attribute>;
2425 /// Metadata associated with an item.
2426 #[derive(Clone, Encodable, Decodable, Debug)]
2427 pub struct Attribute {
2430 /// Denotes if the attribute decorates the following construct (outer)
2431 /// or the construct this attribute is contained within (inner).
2432 pub style: AttrStyle,
2436 #[derive(Clone, Encodable, Decodable, Debug)]
2438 /// A normal attribute.
2441 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2442 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2443 /// variant (which is much less compact and thus more expensive).
2444 DocComment(CommentKind, Symbol),
2447 /// `TraitRef`s appear in impls.
2449 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2450 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2451 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2452 /// same as the impl's `NodeId`).
2453 #[derive(Clone, Encodable, Decodable, Debug)]
2454 pub struct TraitRef {
2459 #[derive(Clone, Encodable, Decodable, Debug)]
2460 pub struct PolyTraitRef {
2461 /// The `'a` in `<'a> Foo<&'a T>`.
2462 pub bound_generic_params: Vec<GenericParam>,
2464 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2465 pub trait_ref: TraitRef,
2471 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2473 bound_generic_params: generic_params,
2474 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2480 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2481 pub enum CrateSugar {
2482 /// Source is `pub(crate)`.
2485 /// Source is (just) `crate`.
2489 pub type Visibility = Spanned<VisibilityKind>;
2491 #[derive(Clone, Encodable, Decodable, Debug)]
2492 pub enum VisibilityKind {
2495 Restricted { path: P<Path>, id: NodeId },
2499 impl VisibilityKind {
2500 pub fn is_pub(&self) -> bool {
2501 if let VisibilityKind::Public = *self { true } else { false }
2505 /// Field of a struct.
2507 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2508 #[derive(Clone, Encodable, Decodable, Debug)]
2509 pub struct StructField {
2510 pub attrs: Vec<Attribute>,
2513 pub vis: Visibility,
2514 pub ident: Option<Ident>,
2517 pub is_placeholder: bool,
2520 /// Fields and constructor ids of enum variants and structs.
2521 #[derive(Clone, Encodable, Decodable, Debug)]
2522 pub enum VariantData {
2525 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2526 Struct(Vec<StructField>, bool),
2529 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2530 Tuple(Vec<StructField>, NodeId),
2533 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2538 /// Return the fields of this variant.
2539 pub fn fields(&self) -> &[StructField] {
2541 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2546 /// Return the `NodeId` of this variant's constructor, if it has one.
2547 pub fn ctor_id(&self) -> Option<NodeId> {
2549 VariantData::Struct(..) => None,
2550 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2555 /// An item definition.
2556 #[derive(Clone, Encodable, Decodable, Debug)]
2557 pub struct Item<K = ItemKind> {
2558 pub attrs: Vec<Attribute>,
2561 pub vis: Visibility,
2562 /// The name of the item.
2563 /// It might be a dummy name in case of anonymous items.
2568 /// Original tokens this item was parsed from. This isn't necessarily
2569 /// available for all items, although over time more and more items should
2570 /// have this be `Some`. Right now this is primarily used for procedural
2571 /// macros, notably custom attributes.
2573 /// Note that the tokens here do not include the outer attributes, but will
2574 /// include inner attributes.
2575 pub tokens: Option<TokenStream>,
2579 /// Return the span that encompasses the attributes.
2580 pub fn span_with_attributes(&self) -> Span {
2581 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2585 impl<K: Into<ItemKind>> Item<K> {
2586 pub fn into_item(self) -> Item {
2587 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2588 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2592 /// `extern` qualifier on a function item or function type.
2593 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2601 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2602 abi.map_or(Extern::Implicit, Extern::Explicit)
2606 /// A function header.
2608 /// All the information between the visibility and the name of the function is
2609 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2610 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2611 pub struct FnHeader {
2612 pub unsafety: Unsafe,
2613 pub asyncness: Async,
2614 pub constness: Const,
2619 /// Does this function header have any qualifiers or is it empty?
2620 pub fn has_qualifiers(&self) -> bool {
2621 let Self { unsafety, asyncness, constness, ext } = self;
2622 matches!(unsafety, Unsafe::Yes(_))
2623 || asyncness.is_async()
2624 || matches!(constness, Const::Yes(_))
2625 || !matches!(ext, Extern::None)
2629 impl Default for FnHeader {
2630 fn default() -> FnHeader {
2632 unsafety: Unsafe::No,
2633 asyncness: Async::No,
2634 constness: Const::No,
2640 #[derive(Clone, Encodable, Decodable, Debug)]
2642 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2644 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2645 ExternCrate(Option<Symbol>),
2646 /// A use declaration item (`use`).
2648 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2650 /// A static item (`static`).
2652 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2653 Static(P<Ty>, Mutability, Option<P<Expr>>),
2654 /// A constant item (`const`).
2656 /// E.g., `const FOO: i32 = 42;`.
2657 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2658 /// A function declaration (`fn`).
2660 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2661 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2662 /// A module declaration (`mod`).
2664 /// E.g., `mod foo;` or `mod foo { .. }`.
2666 /// An external module (`extern`).
2668 /// E.g., `extern {}` or `extern "C" {}`.
2669 ForeignMod(ForeignMod),
2670 /// Module-level inline assembly (from `global_asm!()`).
2671 GlobalAsm(P<GlobalAsm>),
2672 /// A type alias (`type`).
2674 /// E.g., `type Foo = Bar<u8>;`.
2675 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2676 /// An enum definition (`enum`).
2678 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2679 Enum(EnumDef, Generics),
2680 /// A struct definition (`struct`).
2682 /// E.g., `struct Foo<A> { x: A }`.
2683 Struct(VariantData, Generics),
2684 /// A union definition (`union`).
2686 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2687 Union(VariantData, Generics),
2688 /// A trait declaration (`trait`).
2690 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2691 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2694 /// E.g., `trait Foo = Bar + Quux;`.
2695 TraitAlias(Generics, GenericBounds),
2696 /// An implementation.
2698 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2701 polarity: ImplPolarity,
2702 defaultness: Defaultness,
2706 /// The trait being implemented, if any.
2707 of_trait: Option<TraitRef>,
2710 items: Vec<P<AssocItem>>,
2712 /// A macro invocation.
2714 /// E.g., `foo!(..)`.
2717 /// A macro definition.
2722 pub fn article(&self) -> &str {
2725 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2726 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2727 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2731 pub fn descr(&self) -> &str {
2733 ItemKind::ExternCrate(..) => "extern crate",
2734 ItemKind::Use(..) => "`use` import",
2735 ItemKind::Static(..) => "static item",
2736 ItemKind::Const(..) => "constant item",
2737 ItemKind::Fn(..) => "function",
2738 ItemKind::Mod(..) => "module",
2739 ItemKind::ForeignMod(..) => "extern block",
2740 ItemKind::GlobalAsm(..) => "global asm item",
2741 ItemKind::TyAlias(..) => "type alias",
2742 ItemKind::Enum(..) => "enum",
2743 ItemKind::Struct(..) => "struct",
2744 ItemKind::Union(..) => "union",
2745 ItemKind::Trait(..) => "trait",
2746 ItemKind::TraitAlias(..) => "trait alias",
2747 ItemKind::MacCall(..) => "item macro invocation",
2748 ItemKind::MacroDef(..) => "macro definition",
2749 ItemKind::Impl { .. } => "implementation",
2753 pub fn generics(&self) -> Option<&Generics> {
2755 Self::Fn(_, _, generics, _)
2756 | Self::TyAlias(_, generics, ..)
2757 | Self::Enum(_, generics)
2758 | Self::Struct(_, generics)
2759 | Self::Union(_, generics)
2760 | Self::Trait(_, _, generics, ..)
2761 | Self::TraitAlias(generics, _)
2762 | Self::Impl { generics, .. } => Some(generics),
2768 /// Represents associated items.
2769 /// These include items in `impl` and `trait` definitions.
2770 pub type AssocItem = Item<AssocItemKind>;
2772 /// Represents associated item kinds.
2774 /// The term "provided" in the variants below refers to the item having a default
2775 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2776 /// In an implementation, all items must be provided.
2777 /// The `Option`s below denote the bodies, where `Some(_)`
2778 /// means "provided" and conversely `None` means "required".
2779 #[derive(Clone, Encodable, Decodable, Debug)]
2780 pub enum AssocItemKind {
2781 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2782 /// If `def` is parsed, then the constant is provided, and otherwise required.
2783 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2784 /// An associated function.
2785 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2786 /// An associated type.
2787 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2788 /// A macro expanding to associated items.
2792 impl AssocItemKind {
2793 pub fn defaultness(&self) -> Defaultness {
2795 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2796 Self::MacCall(..) => Defaultness::Final,
2801 impl From<AssocItemKind> for ItemKind {
2802 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2803 match assoc_item_kind {
2804 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2805 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2806 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2807 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2812 impl TryFrom<ItemKind> for AssocItemKind {
2813 type Error = ItemKind;
2815 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2816 Ok(match item_kind {
2817 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2818 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2819 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2820 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2821 _ => return Err(item_kind),
2826 /// An item in `extern` block.
2827 #[derive(Clone, Encodable, Decodable, Debug)]
2828 pub enum ForeignItemKind {
2829 /// A foreign static item (`static FOO: u8`).
2830 Static(P<Ty>, Mutability, Option<P<Expr>>),
2831 /// A foreign function.
2832 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2834 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2835 /// A macro expanding to foreign items.
2839 impl From<ForeignItemKind> for ItemKind {
2840 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2841 match foreign_item_kind {
2842 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2843 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2844 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2845 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2850 impl TryFrom<ItemKind> for ForeignItemKind {
2851 type Error = ItemKind;
2853 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2854 Ok(match item_kind {
2855 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2856 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2857 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2858 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2859 _ => return Err(item_kind),
2864 pub type ForeignItem = Item<ForeignItemKind>;