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 {
103 fn eq(&self, symbol: &Symbol) -> bool {
104 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
108 impl<CTX> HashStable<CTX> for Path {
109 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
110 self.segments.len().hash_stable(hcx, hasher);
111 for segment in &self.segments {
112 segment.ident.name.hash_stable(hcx, hasher);
118 // Convert a span and an identifier to the corresponding
120 pub fn from_ident(ident: Ident) -> Path {
121 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
124 pub fn is_global(&self) -> bool {
125 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
129 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
131 /// E.g., `std`, `String` or `Box<T>`.
132 #[derive(Clone, Encodable, Decodable, Debug)]
133 pub struct PathSegment {
134 /// The identifier portion of this path segment.
139 /// Type/lifetime parameters attached to this path. They come in
140 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
141 /// `None` means that no parameter list is supplied (`Path`),
142 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
143 /// but it can be empty (`Path<>`).
144 /// `P` is used as a size optimization for the common case with no parameters.
145 pub args: Option<P<GenericArgs>>,
149 pub fn from_ident(ident: Ident) -> Self {
150 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
153 pub fn path_root(span: Span) -> Self {
154 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
157 pub fn span(&self) -> Span {
159 Some(args) => self.ident.span.to(args.span()),
160 None => self.ident.span,
165 /// The arguments of a path segment.
167 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
168 #[derive(Clone, Encodable, Decodable, Debug)]
169 pub enum GenericArgs {
170 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
171 AngleBracketed(AngleBracketedArgs),
172 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
173 Parenthesized(ParenthesizedArgs),
177 pub fn is_angle_bracketed(&self) -> bool {
178 matches!(self, AngleBracketed(..))
181 pub fn span(&self) -> Span {
183 AngleBracketed(ref data) => data.span,
184 Parenthesized(ref data) => data.span,
189 /// Concrete argument in the sequence of generic args.
190 #[derive(Clone, Encodable, Decodable, Debug)]
191 pub enum GenericArg {
192 /// `'a` in `Foo<'a>`
194 /// `Bar` in `Foo<Bar>`
201 pub fn span(&self) -> Span {
203 GenericArg::Lifetime(lt) => lt.ident.span,
204 GenericArg::Type(ty) => ty.span,
205 GenericArg::Const(ct) => ct.value.span,
210 /// A path like `Foo<'a, T>`.
211 #[derive(Clone, Encodable, Decodable, Debug, Default)]
212 pub struct AngleBracketedArgs {
213 /// The overall span.
215 /// The comma separated parts in the `<...>`.
216 pub args: Vec<AngleBracketedArg>,
219 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
220 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
221 #[derive(Clone, Encodable, Decodable, Debug)]
222 pub enum AngleBracketedArg {
223 /// Argument for a generic parameter.
225 /// Constraint for an associated item.
226 Constraint(AssocTyConstraint),
229 impl AngleBracketedArg {
230 pub fn span(&self) -> Span {
232 AngleBracketedArg::Arg(arg) => arg.span(),
233 AngleBracketedArg::Constraint(constraint) => constraint.span,
238 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
239 fn into(self) -> Option<P<GenericArgs>> {
240 Some(P(GenericArgs::AngleBracketed(self)))
244 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
245 fn into(self) -> Option<P<GenericArgs>> {
246 Some(P(GenericArgs::Parenthesized(self)))
250 /// A path like `Foo(A, B) -> C`.
251 #[derive(Clone, Encodable, Decodable, Debug)]
252 pub struct ParenthesizedArgs {
260 pub inputs: Vec<P<Ty>>,
266 pub inputs_span: Span,
272 impl ParenthesizedArgs {
273 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
278 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
280 AngleBracketedArgs { span: self.span, args }
284 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
286 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
288 /// Negative bounds should also be handled here.
289 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
290 pub enum TraitBoundModifier {
302 // This parses but will be rejected during AST validation.
306 /// The AST represents all type param bounds as types.
307 /// `typeck::collect::compute_bounds` matches these against
308 /// the "special" built-in traits (see `middle::lang_items`) and
309 /// detects `Copy`, `Send` and `Sync`.
310 #[derive(Clone, Encodable, Decodable, Debug)]
311 pub enum GenericBound {
312 Trait(PolyTraitRef, TraitBoundModifier),
317 pub fn span(&self) -> Span {
319 GenericBound::Trait(ref t, ..) => t.span,
320 GenericBound::Outlives(ref l) => l.ident.span,
325 pub type GenericBounds = Vec<GenericBound>;
327 /// Specifies the enforced ordering for generic parameters. In the future,
328 /// if we wanted to relax this order, we could override `PartialEq` and
329 /// `PartialOrd`, to allow the kinds to be unordered.
330 #[derive(Hash, Clone, Copy)]
331 pub enum ParamKindOrd {
334 // `unordered` is only `true` if `sess.has_features().const_generics`
335 // is active. Specifically, if it's only `min_const_generics`, it will still require
336 // ordering consts after types.
337 Const { unordered: bool },
340 impl Ord for ParamKindOrd {
341 fn cmp(&self, other: &Self) -> Ordering {
343 let to_int = |v| match v {
345 Type | Const { unordered: true } => 1,
346 // technically both consts should be ordered equally,
347 // but only one is ever encountered at a time, so this is
349 Const { unordered: false } => 2,
352 to_int(*self).cmp(&to_int(*other))
355 impl PartialOrd for ParamKindOrd {
356 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
357 Some(self.cmp(other))
360 impl PartialEq for ParamKindOrd {
361 fn eq(&self, other: &Self) -> bool {
362 self.cmp(other) == Ordering::Equal
365 impl Eq for ParamKindOrd {}
367 impl fmt::Display for ParamKindOrd {
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 ParamKindOrd::Lifetime => "lifetime".fmt(f),
371 ParamKindOrd::Type => "type".fmt(f),
372 ParamKindOrd::Const { .. } => "const".fmt(f),
377 #[derive(Clone, Encodable, Decodable, Debug)]
378 pub enum GenericParamKind {
379 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
382 default: Option<P<Ty>>,
386 /// Span of the `const` keyword.
389 /// Optional default value for the const generic param
390 default: Option<AnonConst>,
394 #[derive(Clone, Encodable, Decodable, Debug)]
395 pub struct GenericParam {
399 pub bounds: GenericBounds,
400 pub is_placeholder: bool,
401 pub kind: GenericParamKind,
404 /// Represents lifetime, type and const parameters attached to a declaration of
405 /// a function, enum, trait, etc.
406 #[derive(Clone, Encodable, Decodable, Debug)]
407 pub struct Generics {
408 pub params: Vec<GenericParam>,
409 pub where_clause: WhereClause,
413 impl Default for Generics {
414 /// Creates an instance of `Generics`.
415 fn default() -> Generics {
418 where_clause: WhereClause {
419 has_where_token: false,
420 predicates: Vec::new(),
428 /// A where-clause in a definition.
429 #[derive(Clone, Encodable, Decodable, Debug)]
430 pub struct WhereClause {
431 /// `true` if we ate a `where` token: this can happen
432 /// if we parsed no predicates (e.g. `struct Foo where {}`).
433 /// This allows us to accurately pretty-print
434 /// in `nt_to_tokenstream`
435 pub has_where_token: bool,
436 pub predicates: Vec<WherePredicate>,
440 /// A single predicate in a where-clause.
441 #[derive(Clone, Encodable, Decodable, Debug)]
442 pub enum WherePredicate {
443 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
444 BoundPredicate(WhereBoundPredicate),
445 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
446 RegionPredicate(WhereRegionPredicate),
447 /// An equality predicate (unsupported).
448 EqPredicate(WhereEqPredicate),
451 impl WherePredicate {
452 pub fn span(&self) -> Span {
454 WherePredicate::BoundPredicate(p) => p.span,
455 WherePredicate::RegionPredicate(p) => p.span,
456 WherePredicate::EqPredicate(p) => p.span,
463 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
464 #[derive(Clone, Encodable, Decodable, Debug)]
465 pub struct WhereBoundPredicate {
467 /// Any generics from a `for` binding.
468 pub bound_generic_params: Vec<GenericParam>,
469 /// The type being bounded.
470 pub bounded_ty: P<Ty>,
471 /// Trait and lifetime bounds (`Clone + Send + 'static`).
472 pub bounds: GenericBounds,
475 /// A lifetime predicate.
477 /// E.g., `'a: 'b + 'c`.
478 #[derive(Clone, Encodable, Decodable, Debug)]
479 pub struct WhereRegionPredicate {
481 pub lifetime: Lifetime,
482 pub bounds: GenericBounds,
485 /// An equality predicate (unsupported).
488 #[derive(Clone, Encodable, Decodable, Debug)]
489 pub struct WhereEqPredicate {
496 #[derive(Clone, Encodable, Decodable, Debug)]
498 pub attrs: Vec<Attribute>,
499 pub items: Vec<P<Item>>,
501 /// The order of items in the HIR is unrelated to the order of
502 /// items in the AST. However, we generate proc macro harnesses
503 /// based on the AST order, and later refer to these harnesses
504 /// from the HIR. This field keeps track of the order in which
505 /// we generated proc macros harnesses, so that we can map
506 /// HIR proc macros items back to their harness items.
507 pub proc_macros: Vec<NodeId>,
510 /// Possible values inside of compile-time attribute lists.
512 /// E.g., the '..' in `#[name(..)]`.
513 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
514 pub enum NestedMetaItem {
515 /// A full MetaItem, for recursive meta items.
519 /// E.g., `"foo"`, `64`, `true`.
523 /// A spanned compile-time attribute item.
525 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
526 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
527 pub struct MetaItem {
529 pub kind: MetaItemKind,
533 /// A compile-time attribute item.
535 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
536 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
537 pub enum MetaItemKind {
540 /// E.g., `test` as in `#[test]`.
544 /// E.g., `derive(..)` as in `#[derive(..)]`.
545 List(Vec<NestedMetaItem>),
546 /// Name value meta item.
548 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
552 /// A block (`{ .. }`).
554 /// E.g., `{ .. }` as in `fn foo() { .. }`.
555 #[derive(Clone, Encodable, Decodable, Debug)]
557 /// The statements in the block.
558 pub stmts: Vec<Stmt>,
560 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
561 pub rules: BlockCheckMode,
563 pub tokens: Option<LazyTokenStream>,
568 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
569 #[derive(Clone, Encodable, Decodable, Debug)]
574 pub tokens: Option<LazyTokenStream>,
578 /// Attempt reparsing the pattern as a type.
579 /// This is intended for use by diagnostics.
580 pub fn to_ty(&self) -> Option<P<Ty>> {
581 let kind = match &self.kind {
582 // In a type expression `_` is an inference variable.
583 PatKind::Wild => TyKind::Infer,
584 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
585 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
586 TyKind::Path(None, Path::from_ident(*ident))
588 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
589 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
590 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
591 PatKind::Ref(pat, mutbl) => {
592 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
594 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
595 // when `P` can be reparsed as a type `T`.
596 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
597 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
598 // assuming `T0` to `Tn` are all syntactically valid as types.
599 PatKind::Tuple(pats) => {
600 let mut tys = Vec::with_capacity(pats.len());
601 // FIXME(#48994) - could just be collected into an Option<Vec>
603 tys.push(pat.to_ty()?);
610 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
613 /// Walk top-down and call `it` in each place where a pattern occurs
614 /// starting with the root pattern `walk` is called on. If `it` returns
615 /// false then we will descend no further but siblings will be processed.
616 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
622 // Walk into the pattern associated with `Ident` (if any).
623 PatKind::Ident(_, _, Some(p)) => p.walk(it),
625 // Walk into each field of struct.
626 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
628 // Sequence of patterns.
629 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
630 s.iter().for_each(|p| p.walk(it))
633 // Trivial wrappers over inner patterns.
634 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
636 // These patterns do not contain subpatterns, skip.
643 | PatKind::MacCall(_) => {}
647 /// Is this a `..` pattern?
648 pub fn is_rest(&self) -> bool {
649 matches!(self.kind, PatKind::Rest)
653 /// A single field in a struct pattern.
655 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
656 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
657 /// except when `is_shorthand` is true.
658 #[derive(Clone, Encodable, Decodable, Debug)]
659 pub struct PatField {
660 /// The identifier for the field.
662 /// The pattern the field is destructured to.
664 pub is_shorthand: bool,
668 pub is_placeholder: bool,
671 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
672 pub enum BindingMode {
677 #[derive(Clone, Encodable, Decodable, Debug)]
679 Included(RangeSyntax),
683 #[derive(Clone, Encodable, Decodable, Debug)]
684 pub enum RangeSyntax {
691 #[derive(Clone, Encodable, Decodable, Debug)]
693 /// Represents a wildcard pattern (`_`).
696 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
697 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
698 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
699 /// during name resolution.
700 Ident(BindingMode, Ident, Option<P<Pat>>),
702 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
703 /// The `bool` is `true` in the presence of a `..`.
704 Struct(Path, Vec<PatField>, /* recovered */ bool),
706 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
707 TupleStruct(Path, Vec<P<Pat>>),
709 /// An or-pattern `A | B | C`.
710 /// Invariant: `pats.len() >= 2`.
713 /// A possibly qualified path pattern.
714 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
715 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
716 /// only legally refer to associated constants.
717 Path(Option<QSelf>, Path),
719 /// A tuple pattern (`(a, b)`).
725 /// A reference pattern (e.g., `&mut (a, b)`).
726 Ref(P<Pat>, Mutability),
731 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
732 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
734 /// A slice pattern `[a, b, c]`.
737 /// A rest pattern `..`.
739 /// Syntactically it is valid anywhere.
741 /// Semantically however, it only has meaning immediately inside:
742 /// - a slice pattern: `[a, .., b]`,
743 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
744 /// - a tuple pattern: `(a, .., b)`,
745 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
747 /// In all of these cases, an additional restriction applies,
748 /// only one rest pattern may occur in the pattern sequences.
751 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
754 /// A macro pattern; pre-expansion.
758 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
759 #[derive(HashStable_Generic, Encodable, Decodable)]
760 pub enum Mutability {
766 /// Returns `MutMutable` only if both `self` and `other` are mutable.
767 pub fn and(self, other: Self) -> Self {
769 Mutability::Mut => other,
770 Mutability::Not => Mutability::Not,
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)]
1027 pub attrs: Vec<Attribute>,
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 {
1259 pub fields: Vec<ExprField>,
1260 pub rest: StructRest,
1263 #[derive(Clone, Encodable, Decodable, Debug)]
1265 /// A `box x` expression.
1267 /// An array (`[a, b, c, d]`)
1268 Array(Vec<P<Expr>>),
1269 /// Allow anonymous constants from an inline `const` block
1270 ConstBlock(AnonConst),
1273 /// The first field resolves to the function itself,
1274 /// and the second field is the list of arguments.
1275 /// This also represents calling the constructor of
1276 /// tuple-like ADTs such as tuple structs and enum variants.
1277 Call(P<Expr>, Vec<P<Expr>>),
1278 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1280 /// The `PathSegment` represents the method name and its generic arguments
1281 /// (within the angle brackets).
1282 /// The first element of the vector of an `Expr` is the expression that evaluates
1283 /// to the object on which the method is being called on (the receiver),
1284 /// and the remaining elements are the rest of the arguments.
1285 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1286 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1287 /// This `Span` is the span of the function, without the dot and receiver
1288 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1289 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1290 /// A tuple (e.g., `(a, b, c, d)`).
1292 /// A binary operation (e.g., `a + b`, `a * b`).
1293 Binary(BinOp, P<Expr>, P<Expr>),
1294 /// A unary operation (e.g., `!x`, `*x`).
1295 Unary(UnOp, P<Expr>),
1296 /// A literal (e.g., `1`, `"foo"`).
1298 /// A cast (e.g., `foo as f64`).
1299 Cast(P<Expr>, P<Ty>),
1300 /// A type ascription (e.g., `42: usize`).
1301 Type(P<Expr>, P<Ty>),
1302 /// A `let pat = expr` expression that is only semantically allowed in the condition
1303 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1304 Let(P<Pat>, P<Expr>),
1305 /// An `if` block, with an optional `else` block.
1307 /// `if expr { block } else { expr }`
1308 If(P<Expr>, P<Block>, Option<P<Expr>>),
1309 /// A while loop, with an optional label.
1311 /// `'label: while expr { block }`
1312 While(P<Expr>, P<Block>, Option<Label>),
1313 /// A `for` loop, with an optional label.
1315 /// `'label: for pat in expr { block }`
1317 /// This is desugared to a combination of `loop` and `match` expressions.
1318 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1319 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1321 /// `'label: loop { block }`
1322 Loop(P<Block>, Option<Label>),
1323 /// A `match` block.
1324 Match(P<Expr>, Vec<Arm>),
1325 /// A closure (e.g., `move |a, b, c| a + b + c`).
1327 /// The final span is the span of the argument block `|...|`.
1328 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1329 /// A block (`'label: { ... }`).
1330 Block(P<Block>, Option<Label>),
1331 /// An async block (`async move { ... }`).
1333 /// The `NodeId` is the `NodeId` for the closure that results from
1334 /// desugaring an async block, just like the NodeId field in the
1335 /// `Async::Yes` variant. This is necessary in order to create a def for the
1336 /// closure which can be used as a parent of any child defs. Defs
1337 /// created during lowering cannot be made the parent of any other
1338 /// preexisting defs.
1339 Async(CaptureBy, NodeId, P<Block>),
1340 /// An await expression (`my_future.await`).
1343 /// A try block (`try { ... }`).
1346 /// An assignment (`a = foo()`).
1347 /// The `Span` argument is the span of the `=` token.
1348 Assign(P<Expr>, P<Expr>, Span),
1349 /// An assignment with an operator.
1352 AssignOp(BinOp, P<Expr>, P<Expr>),
1353 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1354 Field(P<Expr>, Ident),
1355 /// An indexing operation (e.g., `foo[2]`).
1356 Index(P<Expr>, P<Expr>),
1357 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assingment).
1358 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1359 /// An underscore, used in destructuring assignment to ignore a value.
1362 /// Variable reference, possibly containing `::` and/or type
1363 /// parameters (e.g., `foo::bar::<baz>`).
1365 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1366 Path(Option<QSelf>, Path),
1368 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1369 AddrOf(BorrowKind, Mutability, P<Expr>),
1370 /// A `break`, with an optional label to break, and an optional expression.
1371 Break(Option<Label>, Option<P<Expr>>),
1372 /// A `continue`, with an optional label.
1373 Continue(Option<Label>),
1374 /// A `return`, with an optional value to be returned.
1375 Ret(Option<P<Expr>>),
1377 /// Output of the `asm!()` macro.
1378 InlineAsm(P<InlineAsm>),
1379 /// Output of the `llvm_asm!()` macro.
1380 LlvmInlineAsm(P<LlvmInlineAsm>),
1382 /// A macro invocation; pre-expansion.
1385 /// A struct literal expression.
1387 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1388 Struct(P<StructExpr>),
1390 /// An array literal constructed from one repeated element.
1392 /// E.g., `[1; 5]`. The expression is the element to be
1393 /// repeated; the constant is the number of times to repeat it.
1394 Repeat(P<Expr>, AnonConst),
1396 /// No-op: used solely so we can pretty-print faithfully.
1399 /// A try expression (`expr?`).
1402 /// A `yield`, with an optional value to be yielded.
1403 Yield(Option<P<Expr>>),
1405 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1409 /// The explicit `Self` type in a "qualified path". The actual
1410 /// path, including the trait and the associated item, is stored
1411 /// separately. `position` represents the index of the associated
1412 /// item qualified with this `Self` type.
1414 /// ```ignore (only-for-syntax-highlight)
1415 /// <Vec<T> as a::b::Trait>::AssociatedItem
1416 /// ^~~~~ ~~~~~~~~~~~~~~^
1419 /// <Vec<T>>::AssociatedItem
1423 #[derive(Clone, Encodable, Decodable, Debug)]
1427 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1428 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1429 /// 0`, this is an empty span.
1430 pub path_span: Span,
1431 pub position: usize,
1434 /// A capture clause used in closures and `async` blocks.
1435 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1436 pub enum CaptureBy {
1437 /// `move |x| y + x`.
1439 /// `move` keyword was not specified.
1443 /// The movability of a generator / closure literal:
1444 /// whether a generator contains self-references, causing it to be `!Unpin`.
1445 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1446 #[derive(HashStable_Generic)]
1447 pub enum Movability {
1448 /// May contain self-references, `!Unpin`.
1450 /// Must not contain self-references, `Unpin`.
1454 /// Represents a macro invocation. The `path` indicates which macro
1455 /// is being invoked, and the `args` are arguments passed to it.
1456 #[derive(Clone, Encodable, Decodable, Debug)]
1457 pub struct MacCall {
1459 pub args: P<MacArgs>,
1460 pub prior_type_ascription: Option<(Span, bool)>,
1464 pub fn span(&self) -> Span {
1465 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1469 /// Arguments passed to an attribute or a function-like macro.
1470 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1472 /// No arguments - `#[attr]`.
1474 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1475 Delimited(DelimSpan, MacDelimiter, TokenStream),
1476 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1478 /// Span of the `=` token.
1480 /// "value" as a nonterminal token.
1486 pub fn delim(&self) -> DelimToken {
1488 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1489 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1493 pub fn span(&self) -> Option<Span> {
1495 MacArgs::Empty => None,
1496 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1497 MacArgs::Eq(eq_span, token) => Some(eq_span.to(token.span)),
1501 /// Tokens inside the delimiters or after `=`.
1502 /// Proc macros see these tokens, for example.
1503 pub fn inner_tokens(&self) -> TokenStream {
1505 MacArgs::Empty => TokenStream::default(),
1506 MacArgs::Delimited(.., tokens) => tokens.clone(),
1507 MacArgs::Eq(.., token) => TokenTree::Token(token.clone()).into(),
1511 /// Whether a macro with these arguments needs a semicolon
1512 /// when used as a standalone item or statement.
1513 pub fn need_semicolon(&self) -> bool {
1514 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1518 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1519 pub enum MacDelimiter {
1526 pub fn to_token(self) -> DelimToken {
1528 MacDelimiter::Parenthesis => DelimToken::Paren,
1529 MacDelimiter::Bracket => DelimToken::Bracket,
1530 MacDelimiter::Brace => DelimToken::Brace,
1534 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1536 token::Paren => Some(MacDelimiter::Parenthesis),
1537 token::Bracket => Some(MacDelimiter::Bracket),
1538 token::Brace => Some(MacDelimiter::Brace),
1539 token::NoDelim => None,
1544 /// Represents a macro definition.
1545 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1546 pub struct MacroDef {
1547 pub body: P<MacArgs>,
1548 /// `true` if macro was defined with `macro_rules`.
1549 pub macro_rules: bool,
1552 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1553 #[derive(HashStable_Generic)]
1555 /// A regular string, like `"foo"`.
1557 /// A raw string, like `r##"foo"##`.
1559 /// The value is the number of `#` symbols used.
1564 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1566 /// The original literal token as written in source code.
1567 pub token: token::Lit,
1568 /// The "semantic" representation of the literal lowered from the original tokens.
1569 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1570 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1575 /// Same as `Lit`, but restricted to string literals.
1576 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1578 /// The original literal token as written in source code.
1579 pub style: StrStyle,
1581 pub suffix: Option<Symbol>,
1583 /// The unescaped "semantic" representation of the literal lowered from the original token.
1584 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1585 pub symbol_unescaped: Symbol,
1589 pub fn as_lit(&self) -> Lit {
1590 let token_kind = match self.style {
1591 StrStyle::Cooked => token::Str,
1592 StrStyle::Raw(n) => token::StrRaw(n),
1595 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1597 kind: LitKind::Str(self.symbol_unescaped, self.style),
1602 /// Type of the integer literal based on provided suffix.
1603 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1604 #[derive(HashStable_Generic)]
1605 pub enum LitIntType {
1614 /// Type of the float literal based on provided suffix.
1615 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1616 #[derive(HashStable_Generic)]
1617 pub enum LitFloatType {
1618 /// A float literal with a suffix (`1f32` or `1E10f32`).
1620 /// A float literal without a suffix (`1.0 or 1.0E10`).
1626 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1627 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1629 /// A string literal (`"foo"`).
1630 Str(Symbol, StrStyle),
1631 /// A byte string (`b"foo"`).
1633 /// A byte char (`b'f'`).
1635 /// A character literal (`'a'`).
1637 /// An integer literal (`1`).
1638 Int(u128, LitIntType),
1639 /// A float literal (`1f64` or `1E10f64`).
1640 Float(Symbol, LitFloatType),
1641 /// A boolean literal.
1643 /// Placeholder for a literal that wasn't well-formed in some way.
1648 /// Returns `true` if this literal is a string.
1649 pub fn is_str(&self) -> bool {
1650 matches!(self, LitKind::Str(..))
1653 /// Returns `true` if this literal is byte literal string.
1654 pub fn is_bytestr(&self) -> bool {
1655 matches!(self, LitKind::ByteStr(_))
1658 /// Returns `true` if this is a numeric literal.
1659 pub fn is_numeric(&self) -> bool {
1660 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1663 /// Returns `true` if this literal has no suffix.
1664 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1665 pub fn is_unsuffixed(&self) -> bool {
1669 /// Returns `true` if this literal has a suffix.
1670 pub fn is_suffixed(&self) -> bool {
1672 // suffixed variants
1673 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1674 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1675 // unsuffixed variants
1677 | LitKind::ByteStr(..)
1680 | LitKind::Int(_, LitIntType::Unsuffixed)
1681 | LitKind::Float(_, LitFloatType::Unsuffixed)
1683 | LitKind::Err(..) => false,
1688 // N.B., If you change this, you'll probably want to change the corresponding
1689 // type structure in `middle/ty.rs` as well.
1690 #[derive(Clone, Encodable, Decodable, Debug)]
1693 pub mutbl: Mutability,
1696 /// Represents a function's signature in a trait declaration,
1697 /// trait implementation, or free function.
1698 #[derive(Clone, Encodable, Decodable, Debug)]
1700 pub header: FnHeader,
1701 pub decl: P<FnDecl>,
1705 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1706 #[derive(Encodable, Decodable, HashStable_Generic)]
1713 pub fn name_str(self) -> &'static str {
1715 FloatTy::F32 => "f32",
1716 FloatTy::F64 => "f64",
1720 pub fn name(self) -> Symbol {
1722 FloatTy::F32 => sym::f32,
1723 FloatTy::F64 => sym::f64,
1727 pub fn bit_width(self) -> u64 {
1735 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1736 #[derive(Encodable, Decodable, HashStable_Generic)]
1747 pub fn name_str(&self) -> &'static str {
1749 IntTy::Isize => "isize",
1751 IntTy::I16 => "i16",
1752 IntTy::I32 => "i32",
1753 IntTy::I64 => "i64",
1754 IntTy::I128 => "i128",
1758 pub fn name(&self) -> Symbol {
1760 IntTy::Isize => sym::isize,
1761 IntTy::I8 => sym::i8,
1762 IntTy::I16 => sym::i16,
1763 IntTy::I32 => sym::i32,
1764 IntTy::I64 => sym::i64,
1765 IntTy::I128 => sym::i128,
1769 pub fn bit_width(&self) -> Option<u64> {
1771 IntTy::Isize => return None,
1780 pub fn normalize(&self, target_width: u32) -> Self {
1782 IntTy::Isize => match target_width {
1786 _ => unreachable!(),
1793 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1794 #[derive(Encodable, Decodable, HashStable_Generic)]
1805 pub fn name_str(&self) -> &'static str {
1807 UintTy::Usize => "usize",
1809 UintTy::U16 => "u16",
1810 UintTy::U32 => "u32",
1811 UintTy::U64 => "u64",
1812 UintTy::U128 => "u128",
1816 pub fn name(&self) -> Symbol {
1818 UintTy::Usize => sym::usize,
1819 UintTy::U8 => sym::u8,
1820 UintTy::U16 => sym::u16,
1821 UintTy::U32 => sym::u32,
1822 UintTy::U64 => sym::u64,
1823 UintTy::U128 => sym::u128,
1827 pub fn bit_width(&self) -> Option<u64> {
1829 UintTy::Usize => return None,
1834 UintTy::U128 => 128,
1838 pub fn normalize(&self, target_width: u32) -> Self {
1840 UintTy::Usize => match target_width {
1844 _ => unreachable!(),
1851 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1852 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1853 #[derive(Clone, Encodable, Decodable, Debug)]
1854 pub struct AssocTyConstraint {
1857 pub gen_args: Option<GenericArgs>,
1858 pub kind: AssocTyConstraintKind,
1862 /// The kinds of an `AssocTyConstraint`.
1863 #[derive(Clone, Encodable, Decodable, Debug)]
1864 pub enum AssocTyConstraintKind {
1865 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1866 Equality { ty: P<Ty> },
1867 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1868 Bound { bounds: GenericBounds },
1871 #[derive(Encodable, Decodable, Debug)]
1876 pub tokens: Option<LazyTokenStream>,
1880 fn clone(&self) -> Self {
1881 ensure_sufficient_stack(|| Self {
1883 kind: self.kind.clone(),
1885 tokens: self.tokens.clone(),
1891 pub fn peel_refs(&self) -> &Self {
1892 let mut final_ty = self;
1893 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1900 #[derive(Clone, Encodable, Decodable, Debug)]
1901 pub struct BareFnTy {
1902 pub unsafety: Unsafe,
1904 pub generic_params: Vec<GenericParam>,
1905 pub decl: P<FnDecl>,
1908 /// The various kinds of type recognized by the compiler.
1909 #[derive(Clone, Encodable, Decodable, Debug)]
1911 /// A variable-length slice (`[T]`).
1913 /// A fixed length array (`[T; n]`).
1914 Array(P<Ty>, AnonConst),
1915 /// A raw pointer (`*const T` or `*mut T`).
1917 /// A reference (`&'a T` or `&'a mut T`).
1918 Rptr(Option<Lifetime>, MutTy),
1919 /// A bare function (e.g., `fn(usize) -> bool`).
1920 BareFn(P<BareFnTy>),
1921 /// The never type (`!`).
1923 /// A tuple (`(A, B, C, D,...)`).
1925 /// A path (`module::module::...::Type`), optionally
1926 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1928 /// Type parameters are stored in the `Path` itself.
1929 Path(Option<QSelf>, Path),
1930 /// A trait object type `Bound1 + Bound2 + Bound3`
1931 /// where `Bound` is a trait or a lifetime.
1932 TraitObject(GenericBounds, TraitObjectSyntax),
1933 /// An `impl Bound1 + Bound2 + Bound3` type
1934 /// where `Bound` is a trait or a lifetime.
1936 /// The `NodeId` exists to prevent lowering from having to
1937 /// generate `NodeId`s on the fly, which would complicate
1938 /// the generation of opaque `type Foo = impl Trait` items significantly.
1939 ImplTrait(NodeId, GenericBounds),
1940 /// No-op; kept solely so that we can pretty-print faithfully.
1944 /// This means the type should be inferred instead of it having been
1945 /// specified. This can appear anywhere in a type.
1947 /// Inferred type of a `self` or `&self` argument in a method.
1949 /// A macro in the type position.
1951 /// Placeholder for a kind that has failed to be defined.
1953 /// Placeholder for a `va_list`.
1958 pub fn is_implicit_self(&self) -> bool {
1959 matches!(self, TyKind::ImplicitSelf)
1962 pub fn is_unit(&self) -> bool {
1963 matches!(self, TyKind::Tup(tys) if tys.is_empty())
1967 /// Syntax used to declare a trait object.
1968 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1969 pub enum TraitObjectSyntax {
1974 /// Inline assembly operand explicit register or register class.
1976 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1977 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1978 pub enum InlineAsmRegOrRegClass {
1983 bitflags::bitflags! {
1984 #[derive(Encodable, Decodable, HashStable_Generic)]
1985 pub struct InlineAsmOptions: u8 {
1986 const PURE = 1 << 0;
1987 const NOMEM = 1 << 1;
1988 const READONLY = 1 << 2;
1989 const PRESERVES_FLAGS = 1 << 3;
1990 const NORETURN = 1 << 4;
1991 const NOSTACK = 1 << 5;
1992 const ATT_SYNTAX = 1 << 6;
1996 #[derive(Clone, PartialEq, PartialOrd, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
1997 pub enum InlineAsmTemplatePiece {
1999 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2002 impl fmt::Display for InlineAsmTemplatePiece {
2003 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2005 Self::String(s) => {
2006 for c in s.chars() {
2008 '{' => f.write_str("{{")?,
2009 '}' => f.write_str("}}")?,
2015 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2016 write!(f, "{{{}:{}}}", operand_idx, modifier)
2018 Self::Placeholder { operand_idx, modifier: None, .. } => {
2019 write!(f, "{{{}}}", operand_idx)
2025 impl InlineAsmTemplatePiece {
2026 /// Rebuilds the asm template string from its pieces.
2027 pub fn to_string(s: &[Self]) -> String {
2029 let mut out = String::new();
2031 let _ = write!(out, "{}", p);
2037 /// Inline assembly operand.
2039 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2040 #[derive(Clone, Encodable, Decodable, Debug)]
2041 pub enum InlineAsmOperand {
2043 reg: InlineAsmRegOrRegClass,
2047 reg: InlineAsmRegOrRegClass,
2049 expr: Option<P<Expr>>,
2052 reg: InlineAsmRegOrRegClass,
2057 reg: InlineAsmRegOrRegClass,
2060 out_expr: Option<P<Expr>>,
2070 /// Inline assembly.
2072 /// E.g., `asm!("NOP");`.
2073 #[derive(Clone, Encodable, Decodable, Debug)]
2074 pub struct InlineAsm {
2075 pub template: Vec<InlineAsmTemplatePiece>,
2076 pub operands: Vec<(InlineAsmOperand, Span)>,
2077 pub options: InlineAsmOptions,
2078 pub line_spans: Vec<Span>,
2081 /// Inline assembly dialect.
2083 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2084 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Hash, HashStable_Generic)]
2085 pub enum LlvmAsmDialect {
2090 /// LLVM-style inline assembly.
2092 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2093 #[derive(Clone, Encodable, Decodable, Debug)]
2094 pub struct LlvmInlineAsmOutput {
2095 pub constraint: Symbol,
2098 pub is_indirect: bool,
2101 /// LLVM-style inline assembly.
2103 /// E.g., `llvm_asm!("NOP");`.
2104 #[derive(Clone, Encodable, Decodable, Debug)]
2105 pub struct LlvmInlineAsm {
2107 pub asm_str_style: StrStyle,
2108 pub outputs: Vec<LlvmInlineAsmOutput>,
2109 pub inputs: Vec<(Symbol, P<Expr>)>,
2110 pub clobbers: Vec<Symbol>,
2112 pub alignstack: bool,
2113 pub dialect: LlvmAsmDialect,
2116 /// A parameter in a function header.
2118 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2119 #[derive(Clone, Encodable, Decodable, Debug)]
2126 pub is_placeholder: bool,
2129 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2131 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2132 #[derive(Clone, Encodable, Decodable, Debug)]
2134 /// `self`, `mut self`
2136 /// `&'lt self`, `&'lt mut self`
2137 Region(Option<Lifetime>, Mutability),
2138 /// `self: TYPE`, `mut self: TYPE`
2139 Explicit(P<Ty>, Mutability),
2142 pub type ExplicitSelf = Spanned<SelfKind>;
2145 /// Attempts to cast parameter to `ExplicitSelf`.
2146 pub fn to_self(&self) -> Option<ExplicitSelf> {
2147 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2148 if ident.name == kw::SelfLower {
2149 return match self.ty.kind {
2150 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2151 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2152 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2155 self.pat.span.to(self.ty.span),
2156 SelfKind::Explicit(self.ty.clone(), mutbl),
2164 /// Returns `true` if parameter is `self`.
2165 pub fn is_self(&self) -> bool {
2166 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2167 ident.name == kw::SelfLower
2173 /// Builds a `Param` object from `ExplicitSelf`.
2174 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2175 let span = eself.span.to(eself_ident.span);
2176 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2177 let param = |mutbl, ty| Param {
2181 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2188 is_placeholder: false,
2191 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2192 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2193 SelfKind::Region(lt, mutbl) => param(
2197 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2206 /// A signature (not the body) of a function declaration.
2208 /// E.g., `fn foo(bar: baz)`.
2210 /// Please note that it's different from `FnHeader` structure
2211 /// which contains metadata about function safety, asyncness, constness and ABI.
2212 #[derive(Clone, Encodable, Decodable, Debug)]
2214 pub inputs: Vec<Param>,
2215 pub output: FnRetTy,
2219 pub fn get_self(&self) -> Option<ExplicitSelf> {
2220 self.inputs.get(0).and_then(Param::to_self)
2222 pub fn has_self(&self) -> bool {
2223 self.inputs.get(0).map_or(false, Param::is_self)
2225 pub fn c_variadic(&self) -> bool {
2226 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2230 /// Is the trait definition an auto trait?
2231 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2237 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2238 #[derive(HashStable_Generic)]
2244 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2246 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2251 pub fn is_async(self) -> bool {
2252 matches!(self, Async::Yes { .. })
2255 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2256 pub fn opt_return_id(self) -> Option<NodeId> {
2258 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2264 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2265 #[derive(HashStable_Generic)]
2271 /// Item defaultness.
2272 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2273 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2274 pub enum Defaultness {
2279 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2280 pub enum ImplPolarity {
2281 /// `impl Trait for Type`
2283 /// `impl !Trait for Type`
2287 impl fmt::Debug for ImplPolarity {
2288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2290 ImplPolarity::Positive => "positive".fmt(f),
2291 ImplPolarity::Negative(_) => "negative".fmt(f),
2296 #[derive(Clone, Encodable, Decodable, Debug)]
2298 /// Returns type is not specified.
2300 /// Functions default to `()` and closures default to inference.
2301 /// Span points to where return type would be inserted.
2303 /// Everything else.
2308 pub fn span(&self) -> Span {
2310 FnRetTy::Default(span) => span,
2311 FnRetTy::Ty(ref ty) => ty.span,
2316 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2322 /// Module item kind.
2323 #[derive(Clone, Encodable, Decodable, Debug)]
2325 /// Module with inlined definition `mod foo { ... }`,
2326 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2327 /// The inner span is from the first token past `{` to the last token until `}`,
2328 /// or from the first to the last token in the loaded file.
2329 Loaded(Vec<P<Item>>, Inline, Span),
2330 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2334 /// Foreign module declaration.
2336 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2337 #[derive(Clone, Encodable, Decodable, Debug)]
2338 pub struct ForeignMod {
2339 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2340 /// semantically by Rust.
2341 pub unsafety: Unsafe,
2342 pub abi: Option<StrLit>,
2343 pub items: Vec<P<ForeignItem>>,
2346 /// Global inline assembly.
2348 /// Also known as "module-level assembly" or "file-scoped assembly".
2349 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2350 pub struct GlobalAsm {
2354 #[derive(Clone, Encodable, Decodable, Debug)]
2355 pub struct EnumDef {
2356 pub variants: Vec<Variant>,
2359 #[derive(Clone, Encodable, Decodable, Debug)]
2360 pub struct Variant {
2361 /// Attributes of the variant.
2362 pub attrs: Vec<Attribute>,
2363 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2367 /// The visibility of the variant. Syntactically accepted but not semantically.
2368 pub vis: Visibility,
2369 /// Name of the variant.
2372 /// Fields and constructor id of the variant.
2373 pub data: VariantData,
2374 /// Explicit discriminant, e.g., `Foo = 1`.
2375 pub disr_expr: Option<AnonConst>,
2376 /// Is a macro placeholder
2377 pub is_placeholder: bool,
2380 /// Part of `use` item to the right of its prefix.
2381 #[derive(Clone, Encodable, Decodable, Debug)]
2382 pub enum UseTreeKind {
2383 /// `use prefix` or `use prefix as rename`
2385 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2387 Simple(Option<Ident>, NodeId, NodeId),
2388 /// `use prefix::{...}`
2389 Nested(Vec<(UseTree, NodeId)>),
2394 /// A tree of paths sharing common prefixes.
2395 /// Used in `use` items both at top-level and inside of braces in import groups.
2396 #[derive(Clone, Encodable, Decodable, Debug)]
2397 pub struct UseTree {
2399 pub kind: UseTreeKind,
2404 pub fn ident(&self) -> Ident {
2406 UseTreeKind::Simple(Some(rename), ..) => rename,
2407 UseTreeKind::Simple(None, ..) => {
2408 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2410 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2415 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2416 /// are contained as statements within items. These two cases need to be
2417 /// distinguished for pretty-printing.
2418 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2419 pub enum AttrStyle {
2424 rustc_index::newtype_index! {
2427 DEBUG_FORMAT = "AttrId({})"
2431 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2432 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2437 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2438 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2439 d.read_nil().map(|_| crate::attr::mk_attr_id())
2443 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2444 pub struct AttrItem {
2447 pub tokens: Option<LazyTokenStream>,
2450 /// A list of attributes.
2451 pub type AttrVec = ThinVec<Attribute>;
2453 /// Metadata associated with an item.
2454 #[derive(Clone, Encodable, Decodable, Debug)]
2455 pub struct Attribute {
2458 /// Denotes if the attribute decorates the following construct (outer)
2459 /// or the construct this attribute is contained within (inner).
2460 pub style: AttrStyle,
2464 #[derive(Clone, Encodable, Decodable, Debug)]
2466 /// A normal attribute.
2467 Normal(AttrItem, Option<LazyTokenStream>),
2469 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2470 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2471 /// variant (which is much less compact and thus more expensive).
2472 DocComment(CommentKind, Symbol),
2475 /// `TraitRef`s appear in impls.
2477 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2478 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2479 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2480 /// same as the impl's `NodeId`).
2481 #[derive(Clone, Encodable, Decodable, Debug)]
2482 pub struct TraitRef {
2487 #[derive(Clone, Encodable, Decodable, Debug)]
2488 pub struct PolyTraitRef {
2489 /// The `'a` in `<'a> Foo<&'a T>`.
2490 pub bound_generic_params: Vec<GenericParam>,
2492 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2493 pub trait_ref: TraitRef,
2499 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2501 bound_generic_params: generic_params,
2502 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2508 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2509 pub enum CrateSugar {
2510 /// Source is `pub(crate)`.
2513 /// Source is (just) `crate`.
2517 #[derive(Clone, Encodable, Decodable, Debug)]
2518 pub struct Visibility {
2519 pub kind: VisibilityKind,
2521 pub tokens: Option<LazyTokenStream>,
2524 #[derive(Clone, Encodable, Decodable, Debug)]
2525 pub enum VisibilityKind {
2528 Restricted { path: P<Path>, id: NodeId },
2532 impl VisibilityKind {
2533 pub fn is_pub(&self) -> bool {
2534 matches!(self, VisibilityKind::Public)
2538 /// Field definition in a struct, variant or union.
2540 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2541 #[derive(Clone, Encodable, Decodable, Debug)]
2542 pub struct FieldDef {
2543 pub attrs: Vec<Attribute>,
2546 pub vis: Visibility,
2547 pub ident: Option<Ident>,
2550 pub is_placeholder: bool,
2553 /// Fields and constructor ids of enum variants and structs.
2554 #[derive(Clone, Encodable, Decodable, Debug)]
2555 pub enum VariantData {
2558 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2559 Struct(Vec<FieldDef>, bool),
2562 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2563 Tuple(Vec<FieldDef>, NodeId),
2566 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2571 /// Return the fields of this variant.
2572 pub fn fields(&self) -> &[FieldDef] {
2574 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2579 /// Return the `NodeId` of this variant's constructor, if it has one.
2580 pub fn ctor_id(&self) -> Option<NodeId> {
2582 VariantData::Struct(..) => None,
2583 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2588 /// An item definition.
2589 #[derive(Clone, Encodable, Decodable, Debug)]
2590 pub struct Item<K = ItemKind> {
2591 pub attrs: Vec<Attribute>,
2594 pub vis: Visibility,
2595 /// The name of the item.
2596 /// It might be a dummy name in case of anonymous items.
2601 /// Original tokens this item was parsed from. This isn't necessarily
2602 /// available for all items, although over time more and more items should
2603 /// have this be `Some`. Right now this is primarily used for procedural
2604 /// macros, notably custom attributes.
2606 /// Note that the tokens here do not include the outer attributes, but will
2607 /// include inner attributes.
2608 pub tokens: Option<LazyTokenStream>,
2612 /// Return the span that encompasses the attributes.
2613 pub fn span_with_attributes(&self) -> Span {
2614 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2618 impl<K: Into<ItemKind>> Item<K> {
2619 pub fn into_item(self) -> Item {
2620 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2621 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2625 /// `extern` qualifier on a function item or function type.
2626 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2634 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2635 abi.map_or(Extern::Implicit, Extern::Explicit)
2639 /// A function header.
2641 /// All the information between the visibility and the name of the function is
2642 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2643 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2644 pub struct FnHeader {
2645 pub unsafety: Unsafe,
2646 pub asyncness: Async,
2647 pub constness: Const,
2652 /// Does this function header have any qualifiers or is it empty?
2653 pub fn has_qualifiers(&self) -> bool {
2654 let Self { unsafety, asyncness, constness, ext } = self;
2655 matches!(unsafety, Unsafe::Yes(_))
2656 || asyncness.is_async()
2657 || matches!(constness, Const::Yes(_))
2658 || !matches!(ext, Extern::None)
2662 impl Default for FnHeader {
2663 fn default() -> FnHeader {
2665 unsafety: Unsafe::No,
2666 asyncness: Async::No,
2667 constness: Const::No,
2673 #[derive(Clone, Encodable, Decodable, Debug)]
2674 pub struct TraitKind(
2679 pub Vec<P<AssocItem>>,
2682 #[derive(Clone, Encodable, Decodable, Debug)]
2683 pub struct TyAliasKind(pub Defaultness, pub Generics, pub GenericBounds, pub Option<P<Ty>>);
2685 #[derive(Clone, Encodable, Decodable, Debug)]
2686 pub struct ImplKind {
2687 pub unsafety: Unsafe,
2688 pub polarity: ImplPolarity,
2689 pub defaultness: Defaultness,
2690 pub constness: Const,
2691 pub generics: Generics,
2693 /// The trait being implemented, if any.
2694 pub of_trait: Option<TraitRef>,
2697 pub items: Vec<P<AssocItem>>,
2700 #[derive(Clone, Encodable, Decodable, Debug)]
2701 pub struct FnKind(pub Defaultness, pub FnSig, pub Generics, pub Option<P<Block>>);
2703 #[derive(Clone, Encodable, Decodable, Debug)]
2705 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2707 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2708 ExternCrate(Option<Symbol>),
2709 /// A use declaration item (`use`).
2711 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2713 /// A static item (`static`).
2715 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2716 Static(P<Ty>, Mutability, Option<P<Expr>>),
2717 /// A constant item (`const`).
2719 /// E.g., `const FOO: i32 = 42;`.
2720 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2721 /// A function declaration (`fn`).
2723 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2725 /// A module declaration (`mod`).
2727 /// E.g., `mod foo;` or `mod foo { .. }`.
2728 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2729 /// semantically by Rust.
2730 Mod(Unsafe, ModKind),
2731 /// An external module (`extern`).
2733 /// E.g., `extern {}` or `extern "C" {}`.
2734 ForeignMod(ForeignMod),
2735 /// Module-level inline assembly (from `global_asm!()`).
2736 GlobalAsm(GlobalAsm),
2737 /// A type alias (`type`).
2739 /// E.g., `type Foo = Bar<u8>;`.
2740 TyAlias(Box<TyAliasKind>),
2741 /// An enum definition (`enum`).
2743 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2744 Enum(EnumDef, Generics),
2745 /// A struct definition (`struct`).
2747 /// E.g., `struct Foo<A> { x: A }`.
2748 Struct(VariantData, Generics),
2749 /// A union definition (`union`).
2751 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2752 Union(VariantData, Generics),
2753 /// A trait declaration (`trait`).
2755 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2756 Trait(Box<TraitKind>),
2759 /// E.g., `trait Foo = Bar + Quux;`.
2760 TraitAlias(Generics, GenericBounds),
2761 /// An implementation.
2763 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2764 Impl(Box<ImplKind>),
2765 /// A macro invocation.
2767 /// E.g., `foo!(..)`.
2770 /// A macro definition.
2774 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2775 rustc_data_structures::static_assert_size!(ItemKind, 112);
2778 pub fn article(&self) -> &str {
2781 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2782 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2783 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2787 pub fn descr(&self) -> &str {
2789 ItemKind::ExternCrate(..) => "extern crate",
2790 ItemKind::Use(..) => "`use` import",
2791 ItemKind::Static(..) => "static item",
2792 ItemKind::Const(..) => "constant item",
2793 ItemKind::Fn(..) => "function",
2794 ItemKind::Mod(..) => "module",
2795 ItemKind::ForeignMod(..) => "extern block",
2796 ItemKind::GlobalAsm(..) => "global asm item",
2797 ItemKind::TyAlias(..) => "type alias",
2798 ItemKind::Enum(..) => "enum",
2799 ItemKind::Struct(..) => "struct",
2800 ItemKind::Union(..) => "union",
2801 ItemKind::Trait(..) => "trait",
2802 ItemKind::TraitAlias(..) => "trait alias",
2803 ItemKind::MacCall(..) => "item macro invocation",
2804 ItemKind::MacroDef(..) => "macro definition",
2805 ItemKind::Impl { .. } => "implementation",
2809 pub fn generics(&self) -> Option<&Generics> {
2811 Self::Fn(box FnKind(_, _, generics, _))
2812 | Self::TyAlias(box TyAliasKind(_, generics, ..))
2813 | Self::Enum(_, generics)
2814 | Self::Struct(_, generics)
2815 | Self::Union(_, generics)
2816 | Self::Trait(box TraitKind(_, _, generics, ..))
2817 | Self::TraitAlias(generics, _)
2818 | Self::Impl(box ImplKind { generics, .. }) => Some(generics),
2824 /// Represents associated items.
2825 /// These include items in `impl` and `trait` definitions.
2826 pub type AssocItem = Item<AssocItemKind>;
2828 /// Represents associated item kinds.
2830 /// The term "provided" in the variants below refers to the item having a default
2831 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2832 /// In an implementation, all items must be provided.
2833 /// The `Option`s below denote the bodies, where `Some(_)`
2834 /// means "provided" and conversely `None` means "required".
2835 #[derive(Clone, Encodable, Decodable, Debug)]
2836 pub enum AssocItemKind {
2837 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2838 /// If `def` is parsed, then the constant is provided, and otherwise required.
2839 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2840 /// An associated function.
2842 /// An associated type.
2843 TyAlias(Box<TyAliasKind>),
2844 /// A macro expanding to associated items.
2848 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2849 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2851 impl AssocItemKind {
2852 pub fn defaultness(&self) -> Defaultness {
2854 Self::Const(def, ..)
2855 | Self::Fn(box FnKind(def, ..))
2856 | Self::TyAlias(box TyAliasKind(def, ..)) => def,
2857 Self::MacCall(..) => Defaultness::Final,
2862 impl From<AssocItemKind> for ItemKind {
2863 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2864 match assoc_item_kind {
2865 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2866 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2867 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2868 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2873 impl TryFrom<ItemKind> for AssocItemKind {
2874 type Error = ItemKind;
2876 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2877 Ok(match item_kind {
2878 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2879 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2880 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2881 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2882 _ => return Err(item_kind),
2887 /// An item in `extern` block.
2888 #[derive(Clone, Encodable, Decodable, Debug)]
2889 pub enum ForeignItemKind {
2890 /// A foreign static item (`static FOO: u8`).
2891 Static(P<Ty>, Mutability, Option<P<Expr>>),
2892 /// An foreign function.
2894 /// An foreign type.
2895 TyAlias(Box<TyAliasKind>),
2896 /// A macro expanding to foreign items.
2900 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2901 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
2903 impl From<ForeignItemKind> for ItemKind {
2904 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2905 match foreign_item_kind {
2906 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2907 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2908 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2909 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2914 impl TryFrom<ItemKind> for ForeignItemKind {
2915 type Error = ItemKind;
2917 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2918 Ok(match item_kind {
2919 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2920 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
2921 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
2922 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2923 _ => return Err(item_kind),
2928 pub type ForeignItem = Item<ForeignItemKind>;