1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
26 use crate::token::{self, CommentKind, DelimToken};
27 use crate::tokenstream::{DelimSpan, 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;
47 /// A "Label" is an identifier of some point in sources,
48 /// e.g. in the following code:
56 /// `'outer` is a label.
57 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
62 impl fmt::Debug for Label {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "label({:?})", self.ident)
68 /// A "Lifetime" is an annotation of the scope in which variable
69 /// can be used, e.g. `'a` in `&'a i32`.
70 #[derive(Clone, Encodable, Decodable, Copy)]
76 impl fmt::Debug for Lifetime {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "lifetime({}: {})", self.id, self)
82 impl fmt::Display for Lifetime {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 write!(f, "{}", self.ident.name)
88 /// A "Path" is essentially Rust's notion of a name.
90 /// It's represented as a sequence of identifiers,
91 /// along with a bunch of supporting information.
93 /// E.g., `std::cmp::PartialEq`.
94 #[derive(Clone, Encodable, Decodable, Debug)]
97 /// The segments in the path: the things separated by `::`.
98 /// Global paths begin with `kw::PathRoot`.
99 pub segments: Vec<PathSegment>,
100 pub tokens: Option<LazyTokenStream>,
103 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 }
153 pub fn path_root(span: Span) -> Self {
154 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
158 /// The arguments of a path segment.
160 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
161 #[derive(Clone, Encodable, Decodable, Debug)]
162 pub enum GenericArgs {
163 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
164 AngleBracketed(AngleBracketedArgs),
165 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
166 Parenthesized(ParenthesizedArgs),
170 pub fn is_angle_bracketed(&self) -> bool {
172 AngleBracketed(..) => true,
177 pub fn span(&self) -> Span {
179 AngleBracketed(ref data) => data.span,
180 Parenthesized(ref data) => data.span,
185 /// Concrete argument in the sequence of generic args.
186 #[derive(Clone, Encodable, Decodable, Debug)]
187 pub enum GenericArg {
188 /// `'a` in `Foo<'a>`
190 /// `Bar` in `Foo<Bar>`
197 pub fn span(&self) -> Span {
199 GenericArg::Lifetime(lt) => lt.ident.span,
200 GenericArg::Type(ty) => ty.span,
201 GenericArg::Const(ct) => ct.value.span,
206 /// A path like `Foo<'a, T>`.
207 #[derive(Clone, Encodable, Decodable, Debug, Default)]
208 pub struct AngleBracketedArgs {
209 /// The overall span.
211 /// The comma separated parts in the `<...>`.
212 pub args: Vec<AngleBracketedArg>,
215 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
216 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
217 #[derive(Clone, Encodable, Decodable, Debug)]
218 pub enum AngleBracketedArg {
219 /// Argument for a generic parameter.
221 /// Constraint for an associated item.
222 Constraint(AssocTyConstraint),
225 impl AngleBracketedArg {
226 pub fn span(&self) -> Span {
228 AngleBracketedArg::Arg(arg) => arg.span(),
229 AngleBracketedArg::Constraint(constraint) => constraint.span,
234 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
235 fn into(self) -> Option<P<GenericArgs>> {
236 Some(P(GenericArgs::AngleBracketed(self)))
240 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
241 fn into(self) -> Option<P<GenericArgs>> {
242 Some(P(GenericArgs::Parenthesized(self)))
246 /// A path like `Foo(A, B) -> C`.
247 #[derive(Clone, Encodable, Decodable, Debug)]
248 pub struct ParenthesizedArgs {
253 pub inputs: Vec<P<Ty>>,
259 impl ParenthesizedArgs {
260 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
265 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
267 AngleBracketedArgs { span: self.span, args }
271 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
273 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
275 /// Negative bounds should also be handled here.
276 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
277 pub enum TraitBoundModifier {
289 // This parses but will be rejected during AST validation.
293 /// The AST represents all type param bounds as types.
294 /// `typeck::collect::compute_bounds` matches these against
295 /// the "special" built-in traits (see `middle::lang_items`) and
296 /// detects `Copy`, `Send` and `Sync`.
297 #[derive(Clone, Encodable, Decodable, Debug)]
298 pub enum GenericBound {
299 Trait(PolyTraitRef, TraitBoundModifier),
304 pub fn span(&self) -> Span {
306 GenericBound::Trait(ref t, ..) => t.span,
307 GenericBound::Outlives(ref l) => l.ident.span,
312 pub type GenericBounds = Vec<GenericBound>;
314 /// Specifies the enforced ordering for generic parameters. In the future,
315 /// if we wanted to relax this order, we could override `PartialEq` and
316 /// `PartialOrd`, to allow the kinds to be unordered.
317 #[derive(Hash, Clone, Copy)]
318 pub enum ParamKindOrd {
321 // `unordered` is only `true` if `sess.has_features().const_generics`
322 // is active. Specifically, if it's only `min_const_generics`, it will still require
323 // ordering consts after types.
324 Const { unordered: bool },
327 impl Ord for ParamKindOrd {
328 fn cmp(&self, other: &Self) -> Ordering {
330 let to_int = |v| match v {
332 Type | Const { unordered: true } => 1,
333 // technically both consts should be ordered equally,
334 // but only one is ever encountered at a time, so this is
336 Const { unordered: false } => 2,
339 to_int(*self).cmp(&to_int(*other))
342 impl PartialOrd for ParamKindOrd {
343 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
344 Some(self.cmp(other))
347 impl PartialEq for ParamKindOrd {
348 fn eq(&self, other: &Self) -> bool {
349 self.cmp(other) == Ordering::Equal
352 impl Eq for ParamKindOrd {}
354 impl fmt::Display for ParamKindOrd {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357 ParamKindOrd::Lifetime => "lifetime".fmt(f),
358 ParamKindOrd::Type => "type".fmt(f),
359 ParamKindOrd::Const { .. } => "const".fmt(f),
364 #[derive(Clone, Encodable, Decodable, Debug)]
365 pub enum GenericParamKind {
366 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
369 default: Option<P<Ty>>,
373 /// Span of the `const` keyword.
378 #[derive(Clone, Encodable, Decodable, Debug)]
379 pub struct GenericParam {
383 pub bounds: GenericBounds,
384 pub is_placeholder: bool,
385 pub kind: GenericParamKind,
388 /// Represents lifetime, type and const parameters attached to a declaration of
389 /// a function, enum, trait, etc.
390 #[derive(Clone, Encodable, Decodable, Debug)]
391 pub struct Generics {
392 pub params: Vec<GenericParam>,
393 pub where_clause: WhereClause,
397 impl Default for Generics {
398 /// Creates an instance of `Generics`.
399 fn default() -> Generics {
402 where_clause: WhereClause {
403 has_where_token: false,
404 predicates: Vec::new(),
412 /// A where-clause in a definition.
413 #[derive(Clone, Encodable, Decodable, Debug)]
414 pub struct WhereClause {
415 /// `true` if we ate a `where` token: this can happen
416 /// if we parsed no predicates (e.g. `struct Foo where {}`).
417 /// This allows us to accurately pretty-print
418 /// in `nt_to_tokenstream`
419 pub has_where_token: bool,
420 pub predicates: Vec<WherePredicate>,
424 /// A single predicate in a where-clause.
425 #[derive(Clone, Encodable, Decodable, Debug)]
426 pub enum WherePredicate {
427 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
428 BoundPredicate(WhereBoundPredicate),
429 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
430 RegionPredicate(WhereRegionPredicate),
431 /// An equality predicate (unsupported).
432 EqPredicate(WhereEqPredicate),
435 impl WherePredicate {
436 pub fn span(&self) -> Span {
438 &WherePredicate::BoundPredicate(ref p) => p.span,
439 &WherePredicate::RegionPredicate(ref p) => p.span,
440 &WherePredicate::EqPredicate(ref p) => p.span,
447 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
448 #[derive(Clone, Encodable, Decodable, Debug)]
449 pub struct WhereBoundPredicate {
451 /// Any generics from a `for` binding.
452 pub bound_generic_params: Vec<GenericParam>,
453 /// The type being bounded.
454 pub bounded_ty: P<Ty>,
455 /// Trait and lifetime bounds (`Clone + Send + 'static`).
456 pub bounds: GenericBounds,
459 /// A lifetime predicate.
461 /// E.g., `'a: 'b + 'c`.
462 #[derive(Clone, Encodable, Decodable, Debug)]
463 pub struct WhereRegionPredicate {
465 pub lifetime: Lifetime,
466 pub bounds: GenericBounds,
469 /// An equality predicate (unsupported).
472 #[derive(Clone, Encodable, Decodable, Debug)]
473 pub struct WhereEqPredicate {
480 #[derive(Clone, Encodable, Decodable, Debug)]
483 pub attrs: Vec<Attribute>,
485 /// The order of items in the HIR is unrelated to the order of
486 /// items in the AST. However, we generate proc macro harnesses
487 /// based on the AST order, and later refer to these harnesses
488 /// from the HIR. This field keeps track of the order in which
489 /// we generated proc macros harnesses, so that we can map
490 /// HIR proc macros items back to their harness items.
491 pub proc_macros: Vec<NodeId>,
494 /// Possible values inside of compile-time attribute lists.
496 /// E.g., the '..' in `#[name(..)]`.
497 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
498 pub enum NestedMetaItem {
499 /// A full MetaItem, for recursive meta items.
503 /// E.g., `"foo"`, `64`, `true`.
507 /// A spanned compile-time attribute item.
509 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
510 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
511 pub struct MetaItem {
513 pub kind: MetaItemKind,
517 /// A compile-time attribute item.
519 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
520 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
521 pub enum MetaItemKind {
524 /// E.g., `test` as in `#[test]`.
528 /// E.g., `derive(..)` as in `#[derive(..)]`.
529 List(Vec<NestedMetaItem>),
530 /// Name value meta item.
532 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
536 /// A block (`{ .. }`).
538 /// E.g., `{ .. }` as in `fn foo() { .. }`.
539 #[derive(Clone, Encodable, Decodable, Debug)]
541 /// The statements in the block.
542 pub stmts: Vec<Stmt>,
544 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
545 pub rules: BlockCheckMode,
547 pub tokens: Option<LazyTokenStream>,
552 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
553 #[derive(Clone, Encodable, Decodable, Debug)]
558 pub tokens: Option<LazyTokenStream>,
562 /// Attempt reparsing the pattern as a type.
563 /// This is intended for use by diagnostics.
564 pub fn to_ty(&self) -> Option<P<Ty>> {
565 let kind = match &self.kind {
566 // In a type expression `_` is an inference variable.
567 PatKind::Wild => TyKind::Infer,
568 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
569 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
570 TyKind::Path(None, Path::from_ident(*ident))
572 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
573 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
574 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
575 PatKind::Ref(pat, mutbl) => {
576 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
578 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
579 // when `P` can be reparsed as a type `T`.
580 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
581 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
582 // assuming `T0` to `Tn` are all syntactically valid as types.
583 PatKind::Tuple(pats) => {
584 let mut tys = Vec::with_capacity(pats.len());
585 // FIXME(#48994) - could just be collected into an Option<Vec>
587 tys.push(pat.to_ty()?);
594 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
597 /// Walk top-down and call `it` in each place where a pattern occurs
598 /// starting with the root pattern `walk` is called on. If `it` returns
599 /// false then we will descend no further but siblings will be processed.
600 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
606 // Walk into the pattern associated with `Ident` (if any).
607 PatKind::Ident(_, _, Some(p)) => p.walk(it),
609 // Walk into each field of struct.
610 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
612 // Sequence of patterns.
613 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
614 s.iter().for_each(|p| p.walk(it))
617 // Trivial wrappers over inner patterns.
618 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
620 // These patterns do not contain subpatterns, skip.
627 | PatKind::MacCall(_) => {}
631 /// Is this a `..` pattern?
632 pub fn is_rest(&self) -> bool {
634 PatKind::Rest => true,
640 /// A single field in a struct pattern
642 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
643 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
644 /// except is_shorthand is true
645 #[derive(Clone, Encodable, Decodable, Debug)]
646 pub struct FieldPat {
647 /// The identifier for the field
649 /// The pattern the field is destructured to
651 pub is_shorthand: bool,
655 pub is_placeholder: bool,
658 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
659 pub enum BindingMode {
664 #[derive(Clone, Encodable, Decodable, Debug)]
666 Included(RangeSyntax),
670 #[derive(Clone, Encodable, Decodable, Debug)]
671 pub enum RangeSyntax {
678 #[derive(Clone, Encodable, Decodable, Debug)]
680 /// Represents a wildcard pattern (`_`).
683 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
684 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
685 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
686 /// during name resolution.
687 Ident(BindingMode, Ident, Option<P<Pat>>),
689 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
690 /// The `bool` is `true` in the presence of a `..`.
691 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
693 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
694 TupleStruct(Path, Vec<P<Pat>>),
696 /// An or-pattern `A | B | C`.
697 /// Invariant: `pats.len() >= 2`.
700 /// A possibly qualified path pattern.
701 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
702 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
703 /// only legally refer to associated constants.
704 Path(Option<QSelf>, Path),
706 /// A tuple pattern (`(a, b)`).
712 /// A reference pattern (e.g., `&mut (a, b)`).
713 Ref(P<Pat>, Mutability),
718 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
719 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
721 /// A slice pattern `[a, b, c]`.
724 /// A rest pattern `..`.
726 /// Syntactically it is valid anywhere.
728 /// Semantically however, it only has meaning immediately inside:
729 /// - a slice pattern: `[a, .., b]`,
730 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
731 /// - a tuple pattern: `(a, .., b)`,
732 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
734 /// In all of these cases, an additional restriction applies,
735 /// only one rest pattern may occur in the pattern sequences.
738 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
741 /// A macro pattern; pre-expansion.
745 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
746 #[derive(HashStable_Generic, Encodable, Decodable)]
747 pub enum Mutability {
753 /// Returns `MutMutable` only if both `self` and `other` are mutable.
754 pub fn and(self, other: Self) -> Self {
756 Mutability::Mut => other,
757 Mutability::Not => Mutability::Not,
761 pub fn invert(self) -> Self {
763 Mutability::Mut => Mutability::Not,
764 Mutability::Not => Mutability::Mut,
768 pub fn prefix_str(&self) -> &'static str {
770 Mutability::Mut => "mut ",
771 Mutability::Not => "",
776 /// The kind of borrow in an `AddrOf` expression,
777 /// e.g., `&place` or `&raw const place`.
778 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
779 #[derive(Encodable, Decodable, HashStable_Generic)]
780 pub enum BorrowKind {
781 /// A normal borrow, `&$expr` or `&mut $expr`.
782 /// The resulting type is either `&'a T` or `&'a mut T`
783 /// where `T = typeof($expr)` and `'a` is some lifetime.
785 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
786 /// The resulting type is either `*const T` or `*mut T`
787 /// where `T = typeof($expr)`.
791 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
793 /// The `+` operator (addition)
795 /// The `-` operator (subtraction)
797 /// The `*` operator (multiplication)
799 /// The `/` operator (division)
801 /// The `%` operator (modulus)
803 /// The `&&` operator (logical and)
805 /// The `||` operator (logical or)
807 /// The `^` operator (bitwise xor)
809 /// The `&` operator (bitwise and)
811 /// The `|` operator (bitwise or)
813 /// The `<<` operator (shift left)
815 /// The `>>` operator (shift right)
817 /// The `==` operator (equality)
819 /// The `<` operator (less than)
821 /// The `<=` operator (less than or equal to)
823 /// The `!=` operator (not equal to)
825 /// The `>=` operator (greater than or equal to)
827 /// The `>` operator (greater than)
832 pub fn to_string(&self) -> &'static str {
855 pub fn lazy(&self) -> bool {
857 BinOpKind::And | BinOpKind::Or => true,
862 pub fn is_comparison(&self) -> bool {
864 // Note for developers: please keep this as is;
865 // we want compilation to fail if another variant is added.
867 Eq | Lt | Le | Ne | Gt | Ge => true,
868 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
873 pub type BinOp = Spanned<BinOpKind>;
877 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
878 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
880 /// The `*` operator for dereferencing
882 /// The `!` operator for logical inversion
884 /// The `-` operator for negation
889 pub fn to_string(op: UnOp) -> &'static str {
899 #[derive(Clone, Encodable, Decodable, Debug)]
904 pub tokens: Option<LazyTokenStream>,
908 pub fn has_trailing_semicolon(&self) -> bool {
910 StmtKind::Semi(_) => true,
911 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
915 pub fn add_trailing_semicolon(mut self) -> Self {
916 self.kind = match self.kind {
917 StmtKind::Expr(expr) => StmtKind::Semi(expr),
918 StmtKind::MacCall(mac) => {
919 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs }| MacCallStmt {
921 style: MacStmtStyle::Semicolon,
930 pub fn is_item(&self) -> bool {
932 StmtKind::Item(_) => true,
937 pub fn is_expr(&self) -> bool {
939 StmtKind::Expr(_) => true,
945 #[derive(Clone, Encodable, Decodable, Debug)]
947 /// A local (let) binding.
949 /// An item definition.
951 /// Expr without trailing semi-colon.
953 /// Expr with a trailing semi-colon.
955 /// Just a trailing semi-colon.
958 MacCall(P<MacCallStmt>),
961 #[derive(Clone, Encodable, Decodable, Debug)]
962 pub struct MacCallStmt {
964 pub style: MacStmtStyle,
968 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
969 pub enum MacStmtStyle {
970 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
971 /// `foo!(...);`, `foo![...];`).
973 /// The macro statement had braces (e.g., `foo! { ... }`).
975 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
976 /// `foo!(...)`). All of these will end up being converted into macro
981 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
982 #[derive(Clone, Encodable, Decodable, Debug)]
986 pub ty: Option<P<Ty>>,
987 /// Initializer expression to set the value, if any.
988 pub init: Option<P<Expr>>,
993 /// An arm of a 'match'.
995 /// E.g., `0..=10 => { println!("match!") }` as in
999 /// 0..=10 => { println!("match!") },
1000 /// _ => { println!("no match!") },
1003 #[derive(Clone, Encodable, Decodable, Debug)]
1005 pub attrs: Vec<Attribute>,
1006 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1008 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1009 pub guard: Option<P<Expr>>,
1014 pub is_placeholder: bool,
1017 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1018 #[derive(Clone, Encodable, Decodable, Debug)]
1025 pub is_shorthand: bool,
1026 pub is_placeholder: bool,
1029 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1030 pub enum BlockCheckMode {
1032 Unsafe(UnsafeSource),
1035 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1036 pub enum UnsafeSource {
1041 /// A constant (expression) that's not an item or associated item,
1042 /// but needs its own `DefId` for type-checking, const-eval, etc.
1043 /// These are usually found nested inside types (e.g., array lengths)
1044 /// or expressions (e.g., repeat counts), and also used to define
1045 /// explicit discriminant values for enum variants.
1046 #[derive(Clone, Encodable, Decodable, Debug)]
1047 pub struct AnonConst {
1053 #[derive(Clone, Encodable, Decodable, Debug)]
1059 pub tokens: Option<LazyTokenStream>,
1062 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1063 #[cfg(target_arch = "x86_64")]
1064 rustc_data_structures::static_assert_size!(Expr, 120);
1067 /// Returns `true` if this expression would be valid somewhere that expects a value;
1068 /// for example, an `if` condition.
1069 pub fn returns(&self) -> bool {
1070 if let ExprKind::Block(ref block, _) = self.kind {
1071 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1073 Some(&StmtKind::Expr(_)) => true,
1074 Some(&StmtKind::Semi(ref expr)) => {
1075 if let ExprKind::Ret(_) = expr.kind {
1076 // Last statement is explicit return.
1082 // This is a block that doesn't end in either an implicit or explicit return.
1086 // This is not a block, it is a value.
1091 /// Is this expr either `N`, or `{ N }`.
1093 /// If this is not the case, name resolution does not resolve `N` when using
1094 /// `feature(min_const_generics)` as more complex expressions are not supported.
1095 pub fn is_potential_trivial_const_param(&self) -> bool {
1096 let this = if let ExprKind::Block(ref block, None) = self.kind {
1097 if block.stmts.len() == 1 {
1098 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1106 if let ExprKind::Path(None, ref path) = this.kind {
1107 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1115 pub fn to_bound(&self) -> Option<GenericBound> {
1117 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1118 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1119 TraitBoundModifier::None,
1125 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1126 pub fn to_ty(&self) -> Option<P<Ty>> {
1127 let kind = match &self.kind {
1128 // Trivial conversions.
1129 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1130 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1132 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1134 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1135 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1138 ExprKind::Repeat(expr, expr_len) => {
1139 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1142 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1144 ExprKind::Tup(exprs) => {
1145 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1149 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1150 // then type of result is trait object.
1151 // Otherwise we don't assume the result type.
1152 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1153 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1154 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1160 // This expression doesn't look like a type syntactically.
1164 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1167 pub fn precedence(&self) -> ExprPrecedence {
1169 ExprKind::Box(_) => ExprPrecedence::Box,
1170 ExprKind::Array(_) => ExprPrecedence::Array,
1171 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1172 ExprKind::Call(..) => ExprPrecedence::Call,
1173 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1174 ExprKind::Tup(_) => ExprPrecedence::Tup,
1175 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1176 ExprKind::Unary(..) => ExprPrecedence::Unary,
1177 ExprKind::Lit(_) => ExprPrecedence::Lit,
1178 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1179 ExprKind::Let(..) => ExprPrecedence::Let,
1180 ExprKind::If(..) => ExprPrecedence::If,
1181 ExprKind::While(..) => ExprPrecedence::While,
1182 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1183 ExprKind::Loop(..) => ExprPrecedence::Loop,
1184 ExprKind::Match(..) => ExprPrecedence::Match,
1185 ExprKind::Closure(..) => ExprPrecedence::Closure,
1186 ExprKind::Block(..) => ExprPrecedence::Block,
1187 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1188 ExprKind::Async(..) => ExprPrecedence::Async,
1189 ExprKind::Await(..) => ExprPrecedence::Await,
1190 ExprKind::Assign(..) => ExprPrecedence::Assign,
1191 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1192 ExprKind::Field(..) => ExprPrecedence::Field,
1193 ExprKind::Index(..) => ExprPrecedence::Index,
1194 ExprKind::Range(..) => ExprPrecedence::Range,
1195 ExprKind::Path(..) => ExprPrecedence::Path,
1196 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1197 ExprKind::Break(..) => ExprPrecedence::Break,
1198 ExprKind::Continue(..) => ExprPrecedence::Continue,
1199 ExprKind::Ret(..) => ExprPrecedence::Ret,
1200 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1201 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1202 ExprKind::Struct(..) => ExprPrecedence::Struct,
1203 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1204 ExprKind::Paren(..) => ExprPrecedence::Paren,
1205 ExprKind::Try(..) => ExprPrecedence::Try,
1206 ExprKind::Yield(..) => ExprPrecedence::Yield,
1207 ExprKind::Err => ExprPrecedence::Err,
1212 /// Limit types of a range (inclusive or exclusive)
1213 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1214 pub enum RangeLimits {
1215 /// Inclusive at the beginning, exclusive at the end
1217 /// Inclusive at the beginning and end
1221 #[derive(Clone, Encodable, Decodable, Debug)]
1222 pub enum StructRest {
1227 /// No trailing `..` or expression.
1231 #[derive(Clone, Encodable, Decodable, Debug)]
1233 /// A `box x` expression.
1235 /// An array (`[a, b, c, d]`)
1236 Array(Vec<P<Expr>>),
1237 /// Allow anonymous constants from an inline `const` block
1238 ConstBlock(AnonConst),
1241 /// The first field resolves to the function itself,
1242 /// and the second field is the list of arguments.
1243 /// This also represents calling the constructor of
1244 /// tuple-like ADTs such as tuple structs and enum variants.
1245 Call(P<Expr>, Vec<P<Expr>>),
1246 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1248 /// The `PathSegment` represents the method name and its generic arguments
1249 /// (within the angle brackets).
1250 /// The first element of the vector of an `Expr` is the expression that evaluates
1251 /// to the object on which the method is being called on (the receiver),
1252 /// and the remaining elements are the rest of the arguments.
1253 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1254 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1255 /// This `Span` is the span of the function, without the dot and receiver
1256 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1257 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1258 /// A tuple (e.g., `(a, b, c, d)`).
1260 /// A binary operation (e.g., `a + b`, `a * b`).
1261 Binary(BinOp, P<Expr>, P<Expr>),
1262 /// A unary operation (e.g., `!x`, `*x`).
1263 Unary(UnOp, P<Expr>),
1264 /// A literal (e.g., `1`, `"foo"`).
1266 /// A cast (e.g., `foo as f64`).
1267 Cast(P<Expr>, P<Ty>),
1268 /// A type ascription (e.g., `42: usize`).
1269 Type(P<Expr>, P<Ty>),
1270 /// A `let pat = expr` expression that is only semantically allowed in the condition
1271 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1272 Let(P<Pat>, P<Expr>),
1273 /// An `if` block, with an optional `else` block.
1275 /// `if expr { block } else { expr }`
1276 If(P<Expr>, P<Block>, Option<P<Expr>>),
1277 /// A while loop, with an optional label.
1279 /// `'label: while expr { block }`
1280 While(P<Expr>, P<Block>, Option<Label>),
1281 /// A `for` loop, with an optional label.
1283 /// `'label: for pat in expr { block }`
1285 /// This is desugared to a combination of `loop` and `match` expressions.
1286 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1287 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1289 /// `'label: loop { block }`
1290 Loop(P<Block>, Option<Label>),
1291 /// A `match` block.
1292 Match(P<Expr>, Vec<Arm>),
1293 /// A closure (e.g., `move |a, b, c| a + b + c`).
1295 /// The final span is the span of the argument block `|...|`.
1296 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1297 /// A block (`'label: { ... }`).
1298 Block(P<Block>, Option<Label>),
1299 /// An async block (`async move { ... }`).
1301 /// The `NodeId` is the `NodeId` for the closure that results from
1302 /// desugaring an async block, just like the NodeId field in the
1303 /// `Async::Yes` variant. This is necessary in order to create a def for the
1304 /// closure which can be used as a parent of any child defs. Defs
1305 /// created during lowering cannot be made the parent of any other
1306 /// preexisting defs.
1307 Async(CaptureBy, NodeId, P<Block>),
1308 /// An await expression (`my_future.await`).
1311 /// A try block (`try { ... }`).
1314 /// An assignment (`a = foo()`).
1315 /// The `Span` argument is the span of the `=` token.
1316 Assign(P<Expr>, P<Expr>, Span),
1317 /// An assignment with an operator.
1320 AssignOp(BinOp, P<Expr>, P<Expr>),
1321 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1322 Field(P<Expr>, Ident),
1323 /// An indexing operation (e.g., `foo[2]`).
1324 Index(P<Expr>, P<Expr>),
1325 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assingment).
1326 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1328 /// Variable reference, possibly containing `::` and/or type
1329 /// parameters (e.g., `foo::bar::<baz>`).
1331 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1332 Path(Option<QSelf>, Path),
1334 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1335 AddrOf(BorrowKind, Mutability, P<Expr>),
1336 /// A `break`, with an optional label to break, and an optional expression.
1337 Break(Option<Label>, Option<P<Expr>>),
1338 /// A `continue`, with an optional label.
1339 Continue(Option<Label>),
1340 /// A `return`, with an optional value to be returned.
1341 Ret(Option<P<Expr>>),
1343 /// Output of the `asm!()` macro.
1344 InlineAsm(P<InlineAsm>),
1345 /// Output of the `llvm_asm!()` macro.
1346 LlvmInlineAsm(P<LlvmInlineAsm>),
1348 /// A macro invocation; pre-expansion.
1351 /// A struct literal expression.
1353 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1354 Struct(Path, Vec<Field>, StructRest),
1356 /// An array literal constructed from one repeated element.
1358 /// E.g., `[1; 5]`. The expression is the element to be
1359 /// repeated; the constant is the number of times to repeat it.
1360 Repeat(P<Expr>, AnonConst),
1362 /// No-op: used solely so we can pretty-print faithfully.
1365 /// A try expression (`expr?`).
1368 /// A `yield`, with an optional value to be yielded.
1369 Yield(Option<P<Expr>>),
1371 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1375 /// The explicit `Self` type in a "qualified path". The actual
1376 /// path, including the trait and the associated item, is stored
1377 /// separately. `position` represents the index of the associated
1378 /// item qualified with this `Self` type.
1380 /// ```ignore (only-for-syntax-highlight)
1381 /// <Vec<T> as a::b::Trait>::AssociatedItem
1382 /// ^~~~~ ~~~~~~~~~~~~~~^
1385 /// <Vec<T>>::AssociatedItem
1389 #[derive(Clone, Encodable, Decodable, Debug)]
1393 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1394 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1395 /// 0`, this is an empty span.
1396 pub path_span: Span,
1397 pub position: usize,
1400 /// A capture clause used in closures and `async` blocks.
1401 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1402 pub enum CaptureBy {
1403 /// `move |x| y + x`.
1405 /// `move` keyword was not specified.
1409 /// The movability of a generator / closure literal:
1410 /// whether a generator contains self-references, causing it to be `!Unpin`.
1411 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1412 #[derive(HashStable_Generic)]
1413 pub enum Movability {
1414 /// May contain self-references, `!Unpin`.
1416 /// Must not contain self-references, `Unpin`.
1420 /// Represents a macro invocation. The `path` indicates which macro
1421 /// is being invoked, and the `args` are arguments passed to it.
1422 #[derive(Clone, Encodable, Decodable, Debug)]
1423 pub struct MacCall {
1425 pub args: P<MacArgs>,
1426 pub prior_type_ascription: Option<(Span, bool)>,
1430 pub fn span(&self) -> Span {
1431 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1435 /// Arguments passed to an attribute or a function-like macro.
1436 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1438 /// No arguments - `#[attr]`.
1440 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1441 Delimited(DelimSpan, MacDelimiter, TokenStream),
1442 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1444 /// Span of the `=` token.
1446 /// Token stream of the "value".
1452 pub fn delim(&self) -> DelimToken {
1454 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1455 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1459 pub fn span(&self) -> Option<Span> {
1461 MacArgs::Empty => None,
1462 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1463 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1467 /// Tokens inside the delimiters or after `=`.
1468 /// Proc macros see these tokens, for example.
1469 pub fn inner_tokens(&self) -> TokenStream {
1471 MacArgs::Empty => TokenStream::default(),
1472 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1476 /// Tokens together with the delimiters or `=`.
1477 /// Use of this method generally means that something suboptimal or hacky is happening.
1478 pub fn outer_tokens(&self) -> TokenStream {
1480 MacArgs::Empty => TokenStream::default(),
1481 MacArgs::Delimited(dspan, delim, ref tokens) => {
1482 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1484 MacArgs::Eq(eq_span, ref tokens) => {
1485 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1490 /// Whether a macro with these arguments needs a semicolon
1491 /// when used as a standalone item or statement.
1492 pub fn need_semicolon(&self) -> bool {
1493 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1497 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1498 pub enum MacDelimiter {
1505 pub fn to_token(self) -> DelimToken {
1507 MacDelimiter::Parenthesis => DelimToken::Paren,
1508 MacDelimiter::Bracket => DelimToken::Bracket,
1509 MacDelimiter::Brace => DelimToken::Brace,
1513 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1515 token::Paren => Some(MacDelimiter::Parenthesis),
1516 token::Bracket => Some(MacDelimiter::Bracket),
1517 token::Brace => Some(MacDelimiter::Brace),
1518 token::NoDelim => None,
1523 /// Represents a macro definition.
1524 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1525 pub struct MacroDef {
1526 pub body: P<MacArgs>,
1527 /// `true` if macro was defined with `macro_rules`.
1528 pub macro_rules: bool,
1531 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1532 #[derive(HashStable_Generic)]
1534 /// A regular string, like `"foo"`.
1536 /// A raw string, like `r##"foo"##`.
1538 /// The value is the number of `#` symbols used.
1543 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1545 /// The original literal token as written in source code.
1546 pub token: token::Lit,
1547 /// The "semantic" representation of the literal lowered from the original tokens.
1548 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1549 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1554 /// Same as `Lit`, but restricted to string literals.
1555 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1557 /// The original literal token as written in source code.
1558 pub style: StrStyle,
1560 pub suffix: Option<Symbol>,
1562 /// The unescaped "semantic" representation of the literal lowered from the original token.
1563 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1564 pub symbol_unescaped: Symbol,
1568 pub fn as_lit(&self) -> Lit {
1569 let token_kind = match self.style {
1570 StrStyle::Cooked => token::Str,
1571 StrStyle::Raw(n) => token::StrRaw(n),
1574 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1576 kind: LitKind::Str(self.symbol_unescaped, self.style),
1581 /// Type of the integer literal based on provided suffix.
1582 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1583 #[derive(HashStable_Generic)]
1584 pub enum LitIntType {
1593 /// Type of the float literal based on provided suffix.
1594 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1595 #[derive(HashStable_Generic)]
1596 pub enum LitFloatType {
1597 /// A float literal with a suffix (`1f32` or `1E10f32`).
1599 /// A float literal without a suffix (`1.0 or 1.0E10`).
1605 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1606 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1608 /// A string literal (`"foo"`).
1609 Str(Symbol, StrStyle),
1610 /// A byte string (`b"foo"`).
1612 /// A byte char (`b'f'`).
1614 /// A character literal (`'a'`).
1616 /// An integer literal (`1`).
1617 Int(u128, LitIntType),
1618 /// A float literal (`1f64` or `1E10f64`).
1619 Float(Symbol, LitFloatType),
1620 /// A boolean literal.
1622 /// Placeholder for a literal that wasn't well-formed in some way.
1627 /// Returns `true` if this literal is a string.
1628 pub fn is_str(&self) -> bool {
1630 LitKind::Str(..) => true,
1635 /// Returns `true` if this literal is byte literal string.
1636 pub fn is_bytestr(&self) -> bool {
1638 LitKind::ByteStr(_) => true,
1643 /// Returns `true` if this is a numeric literal.
1644 pub fn is_numeric(&self) -> bool {
1646 LitKind::Int(..) | LitKind::Float(..) => true,
1651 /// Returns `true` if this literal has no suffix.
1652 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1653 pub fn is_unsuffixed(&self) -> bool {
1657 /// Returns `true` if this literal has a suffix.
1658 pub fn is_suffixed(&self) -> bool {
1660 // suffixed variants
1661 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1662 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1663 // unsuffixed variants
1665 | LitKind::ByteStr(..)
1668 | LitKind::Int(_, LitIntType::Unsuffixed)
1669 | LitKind::Float(_, LitFloatType::Unsuffixed)
1671 | LitKind::Err(..) => false,
1676 // N.B., If you change this, you'll probably want to change the corresponding
1677 // type structure in `middle/ty.rs` as well.
1678 #[derive(Clone, Encodable, Decodable, Debug)]
1681 pub mutbl: Mutability,
1684 /// Represents a function's signature in a trait declaration,
1685 /// trait implementation, or free function.
1686 #[derive(Clone, Encodable, Decodable, Debug)]
1688 pub header: FnHeader,
1689 pub decl: P<FnDecl>,
1693 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1694 #[derive(Encodable, Decodable, HashStable_Generic)]
1701 pub fn name_str(self) -> &'static str {
1703 FloatTy::F32 => "f32",
1704 FloatTy::F64 => "f64",
1708 pub fn name(self) -> Symbol {
1710 FloatTy::F32 => sym::f32,
1711 FloatTy::F64 => sym::f64,
1715 pub fn bit_width(self) -> u64 {
1723 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1724 #[derive(Encodable, Decodable, HashStable_Generic)]
1735 pub fn name_str(&self) -> &'static str {
1737 IntTy::Isize => "isize",
1739 IntTy::I16 => "i16",
1740 IntTy::I32 => "i32",
1741 IntTy::I64 => "i64",
1742 IntTy::I128 => "i128",
1746 pub fn name(&self) -> Symbol {
1748 IntTy::Isize => sym::isize,
1749 IntTy::I8 => sym::i8,
1750 IntTy::I16 => sym::i16,
1751 IntTy::I32 => sym::i32,
1752 IntTy::I64 => sym::i64,
1753 IntTy::I128 => sym::i128,
1757 pub fn bit_width(&self) -> Option<u64> {
1759 IntTy::Isize => return None,
1768 pub fn normalize(&self, target_width: u32) -> Self {
1770 IntTy::Isize => match target_width {
1774 _ => unreachable!(),
1781 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1782 #[derive(Encodable, Decodable, HashStable_Generic)]
1793 pub fn name_str(&self) -> &'static str {
1795 UintTy::Usize => "usize",
1797 UintTy::U16 => "u16",
1798 UintTy::U32 => "u32",
1799 UintTy::U64 => "u64",
1800 UintTy::U128 => "u128",
1804 pub fn name(&self) -> Symbol {
1806 UintTy::Usize => sym::usize,
1807 UintTy::U8 => sym::u8,
1808 UintTy::U16 => sym::u16,
1809 UintTy::U32 => sym::u32,
1810 UintTy::U64 => sym::u64,
1811 UintTy::U128 => sym::u128,
1815 pub fn bit_width(&self) -> Option<u64> {
1817 UintTy::Usize => return None,
1822 UintTy::U128 => 128,
1826 pub fn normalize(&self, target_width: u32) -> Self {
1828 UintTy::Usize => match target_width {
1832 _ => unreachable!(),
1839 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1840 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1841 #[derive(Clone, Encodable, Decodable, Debug)]
1842 pub struct AssocTyConstraint {
1845 pub kind: AssocTyConstraintKind,
1849 /// The kinds of an `AssocTyConstraint`.
1850 #[derive(Clone, Encodable, Decodable, Debug)]
1851 pub enum AssocTyConstraintKind {
1852 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1853 Equality { ty: P<Ty> },
1854 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1855 Bound { bounds: GenericBounds },
1858 #[derive(Encodable, Decodable, Debug)]
1863 pub tokens: Option<LazyTokenStream>,
1867 fn clone(&self) -> Self {
1868 ensure_sufficient_stack(|| Self {
1870 kind: self.kind.clone(),
1872 tokens: self.tokens.clone(),
1878 pub fn peel_refs(&self) -> &Self {
1879 let mut final_ty = self;
1880 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1887 #[derive(Clone, Encodable, Decodable, Debug)]
1888 pub struct BareFnTy {
1889 pub unsafety: Unsafe,
1891 pub generic_params: Vec<GenericParam>,
1892 pub decl: P<FnDecl>,
1895 /// The various kinds of type recognized by the compiler.
1896 #[derive(Clone, Encodable, Decodable, Debug)]
1898 /// A variable-length slice (`[T]`).
1900 /// A fixed length array (`[T; n]`).
1901 Array(P<Ty>, AnonConst),
1902 /// A raw pointer (`*const T` or `*mut T`).
1904 /// A reference (`&'a T` or `&'a mut T`).
1905 Rptr(Option<Lifetime>, MutTy),
1906 /// A bare function (e.g., `fn(usize) -> bool`).
1907 BareFn(P<BareFnTy>),
1908 /// The never type (`!`).
1910 /// A tuple (`(A, B, C, D,...)`).
1912 /// A path (`module::module::...::Type`), optionally
1913 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1915 /// Type parameters are stored in the `Path` itself.
1916 Path(Option<QSelf>, Path),
1917 /// A trait object type `Bound1 + Bound2 + Bound3`
1918 /// where `Bound` is a trait or a lifetime.
1919 TraitObject(GenericBounds, TraitObjectSyntax),
1920 /// An `impl Bound1 + Bound2 + Bound3` type
1921 /// where `Bound` is a trait or a lifetime.
1923 /// The `NodeId` exists to prevent lowering from having to
1924 /// generate `NodeId`s on the fly, which would complicate
1925 /// the generation of opaque `type Foo = impl Trait` items significantly.
1926 ImplTrait(NodeId, GenericBounds),
1927 /// No-op; kept solely so that we can pretty-print faithfully.
1931 /// This means the type should be inferred instead of it having been
1932 /// specified. This can appear anywhere in a type.
1934 /// Inferred type of a `self` or `&self` argument in a method.
1936 /// A macro in the type position.
1938 /// Placeholder for a kind that has failed to be defined.
1940 /// Placeholder for a `va_list`.
1945 pub fn is_implicit_self(&self) -> bool {
1946 matches!(self, TyKind::ImplicitSelf)
1949 pub fn is_unit(&self) -> bool {
1950 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1954 /// Syntax used to declare a trait object.
1955 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1956 pub enum TraitObjectSyntax {
1961 /// Inline assembly operand explicit register or register class.
1963 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1964 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1965 pub enum InlineAsmRegOrRegClass {
1970 bitflags::bitflags! {
1971 #[derive(Encodable, Decodable, HashStable_Generic)]
1972 pub struct InlineAsmOptions: u8 {
1973 const PURE = 1 << 0;
1974 const NOMEM = 1 << 1;
1975 const READONLY = 1 << 2;
1976 const PRESERVES_FLAGS = 1 << 3;
1977 const NORETURN = 1 << 4;
1978 const NOSTACK = 1 << 5;
1979 const ATT_SYNTAX = 1 << 6;
1983 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1984 pub enum InlineAsmTemplatePiece {
1986 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1989 impl fmt::Display for InlineAsmTemplatePiece {
1990 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1992 Self::String(s) => {
1993 for c in s.chars() {
1995 '{' => f.write_str("{{")?,
1996 '}' => f.write_str("}}")?,
2002 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2003 write!(f, "{{{}:{}}}", operand_idx, modifier)
2005 Self::Placeholder { operand_idx, modifier: None, .. } => {
2006 write!(f, "{{{}}}", operand_idx)
2012 impl InlineAsmTemplatePiece {
2013 /// Rebuilds the asm template string from its pieces.
2014 pub fn to_string(s: &[Self]) -> String {
2016 let mut out = String::new();
2018 let _ = write!(out, "{}", p);
2024 /// Inline assembly operand.
2026 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2027 #[derive(Clone, Encodable, Decodable, Debug)]
2028 pub enum InlineAsmOperand {
2030 reg: InlineAsmRegOrRegClass,
2034 reg: InlineAsmRegOrRegClass,
2036 expr: Option<P<Expr>>,
2039 reg: InlineAsmRegOrRegClass,
2044 reg: InlineAsmRegOrRegClass,
2047 out_expr: Option<P<Expr>>,
2057 /// Inline assembly.
2059 /// E.g., `asm!("NOP");`.
2060 #[derive(Clone, Encodable, Decodable, Debug)]
2061 pub struct InlineAsm {
2062 pub template: Vec<InlineAsmTemplatePiece>,
2063 pub operands: Vec<(InlineAsmOperand, Span)>,
2064 pub options: InlineAsmOptions,
2065 pub line_spans: Vec<Span>,
2068 /// Inline assembly dialect.
2070 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2071 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2072 pub enum LlvmAsmDialect {
2077 /// LLVM-style inline assembly.
2079 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2080 #[derive(Clone, Encodable, Decodable, Debug)]
2081 pub struct LlvmInlineAsmOutput {
2082 pub constraint: Symbol,
2085 pub is_indirect: bool,
2088 /// LLVM-style inline assembly.
2090 /// E.g., `llvm_asm!("NOP");`.
2091 #[derive(Clone, Encodable, Decodable, Debug)]
2092 pub struct LlvmInlineAsm {
2094 pub asm_str_style: StrStyle,
2095 pub outputs: Vec<LlvmInlineAsmOutput>,
2096 pub inputs: Vec<(Symbol, P<Expr>)>,
2097 pub clobbers: Vec<Symbol>,
2099 pub alignstack: bool,
2100 pub dialect: LlvmAsmDialect,
2103 /// A parameter in a function header.
2105 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2106 #[derive(Clone, Encodable, Decodable, Debug)]
2113 pub is_placeholder: bool,
2116 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2118 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2119 #[derive(Clone, Encodable, Decodable, Debug)]
2121 /// `self`, `mut self`
2123 /// `&'lt self`, `&'lt mut self`
2124 Region(Option<Lifetime>, Mutability),
2125 /// `self: TYPE`, `mut self: TYPE`
2126 Explicit(P<Ty>, Mutability),
2129 pub type ExplicitSelf = Spanned<SelfKind>;
2132 /// Attempts to cast parameter to `ExplicitSelf`.
2133 pub fn to_self(&self) -> Option<ExplicitSelf> {
2134 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2135 if ident.name == kw::SelfLower {
2136 return match self.ty.kind {
2137 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2138 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2139 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2142 self.pat.span.to(self.ty.span),
2143 SelfKind::Explicit(self.ty.clone(), mutbl),
2151 /// Returns `true` if parameter is `self`.
2152 pub fn is_self(&self) -> bool {
2153 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2154 ident.name == kw::SelfLower
2160 /// Builds a `Param` object from `ExplicitSelf`.
2161 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2162 let span = eself.span.to(eself_ident.span);
2163 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2164 let param = |mutbl, ty| Param {
2168 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2175 is_placeholder: false,
2178 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2179 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2180 SelfKind::Region(lt, mutbl) => param(
2184 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2193 /// A signature (not the body) of a function declaration.
2195 /// E.g., `fn foo(bar: baz)`.
2197 /// Please note that it's different from `FnHeader` structure
2198 /// which contains metadata about function safety, asyncness, constness and ABI.
2199 #[derive(Clone, Encodable, Decodable, Debug)]
2201 pub inputs: Vec<Param>,
2202 pub output: FnRetTy,
2206 pub fn get_self(&self) -> Option<ExplicitSelf> {
2207 self.inputs.get(0).and_then(Param::to_self)
2209 pub fn has_self(&self) -> bool {
2210 self.inputs.get(0).map_or(false, Param::is_self)
2212 pub fn c_variadic(&self) -> bool {
2213 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2214 TyKind::CVarArgs => true,
2220 /// Is the trait definition an auto trait?
2221 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2227 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2228 #[derive(HashStable_Generic)]
2234 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2236 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2241 pub fn is_async(self) -> bool {
2242 matches!(self, Async::Yes { .. })
2245 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2246 pub fn opt_return_id(self) -> Option<NodeId> {
2248 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2254 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2255 #[derive(HashStable_Generic)]
2261 /// Item defaultness.
2262 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2263 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2264 pub enum Defaultness {
2269 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2270 pub enum ImplPolarity {
2271 /// `impl Trait for Type`
2273 /// `impl !Trait for Type`
2277 impl fmt::Debug for ImplPolarity {
2278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2280 ImplPolarity::Positive => "positive".fmt(f),
2281 ImplPolarity::Negative(_) => "negative".fmt(f),
2286 #[derive(Clone, Encodable, Decodable, Debug)]
2288 /// Returns type is not specified.
2290 /// Functions default to `()` and closures default to inference.
2291 /// Span points to where return type would be inserted.
2293 /// Everything else.
2298 pub fn span(&self) -> Span {
2300 FnRetTy::Default(span) => span,
2301 FnRetTy::Ty(ref ty) => ty.span,
2306 /// Module declaration.
2308 /// E.g., `mod foo;` or `mod foo { .. }`.
2309 #[derive(Clone, Encodable, Decodable, Debug)]
2311 /// A span from the first token past `{` to the last token until `}`.
2312 /// For `mod foo;`, the inner span ranges from the first token
2313 /// to the last token in the external file.
2315 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2316 /// semantically by Rust.
2317 pub unsafety: Unsafe,
2318 pub items: Vec<P<Item>>,
2319 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2323 /// Foreign module declaration.
2325 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2326 #[derive(Clone, Encodable, Decodable, Debug)]
2327 pub struct ForeignMod {
2328 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2329 /// semantically by Rust.
2330 pub unsafety: Unsafe,
2331 pub abi: Option<StrLit>,
2332 pub items: Vec<P<ForeignItem>>,
2335 /// Global inline assembly.
2337 /// Also known as "module-level assembly" or "file-scoped assembly".
2338 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2339 pub struct GlobalAsm {
2343 #[derive(Clone, Encodable, Decodable, Debug)]
2344 pub struct EnumDef {
2345 pub variants: Vec<Variant>,
2348 #[derive(Clone, Encodable, Decodable, Debug)]
2349 pub struct Variant {
2350 /// Attributes of the variant.
2351 pub attrs: Vec<Attribute>,
2352 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2356 /// The visibility of the variant. Syntactically accepted but not semantically.
2357 pub vis: Visibility,
2358 /// Name of the variant.
2361 /// Fields and constructor id of the variant.
2362 pub data: VariantData,
2363 /// Explicit discriminant, e.g., `Foo = 1`.
2364 pub disr_expr: Option<AnonConst>,
2365 /// Is a macro placeholder
2366 pub is_placeholder: bool,
2369 /// Part of `use` item to the right of its prefix.
2370 #[derive(Clone, Encodable, Decodable, Debug)]
2371 pub enum UseTreeKind {
2372 /// `use prefix` or `use prefix as rename`
2374 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2376 Simple(Option<Ident>, NodeId, NodeId),
2377 /// `use prefix::{...}`
2378 Nested(Vec<(UseTree, NodeId)>),
2383 /// A tree of paths sharing common prefixes.
2384 /// Used in `use` items both at top-level and inside of braces in import groups.
2385 #[derive(Clone, Encodable, Decodable, Debug)]
2386 pub struct UseTree {
2388 pub kind: UseTreeKind,
2393 pub fn ident(&self) -> Ident {
2395 UseTreeKind::Simple(Some(rename), ..) => rename,
2396 UseTreeKind::Simple(None, ..) => {
2397 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2399 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2404 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2405 /// are contained as statements within items. These two cases need to be
2406 /// distinguished for pretty-printing.
2407 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2408 pub enum AttrStyle {
2413 rustc_index::newtype_index! {
2416 DEBUG_FORMAT = "AttrId({})"
2420 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2421 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2426 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2427 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2428 d.read_nil().map(|_| crate::attr::mk_attr_id())
2432 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2433 pub struct AttrItem {
2436 pub tokens: Option<LazyTokenStream>,
2439 /// A list of attributes.
2440 pub type AttrVec = ThinVec<Attribute>;
2442 /// Metadata associated with an item.
2443 #[derive(Clone, Encodable, Decodable, Debug)]
2444 pub struct Attribute {
2447 /// Denotes if the attribute decorates the following construct (outer)
2448 /// or the construct this attribute is contained within (inner).
2449 pub style: AttrStyle,
2453 #[derive(Clone, Encodable, Decodable, Debug)]
2455 /// A normal attribute.
2456 Normal(AttrItem, Option<LazyTokenStream>),
2458 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2459 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2460 /// variant (which is much less compact and thus more expensive).
2461 DocComment(CommentKind, Symbol),
2464 /// `TraitRef`s appear in impls.
2466 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2467 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2468 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2469 /// same as the impl's `NodeId`).
2470 #[derive(Clone, Encodable, Decodable, Debug)]
2471 pub struct TraitRef {
2476 #[derive(Clone, Encodable, Decodable, Debug)]
2477 pub struct PolyTraitRef {
2478 /// The `'a` in `<'a> Foo<&'a T>`.
2479 pub bound_generic_params: Vec<GenericParam>,
2481 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2482 pub trait_ref: TraitRef,
2488 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2490 bound_generic_params: generic_params,
2491 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2497 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2498 pub enum CrateSugar {
2499 /// Source is `pub(crate)`.
2502 /// Source is (just) `crate`.
2506 #[derive(Clone, Encodable, Decodable, Debug)]
2507 pub struct Visibility {
2508 pub kind: VisibilityKind,
2510 pub tokens: Option<LazyTokenStream>,
2513 #[derive(Clone, Encodable, Decodable, Debug)]
2514 pub enum VisibilityKind {
2517 Restricted { path: P<Path>, id: NodeId },
2521 impl VisibilityKind {
2522 pub fn is_pub(&self) -> bool {
2523 matches!(self, VisibilityKind::Public)
2527 /// Field of a struct.
2529 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2530 #[derive(Clone, Encodable, Decodable, Debug)]
2531 pub struct StructField {
2532 pub attrs: Vec<Attribute>,
2535 pub vis: Visibility,
2536 pub ident: Option<Ident>,
2539 pub is_placeholder: bool,
2542 /// Fields and constructor ids of enum variants and structs.
2543 #[derive(Clone, Encodable, Decodable, Debug)]
2544 pub enum VariantData {
2547 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2548 Struct(Vec<StructField>, bool),
2551 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2552 Tuple(Vec<StructField>, NodeId),
2555 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2560 /// Return the fields of this variant.
2561 pub fn fields(&self) -> &[StructField] {
2563 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2568 /// Return the `NodeId` of this variant's constructor, if it has one.
2569 pub fn ctor_id(&self) -> Option<NodeId> {
2571 VariantData::Struct(..) => None,
2572 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2577 /// An item definition.
2578 #[derive(Clone, Encodable, Decodable, Debug)]
2579 pub struct Item<K = ItemKind> {
2580 pub attrs: Vec<Attribute>,
2583 pub vis: Visibility,
2584 /// The name of the item.
2585 /// It might be a dummy name in case of anonymous items.
2590 /// Original tokens this item was parsed from. This isn't necessarily
2591 /// available for all items, although over time more and more items should
2592 /// have this be `Some`. Right now this is primarily used for procedural
2593 /// macros, notably custom attributes.
2595 /// Note that the tokens here do not include the outer attributes, but will
2596 /// include inner attributes.
2597 pub tokens: Option<LazyTokenStream>,
2601 /// Return the span that encompasses the attributes.
2602 pub fn span_with_attributes(&self) -> Span {
2603 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2607 impl<K: Into<ItemKind>> Item<K> {
2608 pub fn into_item(self) -> Item {
2609 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2610 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2614 /// `extern` qualifier on a function item or function type.
2615 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2623 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2624 abi.map_or(Extern::Implicit, Extern::Explicit)
2628 /// A function header.
2630 /// All the information between the visibility and the name of the function is
2631 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2632 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2633 pub struct FnHeader {
2634 pub unsafety: Unsafe,
2635 pub asyncness: Async,
2636 pub constness: Const,
2641 /// Does this function header have any qualifiers or is it empty?
2642 pub fn has_qualifiers(&self) -> bool {
2643 let Self { unsafety, asyncness, constness, ext } = self;
2644 matches!(unsafety, Unsafe::Yes(_))
2645 || asyncness.is_async()
2646 || matches!(constness, Const::Yes(_))
2647 || !matches!(ext, Extern::None)
2651 impl Default for FnHeader {
2652 fn default() -> FnHeader {
2654 unsafety: Unsafe::No,
2655 asyncness: Async::No,
2656 constness: Const::No,
2662 #[derive(Clone, Encodable, Decodable, Debug)]
2664 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2666 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2667 ExternCrate(Option<Symbol>),
2668 /// A use declaration item (`use`).
2670 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2672 /// A static item (`static`).
2674 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2675 Static(P<Ty>, Mutability, Option<P<Expr>>),
2676 /// A constant item (`const`).
2678 /// E.g., `const FOO: i32 = 42;`.
2679 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2680 /// A function declaration (`fn`).
2682 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2683 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2684 /// A module declaration (`mod`).
2686 /// E.g., `mod foo;` or `mod foo { .. }`.
2688 /// An external module (`extern`).
2690 /// E.g., `extern {}` or `extern "C" {}`.
2691 ForeignMod(ForeignMod),
2692 /// Module-level inline assembly (from `global_asm!()`).
2693 GlobalAsm(P<GlobalAsm>),
2694 /// A type alias (`type`).
2696 /// E.g., `type Foo = Bar<u8>;`.
2697 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2698 /// An enum definition (`enum`).
2700 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2701 Enum(EnumDef, Generics),
2702 /// A struct definition (`struct`).
2704 /// E.g., `struct Foo<A> { x: A }`.
2705 Struct(VariantData, Generics),
2706 /// A union definition (`union`).
2708 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2709 Union(VariantData, Generics),
2710 /// A trait declaration (`trait`).
2712 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2713 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2716 /// E.g., `trait Foo = Bar + Quux;`.
2717 TraitAlias(Generics, GenericBounds),
2718 /// An implementation.
2720 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2723 polarity: ImplPolarity,
2724 defaultness: Defaultness,
2728 /// The trait being implemented, if any.
2729 of_trait: Option<TraitRef>,
2732 items: Vec<P<AssocItem>>,
2734 /// A macro invocation.
2736 /// E.g., `foo!(..)`.
2739 /// A macro definition.
2744 pub fn article(&self) -> &str {
2747 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2748 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2749 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2753 pub fn descr(&self) -> &str {
2755 ItemKind::ExternCrate(..) => "extern crate",
2756 ItemKind::Use(..) => "`use` import",
2757 ItemKind::Static(..) => "static item",
2758 ItemKind::Const(..) => "constant item",
2759 ItemKind::Fn(..) => "function",
2760 ItemKind::Mod(..) => "module",
2761 ItemKind::ForeignMod(..) => "extern block",
2762 ItemKind::GlobalAsm(..) => "global asm item",
2763 ItemKind::TyAlias(..) => "type alias",
2764 ItemKind::Enum(..) => "enum",
2765 ItemKind::Struct(..) => "struct",
2766 ItemKind::Union(..) => "union",
2767 ItemKind::Trait(..) => "trait",
2768 ItemKind::TraitAlias(..) => "trait alias",
2769 ItemKind::MacCall(..) => "item macro invocation",
2770 ItemKind::MacroDef(..) => "macro definition",
2771 ItemKind::Impl { .. } => "implementation",
2775 pub fn generics(&self) -> Option<&Generics> {
2777 Self::Fn(_, _, generics, _)
2778 | Self::TyAlias(_, generics, ..)
2779 | Self::Enum(_, generics)
2780 | Self::Struct(_, generics)
2781 | Self::Union(_, generics)
2782 | Self::Trait(_, _, generics, ..)
2783 | Self::TraitAlias(generics, _)
2784 | Self::Impl { generics, .. } => Some(generics),
2790 /// Represents associated items.
2791 /// These include items in `impl` and `trait` definitions.
2792 pub type AssocItem = Item<AssocItemKind>;
2794 /// Represents associated item kinds.
2796 /// The term "provided" in the variants below refers to the item having a default
2797 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2798 /// In an implementation, all items must be provided.
2799 /// The `Option`s below denote the bodies, where `Some(_)`
2800 /// means "provided" and conversely `None` means "required".
2801 #[derive(Clone, Encodable, Decodable, Debug)]
2802 pub enum AssocItemKind {
2803 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2804 /// If `def` is parsed, then the constant is provided, and otherwise required.
2805 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2806 /// An associated function.
2807 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2808 /// An associated type.
2809 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2810 /// A macro expanding to associated items.
2814 impl AssocItemKind {
2815 pub fn defaultness(&self) -> Defaultness {
2817 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2818 Self::MacCall(..) => Defaultness::Final,
2823 impl From<AssocItemKind> for ItemKind {
2824 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2825 match assoc_item_kind {
2826 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2827 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2828 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2829 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2834 impl TryFrom<ItemKind> for AssocItemKind {
2835 type Error = ItemKind;
2837 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2838 Ok(match item_kind {
2839 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2840 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2841 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2842 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2843 _ => return Err(item_kind),
2848 /// An item in `extern` block.
2849 #[derive(Clone, Encodable, Decodable, Debug)]
2850 pub enum ForeignItemKind {
2851 /// A foreign static item (`static FOO: u8`).
2852 Static(P<Ty>, Mutability, Option<P<Expr>>),
2853 /// A foreign function.
2854 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2856 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2857 /// A macro expanding to foreign items.
2861 impl From<ForeignItemKind> for ItemKind {
2862 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2863 match foreign_item_kind {
2864 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2865 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2866 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2867 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2872 impl TryFrom<ItemKind> for ForeignItemKind {
2873 type Error = ItemKind;
2875 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2876 Ok(match item_kind {
2877 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2878 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2879 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2880 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2881 _ => return Err(item_kind),
2886 pub type ForeignItem = Item<ForeignItemKind>;