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, Token};
27 use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree};
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable_Generic;
34 use rustc_serialize::{self, Decoder, Encoder};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
39 use std::cmp::Ordering;
40 use std::convert::TryFrom;
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
55 /// `'outer` is a label.
56 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
61 impl fmt::Debug for Label {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "label({:?})", self.ident)
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, Encodable, Decodable, Copy)]
75 impl fmt::Debug for Lifetime {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "lifetime({}: {})", self.id, self)
81 impl fmt::Display for Lifetime {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "{}", self.ident.name)
87 /// A "Path" is essentially Rust's notion of a name.
89 /// It's represented as a sequence of identifiers,
90 /// along with a bunch of supporting information.
92 /// E.g., `std::cmp::PartialEq`.
93 #[derive(Clone, Encodable, Decodable, Debug)]
96 /// The segments in the path: the things separated by `::`.
97 /// Global paths begin with `kw::PathRoot`.
98 pub segments: Vec<PathSegment>,
99 pub tokens: Option<LazyTokenStream>,
102 impl PartialEq<Symbol> for Path {
104 fn eq(&self, symbol: &Symbol) -> bool {
105 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
109 impl<CTX> HashStable<CTX> for Path {
110 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
111 self.segments.len().hash_stable(hcx, hasher);
112 for segment in &self.segments {
113 segment.ident.name.hash_stable(hcx, hasher);
119 // Convert a span and an identifier to the corresponding
121 pub fn from_ident(ident: Ident) -> Path {
122 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
125 pub fn is_global(&self) -> bool {
126 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
130 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
132 /// E.g., `std`, `String` or `Box<T>`.
133 #[derive(Clone, Encodable, Decodable, Debug)]
134 pub struct PathSegment {
135 /// The identifier portion of this path segment.
140 /// Type/lifetime parameters attached to this path. They come in
141 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
142 /// `None` means that no parameter list is supplied (`Path`),
143 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
144 /// but it can be empty (`Path<>`).
145 /// `P` is used as a size optimization for the common case with no parameters.
146 pub args: Option<P<GenericArgs>>,
150 pub fn from_ident(ident: Ident) -> Self {
151 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
154 pub fn path_root(span: Span) -> Self {
155 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
158 pub fn span(&self) -> Span {
160 Some(args) => self.ident.span.to(args.span()),
161 None => self.ident.span,
166 /// The arguments of a path segment.
168 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
169 #[derive(Clone, Encodable, Decodable, Debug)]
170 pub enum GenericArgs {
171 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
172 AngleBracketed(AngleBracketedArgs),
173 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
174 Parenthesized(ParenthesizedArgs),
178 pub fn is_angle_bracketed(&self) -> bool {
179 matches!(self, AngleBracketed(..))
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 AngleBracketedArg {
231 pub fn span(&self) -> Span {
233 AngleBracketedArg::Arg(arg) => arg.span(),
234 AngleBracketedArg::Constraint(constraint) => constraint.span,
239 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
240 fn into(self) -> Option<P<GenericArgs>> {
241 Some(P(GenericArgs::AngleBracketed(self)))
245 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
246 fn into(self) -> Option<P<GenericArgs>> {
247 Some(P(GenericArgs::Parenthesized(self)))
251 /// A path like `Foo(A, B) -> C`.
252 #[derive(Clone, Encodable, Decodable, Debug)]
253 pub struct ParenthesizedArgs {
261 pub inputs: Vec<P<Ty>>,
267 pub inputs_span: Span,
273 impl ParenthesizedArgs {
274 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
279 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
281 AngleBracketedArgs { span: self.inputs_span, args }
285 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
287 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
289 /// Negative bounds should also be handled here.
290 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
291 pub enum TraitBoundModifier {
303 // This parses but will be rejected during AST validation.
307 /// The AST represents all type param bounds as types.
308 /// `typeck::collect::compute_bounds` matches these against
309 /// the "special" built-in traits (see `middle::lang_items`) and
310 /// detects `Copy`, `Send` and `Sync`.
311 #[derive(Clone, Encodable, Decodable, Debug)]
312 pub enum GenericBound {
313 Trait(PolyTraitRef, TraitBoundModifier),
318 pub fn span(&self) -> Span {
320 GenericBound::Trait(ref t, ..) => t.span,
321 GenericBound::Outlives(ref l) => l.ident.span,
326 pub type GenericBounds = Vec<GenericBound>;
328 /// Specifies the enforced ordering for generic parameters. In the future,
329 /// if we wanted to relax this order, we could override `PartialEq` and
330 /// `PartialOrd`, to allow the kinds to be unordered.
331 #[derive(Hash, Clone, Copy)]
332 pub enum ParamKindOrd {
335 // `unordered` is only `true` if `sess.has_features().const_generics`
336 // is active. Specifically, if it's only `min_const_generics`, it will still require
337 // ordering consts after types.
338 Const { unordered: bool },
339 // `Infer` is not actually constructed directly from the AST, but is implicitly constructed
340 // during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last.
344 impl Ord for ParamKindOrd {
345 fn cmp(&self, other: &Self) -> Ordering {
347 let to_int = |v| match v {
349 Infer | Type | Const { unordered: true } => 1,
350 // technically both consts should be ordered equally,
351 // but only one is ever encountered at a time, so this is
353 Const { unordered: false } => 2,
356 to_int(*self).cmp(&to_int(*other))
359 impl PartialOrd for ParamKindOrd {
360 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
361 Some(self.cmp(other))
364 impl PartialEq for ParamKindOrd {
365 fn eq(&self, other: &Self) -> bool {
366 self.cmp(other) == Ordering::Equal
369 impl Eq for ParamKindOrd {}
371 impl fmt::Display for ParamKindOrd {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374 ParamKindOrd::Lifetime => "lifetime".fmt(f),
375 ParamKindOrd::Type => "type".fmt(f),
376 ParamKindOrd::Const { .. } => "const".fmt(f),
377 ParamKindOrd::Infer => "infer".fmt(f),
382 #[derive(Clone, Encodable, Decodable, Debug)]
383 pub enum GenericParamKind {
384 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
387 default: Option<P<Ty>>,
391 /// Span of the `const` keyword.
393 /// Optional default value for the const generic param
394 default: Option<AnonConst>,
398 #[derive(Clone, Encodable, Decodable, Debug)]
399 pub struct GenericParam {
403 pub bounds: GenericBounds,
404 pub is_placeholder: bool,
405 pub kind: GenericParamKind,
408 /// Represents lifetime, type and const parameters attached to a declaration of
409 /// a function, enum, trait, etc.
410 #[derive(Clone, Encodable, Decodable, Debug)]
411 pub struct Generics {
412 pub params: Vec<GenericParam>,
413 pub where_clause: WhereClause,
417 impl Default for Generics {
418 /// Creates an instance of `Generics`.
419 fn default() -> Generics {
422 where_clause: WhereClause {
423 has_where_token: false,
424 predicates: Vec::new(),
432 /// A where-clause in a definition.
433 #[derive(Clone, Encodable, Decodable, Debug)]
434 pub struct WhereClause {
435 /// `true` if we ate a `where` token: this can happen
436 /// if we parsed no predicates (e.g. `struct Foo where {}`).
437 /// This allows us to accurately pretty-print
438 /// in `nt_to_tokenstream`
439 pub has_where_token: bool,
440 pub predicates: Vec<WherePredicate>,
444 /// A single predicate in a where-clause.
445 #[derive(Clone, Encodable, Decodable, Debug)]
446 pub enum WherePredicate {
447 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
448 BoundPredicate(WhereBoundPredicate),
449 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
450 RegionPredicate(WhereRegionPredicate),
451 /// An equality predicate (unsupported).
452 EqPredicate(WhereEqPredicate),
455 impl WherePredicate {
456 pub fn span(&self) -> Span {
458 WherePredicate::BoundPredicate(p) => p.span,
459 WherePredicate::RegionPredicate(p) => p.span,
460 WherePredicate::EqPredicate(p) => p.span,
467 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
468 #[derive(Clone, Encodable, Decodable, Debug)]
469 pub struct WhereBoundPredicate {
471 /// Any generics from a `for` binding.
472 pub bound_generic_params: Vec<GenericParam>,
473 /// The type being bounded.
474 pub bounded_ty: P<Ty>,
475 /// Trait and lifetime bounds (`Clone + Send + 'static`).
476 pub bounds: GenericBounds,
479 /// A lifetime predicate.
481 /// E.g., `'a: 'b + 'c`.
482 #[derive(Clone, Encodable, Decodable, Debug)]
483 pub struct WhereRegionPredicate {
485 pub lifetime: Lifetime,
486 pub bounds: GenericBounds,
489 /// An equality predicate (unsupported).
492 #[derive(Clone, Encodable, Decodable, Debug)]
493 pub struct WhereEqPredicate {
500 #[derive(Clone, Encodable, Decodable, Debug)]
502 pub attrs: Vec<Attribute>,
503 pub items: Vec<P<Item>>,
505 /// The order of items in the HIR is unrelated to the order of
506 /// items in the AST. However, we generate proc macro harnesses
507 /// based on the AST order, and later refer to these harnesses
508 /// from the HIR. This field keeps track of the order in which
509 /// we generated proc macros harnesses, so that we can map
510 /// HIR proc macros items back to their harness items.
511 pub proc_macros: Vec<NodeId>,
514 /// Possible values inside of compile-time attribute lists.
516 /// E.g., the '..' in `#[name(..)]`.
517 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
518 pub enum NestedMetaItem {
519 /// A full MetaItem, for recursive meta items.
523 /// E.g., `"foo"`, `64`, `true`.
527 /// A spanned compile-time attribute item.
529 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
530 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
531 pub struct MetaItem {
533 pub kind: MetaItemKind,
537 /// A compile-time attribute item.
539 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
540 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
541 pub enum MetaItemKind {
544 /// E.g., `test` as in `#[test]`.
548 /// E.g., `derive(..)` as in `#[derive(..)]`.
549 List(Vec<NestedMetaItem>),
550 /// Name value meta item.
552 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
556 /// A block (`{ .. }`).
558 /// E.g., `{ .. }` as in `fn foo() { .. }`.
559 #[derive(Clone, Encodable, Decodable, Debug)]
561 /// The statements in the block.
562 pub stmts: Vec<Stmt>,
564 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
565 pub rules: BlockCheckMode,
567 pub tokens: Option<LazyTokenStream>,
572 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
573 #[derive(Clone, Encodable, Decodable, Debug)]
578 pub tokens: Option<LazyTokenStream>,
582 /// Attempt reparsing the pattern as a type.
583 /// This is intended for use by diagnostics.
584 pub fn to_ty(&self) -> Option<P<Ty>> {
585 let kind = match &self.kind {
586 // In a type expression `_` is an inference variable.
587 PatKind::Wild => TyKind::Infer,
588 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
589 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
590 TyKind::Path(None, Path::from_ident(*ident))
592 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
593 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
594 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
595 PatKind::Ref(pat, mutbl) => {
596 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
598 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
599 // when `P` can be reparsed as a type `T`.
600 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
601 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
602 // assuming `T0` to `Tn` are all syntactically valid as types.
603 PatKind::Tuple(pats) => {
604 let mut tys = Vec::with_capacity(pats.len());
605 // FIXME(#48994) - could just be collected into an Option<Vec>
607 tys.push(pat.to_ty()?);
614 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
617 /// Walk top-down and call `it` in each place where a pattern occurs
618 /// starting with the root pattern `walk` is called on. If `it` returns
619 /// false then we will descend no further but siblings will be processed.
620 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
626 // Walk into the pattern associated with `Ident` (if any).
627 PatKind::Ident(_, _, Some(p)) => p.walk(it),
629 // Walk into each field of struct.
630 PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
632 // Sequence of patterns.
633 PatKind::TupleStruct(_, _, s)
636 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
638 // Trivial wrappers over inner patterns.
639 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
641 // These patterns do not contain subpatterns, skip.
648 | PatKind::MacCall(_) => {}
652 /// Is this a `..` pattern?
653 pub fn is_rest(&self) -> bool {
654 matches!(self.kind, PatKind::Rest)
658 /// A single field in a struct pattern.
660 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
661 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
662 /// except when `is_shorthand` is true.
663 #[derive(Clone, Encodable, Decodable, Debug)]
664 pub struct PatField {
665 /// The identifier for the field.
667 /// The pattern the field is destructured to.
669 pub is_shorthand: bool,
673 pub is_placeholder: bool,
676 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
677 pub enum BindingMode {
682 #[derive(Clone, Encodable, Decodable, Debug)]
685 Included(RangeSyntax),
690 #[derive(Clone, Encodable, Decodable, Debug)]
691 pub enum RangeSyntax {
698 /// All the different flavors of pattern that Rust recognizes.
699 #[derive(Clone, Encodable, Decodable, Debug)]
701 /// Represents a wildcard pattern (`_`).
704 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
705 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
706 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
707 /// during name resolution.
708 Ident(BindingMode, Ident, Option<P<Pat>>),
710 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
711 /// The `bool` is `true` in the presence of a `..`.
712 Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool),
714 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
715 TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>),
717 /// An or-pattern `A | B | C`.
718 /// Invariant: `pats.len() >= 2`.
721 /// A possibly qualified path pattern.
722 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
723 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
724 /// only legally refer to associated constants.
725 Path(Option<QSelf>, Path),
727 /// A tuple pattern (`(a, b)`).
733 /// A reference pattern (e.g., `&mut (a, b)`).
734 Ref(P<Pat>, Mutability),
739 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
740 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
742 /// A slice pattern `[a, b, c]`.
745 /// A rest pattern `..`.
747 /// Syntactically it is valid anywhere.
749 /// Semantically however, it only has meaning immediately inside:
750 /// - a slice pattern: `[a, .., b]`,
751 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
752 /// - a tuple pattern: `(a, .., b)`,
753 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
755 /// In all of these cases, an additional restriction applies,
756 /// only one rest pattern may occur in the pattern sequences.
759 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
762 /// A macro pattern; pre-expansion.
766 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
767 #[derive(HashStable_Generic, Encodable, Decodable)]
768 pub enum Mutability {
774 pub fn invert(self) -> Self {
776 Mutability::Mut => Mutability::Not,
777 Mutability::Not => Mutability::Mut,
781 pub fn prefix_str(&self) -> &'static str {
783 Mutability::Mut => "mut ",
784 Mutability::Not => "",
789 /// The kind of borrow in an `AddrOf` expression,
790 /// e.g., `&place` or `&raw const place`.
791 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
792 #[derive(Encodable, Decodable, HashStable_Generic)]
793 pub enum BorrowKind {
794 /// A normal borrow, `&$expr` or `&mut $expr`.
795 /// The resulting type is either `&'a T` or `&'a mut T`
796 /// where `T = typeof($expr)` and `'a` is some lifetime.
798 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
799 /// The resulting type is either `*const T` or `*mut T`
800 /// where `T = typeof($expr)`.
804 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
806 /// The `+` operator (addition)
808 /// The `-` operator (subtraction)
810 /// The `*` operator (multiplication)
812 /// The `/` operator (division)
814 /// The `%` operator (modulus)
816 /// The `&&` operator (logical and)
818 /// The `||` operator (logical or)
820 /// The `^` operator (bitwise xor)
822 /// The `&` operator (bitwise and)
824 /// The `|` operator (bitwise or)
826 /// The `<<` operator (shift left)
828 /// The `>>` operator (shift right)
830 /// The `==` operator (equality)
832 /// The `<` operator (less than)
834 /// The `<=` operator (less than or equal to)
836 /// The `!=` operator (not equal to)
838 /// The `>=` operator (greater than or equal to)
840 /// The `>` operator (greater than)
845 pub fn to_string(&self) -> &'static str {
868 pub fn lazy(&self) -> bool {
869 matches!(self, BinOpKind::And | BinOpKind::Or)
872 pub fn is_comparison(&self) -> bool {
874 // Note for developers: please keep this as is;
875 // we want compilation to fail if another variant is added.
877 Eq | Lt | Le | Ne | Gt | Ge => true,
878 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
883 pub type BinOp = Spanned<BinOpKind>;
887 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
888 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
890 /// The `*` operator for dereferencing
892 /// The `!` operator for logical inversion
894 /// The `-` operator for negation
899 pub fn to_string(op: UnOp) -> &'static str {
909 #[derive(Clone, Encodable, Decodable, Debug)]
917 pub fn tokens(&self) -> Option<&LazyTokenStream> {
919 StmtKind::Local(ref local) => local.tokens.as_ref(),
920 StmtKind::Item(ref item) => item.tokens.as_ref(),
921 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(),
922 StmtKind::Empty => None,
923 StmtKind::MacCall(ref mac) => mac.tokens.as_ref(),
927 pub fn has_trailing_semicolon(&self) -> bool {
929 StmtKind::Semi(_) => true,
930 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
935 /// Converts a parsed `Stmt` to a `Stmt` with
936 /// a trailing semicolon.
938 /// This only modifies the parsed AST struct, not the attached
939 /// `LazyTokenStream`. The parser is responsible for calling
940 /// `CreateTokenStream::add_trailing_semi` when there is actually
941 /// a semicolon in the tokenstream.
942 pub fn add_trailing_semicolon(mut self) -> Self {
943 self.kind = match self.kind {
944 StmtKind::Expr(expr) => StmtKind::Semi(expr),
945 StmtKind::MacCall(mac) => {
946 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
947 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
956 pub fn is_item(&self) -> bool {
957 matches!(self.kind, StmtKind::Item(_))
960 pub fn is_expr(&self) -> bool {
961 matches!(self.kind, StmtKind::Expr(_))
965 #[derive(Clone, Encodable, Decodable, Debug)]
967 /// A local (let) binding.
969 /// An item definition.
971 /// Expr without trailing semi-colon.
973 /// Expr with a trailing semi-colon.
975 /// Just a trailing semi-colon.
978 MacCall(P<MacCallStmt>),
981 #[derive(Clone, Encodable, Decodable, Debug)]
982 pub struct MacCallStmt {
984 pub style: MacStmtStyle,
986 pub tokens: Option<LazyTokenStream>,
989 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
990 pub enum MacStmtStyle {
991 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
992 /// `foo!(...);`, `foo![...];`).
994 /// The macro statement had braces (e.g., `foo! { ... }`).
996 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
997 /// `foo!(...)`). All of these will end up being converted into macro
1002 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1003 #[derive(Clone, Encodable, Decodable, Debug)]
1007 pub ty: Option<P<Ty>>,
1008 /// Initializer expression to set the value, if any.
1009 pub init: Option<P<Expr>>,
1012 pub tokens: Option<LazyTokenStream>,
1015 /// An arm of a 'match'.
1017 /// E.g., `0..=10 => { println!("match!") }` as in
1021 /// 0..=10 => { println!("match!") },
1022 /// _ => { println!("no match!") },
1025 #[derive(Clone, Encodable, Decodable, Debug)]
1028 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1030 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1031 pub guard: Option<P<Expr>>,
1036 pub is_placeholder: bool,
1039 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1040 #[derive(Clone, Encodable, Decodable, Debug)]
1041 pub struct ExprField {
1047 pub is_shorthand: bool,
1048 pub is_placeholder: bool,
1051 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1052 pub enum BlockCheckMode {
1054 Unsafe(UnsafeSource),
1057 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1058 pub enum UnsafeSource {
1063 /// A constant (expression) that's not an item or associated item,
1064 /// but needs its own `DefId` for type-checking, const-eval, etc.
1065 /// These are usually found nested inside types (e.g., array lengths)
1066 /// or expressions (e.g., repeat counts), and also used to define
1067 /// explicit discriminant values for enum variants.
1068 #[derive(Clone, Encodable, Decodable, Debug)]
1069 pub struct AnonConst {
1075 #[derive(Clone, Encodable, Decodable, Debug)]
1081 pub tokens: Option<LazyTokenStream>,
1084 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1085 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1086 rustc_data_structures::static_assert_size!(Expr, 104);
1089 /// Returns `true` if this expression would be valid somewhere that expects a value;
1090 /// for example, an `if` condition.
1091 pub fn returns(&self) -> bool {
1092 if let ExprKind::Block(ref block, _) = self.kind {
1093 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1095 Some(StmtKind::Expr(_)) => true,
1096 // Last statement is an explicit return?
1097 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1098 // This is a block that doesn't end in either an implicit or explicit return.
1102 // This is not a block, it is a value.
1107 /// Is this expr either `N`, or `{ N }`.
1109 /// If this is not the case, name resolution does not resolve `N` when using
1110 /// `min_const_generics` as more complex expressions are not supported.
1111 pub fn is_potential_trivial_const_param(&self) -> bool {
1112 let this = if let ExprKind::Block(ref block, None) = self.kind {
1113 if block.stmts.len() == 1 {
1114 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1122 if let ExprKind::Path(None, ref path) = this.kind {
1123 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1131 pub fn to_bound(&self) -> Option<GenericBound> {
1133 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1134 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1135 TraitBoundModifier::None,
1141 pub fn peel_parens(&self) -> &Expr {
1142 let mut expr = self;
1143 while let ExprKind::Paren(inner) = &expr.kind {
1149 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1150 pub fn to_ty(&self) -> Option<P<Ty>> {
1151 let kind = match &self.kind {
1152 // Trivial conversions.
1153 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1154 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1156 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1158 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1159 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1162 ExprKind::Repeat(expr, expr_len) => {
1163 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1166 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1168 ExprKind::Tup(exprs) => {
1169 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1173 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1174 // then type of result is trait object.
1175 // Otherwise we don't assume the result type.
1176 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1177 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1178 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1184 // This expression doesn't look like a type syntactically.
1188 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1191 pub fn precedence(&self) -> ExprPrecedence {
1193 ExprKind::Box(_) => ExprPrecedence::Box,
1194 ExprKind::Array(_) => ExprPrecedence::Array,
1195 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1196 ExprKind::Call(..) => ExprPrecedence::Call,
1197 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1198 ExprKind::Tup(_) => ExprPrecedence::Tup,
1199 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1200 ExprKind::Unary(..) => ExprPrecedence::Unary,
1201 ExprKind::Lit(_) => ExprPrecedence::Lit,
1202 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1203 ExprKind::Let(..) => ExprPrecedence::Let,
1204 ExprKind::If(..) => ExprPrecedence::If,
1205 ExprKind::While(..) => ExprPrecedence::While,
1206 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1207 ExprKind::Loop(..) => ExprPrecedence::Loop,
1208 ExprKind::Match(..) => ExprPrecedence::Match,
1209 ExprKind::Closure(..) => ExprPrecedence::Closure,
1210 ExprKind::Block(..) => ExprPrecedence::Block,
1211 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1212 ExprKind::Async(..) => ExprPrecedence::Async,
1213 ExprKind::Await(..) => ExprPrecedence::Await,
1214 ExprKind::Assign(..) => ExprPrecedence::Assign,
1215 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1216 ExprKind::Field(..) => ExprPrecedence::Field,
1217 ExprKind::Index(..) => ExprPrecedence::Index,
1218 ExprKind::Range(..) => ExprPrecedence::Range,
1219 ExprKind::Underscore => ExprPrecedence::Path,
1220 ExprKind::Path(..) => ExprPrecedence::Path,
1221 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1222 ExprKind::Break(..) => ExprPrecedence::Break,
1223 ExprKind::Continue(..) => ExprPrecedence::Continue,
1224 ExprKind::Ret(..) => ExprPrecedence::Ret,
1225 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1226 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1227 ExprKind::Struct(..) => ExprPrecedence::Struct,
1228 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1229 ExprKind::Paren(..) => ExprPrecedence::Paren,
1230 ExprKind::Try(..) => ExprPrecedence::Try,
1231 ExprKind::Yield(..) => ExprPrecedence::Yield,
1232 ExprKind::Err => ExprPrecedence::Err,
1237 /// Limit types of a range (inclusive or exclusive)
1238 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1239 pub enum RangeLimits {
1240 /// Inclusive at the beginning, exclusive at the end
1242 /// Inclusive at the beginning and end
1246 #[derive(Clone, Encodable, Decodable, Debug)]
1247 pub enum StructRest {
1252 /// No trailing `..` or expression.
1256 #[derive(Clone, Encodable, Decodable, Debug)]
1257 pub struct StructExpr {
1258 pub qself: Option<QSelf>,
1260 pub fields: Vec<ExprField>,
1261 pub rest: StructRest,
1264 #[derive(Clone, Encodable, Decodable, Debug)]
1266 /// A `box x` expression.
1268 /// An array (`[a, b, c, d]`)
1269 Array(Vec<P<Expr>>),
1270 /// Allow anonymous constants from an inline `const` block
1271 ConstBlock(AnonConst),
1274 /// The first field resolves to the function itself,
1275 /// and the second field is the list of arguments.
1276 /// This also represents calling the constructor of
1277 /// tuple-like ADTs such as tuple structs and enum variants.
1278 Call(P<Expr>, Vec<P<Expr>>),
1279 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1281 /// The `PathSegment` represents the method name and its generic arguments
1282 /// (within the angle brackets).
1283 /// The first element of the vector of an `Expr` is the expression that evaluates
1284 /// to the object on which the method is being called on (the receiver),
1285 /// and the remaining elements are the rest of the arguments.
1286 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1287 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1288 /// This `Span` is the span of the function, without the dot and receiver
1289 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1290 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1291 /// A tuple (e.g., `(a, b, c, d)`).
1293 /// A binary operation (e.g., `a + b`, `a * b`).
1294 Binary(BinOp, P<Expr>, P<Expr>),
1295 /// A unary operation (e.g., `!x`, `*x`).
1296 Unary(UnOp, P<Expr>),
1297 /// A literal (e.g., `1`, `"foo"`).
1299 /// A cast (e.g., `foo as f64`).
1300 Cast(P<Expr>, P<Ty>),
1301 /// A type ascription (e.g., `42: usize`).
1302 Type(P<Expr>, P<Ty>),
1303 /// A `let pat = expr` expression that is only semantically allowed in the condition
1304 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1306 /// `Span` represents the whole `let pat = expr` statement.
1307 Let(P<Pat>, P<Expr>, Span),
1308 /// An `if` block, with an optional `else` block.
1310 /// `if expr { block } else { expr }`
1311 If(P<Expr>, P<Block>, Option<P<Expr>>),
1312 /// A while loop, with an optional label.
1314 /// `'label: while expr { block }`
1315 While(P<Expr>, P<Block>, Option<Label>),
1316 /// A `for` loop, with an optional label.
1318 /// `'label: for pat in expr { block }`
1320 /// This is desugared to a combination of `loop` and `match` expressions.
1321 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1322 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1324 /// `'label: loop { block }`
1325 Loop(P<Block>, Option<Label>),
1326 /// A `match` block.
1327 Match(P<Expr>, Vec<Arm>),
1328 /// A closure (e.g., `move |a, b, c| a + b + c`).
1330 /// The final span is the span of the argument block `|...|`.
1331 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1332 /// A block (`'label: { ... }`).
1333 Block(P<Block>, Option<Label>),
1334 /// An async block (`async move { ... }`).
1336 /// The `NodeId` is the `NodeId` for the closure that results from
1337 /// desugaring an async block, just like the NodeId field in the
1338 /// `Async::Yes` variant. This is necessary in order to create a def for the
1339 /// closure which can be used as a parent of any child defs. Defs
1340 /// created during lowering cannot be made the parent of any other
1341 /// preexisting defs.
1342 Async(CaptureBy, NodeId, P<Block>),
1343 /// An await expression (`my_future.await`).
1346 /// A try block (`try { ... }`).
1349 /// An assignment (`a = foo()`).
1350 /// The `Span` argument is the span of the `=` token.
1351 Assign(P<Expr>, P<Expr>, Span),
1352 /// An assignment with an operator.
1355 AssignOp(BinOp, P<Expr>, P<Expr>),
1356 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1357 Field(P<Expr>, Ident),
1358 /// An indexing operation (e.g., `foo[2]`).
1359 Index(P<Expr>, P<Expr>),
1360 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1361 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1362 /// An underscore, used in destructuring assignment to ignore a value.
1365 /// Variable reference, possibly containing `::` and/or type
1366 /// parameters (e.g., `foo::bar::<baz>`).
1368 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1369 Path(Option<QSelf>, Path),
1371 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1372 AddrOf(BorrowKind, Mutability, P<Expr>),
1373 /// A `break`, with an optional label to break, and an optional expression.
1374 Break(Option<Label>, Option<P<Expr>>),
1375 /// A `continue`, with an optional label.
1376 Continue(Option<Label>),
1377 /// A `return`, with an optional value to be returned.
1378 Ret(Option<P<Expr>>),
1380 /// Output of the `asm!()` macro.
1381 InlineAsm(P<InlineAsm>),
1382 /// Output of the `llvm_asm!()` macro.
1383 LlvmInlineAsm(P<LlvmInlineAsm>),
1385 /// A macro invocation; pre-expansion.
1388 /// A struct literal expression.
1390 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1391 Struct(P<StructExpr>),
1393 /// An array literal constructed from one repeated element.
1395 /// E.g., `[1; 5]`. The expression is the element to be
1396 /// repeated; the constant is the number of times to repeat it.
1397 Repeat(P<Expr>, AnonConst),
1399 /// No-op: used solely so we can pretty-print faithfully.
1402 /// A try expression (`expr?`).
1405 /// A `yield`, with an optional value to be yielded.
1406 Yield(Option<P<Expr>>),
1408 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1412 /// The explicit `Self` type in a "qualified path". The actual
1413 /// path, including the trait and the associated item, is stored
1414 /// separately. `position` represents the index of the associated
1415 /// item qualified with this `Self` type.
1417 /// ```ignore (only-for-syntax-highlight)
1418 /// <Vec<T> as a::b::Trait>::AssociatedItem
1419 /// ^~~~~ ~~~~~~~~~~~~~~^
1422 /// <Vec<T>>::AssociatedItem
1426 #[derive(Clone, Encodable, Decodable, Debug)]
1430 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1431 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1432 /// 0`, this is an empty span.
1433 pub path_span: Span,
1434 pub position: usize,
1437 /// A capture clause used in closures and `async` blocks.
1438 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1439 pub enum CaptureBy {
1440 /// `move |x| y + x`.
1442 /// `move` keyword was not specified.
1446 /// The movability of a generator / closure literal:
1447 /// whether a generator contains self-references, causing it to be `!Unpin`.
1448 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1449 #[derive(HashStable_Generic)]
1450 pub enum Movability {
1451 /// May contain self-references, `!Unpin`.
1453 /// Must not contain self-references, `Unpin`.
1457 /// Represents a macro invocation. The `path` indicates which macro
1458 /// is being invoked, and the `args` are arguments passed to it.
1459 #[derive(Clone, Encodable, Decodable, Debug)]
1460 pub struct MacCall {
1462 pub args: P<MacArgs>,
1463 pub prior_type_ascription: Option<(Span, bool)>,
1467 pub fn span(&self) -> Span {
1468 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1472 /// Arguments passed to an attribute or a function-like macro.
1473 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1475 /// No arguments - `#[attr]`.
1477 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1478 Delimited(DelimSpan, MacDelimiter, TokenStream),
1479 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1481 /// Span of the `=` token.
1483 /// "value" as a nonterminal token.
1489 pub fn delim(&self) -> DelimToken {
1491 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1492 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1496 pub fn span(&self) -> Option<Span> {
1498 MacArgs::Empty => None,
1499 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1500 MacArgs::Eq(eq_span, token) => Some(eq_span.to(token.span)),
1504 /// Tokens inside the delimiters or after `=`.
1505 /// Proc macros see these tokens, for example.
1506 pub fn inner_tokens(&self) -> TokenStream {
1508 MacArgs::Empty => TokenStream::default(),
1509 MacArgs::Delimited(.., tokens) => tokens.clone(),
1510 MacArgs::Eq(.., token) => TokenTree::Token(token.clone()).into(),
1514 /// Whether a macro with these arguments needs a semicolon
1515 /// when used as a standalone item or statement.
1516 pub fn need_semicolon(&self) -> bool {
1517 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1521 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1522 pub enum MacDelimiter {
1529 pub fn to_token(self) -> DelimToken {
1531 MacDelimiter::Parenthesis => DelimToken::Paren,
1532 MacDelimiter::Bracket => DelimToken::Bracket,
1533 MacDelimiter::Brace => DelimToken::Brace,
1537 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1539 token::Paren => Some(MacDelimiter::Parenthesis),
1540 token::Bracket => Some(MacDelimiter::Bracket),
1541 token::Brace => Some(MacDelimiter::Brace),
1542 token::NoDelim => None,
1547 /// Represents a macro definition.
1548 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1549 pub struct MacroDef {
1550 pub body: P<MacArgs>,
1551 /// `true` if macro was defined with `macro_rules`.
1552 pub macro_rules: bool,
1555 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1556 #[derive(HashStable_Generic)]
1558 /// A regular string, like `"foo"`.
1560 /// A raw string, like `r##"foo"##`.
1562 /// The value is the number of `#` symbols used.
1567 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1569 /// The original literal token as written in source code.
1570 pub token: token::Lit,
1571 /// The "semantic" representation of the literal lowered from the original tokens.
1572 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1573 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1578 /// Same as `Lit`, but restricted to string literals.
1579 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1581 /// The original literal token as written in source code.
1582 pub style: StrStyle,
1584 pub suffix: Option<Symbol>,
1586 /// The unescaped "semantic" representation of the literal lowered from the original token.
1587 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1588 pub symbol_unescaped: Symbol,
1592 pub fn as_lit(&self) -> Lit {
1593 let token_kind = match self.style {
1594 StrStyle::Cooked => token::Str,
1595 StrStyle::Raw(n) => token::StrRaw(n),
1598 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1600 kind: LitKind::Str(self.symbol_unescaped, self.style),
1605 /// Type of the integer literal based on provided suffix.
1606 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1607 #[derive(HashStable_Generic)]
1608 pub enum LitIntType {
1617 /// Type of the float literal based on provided suffix.
1618 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1619 #[derive(HashStable_Generic)]
1620 pub enum LitFloatType {
1621 /// A float literal with a suffix (`1f32` or `1E10f32`).
1623 /// A float literal without a suffix (`1.0 or 1.0E10`).
1629 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1630 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1632 /// A string literal (`"foo"`).
1633 Str(Symbol, StrStyle),
1634 /// A byte string (`b"foo"`).
1636 /// A byte char (`b'f'`).
1638 /// A character literal (`'a'`).
1640 /// An integer literal (`1`).
1641 Int(u128, LitIntType),
1642 /// A float literal (`1f64` or `1E10f64`).
1643 Float(Symbol, LitFloatType),
1644 /// A boolean literal.
1646 /// Placeholder for a literal that wasn't well-formed in some way.
1651 /// Returns `true` if this literal is a string.
1652 pub fn is_str(&self) -> bool {
1653 matches!(self, LitKind::Str(..))
1656 /// Returns `true` if this literal is byte literal string.
1657 pub fn is_bytestr(&self) -> bool {
1658 matches!(self, LitKind::ByteStr(_))
1661 /// Returns `true` if this is a numeric literal.
1662 pub fn is_numeric(&self) -> bool {
1663 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1666 /// Returns `true` if this literal has no suffix.
1667 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1668 pub fn is_unsuffixed(&self) -> bool {
1672 /// Returns `true` if this literal has a suffix.
1673 pub fn is_suffixed(&self) -> bool {
1675 // suffixed variants
1676 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1677 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1678 // unsuffixed variants
1680 | LitKind::ByteStr(..)
1683 | LitKind::Int(_, LitIntType::Unsuffixed)
1684 | LitKind::Float(_, LitFloatType::Unsuffixed)
1686 | LitKind::Err(..) => false,
1691 // N.B., If you change this, you'll probably want to change the corresponding
1692 // type structure in `middle/ty.rs` as well.
1693 #[derive(Clone, Encodable, Decodable, Debug)]
1696 pub mutbl: Mutability,
1699 /// Represents a function's signature in a trait declaration,
1700 /// trait implementation, or free function.
1701 #[derive(Clone, Encodable, Decodable, Debug)]
1703 pub header: FnHeader,
1704 pub decl: P<FnDecl>,
1708 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1709 #[derive(Encodable, Decodable, HashStable_Generic)]
1716 pub fn name_str(self) -> &'static str {
1718 FloatTy::F32 => "f32",
1719 FloatTy::F64 => "f64",
1723 pub fn name(self) -> Symbol {
1725 FloatTy::F32 => sym::f32,
1726 FloatTy::F64 => sym::f64,
1731 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1732 #[derive(Encodable, Decodable, HashStable_Generic)]
1743 pub fn name_str(&self) -> &'static str {
1745 IntTy::Isize => "isize",
1747 IntTy::I16 => "i16",
1748 IntTy::I32 => "i32",
1749 IntTy::I64 => "i64",
1750 IntTy::I128 => "i128",
1754 pub fn name(&self) -> Symbol {
1756 IntTy::Isize => sym::isize,
1757 IntTy::I8 => sym::i8,
1758 IntTy::I16 => sym::i16,
1759 IntTy::I32 => sym::i32,
1760 IntTy::I64 => sym::i64,
1761 IntTy::I128 => sym::i128,
1766 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1767 #[derive(Encodable, Decodable, HashStable_Generic)]
1778 pub fn name_str(&self) -> &'static str {
1780 UintTy::Usize => "usize",
1782 UintTy::U16 => "u16",
1783 UintTy::U32 => "u32",
1784 UintTy::U64 => "u64",
1785 UintTy::U128 => "u128",
1789 pub fn name(&self) -> Symbol {
1791 UintTy::Usize => sym::usize,
1792 UintTy::U8 => sym::u8,
1793 UintTy::U16 => sym::u16,
1794 UintTy::U32 => sym::u32,
1795 UintTy::U64 => sym::u64,
1796 UintTy::U128 => sym::u128,
1801 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1802 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1803 #[derive(Clone, Encodable, Decodable, Debug)]
1804 pub struct AssocTyConstraint {
1807 pub gen_args: Option<GenericArgs>,
1808 pub kind: AssocTyConstraintKind,
1812 /// The kinds of an `AssocTyConstraint`.
1813 #[derive(Clone, Encodable, Decodable, Debug)]
1814 pub enum AssocTyConstraintKind {
1815 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1816 Equality { ty: P<Ty> },
1817 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1818 Bound { bounds: GenericBounds },
1821 #[derive(Encodable, Decodable, Debug)]
1826 pub tokens: Option<LazyTokenStream>,
1830 fn clone(&self) -> Self {
1831 ensure_sufficient_stack(|| Self {
1833 kind: self.kind.clone(),
1835 tokens: self.tokens.clone(),
1841 pub fn peel_refs(&self) -> &Self {
1842 let mut final_ty = self;
1843 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1850 #[derive(Clone, Encodable, Decodable, Debug)]
1851 pub struct BareFnTy {
1852 pub unsafety: Unsafe,
1854 pub generic_params: Vec<GenericParam>,
1855 pub decl: P<FnDecl>,
1858 /// The various kinds of type recognized by the compiler.
1859 #[derive(Clone, Encodable, Decodable, Debug)]
1861 /// A variable-length slice (`[T]`).
1863 /// A fixed length array (`[T; n]`).
1864 Array(P<Ty>, AnonConst),
1865 /// A raw pointer (`*const T` or `*mut T`).
1867 /// A reference (`&'a T` or `&'a mut T`).
1868 Rptr(Option<Lifetime>, MutTy),
1869 /// A bare function (e.g., `fn(usize) -> bool`).
1870 BareFn(P<BareFnTy>),
1871 /// The never type (`!`).
1873 /// A tuple (`(A, B, C, D,...)`).
1875 /// An anonymous struct type i.e. `struct { foo: Type }`
1876 AnonymousStruct(Vec<FieldDef>, bool),
1877 /// An anonymous union type i.e. `union { bar: Type }`
1878 AnonymousUnion(Vec<FieldDef>, bool),
1879 /// A path (`module::module::...::Type`), optionally
1880 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1882 /// Type parameters are stored in the `Path` itself.
1883 Path(Option<QSelf>, Path),
1884 /// A trait object type `Bound1 + Bound2 + Bound3`
1885 /// where `Bound` is a trait or a lifetime.
1886 TraitObject(GenericBounds, TraitObjectSyntax),
1887 /// An `impl Bound1 + Bound2 + Bound3` type
1888 /// where `Bound` is a trait or a lifetime.
1890 /// The `NodeId` exists to prevent lowering from having to
1891 /// generate `NodeId`s on the fly, which would complicate
1892 /// the generation of opaque `type Foo = impl Trait` items significantly.
1893 ImplTrait(NodeId, GenericBounds),
1894 /// No-op; kept solely so that we can pretty-print faithfully.
1898 /// This means the type should be inferred instead of it having been
1899 /// specified. This can appear anywhere in a type.
1901 /// Inferred type of a `self` or `&self` argument in a method.
1903 /// A macro in the type position.
1905 /// Placeholder for a kind that has failed to be defined.
1907 /// Placeholder for a `va_list`.
1912 pub fn is_implicit_self(&self) -> bool {
1913 matches!(self, TyKind::ImplicitSelf)
1916 pub fn is_unit(&self) -> bool {
1917 matches!(self, TyKind::Tup(tys) if tys.is_empty())
1921 /// Syntax used to declare a trait object.
1922 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1923 pub enum TraitObjectSyntax {
1928 /// Inline assembly operand explicit register or register class.
1930 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1931 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1932 pub enum InlineAsmRegOrRegClass {
1937 bitflags::bitflags! {
1938 #[derive(Encodable, Decodable, HashStable_Generic)]
1939 pub struct InlineAsmOptions: u8 {
1940 const PURE = 1 << 0;
1941 const NOMEM = 1 << 1;
1942 const READONLY = 1 << 2;
1943 const PRESERVES_FLAGS = 1 << 3;
1944 const NORETURN = 1 << 4;
1945 const NOSTACK = 1 << 5;
1946 const ATT_SYNTAX = 1 << 6;
1951 #[derive(Clone, PartialEq, PartialOrd, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
1952 pub enum InlineAsmTemplatePiece {
1954 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1957 impl fmt::Display for InlineAsmTemplatePiece {
1958 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1960 Self::String(s) => {
1961 for c in s.chars() {
1963 '{' => f.write_str("{{")?,
1964 '}' => f.write_str("}}")?,
1970 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1971 write!(f, "{{{}:{}}}", operand_idx, modifier)
1973 Self::Placeholder { operand_idx, modifier: None, .. } => {
1974 write!(f, "{{{}}}", operand_idx)
1980 impl InlineAsmTemplatePiece {
1981 /// Rebuilds the asm template string from its pieces.
1982 pub fn to_string(s: &[Self]) -> String {
1984 let mut out = String::new();
1986 let _ = write!(out, "{}", p);
1992 /// Inline assembly operand.
1994 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
1995 #[derive(Clone, Encodable, Decodable, Debug)]
1996 pub enum InlineAsmOperand {
1998 reg: InlineAsmRegOrRegClass,
2002 reg: InlineAsmRegOrRegClass,
2004 expr: Option<P<Expr>>,
2007 reg: InlineAsmRegOrRegClass,
2012 reg: InlineAsmRegOrRegClass,
2015 out_expr: Option<P<Expr>>,
2018 anon_const: AnonConst,
2025 /// Inline assembly.
2027 /// E.g., `asm!("NOP");`.
2028 #[derive(Clone, Encodable, Decodable, Debug)]
2029 pub struct InlineAsm {
2030 pub template: Vec<InlineAsmTemplatePiece>,
2031 pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2032 pub operands: Vec<(InlineAsmOperand, Span)>,
2033 pub clobber_abi: Option<(Symbol, Span)>,
2034 pub options: InlineAsmOptions,
2035 pub line_spans: Vec<Span>,
2038 /// Inline assembly dialect.
2040 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2041 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Hash, HashStable_Generic)]
2042 pub enum LlvmAsmDialect {
2047 /// LLVM-style inline assembly.
2049 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2050 #[derive(Clone, Encodable, Decodable, Debug)]
2051 pub struct LlvmInlineAsmOutput {
2052 pub constraint: Symbol,
2055 pub is_indirect: bool,
2058 /// LLVM-style inline assembly.
2060 /// E.g., `llvm_asm!("NOP");`.
2061 #[derive(Clone, Encodable, Decodable, Debug)]
2062 pub struct LlvmInlineAsm {
2064 pub asm_str_style: StrStyle,
2065 pub outputs: Vec<LlvmInlineAsmOutput>,
2066 pub inputs: Vec<(Symbol, P<Expr>)>,
2067 pub clobbers: Vec<Symbol>,
2069 pub alignstack: bool,
2070 pub dialect: LlvmAsmDialect,
2073 /// A parameter in a function header.
2075 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2076 #[derive(Clone, Encodable, Decodable, Debug)]
2083 pub is_placeholder: bool,
2086 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2088 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2089 #[derive(Clone, Encodable, Decodable, Debug)]
2091 /// `self`, `mut self`
2093 /// `&'lt self`, `&'lt mut self`
2094 Region(Option<Lifetime>, Mutability),
2095 /// `self: TYPE`, `mut self: TYPE`
2096 Explicit(P<Ty>, Mutability),
2099 pub type ExplicitSelf = Spanned<SelfKind>;
2102 /// Attempts to cast parameter to `ExplicitSelf`.
2103 pub fn to_self(&self) -> Option<ExplicitSelf> {
2104 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2105 if ident.name == kw::SelfLower {
2106 return match self.ty.kind {
2107 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2108 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2109 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2112 self.pat.span.to(self.ty.span),
2113 SelfKind::Explicit(self.ty.clone(), mutbl),
2121 /// Returns `true` if parameter is `self`.
2122 pub fn is_self(&self) -> bool {
2123 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2124 ident.name == kw::SelfLower
2130 /// Builds a `Param` object from `ExplicitSelf`.
2131 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2132 let span = eself.span.to(eself_ident.span);
2133 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2134 let param = |mutbl, ty| Param {
2138 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 }),
2163 /// A signature (not the body) of a function declaration.
2165 /// E.g., `fn foo(bar: baz)`.
2167 /// Please note that it's different from `FnHeader` structure
2168 /// which contains metadata about function safety, asyncness, constness and ABI.
2169 #[derive(Clone, Encodable, Decodable, Debug)]
2171 pub inputs: Vec<Param>,
2172 pub output: FnRetTy,
2176 pub fn has_self(&self) -> bool {
2177 self.inputs.get(0).map_or(false, Param::is_self)
2179 pub fn c_variadic(&self) -> bool {
2180 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2184 /// Is the trait definition an auto trait?
2185 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2191 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2192 #[derive(HashStable_Generic)]
2198 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2200 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2205 pub fn is_async(self) -> bool {
2206 matches!(self, Async::Yes { .. })
2209 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2210 pub fn opt_return_id(self) -> Option<NodeId> {
2212 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2218 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2219 #[derive(HashStable_Generic)]
2225 /// Item defaultness.
2226 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2227 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2228 pub enum Defaultness {
2233 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2234 pub enum ImplPolarity {
2235 /// `impl Trait for Type`
2237 /// `impl !Trait for Type`
2241 impl fmt::Debug for ImplPolarity {
2242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2244 ImplPolarity::Positive => "positive".fmt(f),
2245 ImplPolarity::Negative(_) => "negative".fmt(f),
2250 #[derive(Clone, Encodable, Decodable, Debug)]
2252 /// Returns type is not specified.
2254 /// Functions default to `()` and closures default to inference.
2255 /// Span points to where return type would be inserted.
2257 /// Everything else.
2262 pub fn span(&self) -> Span {
2264 FnRetTy::Default(span) => span,
2265 FnRetTy::Ty(ref ty) => ty.span,
2270 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2276 /// Module item kind.
2277 #[derive(Clone, Encodable, Decodable, Debug)]
2279 /// Module with inlined definition `mod foo { ... }`,
2280 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2281 /// The inner span is from the first token past `{` to the last token until `}`,
2282 /// or from the first to the last token in the loaded file.
2283 Loaded(Vec<P<Item>>, Inline, Span),
2284 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2288 /// Foreign module declaration.
2290 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2291 #[derive(Clone, Encodable, Decodable, Debug)]
2292 pub struct ForeignMod {
2293 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2294 /// semantically by Rust.
2295 pub unsafety: Unsafe,
2296 pub abi: Option<StrLit>,
2297 pub items: Vec<P<ForeignItem>>,
2300 #[derive(Clone, Encodable, Decodable, Debug)]
2301 pub struct EnumDef {
2302 pub variants: Vec<Variant>,
2305 #[derive(Clone, Encodable, Decodable, Debug)]
2306 pub struct Variant {
2307 /// Attributes of the variant.
2309 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2313 /// The visibility of the variant. Syntactically accepted but not semantically.
2314 pub vis: Visibility,
2315 /// Name of the variant.
2318 /// Fields and constructor id of the variant.
2319 pub data: VariantData,
2320 /// Explicit discriminant, e.g., `Foo = 1`.
2321 pub disr_expr: Option<AnonConst>,
2322 /// Is a macro placeholder
2323 pub is_placeholder: bool,
2326 /// Part of `use` item to the right of its prefix.
2327 #[derive(Clone, Encodable, Decodable, Debug)]
2328 pub enum UseTreeKind {
2329 /// `use prefix` or `use prefix as rename`
2331 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2333 Simple(Option<Ident>, NodeId, NodeId),
2334 /// `use prefix::{...}`
2335 Nested(Vec<(UseTree, NodeId)>),
2340 /// A tree of paths sharing common prefixes.
2341 /// Used in `use` items both at top-level and inside of braces in import groups.
2342 #[derive(Clone, Encodable, Decodable, Debug)]
2343 pub struct UseTree {
2345 pub kind: UseTreeKind,
2350 pub fn ident(&self) -> Ident {
2352 UseTreeKind::Simple(Some(rename), ..) => rename,
2353 UseTreeKind::Simple(None, ..) => {
2354 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2356 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2361 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2362 /// are contained as statements within items. These two cases need to be
2363 /// distinguished for pretty-printing.
2364 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2365 pub enum AttrStyle {
2370 rustc_index::newtype_index! {
2373 DEBUG_FORMAT = "AttrId({})"
2377 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2378 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2383 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2384 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2385 d.read_nil().map(|_| crate::attr::mk_attr_id())
2389 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2390 pub struct AttrItem {
2393 pub tokens: Option<LazyTokenStream>,
2396 /// A list of attributes.
2397 pub type AttrVec = ThinVec<Attribute>;
2399 /// Metadata associated with an item.
2400 #[derive(Clone, Encodable, Decodable, Debug)]
2401 pub struct Attribute {
2404 /// Denotes if the attribute decorates the following construct (outer)
2405 /// or the construct this attribute is contained within (inner).
2406 pub style: AttrStyle,
2410 #[derive(Clone, Encodable, Decodable, Debug)]
2412 /// A normal attribute.
2413 Normal(AttrItem, Option<LazyTokenStream>),
2415 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2416 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2417 /// variant (which is much less compact and thus more expensive).
2418 DocComment(CommentKind, Symbol),
2421 /// `TraitRef`s appear in impls.
2423 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2424 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2425 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2426 /// same as the impl's `NodeId`).
2427 #[derive(Clone, Encodable, Decodable, Debug)]
2428 pub struct TraitRef {
2433 #[derive(Clone, Encodable, Decodable, Debug)]
2434 pub struct PolyTraitRef {
2435 /// The `'a` in `<'a> Foo<&'a T>`.
2436 pub bound_generic_params: Vec<GenericParam>,
2438 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2439 pub trait_ref: TraitRef,
2445 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2447 bound_generic_params: generic_params,
2448 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2454 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2455 pub enum CrateSugar {
2456 /// Source is `pub(crate)`.
2459 /// Source is (just) `crate`.
2463 #[derive(Clone, Encodable, Decodable, Debug)]
2464 pub struct Visibility {
2465 pub kind: VisibilityKind,
2467 pub tokens: Option<LazyTokenStream>,
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 matches!(self, VisibilityKind::Public)
2484 /// Field definition in a struct, variant or union.
2486 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2487 #[derive(Clone, Encodable, Decodable, Debug)]
2488 pub struct FieldDef {
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<FieldDef>, bool),
2508 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2509 Tuple(Vec<FieldDef>, NodeId),
2512 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2517 /// Return the fields of this variant.
2518 pub fn fields(&self) -> &[FieldDef] {
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<LazyTokenStream>,
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)]
2620 pub struct TraitKind(
2625 pub Vec<P<AssocItem>>,
2628 #[derive(Clone, Encodable, Decodable, Debug)]
2629 pub struct TyAliasKind(pub Defaultness, pub Generics, pub GenericBounds, pub Option<P<Ty>>);
2631 #[derive(Clone, Encodable, Decodable, Debug)]
2632 pub struct ImplKind {
2633 pub unsafety: Unsafe,
2634 pub polarity: ImplPolarity,
2635 pub defaultness: Defaultness,
2636 pub constness: Const,
2637 pub generics: Generics,
2639 /// The trait being implemented, if any.
2640 pub of_trait: Option<TraitRef>,
2643 pub items: Vec<P<AssocItem>>,
2646 #[derive(Clone, Encodable, Decodable, Debug)]
2647 pub struct FnKind(pub Defaultness, pub FnSig, pub Generics, pub Option<P<Block>>);
2649 #[derive(Clone, Encodable, Decodable, Debug)]
2651 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2653 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2654 ExternCrate(Option<Symbol>),
2655 /// A use declaration item (`use`).
2657 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2659 /// A static item (`static`).
2661 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2662 Static(P<Ty>, Mutability, Option<P<Expr>>),
2663 /// A constant item (`const`).
2665 /// E.g., `const FOO: i32 = 42;`.
2666 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2667 /// A function declaration (`fn`).
2669 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2671 /// A module declaration (`mod`).
2673 /// E.g., `mod foo;` or `mod foo { .. }`.
2674 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2675 /// semantically by Rust.
2676 Mod(Unsafe, ModKind),
2677 /// An external module (`extern`).
2679 /// E.g., `extern {}` or `extern "C" {}`.
2680 ForeignMod(ForeignMod),
2681 /// Module-level inline assembly (from `global_asm!()`).
2682 GlobalAsm(InlineAsm),
2683 /// A type alias (`type`).
2685 /// E.g., `type Foo = Bar<u8>;`.
2686 TyAlias(Box<TyAliasKind>),
2687 /// An enum definition (`enum`).
2689 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2690 Enum(EnumDef, Generics),
2691 /// A struct definition (`struct`).
2693 /// E.g., `struct Foo<A> { x: A }`.
2694 Struct(VariantData, Generics),
2695 /// A union definition (`union`).
2697 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2698 Union(VariantData, Generics),
2699 /// A trait declaration (`trait`).
2701 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2702 Trait(Box<TraitKind>),
2705 /// E.g., `trait Foo = Bar + Quux;`.
2706 TraitAlias(Generics, GenericBounds),
2707 /// An implementation.
2709 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2710 Impl(Box<ImplKind>),
2711 /// A macro invocation.
2713 /// E.g., `foo!(..)`.
2716 /// A macro definition.
2720 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2721 rustc_data_structures::static_assert_size!(ItemKind, 112);
2724 pub fn article(&self) -> &str {
2727 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2728 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2729 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2733 pub fn descr(&self) -> &str {
2735 ItemKind::ExternCrate(..) => "extern crate",
2736 ItemKind::Use(..) => "`use` import",
2737 ItemKind::Static(..) => "static item",
2738 ItemKind::Const(..) => "constant item",
2739 ItemKind::Fn(..) => "function",
2740 ItemKind::Mod(..) => "module",
2741 ItemKind::ForeignMod(..) => "extern block",
2742 ItemKind::GlobalAsm(..) => "global asm item",
2743 ItemKind::TyAlias(..) => "type alias",
2744 ItemKind::Enum(..) => "enum",
2745 ItemKind::Struct(..) => "struct",
2746 ItemKind::Union(..) => "union",
2747 ItemKind::Trait(..) => "trait",
2748 ItemKind::TraitAlias(..) => "trait alias",
2749 ItemKind::MacCall(..) => "item macro invocation",
2750 ItemKind::MacroDef(..) => "macro definition",
2751 ItemKind::Impl { .. } => "implementation",
2755 pub fn generics(&self) -> Option<&Generics> {
2757 Self::Fn(box FnKind(_, _, generics, _))
2758 | Self::TyAlias(box TyAliasKind(_, generics, ..))
2759 | Self::Enum(_, generics)
2760 | Self::Struct(_, generics)
2761 | Self::Union(_, generics)
2762 | Self::Trait(box TraitKind(_, _, generics, ..))
2763 | Self::TraitAlias(generics, _)
2764 | Self::Impl(box ImplKind { generics, .. }) => Some(generics),
2770 /// Represents associated items.
2771 /// These include items in `impl` and `trait` definitions.
2772 pub type AssocItem = Item<AssocItemKind>;
2774 /// Represents associated item kinds.
2776 /// The term "provided" in the variants below refers to the item having a default
2777 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2778 /// In an implementation, all items must be provided.
2779 /// The `Option`s below denote the bodies, where `Some(_)`
2780 /// means "provided" and conversely `None` means "required".
2781 #[derive(Clone, Encodable, Decodable, Debug)]
2782 pub enum AssocItemKind {
2783 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2784 /// If `def` is parsed, then the constant is provided, and otherwise required.
2785 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2786 /// An associated function.
2788 /// An associated type.
2789 TyAlias(Box<TyAliasKind>),
2790 /// A macro expanding to associated items.
2794 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2795 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2797 impl AssocItemKind {
2798 pub fn defaultness(&self) -> Defaultness {
2800 Self::Const(def, ..)
2801 | Self::Fn(box FnKind(def, ..))
2802 | Self::TyAlias(box TyAliasKind(def, ..)) => def,
2803 Self::MacCall(..) => Defaultness::Final,
2808 impl From<AssocItemKind> for ItemKind {
2809 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2810 match assoc_item_kind {
2811 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2812 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2813 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2814 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2819 impl TryFrom<ItemKind> for AssocItemKind {
2820 type Error = ItemKind;
2822 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2823 Ok(match item_kind {
2824 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2825 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2826 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2827 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2828 _ => return Err(item_kind),
2833 /// An item in `extern` block.
2834 #[derive(Clone, Encodable, Decodable, Debug)]
2835 pub enum ForeignItemKind {
2836 /// A foreign static item (`static FOO: u8`).
2837 Static(P<Ty>, Mutability, Option<P<Expr>>),
2838 /// An foreign function.
2840 /// An foreign type.
2841 TyAlias(Box<TyAliasKind>),
2842 /// A macro expanding to foreign items.
2846 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2847 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
2849 impl From<ForeignItemKind> for ItemKind {
2850 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2851 match foreign_item_kind {
2852 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2853 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2854 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2855 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2860 impl TryFrom<ItemKind> for ForeignItemKind {
2861 type Error = ItemKind;
2863 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2864 Ok(match item_kind {
2865 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2866 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
2867 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
2868 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2869 _ => return Err(item_kind),
2874 pub type ForeignItem = Item<ForeignItemKind>;