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::Underscore => ExprPrecedence::Path,
1196 ExprKind::Path(..) => ExprPrecedence::Path,
1197 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1198 ExprKind::Break(..) => ExprPrecedence::Break,
1199 ExprKind::Continue(..) => ExprPrecedence::Continue,
1200 ExprKind::Ret(..) => ExprPrecedence::Ret,
1201 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1202 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1203 ExprKind::Struct(..) => ExprPrecedence::Struct,
1204 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1205 ExprKind::Paren(..) => ExprPrecedence::Paren,
1206 ExprKind::Try(..) => ExprPrecedence::Try,
1207 ExprKind::Yield(..) => ExprPrecedence::Yield,
1208 ExprKind::Err => ExprPrecedence::Err,
1213 /// Limit types of a range (inclusive or exclusive)
1214 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1215 pub enum RangeLimits {
1216 /// Inclusive at the beginning, exclusive at the end
1218 /// Inclusive at the beginning and end
1222 #[derive(Clone, Encodable, Decodable, Debug)]
1223 pub enum StructRest {
1228 /// No trailing `..` or expression.
1232 #[derive(Clone, Encodable, Decodable, Debug)]
1234 /// A `box x` expression.
1236 /// An array (`[a, b, c, d]`)
1237 Array(Vec<P<Expr>>),
1238 /// Allow anonymous constants from an inline `const` block
1239 ConstBlock(AnonConst),
1242 /// The first field resolves to the function itself,
1243 /// and the second field is the list of arguments.
1244 /// This also represents calling the constructor of
1245 /// tuple-like ADTs such as tuple structs and enum variants.
1246 Call(P<Expr>, Vec<P<Expr>>),
1247 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1249 /// The `PathSegment` represents the method name and its generic arguments
1250 /// (within the angle brackets).
1251 /// The first element of the vector of an `Expr` is the expression that evaluates
1252 /// to the object on which the method is being called on (the receiver),
1253 /// and the remaining elements are the rest of the arguments.
1254 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1255 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1256 /// This `Span` is the span of the function, without the dot and receiver
1257 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1258 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1259 /// A tuple (e.g., `(a, b, c, d)`).
1261 /// A binary operation (e.g., `a + b`, `a * b`).
1262 Binary(BinOp, P<Expr>, P<Expr>),
1263 /// A unary operation (e.g., `!x`, `*x`).
1264 Unary(UnOp, P<Expr>),
1265 /// A literal (e.g., `1`, `"foo"`).
1267 /// A cast (e.g., `foo as f64`).
1268 Cast(P<Expr>, P<Ty>),
1269 /// A type ascription (e.g., `42: usize`).
1270 Type(P<Expr>, P<Ty>),
1271 /// A `let pat = expr` expression that is only semantically allowed in the condition
1272 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1273 Let(P<Pat>, P<Expr>),
1274 /// An `if` block, with an optional `else` block.
1276 /// `if expr { block } else { expr }`
1277 If(P<Expr>, P<Block>, Option<P<Expr>>),
1278 /// A while loop, with an optional label.
1280 /// `'label: while expr { block }`
1281 While(P<Expr>, P<Block>, Option<Label>),
1282 /// A `for` loop, with an optional label.
1284 /// `'label: for pat in expr { block }`
1286 /// This is desugared to a combination of `loop` and `match` expressions.
1287 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1288 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1290 /// `'label: loop { block }`
1291 Loop(P<Block>, Option<Label>),
1292 /// A `match` block.
1293 Match(P<Expr>, Vec<Arm>),
1294 /// A closure (e.g., `move |a, b, c| a + b + c`).
1296 /// The final span is the span of the argument block `|...|`.
1297 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1298 /// A block (`'label: { ... }`).
1299 Block(P<Block>, Option<Label>),
1300 /// An async block (`async move { ... }`).
1302 /// The `NodeId` is the `NodeId` for the closure that results from
1303 /// desugaring an async block, just like the NodeId field in the
1304 /// `Async::Yes` variant. This is necessary in order to create a def for the
1305 /// closure which can be used as a parent of any child defs. Defs
1306 /// created during lowering cannot be made the parent of any other
1307 /// preexisting defs.
1308 Async(CaptureBy, NodeId, P<Block>),
1309 /// An await expression (`my_future.await`).
1312 /// A try block (`try { ... }`).
1315 /// An assignment (`a = foo()`).
1316 /// The `Span` argument is the span of the `=` token.
1317 Assign(P<Expr>, P<Expr>, Span),
1318 /// An assignment with an operator.
1321 AssignOp(BinOp, P<Expr>, P<Expr>),
1322 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1323 Field(P<Expr>, Ident),
1324 /// An indexing operation (e.g., `foo[2]`).
1325 Index(P<Expr>, P<Expr>),
1326 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assingment).
1327 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1328 /// An underscore, used in destructuring assignment to ignore a value.
1331 /// Variable reference, possibly containing `::` and/or type
1332 /// parameters (e.g., `foo::bar::<baz>`).
1334 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1335 Path(Option<QSelf>, Path),
1337 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1338 AddrOf(BorrowKind, Mutability, P<Expr>),
1339 /// A `break`, with an optional label to break, and an optional expression.
1340 Break(Option<Label>, Option<P<Expr>>),
1341 /// A `continue`, with an optional label.
1342 Continue(Option<Label>),
1343 /// A `return`, with an optional value to be returned.
1344 Ret(Option<P<Expr>>),
1346 /// Output of the `asm!()` macro.
1347 InlineAsm(P<InlineAsm>),
1348 /// Output of the `llvm_asm!()` macro.
1349 LlvmInlineAsm(P<LlvmInlineAsm>),
1351 /// A macro invocation; pre-expansion.
1354 /// A struct literal expression.
1356 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1357 Struct(Path, Vec<Field>, StructRest),
1359 /// An array literal constructed from one repeated element.
1361 /// E.g., `[1; 5]`. The expression is the element to be
1362 /// repeated; the constant is the number of times to repeat it.
1363 Repeat(P<Expr>, AnonConst),
1365 /// No-op: used solely so we can pretty-print faithfully.
1368 /// A try expression (`expr?`).
1371 /// A `yield`, with an optional value to be yielded.
1372 Yield(Option<P<Expr>>),
1374 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1378 /// The explicit `Self` type in a "qualified path". The actual
1379 /// path, including the trait and the associated item, is stored
1380 /// separately. `position` represents the index of the associated
1381 /// item qualified with this `Self` type.
1383 /// ```ignore (only-for-syntax-highlight)
1384 /// <Vec<T> as a::b::Trait>::AssociatedItem
1385 /// ^~~~~ ~~~~~~~~~~~~~~^
1388 /// <Vec<T>>::AssociatedItem
1392 #[derive(Clone, Encodable, Decodable, Debug)]
1396 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1397 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1398 /// 0`, this is an empty span.
1399 pub path_span: Span,
1400 pub position: usize,
1403 /// A capture clause used in closures and `async` blocks.
1404 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1405 pub enum CaptureBy {
1406 /// `move |x| y + x`.
1408 /// `move` keyword was not specified.
1412 /// The movability of a generator / closure literal:
1413 /// whether a generator contains self-references, causing it to be `!Unpin`.
1414 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1415 #[derive(HashStable_Generic)]
1416 pub enum Movability {
1417 /// May contain self-references, `!Unpin`.
1419 /// Must not contain self-references, `Unpin`.
1423 /// Represents a macro invocation. The `path` indicates which macro
1424 /// is being invoked, and the `args` are arguments passed to it.
1425 #[derive(Clone, Encodable, Decodable, Debug)]
1426 pub struct MacCall {
1428 pub args: P<MacArgs>,
1429 pub prior_type_ascription: Option<(Span, bool)>,
1433 pub fn span(&self) -> Span {
1434 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1438 /// Arguments passed to an attribute or a function-like macro.
1439 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1441 /// No arguments - `#[attr]`.
1443 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1444 Delimited(DelimSpan, MacDelimiter, TokenStream),
1445 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1447 /// Span of the `=` token.
1449 /// Token stream of the "value".
1455 pub fn delim(&self) -> DelimToken {
1457 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1458 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1462 pub fn span(&self) -> Option<Span> {
1464 MacArgs::Empty => None,
1465 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1466 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1470 /// Tokens inside the delimiters or after `=`.
1471 /// Proc macros see these tokens, for example.
1472 pub fn inner_tokens(&self) -> TokenStream {
1474 MacArgs::Empty => TokenStream::default(),
1475 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1479 /// Tokens together with the delimiters or `=`.
1480 /// Use of this method generally means that something suboptimal or hacky is happening.
1481 pub fn outer_tokens(&self) -> TokenStream {
1483 MacArgs::Empty => TokenStream::default(),
1484 MacArgs::Delimited(dspan, delim, ref tokens) => {
1485 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1487 MacArgs::Eq(eq_span, ref tokens) => {
1488 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1493 /// Whether a macro with these arguments needs a semicolon
1494 /// when used as a standalone item or statement.
1495 pub fn need_semicolon(&self) -> bool {
1496 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1500 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1501 pub enum MacDelimiter {
1508 pub fn to_token(self) -> DelimToken {
1510 MacDelimiter::Parenthesis => DelimToken::Paren,
1511 MacDelimiter::Bracket => DelimToken::Bracket,
1512 MacDelimiter::Brace => DelimToken::Brace,
1516 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1518 token::Paren => Some(MacDelimiter::Parenthesis),
1519 token::Bracket => Some(MacDelimiter::Bracket),
1520 token::Brace => Some(MacDelimiter::Brace),
1521 token::NoDelim => None,
1526 /// Represents a macro definition.
1527 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1528 pub struct MacroDef {
1529 pub body: P<MacArgs>,
1530 /// `true` if macro was defined with `macro_rules`.
1531 pub macro_rules: bool,
1534 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1535 #[derive(HashStable_Generic)]
1537 /// A regular string, like `"foo"`.
1539 /// A raw string, like `r##"foo"##`.
1541 /// The value is the number of `#` symbols used.
1546 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1548 /// The original literal token as written in source code.
1549 pub token: token::Lit,
1550 /// The "semantic" representation of the literal lowered from the original tokens.
1551 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1552 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1557 /// Same as `Lit`, but restricted to string literals.
1558 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1560 /// The original literal token as written in source code.
1561 pub style: StrStyle,
1563 pub suffix: Option<Symbol>,
1565 /// The unescaped "semantic" representation of the literal lowered from the original token.
1566 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1567 pub symbol_unescaped: Symbol,
1571 pub fn as_lit(&self) -> Lit {
1572 let token_kind = match self.style {
1573 StrStyle::Cooked => token::Str,
1574 StrStyle::Raw(n) => token::StrRaw(n),
1577 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1579 kind: LitKind::Str(self.symbol_unescaped, self.style),
1584 /// Type of the integer literal based on provided suffix.
1585 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1586 #[derive(HashStable_Generic)]
1587 pub enum LitIntType {
1596 /// Type of the float literal based on provided suffix.
1597 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1598 #[derive(HashStable_Generic)]
1599 pub enum LitFloatType {
1600 /// A float literal with a suffix (`1f32` or `1E10f32`).
1602 /// A float literal without a suffix (`1.0 or 1.0E10`).
1608 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1609 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1611 /// A string literal (`"foo"`).
1612 Str(Symbol, StrStyle),
1613 /// A byte string (`b"foo"`).
1615 /// A byte char (`b'f'`).
1617 /// A character literal (`'a'`).
1619 /// An integer literal (`1`).
1620 Int(u128, LitIntType),
1621 /// A float literal (`1f64` or `1E10f64`).
1622 Float(Symbol, LitFloatType),
1623 /// A boolean literal.
1625 /// Placeholder for a literal that wasn't well-formed in some way.
1630 /// Returns `true` if this literal is a string.
1631 pub fn is_str(&self) -> bool {
1633 LitKind::Str(..) => true,
1638 /// Returns `true` if this literal is byte literal string.
1639 pub fn is_bytestr(&self) -> bool {
1641 LitKind::ByteStr(_) => true,
1646 /// Returns `true` if this is a numeric literal.
1647 pub fn is_numeric(&self) -> bool {
1649 LitKind::Int(..) | LitKind::Float(..) => true,
1654 /// Returns `true` if this literal has no suffix.
1655 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1656 pub fn is_unsuffixed(&self) -> bool {
1660 /// Returns `true` if this literal has a suffix.
1661 pub fn is_suffixed(&self) -> bool {
1663 // suffixed variants
1664 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1665 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1666 // unsuffixed variants
1668 | LitKind::ByteStr(..)
1671 | LitKind::Int(_, LitIntType::Unsuffixed)
1672 | LitKind::Float(_, LitFloatType::Unsuffixed)
1674 | LitKind::Err(..) => false,
1679 // N.B., If you change this, you'll probably want to change the corresponding
1680 // type structure in `middle/ty.rs` as well.
1681 #[derive(Clone, Encodable, Decodable, Debug)]
1684 pub mutbl: Mutability,
1687 /// Represents a function's signature in a trait declaration,
1688 /// trait implementation, or free function.
1689 #[derive(Clone, Encodable, Decodable, Debug)]
1691 pub header: FnHeader,
1692 pub decl: P<FnDecl>,
1696 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1697 #[derive(Encodable, Decodable, HashStable_Generic)]
1704 pub fn name_str(self) -> &'static str {
1706 FloatTy::F32 => "f32",
1707 FloatTy::F64 => "f64",
1711 pub fn name(self) -> Symbol {
1713 FloatTy::F32 => sym::f32,
1714 FloatTy::F64 => sym::f64,
1718 pub fn bit_width(self) -> u64 {
1726 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1727 #[derive(Encodable, Decodable, HashStable_Generic)]
1738 pub fn name_str(&self) -> &'static str {
1740 IntTy::Isize => "isize",
1742 IntTy::I16 => "i16",
1743 IntTy::I32 => "i32",
1744 IntTy::I64 => "i64",
1745 IntTy::I128 => "i128",
1749 pub fn name(&self) -> Symbol {
1751 IntTy::Isize => sym::isize,
1752 IntTy::I8 => sym::i8,
1753 IntTy::I16 => sym::i16,
1754 IntTy::I32 => sym::i32,
1755 IntTy::I64 => sym::i64,
1756 IntTy::I128 => sym::i128,
1760 pub fn bit_width(&self) -> Option<u64> {
1762 IntTy::Isize => return None,
1771 pub fn normalize(&self, target_width: u32) -> Self {
1773 IntTy::Isize => match target_width {
1777 _ => unreachable!(),
1784 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1785 #[derive(Encodable, Decodable, HashStable_Generic)]
1796 pub fn name_str(&self) -> &'static str {
1798 UintTy::Usize => "usize",
1800 UintTy::U16 => "u16",
1801 UintTy::U32 => "u32",
1802 UintTy::U64 => "u64",
1803 UintTy::U128 => "u128",
1807 pub fn name(&self) -> Symbol {
1809 UintTy::Usize => sym::usize,
1810 UintTy::U8 => sym::u8,
1811 UintTy::U16 => sym::u16,
1812 UintTy::U32 => sym::u32,
1813 UintTy::U64 => sym::u64,
1814 UintTy::U128 => sym::u128,
1818 pub fn bit_width(&self) -> Option<u64> {
1820 UintTy::Usize => return None,
1825 UintTy::U128 => 128,
1829 pub fn normalize(&self, target_width: u32) -> Self {
1831 UintTy::Usize => match target_width {
1835 _ => unreachable!(),
1842 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1843 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1844 #[derive(Clone, Encodable, Decodable, Debug)]
1845 pub struct AssocTyConstraint {
1848 pub kind: AssocTyConstraintKind,
1852 /// The kinds of an `AssocTyConstraint`.
1853 #[derive(Clone, Encodable, Decodable, Debug)]
1854 pub enum AssocTyConstraintKind {
1855 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1856 Equality { ty: P<Ty> },
1857 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1858 Bound { bounds: GenericBounds },
1861 #[derive(Encodable, Decodable, Debug)]
1866 pub tokens: Option<LazyTokenStream>,
1870 fn clone(&self) -> Self {
1871 ensure_sufficient_stack(|| Self {
1873 kind: self.kind.clone(),
1875 tokens: self.tokens.clone(),
1881 pub fn peel_refs(&self) -> &Self {
1882 let mut final_ty = self;
1883 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1890 #[derive(Clone, Encodable, Decodable, Debug)]
1891 pub struct BareFnTy {
1892 pub unsafety: Unsafe,
1894 pub generic_params: Vec<GenericParam>,
1895 pub decl: P<FnDecl>,
1898 /// The various kinds of type recognized by the compiler.
1899 #[derive(Clone, Encodable, Decodable, Debug)]
1901 /// A variable-length slice (`[T]`).
1903 /// A fixed length array (`[T; n]`).
1904 Array(P<Ty>, AnonConst),
1905 /// A raw pointer (`*const T` or `*mut T`).
1907 /// A reference (`&'a T` or `&'a mut T`).
1908 Rptr(Option<Lifetime>, MutTy),
1909 /// A bare function (e.g., `fn(usize) -> bool`).
1910 BareFn(P<BareFnTy>),
1911 /// The never type (`!`).
1913 /// A tuple (`(A, B, C, D,...)`).
1915 /// A path (`module::module::...::Type`), optionally
1916 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1918 /// Type parameters are stored in the `Path` itself.
1919 Path(Option<QSelf>, Path),
1920 /// A trait object type `Bound1 + Bound2 + Bound3`
1921 /// where `Bound` is a trait or a lifetime.
1922 TraitObject(GenericBounds, TraitObjectSyntax),
1923 /// An `impl Bound1 + Bound2 + Bound3` type
1924 /// where `Bound` is a trait or a lifetime.
1926 /// The `NodeId` exists to prevent lowering from having to
1927 /// generate `NodeId`s on the fly, which would complicate
1928 /// the generation of opaque `type Foo = impl Trait` items significantly.
1929 ImplTrait(NodeId, GenericBounds),
1930 /// No-op; kept solely so that we can pretty-print faithfully.
1934 /// This means the type should be inferred instead of it having been
1935 /// specified. This can appear anywhere in a type.
1937 /// Inferred type of a `self` or `&self` argument in a method.
1939 /// A macro in the type position.
1941 /// Placeholder for a kind that has failed to be defined.
1943 /// Placeholder for a `va_list`.
1948 pub fn is_implicit_self(&self) -> bool {
1949 matches!(self, TyKind::ImplicitSelf)
1952 pub fn is_unit(&self) -> bool {
1953 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1957 /// Syntax used to declare a trait object.
1958 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1959 pub enum TraitObjectSyntax {
1964 /// Inline assembly operand explicit register or register class.
1966 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1967 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1968 pub enum InlineAsmRegOrRegClass {
1973 bitflags::bitflags! {
1974 #[derive(Encodable, Decodable, HashStable_Generic)]
1975 pub struct InlineAsmOptions: u8 {
1976 const PURE = 1 << 0;
1977 const NOMEM = 1 << 1;
1978 const READONLY = 1 << 2;
1979 const PRESERVES_FLAGS = 1 << 3;
1980 const NORETURN = 1 << 4;
1981 const NOSTACK = 1 << 5;
1982 const ATT_SYNTAX = 1 << 6;
1986 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1987 pub enum InlineAsmTemplatePiece {
1989 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1992 impl fmt::Display for InlineAsmTemplatePiece {
1993 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1995 Self::String(s) => {
1996 for c in s.chars() {
1998 '{' => f.write_str("{{")?,
1999 '}' => f.write_str("}}")?,
2005 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2006 write!(f, "{{{}:{}}}", operand_idx, modifier)
2008 Self::Placeholder { operand_idx, modifier: None, .. } => {
2009 write!(f, "{{{}}}", operand_idx)
2015 impl InlineAsmTemplatePiece {
2016 /// Rebuilds the asm template string from its pieces.
2017 pub fn to_string(s: &[Self]) -> String {
2019 let mut out = String::new();
2021 let _ = write!(out, "{}", p);
2027 /// Inline assembly operand.
2029 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2030 #[derive(Clone, Encodable, Decodable, Debug)]
2031 pub enum InlineAsmOperand {
2033 reg: InlineAsmRegOrRegClass,
2037 reg: InlineAsmRegOrRegClass,
2039 expr: Option<P<Expr>>,
2042 reg: InlineAsmRegOrRegClass,
2047 reg: InlineAsmRegOrRegClass,
2050 out_expr: Option<P<Expr>>,
2060 /// Inline assembly.
2062 /// E.g., `asm!("NOP");`.
2063 #[derive(Clone, Encodable, Decodable, Debug)]
2064 pub struct InlineAsm {
2065 pub template: Vec<InlineAsmTemplatePiece>,
2066 pub operands: Vec<(InlineAsmOperand, Span)>,
2067 pub options: InlineAsmOptions,
2068 pub line_spans: Vec<Span>,
2071 /// Inline assembly dialect.
2073 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2074 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2075 pub enum LlvmAsmDialect {
2080 /// LLVM-style inline assembly.
2082 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2083 #[derive(Clone, Encodable, Decodable, Debug)]
2084 pub struct LlvmInlineAsmOutput {
2085 pub constraint: Symbol,
2088 pub is_indirect: bool,
2091 /// LLVM-style inline assembly.
2093 /// E.g., `llvm_asm!("NOP");`.
2094 #[derive(Clone, Encodable, Decodable, Debug)]
2095 pub struct LlvmInlineAsm {
2097 pub asm_str_style: StrStyle,
2098 pub outputs: Vec<LlvmInlineAsmOutput>,
2099 pub inputs: Vec<(Symbol, P<Expr>)>,
2100 pub clobbers: Vec<Symbol>,
2102 pub alignstack: bool,
2103 pub dialect: LlvmAsmDialect,
2106 /// A parameter in a function header.
2108 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2109 #[derive(Clone, Encodable, Decodable, Debug)]
2116 pub is_placeholder: bool,
2119 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2121 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2122 #[derive(Clone, Encodable, Decodable, Debug)]
2124 /// `self`, `mut self`
2126 /// `&'lt self`, `&'lt mut self`
2127 Region(Option<Lifetime>, Mutability),
2128 /// `self: TYPE`, `mut self: TYPE`
2129 Explicit(P<Ty>, Mutability),
2132 pub type ExplicitSelf = Spanned<SelfKind>;
2135 /// Attempts to cast parameter to `ExplicitSelf`.
2136 pub fn to_self(&self) -> Option<ExplicitSelf> {
2137 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2138 if ident.name == kw::SelfLower {
2139 return match self.ty.kind {
2140 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2141 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2142 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2145 self.pat.span.to(self.ty.span),
2146 SelfKind::Explicit(self.ty.clone(), mutbl),
2154 /// Returns `true` if parameter is `self`.
2155 pub fn is_self(&self) -> bool {
2156 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2157 ident.name == kw::SelfLower
2163 /// Builds a `Param` object from `ExplicitSelf`.
2164 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2165 let span = eself.span.to(eself_ident.span);
2166 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2167 let param = |mutbl, ty| Param {
2171 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2178 is_placeholder: false,
2181 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2182 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2183 SelfKind::Region(lt, mutbl) => param(
2187 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2196 /// A signature (not the body) of a function declaration.
2198 /// E.g., `fn foo(bar: baz)`.
2200 /// Please note that it's different from `FnHeader` structure
2201 /// which contains metadata about function safety, asyncness, constness and ABI.
2202 #[derive(Clone, Encodable, Decodable, Debug)]
2204 pub inputs: Vec<Param>,
2205 pub output: FnRetTy,
2209 pub fn get_self(&self) -> Option<ExplicitSelf> {
2210 self.inputs.get(0).and_then(Param::to_self)
2212 pub fn has_self(&self) -> bool {
2213 self.inputs.get(0).map_or(false, Param::is_self)
2215 pub fn c_variadic(&self) -> bool {
2216 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2217 TyKind::CVarArgs => true,
2223 /// Is the trait definition an auto trait?
2224 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2230 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2231 #[derive(HashStable_Generic)]
2237 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2239 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2244 pub fn is_async(self) -> bool {
2245 matches!(self, Async::Yes { .. })
2248 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2249 pub fn opt_return_id(self) -> Option<NodeId> {
2251 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2257 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2258 #[derive(HashStable_Generic)]
2264 /// Item defaultness.
2265 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2266 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2267 pub enum Defaultness {
2272 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2273 pub enum ImplPolarity {
2274 /// `impl Trait for Type`
2276 /// `impl !Trait for Type`
2280 impl fmt::Debug for ImplPolarity {
2281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2283 ImplPolarity::Positive => "positive".fmt(f),
2284 ImplPolarity::Negative(_) => "negative".fmt(f),
2289 #[derive(Clone, Encodable, Decodable, Debug)]
2291 /// Returns type is not specified.
2293 /// Functions default to `()` and closures default to inference.
2294 /// Span points to where return type would be inserted.
2296 /// Everything else.
2301 pub fn span(&self) -> Span {
2303 FnRetTy::Default(span) => span,
2304 FnRetTy::Ty(ref ty) => ty.span,
2309 /// Module declaration.
2311 /// E.g., `mod foo;` or `mod foo { .. }`.
2312 #[derive(Clone, Encodable, Decodable, Debug)]
2314 /// A span from the first token past `{` to the last token until `}`.
2315 /// For `mod foo;`, the inner span ranges from the first token
2316 /// to the last token in the external file.
2318 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2319 /// semantically by Rust.
2320 pub unsafety: Unsafe,
2321 pub items: Vec<P<Item>>,
2322 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2326 /// Foreign module declaration.
2328 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2329 #[derive(Clone, Encodable, Decodable, Debug)]
2330 pub struct ForeignMod {
2331 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2332 /// semantically by Rust.
2333 pub unsafety: Unsafe,
2334 pub abi: Option<StrLit>,
2335 pub items: Vec<P<ForeignItem>>,
2338 /// Global inline assembly.
2340 /// Also known as "module-level assembly" or "file-scoped assembly".
2341 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2342 pub struct GlobalAsm {
2346 #[derive(Clone, Encodable, Decodable, Debug)]
2347 pub struct EnumDef {
2348 pub variants: Vec<Variant>,
2351 #[derive(Clone, Encodable, Decodable, Debug)]
2352 pub struct Variant {
2353 /// Attributes of the variant.
2354 pub attrs: Vec<Attribute>,
2355 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2359 /// The visibility of the variant. Syntactically accepted but not semantically.
2360 pub vis: Visibility,
2361 /// Name of the variant.
2364 /// Fields and constructor id of the variant.
2365 pub data: VariantData,
2366 /// Explicit discriminant, e.g., `Foo = 1`.
2367 pub disr_expr: Option<AnonConst>,
2368 /// Is a macro placeholder
2369 pub is_placeholder: bool,
2372 /// Part of `use` item to the right of its prefix.
2373 #[derive(Clone, Encodable, Decodable, Debug)]
2374 pub enum UseTreeKind {
2375 /// `use prefix` or `use prefix as rename`
2377 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2379 Simple(Option<Ident>, NodeId, NodeId),
2380 /// `use prefix::{...}`
2381 Nested(Vec<(UseTree, NodeId)>),
2386 /// A tree of paths sharing common prefixes.
2387 /// Used in `use` items both at top-level and inside of braces in import groups.
2388 #[derive(Clone, Encodable, Decodable, Debug)]
2389 pub struct UseTree {
2391 pub kind: UseTreeKind,
2396 pub fn ident(&self) -> Ident {
2398 UseTreeKind::Simple(Some(rename), ..) => rename,
2399 UseTreeKind::Simple(None, ..) => {
2400 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2402 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2407 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2408 /// are contained as statements within items. These two cases need to be
2409 /// distinguished for pretty-printing.
2410 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2411 pub enum AttrStyle {
2416 rustc_index::newtype_index! {
2419 DEBUG_FORMAT = "AttrId({})"
2423 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2424 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2429 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2430 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2431 d.read_nil().map(|_| crate::attr::mk_attr_id())
2435 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2436 pub struct AttrItem {
2439 pub tokens: Option<LazyTokenStream>,
2442 /// A list of attributes.
2443 pub type AttrVec = ThinVec<Attribute>;
2445 /// Metadata associated with an item.
2446 #[derive(Clone, Encodable, Decodable, Debug)]
2447 pub struct Attribute {
2450 /// Denotes if the attribute decorates the following construct (outer)
2451 /// or the construct this attribute is contained within (inner).
2452 pub style: AttrStyle,
2456 #[derive(Clone, Encodable, Decodable, Debug)]
2458 /// A normal attribute.
2459 Normal(AttrItem, Option<LazyTokenStream>),
2461 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2462 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2463 /// variant (which is much less compact and thus more expensive).
2464 DocComment(CommentKind, Symbol),
2467 /// `TraitRef`s appear in impls.
2469 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2470 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2471 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2472 /// same as the impl's `NodeId`).
2473 #[derive(Clone, Encodable, Decodable, Debug)]
2474 pub struct TraitRef {
2479 #[derive(Clone, Encodable, Decodable, Debug)]
2480 pub struct PolyTraitRef {
2481 /// The `'a` in `<'a> Foo<&'a T>`.
2482 pub bound_generic_params: Vec<GenericParam>,
2484 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2485 pub trait_ref: TraitRef,
2491 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2493 bound_generic_params: generic_params,
2494 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2500 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2501 pub enum CrateSugar {
2502 /// Source is `pub(crate)`.
2505 /// Source is (just) `crate`.
2509 #[derive(Clone, Encodable, Decodable, Debug)]
2510 pub struct Visibility {
2511 pub kind: VisibilityKind,
2513 pub tokens: Option<LazyTokenStream>,
2516 #[derive(Clone, Encodable, Decodable, Debug)]
2517 pub enum VisibilityKind {
2520 Restricted { path: P<Path>, id: NodeId },
2524 impl VisibilityKind {
2525 pub fn is_pub(&self) -> bool {
2526 matches!(self, VisibilityKind::Public)
2530 /// Field of a struct.
2532 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2533 #[derive(Clone, Encodable, Decodable, Debug)]
2534 pub struct StructField {
2535 pub attrs: Vec<Attribute>,
2538 pub vis: Visibility,
2539 pub ident: Option<Ident>,
2542 pub is_placeholder: bool,
2545 /// Fields and constructor ids of enum variants and structs.
2546 #[derive(Clone, Encodable, Decodable, Debug)]
2547 pub enum VariantData {
2550 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2551 Struct(Vec<StructField>, bool),
2554 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2555 Tuple(Vec<StructField>, NodeId),
2558 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2563 /// Return the fields of this variant.
2564 pub fn fields(&self) -> &[StructField] {
2566 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2571 /// Return the `NodeId` of this variant's constructor, if it has one.
2572 pub fn ctor_id(&self) -> Option<NodeId> {
2574 VariantData::Struct(..) => None,
2575 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2580 /// An item definition.
2581 #[derive(Clone, Encodable, Decodable, Debug)]
2582 pub struct Item<K = ItemKind> {
2583 pub attrs: Vec<Attribute>,
2586 pub vis: Visibility,
2587 /// The name of the item.
2588 /// It might be a dummy name in case of anonymous items.
2593 /// Original tokens this item was parsed from. This isn't necessarily
2594 /// available for all items, although over time more and more items should
2595 /// have this be `Some`. Right now this is primarily used for procedural
2596 /// macros, notably custom attributes.
2598 /// Note that the tokens here do not include the outer attributes, but will
2599 /// include inner attributes.
2600 pub tokens: Option<LazyTokenStream>,
2604 /// Return the span that encompasses the attributes.
2605 pub fn span_with_attributes(&self) -> Span {
2606 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2610 impl<K: Into<ItemKind>> Item<K> {
2611 pub fn into_item(self) -> Item {
2612 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2613 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2617 /// `extern` qualifier on a function item or function type.
2618 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2626 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2627 abi.map_or(Extern::Implicit, Extern::Explicit)
2631 /// A function header.
2633 /// All the information between the visibility and the name of the function is
2634 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2635 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2636 pub struct FnHeader {
2637 pub unsafety: Unsafe,
2638 pub asyncness: Async,
2639 pub constness: Const,
2644 /// Does this function header have any qualifiers or is it empty?
2645 pub fn has_qualifiers(&self) -> bool {
2646 let Self { unsafety, asyncness, constness, ext } = self;
2647 matches!(unsafety, Unsafe::Yes(_))
2648 || asyncness.is_async()
2649 || matches!(constness, Const::Yes(_))
2650 || !matches!(ext, Extern::None)
2654 impl Default for FnHeader {
2655 fn default() -> FnHeader {
2657 unsafety: Unsafe::No,
2658 asyncness: Async::No,
2659 constness: Const::No,
2665 #[derive(Clone, Encodable, Decodable, Debug)]
2667 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2669 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2670 ExternCrate(Option<Symbol>),
2671 /// A use declaration item (`use`).
2673 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2675 /// A static item (`static`).
2677 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2678 Static(P<Ty>, Mutability, Option<P<Expr>>),
2679 /// A constant item (`const`).
2681 /// E.g., `const FOO: i32 = 42;`.
2682 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2683 /// A function declaration (`fn`).
2685 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2686 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2687 /// A module declaration (`mod`).
2689 /// E.g., `mod foo;` or `mod foo { .. }`.
2691 /// An external module (`extern`).
2693 /// E.g., `extern {}` or `extern "C" {}`.
2694 ForeignMod(ForeignMod),
2695 /// Module-level inline assembly (from `global_asm!()`).
2696 GlobalAsm(P<GlobalAsm>),
2697 /// A type alias (`type`).
2699 /// E.g., `type Foo = Bar<u8>;`.
2700 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2701 /// An enum definition (`enum`).
2703 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2704 Enum(EnumDef, Generics),
2705 /// A struct definition (`struct`).
2707 /// E.g., `struct Foo<A> { x: A }`.
2708 Struct(VariantData, Generics),
2709 /// A union definition (`union`).
2711 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2712 Union(VariantData, Generics),
2713 /// A trait declaration (`trait`).
2715 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2716 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2719 /// E.g., `trait Foo = Bar + Quux;`.
2720 TraitAlias(Generics, GenericBounds),
2721 /// An implementation.
2723 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2726 polarity: ImplPolarity,
2727 defaultness: Defaultness,
2731 /// The trait being implemented, if any.
2732 of_trait: Option<TraitRef>,
2735 items: Vec<P<AssocItem>>,
2737 /// A macro invocation.
2739 /// E.g., `foo!(..)`.
2742 /// A macro definition.
2747 pub fn article(&self) -> &str {
2750 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2751 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2752 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2756 pub fn descr(&self) -> &str {
2758 ItemKind::ExternCrate(..) => "extern crate",
2759 ItemKind::Use(..) => "`use` import",
2760 ItemKind::Static(..) => "static item",
2761 ItemKind::Const(..) => "constant item",
2762 ItemKind::Fn(..) => "function",
2763 ItemKind::Mod(..) => "module",
2764 ItemKind::ForeignMod(..) => "extern block",
2765 ItemKind::GlobalAsm(..) => "global asm item",
2766 ItemKind::TyAlias(..) => "type alias",
2767 ItemKind::Enum(..) => "enum",
2768 ItemKind::Struct(..) => "struct",
2769 ItemKind::Union(..) => "union",
2770 ItemKind::Trait(..) => "trait",
2771 ItemKind::TraitAlias(..) => "trait alias",
2772 ItemKind::MacCall(..) => "item macro invocation",
2773 ItemKind::MacroDef(..) => "macro definition",
2774 ItemKind::Impl { .. } => "implementation",
2778 pub fn generics(&self) -> Option<&Generics> {
2780 Self::Fn(_, _, generics, _)
2781 | Self::TyAlias(_, generics, ..)
2782 | Self::Enum(_, generics)
2783 | Self::Struct(_, generics)
2784 | Self::Union(_, generics)
2785 | Self::Trait(_, _, generics, ..)
2786 | Self::TraitAlias(generics, _)
2787 | Self::Impl { generics, .. } => Some(generics),
2793 /// Represents associated items.
2794 /// These include items in `impl` and `trait` definitions.
2795 pub type AssocItem = Item<AssocItemKind>;
2797 /// Represents associated item kinds.
2799 /// The term "provided" in the variants below refers to the item having a default
2800 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2801 /// In an implementation, all items must be provided.
2802 /// The `Option`s below denote the bodies, where `Some(_)`
2803 /// means "provided" and conversely `None` means "required".
2804 #[derive(Clone, Encodable, Decodable, Debug)]
2805 pub enum AssocItemKind {
2806 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2807 /// If `def` is parsed, then the constant is provided, and otherwise required.
2808 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2809 /// An associated function.
2810 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2811 /// An associated type.
2812 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2813 /// A macro expanding to associated items.
2817 impl AssocItemKind {
2818 pub fn defaultness(&self) -> Defaultness {
2820 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2821 Self::MacCall(..) => Defaultness::Final,
2826 impl From<AssocItemKind> for ItemKind {
2827 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2828 match assoc_item_kind {
2829 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2830 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2831 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2832 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2837 impl TryFrom<ItemKind> for AssocItemKind {
2838 type Error = ItemKind;
2840 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2841 Ok(match item_kind {
2842 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2843 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2844 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2845 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2846 _ => return Err(item_kind),
2851 /// An item in `extern` block.
2852 #[derive(Clone, Encodable, Decodable, Debug)]
2853 pub enum ForeignItemKind {
2854 /// A foreign static item (`static FOO: u8`).
2855 Static(P<Ty>, Mutability, Option<P<Expr>>),
2856 /// A foreign function.
2857 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2859 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2860 /// A macro expanding to foreign items.
2864 impl From<ForeignItemKind> for ItemKind {
2865 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2866 match foreign_item_kind {
2867 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2868 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2869 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2870 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2875 impl TryFrom<ItemKind> for ForeignItemKind {
2876 type Error = ItemKind;
2878 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2879 Ok(match item_kind {
2880 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2881 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2882 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2883 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2884 _ => return Err(item_kind),
2889 pub type ForeignItem = Item<ForeignItemKind>;