1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
26 use crate::token::{self, CommentKind, DelimToken, Token};
27 use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree};
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable_Generic;
34 use rustc_serialize::{self, Decoder, Encoder};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
39 use std::cmp::Ordering;
40 use std::convert::TryFrom;
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
55 /// `'outer` is a label.
56 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
61 impl fmt::Debug for Label {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "label({:?})", self.ident)
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, Encodable, Decodable, Copy)]
75 impl fmt::Debug for Lifetime {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "lifetime({}: {})", self.id, self)
81 impl fmt::Display for Lifetime {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "{}", self.ident.name)
87 /// A "Path" is essentially Rust's notion of a name.
89 /// It's represented as a sequence of identifiers,
90 /// along with a bunch of supporting information.
92 /// E.g., `std::cmp::PartialEq`.
93 #[derive(Clone, Encodable, Decodable, Debug)]
96 /// The segments in the path: the things separated by `::`.
97 /// Global paths begin with `kw::PathRoot`.
98 pub segments: Vec<PathSegment>,
99 pub tokens: Option<LazyTokenStream>,
102 impl PartialEq<Symbol> for Path {
103 fn eq(&self, symbol: &Symbol) -> bool {
104 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
108 impl<CTX> HashStable<CTX> for Path {
109 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
110 self.segments.len().hash_stable(hcx, hasher);
111 for segment in &self.segments {
112 segment.ident.name.hash_stable(hcx, hasher);
118 // Convert a span and an identifier to the corresponding
120 pub fn from_ident(ident: Ident) -> Path {
121 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
124 pub fn is_global(&self) -> bool {
125 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
129 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
131 /// E.g., `std`, `String` or `Box<T>`.
132 #[derive(Clone, Encodable, Decodable, Debug)]
133 pub struct PathSegment {
134 /// The identifier portion of this path segment.
139 /// Type/lifetime parameters attached to this path. They come in
140 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
141 /// `None` means that no parameter list is supplied (`Path`),
142 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
143 /// but it can be empty (`Path<>`).
144 /// `P` is used as a size optimization for the common case with no parameters.
145 pub args: Option<P<GenericArgs>>,
149 pub fn from_ident(ident: Ident) -> Self {
150 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
153 pub fn path_root(span: Span) -> Self {
154 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
157 pub fn span(&self) -> Span {
159 Some(args) => self.ident.span.to(args.span()),
160 None => self.ident.span,
165 /// The arguments of a path segment.
167 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
168 #[derive(Clone, Encodable, Decodable, Debug)]
169 pub enum GenericArgs {
170 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
171 AngleBracketed(AngleBracketedArgs),
172 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
173 Parenthesized(ParenthesizedArgs),
177 pub fn is_angle_bracketed(&self) -> bool {
178 matches!(self, AngleBracketed(..))
181 pub fn span(&self) -> Span {
183 AngleBracketed(ref data) => data.span,
184 Parenthesized(ref data) => data.span,
189 /// Concrete argument in the sequence of generic args.
190 #[derive(Clone, Encodable, Decodable, Debug)]
191 pub enum GenericArg {
192 /// `'a` in `Foo<'a>`
194 /// `Bar` in `Foo<Bar>`
201 pub fn span(&self) -> Span {
203 GenericArg::Lifetime(lt) => lt.ident.span,
204 GenericArg::Type(ty) => ty.span,
205 GenericArg::Const(ct) => ct.value.span,
210 /// A path like `Foo<'a, T>`.
211 #[derive(Clone, Encodable, Decodable, Debug, Default)]
212 pub struct AngleBracketedArgs {
213 /// The overall span.
215 /// The comma separated parts in the `<...>`.
216 pub args: Vec<AngleBracketedArg>,
219 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
220 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
221 #[derive(Clone, Encodable, Decodable, Debug)]
222 pub enum AngleBracketedArg {
223 /// Argument for a generic parameter.
225 /// Constraint for an associated item.
226 Constraint(AssocTyConstraint),
229 impl AngleBracketedArg {
230 pub fn span(&self) -> Span {
232 AngleBracketedArg::Arg(arg) => arg.span(),
233 AngleBracketedArg::Constraint(constraint) => constraint.span,
238 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
239 fn into(self) -> Option<P<GenericArgs>> {
240 Some(P(GenericArgs::AngleBracketed(self)))
244 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
245 fn into(self) -> Option<P<GenericArgs>> {
246 Some(P(GenericArgs::Parenthesized(self)))
250 /// A path like `Foo(A, B) -> C`.
251 #[derive(Clone, Encodable, Decodable, Debug)]
252 pub struct ParenthesizedArgs {
260 pub inputs: Vec<P<Ty>>,
266 pub inputs_span: Span,
272 impl ParenthesizedArgs {
273 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
278 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
280 AngleBracketedArgs { span: self.span, args }
284 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
286 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
288 /// Negative bounds should also be handled here.
289 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
290 pub enum TraitBoundModifier {
302 // This parses but will be rejected during AST validation.
306 /// The AST represents all type param bounds as types.
307 /// `typeck::collect::compute_bounds` matches these against
308 /// the "special" built-in traits (see `middle::lang_items`) and
309 /// detects `Copy`, `Send` and `Sync`.
310 #[derive(Clone, Encodable, Decodable, Debug)]
311 pub enum GenericBound {
312 Trait(PolyTraitRef, TraitBoundModifier),
317 pub fn span(&self) -> Span {
319 GenericBound::Trait(ref t, ..) => t.span,
320 GenericBound::Outlives(ref l) => l.ident.span,
325 pub type GenericBounds = Vec<GenericBound>;
327 /// Specifies the enforced ordering for generic parameters. In the future,
328 /// if we wanted to relax this order, we could override `PartialEq` and
329 /// `PartialOrd`, to allow the kinds to be unordered.
330 #[derive(Hash, Clone, Copy)]
331 pub enum ParamKindOrd {
334 // `unordered` is only `true` if `sess.has_features().const_generics`
335 // is active. Specifically, if it's only `min_const_generics`, it will still require
336 // ordering consts after types.
337 Const { unordered: bool },
340 impl Ord for ParamKindOrd {
341 fn cmp(&self, other: &Self) -> Ordering {
343 let to_int = |v| match v {
345 Type | Const { unordered: true } => 1,
346 // technically both consts should be ordered equally,
347 // but only one is ever encountered at a time, so this is
349 Const { unordered: false } => 2,
352 to_int(*self).cmp(&to_int(*other))
355 impl PartialOrd for ParamKindOrd {
356 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
357 Some(self.cmp(other))
360 impl PartialEq for ParamKindOrd {
361 fn eq(&self, other: &Self) -> bool {
362 self.cmp(other) == Ordering::Equal
365 impl Eq for ParamKindOrd {}
367 impl fmt::Display for ParamKindOrd {
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 ParamKindOrd::Lifetime => "lifetime".fmt(f),
371 ParamKindOrd::Type => "type".fmt(f),
372 ParamKindOrd::Const { .. } => "const".fmt(f),
377 #[derive(Clone, Encodable, Decodable, Debug)]
378 pub enum GenericParamKind {
379 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
382 default: Option<P<Ty>>,
386 /// Span of the `const` keyword.
388 /// Optional default value for the const generic param
389 default: Option<AnonConst>,
393 #[derive(Clone, Encodable, Decodable, Debug)]
394 pub struct GenericParam {
398 pub bounds: GenericBounds,
399 pub is_placeholder: bool,
400 pub kind: GenericParamKind,
403 /// Represents lifetime, type and const parameters attached to a declaration of
404 /// a function, enum, trait, etc.
405 #[derive(Clone, Encodable, Decodable, Debug)]
406 pub struct Generics {
407 pub params: Vec<GenericParam>,
408 pub where_clause: WhereClause,
412 impl Default for Generics {
413 /// Creates an instance of `Generics`.
414 fn default() -> Generics {
417 where_clause: WhereClause {
418 has_where_token: false,
419 predicates: Vec::new(),
427 /// A where-clause in a definition.
428 #[derive(Clone, Encodable, Decodable, Debug)]
429 pub struct WhereClause {
430 /// `true` if we ate a `where` token: this can happen
431 /// if we parsed no predicates (e.g. `struct Foo where {}`).
432 /// This allows us to accurately pretty-print
433 /// in `nt_to_tokenstream`
434 pub has_where_token: bool,
435 pub predicates: Vec<WherePredicate>,
439 /// A single predicate in a where-clause.
440 #[derive(Clone, Encodable, Decodable, Debug)]
441 pub enum WherePredicate {
442 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
443 BoundPredicate(WhereBoundPredicate),
444 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
445 RegionPredicate(WhereRegionPredicate),
446 /// An equality predicate (unsupported).
447 EqPredicate(WhereEqPredicate),
450 impl WherePredicate {
451 pub fn span(&self) -> Span {
453 WherePredicate::BoundPredicate(p) => p.span,
454 WherePredicate::RegionPredicate(p) => p.span,
455 WherePredicate::EqPredicate(p) => p.span,
462 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
463 #[derive(Clone, Encodable, Decodable, Debug)]
464 pub struct WhereBoundPredicate {
466 /// Any generics from a `for` binding.
467 pub bound_generic_params: Vec<GenericParam>,
468 /// The type being bounded.
469 pub bounded_ty: P<Ty>,
470 /// Trait and lifetime bounds (`Clone + Send + 'static`).
471 pub bounds: GenericBounds,
474 /// A lifetime predicate.
476 /// E.g., `'a: 'b + 'c`.
477 #[derive(Clone, Encodable, Decodable, Debug)]
478 pub struct WhereRegionPredicate {
480 pub lifetime: Lifetime,
481 pub bounds: GenericBounds,
484 /// An equality predicate (unsupported).
487 #[derive(Clone, Encodable, Decodable, Debug)]
488 pub struct WhereEqPredicate {
495 #[derive(Clone, Encodable, Decodable, Debug)]
497 pub attrs: Vec<Attribute>,
498 pub items: Vec<P<Item>>,
500 /// The order of items in the HIR is unrelated to the order of
501 /// items in the AST. However, we generate proc macro harnesses
502 /// based on the AST order, and later refer to these harnesses
503 /// from the HIR. This field keeps track of the order in which
504 /// we generated proc macros harnesses, so that we can map
505 /// HIR proc macros items back to their harness items.
506 pub proc_macros: Vec<NodeId>,
509 /// Possible values inside of compile-time attribute lists.
511 /// E.g., the '..' in `#[name(..)]`.
512 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
513 pub enum NestedMetaItem {
514 /// A full MetaItem, for recursive meta items.
518 /// E.g., `"foo"`, `64`, `true`.
522 /// A spanned compile-time attribute item.
524 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
525 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
526 pub struct MetaItem {
528 pub kind: MetaItemKind,
532 /// A compile-time attribute item.
534 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
535 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
536 pub enum MetaItemKind {
539 /// E.g., `test` as in `#[test]`.
543 /// E.g., `derive(..)` as in `#[derive(..)]`.
544 List(Vec<NestedMetaItem>),
545 /// Name value meta item.
547 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
551 /// A block (`{ .. }`).
553 /// E.g., `{ .. }` as in `fn foo() { .. }`.
554 #[derive(Clone, Encodable, Decodable, Debug)]
556 /// The statements in the block.
557 pub stmts: Vec<Stmt>,
559 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
560 pub rules: BlockCheckMode,
562 pub tokens: Option<LazyTokenStream>,
567 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
568 #[derive(Clone, Encodable, Decodable, Debug)]
573 pub tokens: Option<LazyTokenStream>,
577 /// Attempt reparsing the pattern as a type.
578 /// This is intended for use by diagnostics.
579 pub fn to_ty(&self) -> Option<P<Ty>> {
580 let kind = match &self.kind {
581 // In a type expression `_` is an inference variable.
582 PatKind::Wild => TyKind::Infer,
583 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
584 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
585 TyKind::Path(None, Path::from_ident(*ident))
587 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
588 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
589 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
590 PatKind::Ref(pat, mutbl) => {
591 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
593 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
594 // when `P` can be reparsed as a type `T`.
595 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
596 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
597 // assuming `T0` to `Tn` are all syntactically valid as types.
598 PatKind::Tuple(pats) => {
599 let mut tys = Vec::with_capacity(pats.len());
600 // FIXME(#48994) - could just be collected into an Option<Vec>
602 tys.push(pat.to_ty()?);
609 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
612 /// Walk top-down and call `it` in each place where a pattern occurs
613 /// starting with the root pattern `walk` is called on. If `it` returns
614 /// false then we will descend no further but siblings will be processed.
615 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
621 // Walk into the pattern associated with `Ident` (if any).
622 PatKind::Ident(_, _, Some(p)) => p.walk(it),
624 // Walk into each field of struct.
625 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
627 // Sequence of patterns.
628 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
629 s.iter().for_each(|p| p.walk(it))
632 // Trivial wrappers over inner patterns.
633 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
635 // These patterns do not contain subpatterns, skip.
642 | PatKind::MacCall(_) => {}
646 /// Is this a `..` pattern?
647 pub fn is_rest(&self) -> bool {
648 matches!(self.kind, PatKind::Rest)
652 /// A single field in a struct pattern.
654 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
655 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
656 /// except when `is_shorthand` is true.
657 #[derive(Clone, Encodable, Decodable, Debug)]
658 pub struct PatField {
659 /// The identifier for the field.
661 /// The pattern the field is destructured to.
663 pub is_shorthand: bool,
667 pub is_placeholder: bool,
670 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
671 pub enum BindingMode {
676 #[derive(Clone, Encodable, Decodable, Debug)]
678 Included(RangeSyntax),
682 #[derive(Clone, Encodable, Decodable, Debug)]
683 pub enum RangeSyntax {
690 #[derive(Clone, Encodable, Decodable, Debug)]
692 /// Represents a wildcard pattern (`_`).
695 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
696 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
697 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
698 /// during name resolution.
699 Ident(BindingMode, Ident, Option<P<Pat>>),
701 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
702 /// The `bool` is `true` in the presence of a `..`.
703 Struct(Path, Vec<PatField>, /* recovered */ bool),
705 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
706 TupleStruct(Path, Vec<P<Pat>>),
708 /// An or-pattern `A | B | C`.
709 /// Invariant: `pats.len() >= 2`.
712 /// A possibly qualified path pattern.
713 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
714 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
715 /// only legally refer to associated constants.
716 Path(Option<QSelf>, Path),
718 /// A tuple pattern (`(a, b)`).
724 /// A reference pattern (e.g., `&mut (a, b)`).
725 Ref(P<Pat>, Mutability),
730 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
731 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
733 /// A slice pattern `[a, b, c]`.
736 /// A rest pattern `..`.
738 /// Syntactically it is valid anywhere.
740 /// Semantically however, it only has meaning immediately inside:
741 /// - a slice pattern: `[a, .., b]`,
742 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
743 /// - a tuple pattern: `(a, .., b)`,
744 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
746 /// In all of these cases, an additional restriction applies,
747 /// only one rest pattern may occur in the pattern sequences.
750 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
753 /// A macro pattern; pre-expansion.
757 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
758 #[derive(HashStable_Generic, Encodable, Decodable)]
759 pub enum Mutability {
765 pub fn invert(self) -> Self {
767 Mutability::Mut => Mutability::Not,
768 Mutability::Not => Mutability::Mut,
772 pub fn prefix_str(&self) -> &'static str {
774 Mutability::Mut => "mut ",
775 Mutability::Not => "",
780 /// The kind of borrow in an `AddrOf` expression,
781 /// e.g., `&place` or `&raw const place`.
782 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
783 #[derive(Encodable, Decodable, HashStable_Generic)]
784 pub enum BorrowKind {
785 /// A normal borrow, `&$expr` or `&mut $expr`.
786 /// The resulting type is either `&'a T` or `&'a mut T`
787 /// where `T = typeof($expr)` and `'a` is some lifetime.
789 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
790 /// The resulting type is either `*const T` or `*mut T`
791 /// where `T = typeof($expr)`.
795 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
797 /// The `+` operator (addition)
799 /// The `-` operator (subtraction)
801 /// The `*` operator (multiplication)
803 /// The `/` operator (division)
805 /// The `%` operator (modulus)
807 /// The `&&` operator (logical and)
809 /// The `||` operator (logical or)
811 /// The `^` operator (bitwise xor)
813 /// The `&` operator (bitwise and)
815 /// The `|` operator (bitwise or)
817 /// The `<<` operator (shift left)
819 /// The `>>` operator (shift right)
821 /// The `==` operator (equality)
823 /// The `<` operator (less than)
825 /// The `<=` operator (less than or equal to)
827 /// The `!=` operator (not equal to)
829 /// The `>=` operator (greater than or equal to)
831 /// The `>` operator (greater than)
836 pub fn to_string(&self) -> &'static str {
859 pub fn lazy(&self) -> bool {
860 matches!(self, BinOpKind::And | BinOpKind::Or)
863 pub fn is_comparison(&self) -> bool {
865 // Note for developers: please keep this as is;
866 // we want compilation to fail if another variant is added.
868 Eq | Lt | Le | Ne | Gt | Ge => true,
869 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
874 pub type BinOp = Spanned<BinOpKind>;
878 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
879 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
881 /// The `*` operator for dereferencing
883 /// The `!` operator for logical inversion
885 /// The `-` operator for negation
890 pub fn to_string(op: UnOp) -> &'static str {
900 #[derive(Clone, Encodable, Decodable, Debug)]
908 pub fn tokens(&self) -> Option<&LazyTokenStream> {
910 StmtKind::Local(ref local) => local.tokens.as_ref(),
911 StmtKind::Item(ref item) => item.tokens.as_ref(),
912 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(),
913 StmtKind::Empty => None,
914 StmtKind::MacCall(ref mac) => mac.tokens.as_ref(),
918 pub fn has_trailing_semicolon(&self) -> bool {
920 StmtKind::Semi(_) => true,
921 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
926 /// Converts a parsed `Stmt` to a `Stmt` with
927 /// a trailing semicolon.
929 /// This only modifies the parsed AST struct, not the attached
930 /// `LazyTokenStream`. The parser is responsible for calling
931 /// `CreateTokenStream::add_trailing_semi` when there is actually
932 /// a semicolon in the tokenstream.
933 pub fn add_trailing_semicolon(mut self) -> Self {
934 self.kind = match self.kind {
935 StmtKind::Expr(expr) => StmtKind::Semi(expr),
936 StmtKind::MacCall(mac) => {
937 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
938 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
947 pub fn is_item(&self) -> bool {
948 matches!(self.kind, StmtKind::Item(_))
951 pub fn is_expr(&self) -> bool {
952 matches!(self.kind, StmtKind::Expr(_))
956 #[derive(Clone, Encodable, Decodable, Debug)]
958 /// A local (let) binding.
960 /// An item definition.
962 /// Expr without trailing semi-colon.
964 /// Expr with a trailing semi-colon.
966 /// Just a trailing semi-colon.
969 MacCall(P<MacCallStmt>),
972 #[derive(Clone, Encodable, Decodable, Debug)]
973 pub struct MacCallStmt {
975 pub style: MacStmtStyle,
977 pub tokens: Option<LazyTokenStream>,
980 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
981 pub enum MacStmtStyle {
982 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
983 /// `foo!(...);`, `foo![...];`).
985 /// The macro statement had braces (e.g., `foo! { ... }`).
987 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
988 /// `foo!(...)`). All of these will end up being converted into macro
993 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
994 #[derive(Clone, Encodable, Decodable, Debug)]
998 pub ty: Option<P<Ty>>,
999 /// Initializer expression to set the value, if any.
1000 pub init: Option<P<Expr>>,
1003 pub tokens: Option<LazyTokenStream>,
1006 /// An arm of a 'match'.
1008 /// E.g., `0..=10 => { println!("match!") }` as in
1012 /// 0..=10 => { println!("match!") },
1013 /// _ => { println!("no match!") },
1016 #[derive(Clone, Encodable, Decodable, Debug)]
1018 pub attrs: Vec<Attribute>,
1019 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1021 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1022 pub guard: Option<P<Expr>>,
1027 pub is_placeholder: bool,
1030 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1031 #[derive(Clone, Encodable, Decodable, Debug)]
1032 pub struct ExprField {
1038 pub is_shorthand: bool,
1039 pub is_placeholder: bool,
1042 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1043 pub enum BlockCheckMode {
1045 Unsafe(UnsafeSource),
1048 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1049 pub enum UnsafeSource {
1054 /// A constant (expression) that's not an item or associated item,
1055 /// but needs its own `DefId` for type-checking, const-eval, etc.
1056 /// These are usually found nested inside types (e.g., array lengths)
1057 /// or expressions (e.g., repeat counts), and also used to define
1058 /// explicit discriminant values for enum variants.
1059 #[derive(Clone, Encodable, Decodable, Debug)]
1060 pub struct AnonConst {
1066 #[derive(Clone, Encodable, Decodable, Debug)]
1072 pub tokens: Option<LazyTokenStream>,
1075 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1076 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1077 rustc_data_structures::static_assert_size!(Expr, 104);
1080 /// Returns `true` if this expression would be valid somewhere that expects a value;
1081 /// for example, an `if` condition.
1082 pub fn returns(&self) -> bool {
1083 if let ExprKind::Block(ref block, _) = self.kind {
1084 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1086 Some(StmtKind::Expr(_)) => true,
1087 // Last statement is an explicit return?
1088 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1089 // This is a block that doesn't end in either an implicit or explicit return.
1093 // This is not a block, it is a value.
1098 /// Is this expr either `N`, or `{ N }`.
1100 /// If this is not the case, name resolution does not resolve `N` when using
1101 /// `min_const_generics` as more complex expressions are not supported.
1102 pub fn is_potential_trivial_const_param(&self) -> bool {
1103 let this = if let ExprKind::Block(ref block, None) = self.kind {
1104 if block.stmts.len() == 1 {
1105 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1113 if let ExprKind::Path(None, ref path) = this.kind {
1114 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1122 pub fn to_bound(&self) -> Option<GenericBound> {
1124 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1125 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1126 TraitBoundModifier::None,
1132 pub fn peel_parens(&self) -> &Expr {
1133 let mut expr = self;
1134 while let ExprKind::Paren(inner) = &expr.kind {
1140 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1141 pub fn to_ty(&self) -> Option<P<Ty>> {
1142 let kind = match &self.kind {
1143 // Trivial conversions.
1144 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1145 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1147 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1149 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1150 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1153 ExprKind::Repeat(expr, expr_len) => {
1154 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1157 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1159 ExprKind::Tup(exprs) => {
1160 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1164 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1165 // then type of result is trait object.
1166 // Otherwise we don't assume the result type.
1167 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1168 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1169 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1175 // This expression doesn't look like a type syntactically.
1179 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1182 pub fn precedence(&self) -> ExprPrecedence {
1184 ExprKind::Box(_) => ExprPrecedence::Box,
1185 ExprKind::Array(_) => ExprPrecedence::Array,
1186 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1187 ExprKind::Call(..) => ExprPrecedence::Call,
1188 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1189 ExprKind::Tup(_) => ExprPrecedence::Tup,
1190 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1191 ExprKind::Unary(..) => ExprPrecedence::Unary,
1192 ExprKind::Lit(_) => ExprPrecedence::Lit,
1193 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1194 ExprKind::Let(..) => ExprPrecedence::Let,
1195 ExprKind::If(..) => ExprPrecedence::If,
1196 ExprKind::While(..) => ExprPrecedence::While,
1197 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1198 ExprKind::Loop(..) => ExprPrecedence::Loop,
1199 ExprKind::Match(..) => ExprPrecedence::Match,
1200 ExprKind::Closure(..) => ExprPrecedence::Closure,
1201 ExprKind::Block(..) => ExprPrecedence::Block,
1202 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1203 ExprKind::Async(..) => ExprPrecedence::Async,
1204 ExprKind::Await(..) => ExprPrecedence::Await,
1205 ExprKind::Assign(..) => ExprPrecedence::Assign,
1206 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1207 ExprKind::Field(..) => ExprPrecedence::Field,
1208 ExprKind::Index(..) => ExprPrecedence::Index,
1209 ExprKind::Range(..) => ExprPrecedence::Range,
1210 ExprKind::Underscore => ExprPrecedence::Path,
1211 ExprKind::Path(..) => ExprPrecedence::Path,
1212 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1213 ExprKind::Break(..) => ExprPrecedence::Break,
1214 ExprKind::Continue(..) => ExprPrecedence::Continue,
1215 ExprKind::Ret(..) => ExprPrecedence::Ret,
1216 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1217 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1218 ExprKind::Struct(..) => ExprPrecedence::Struct,
1219 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1220 ExprKind::Paren(..) => ExprPrecedence::Paren,
1221 ExprKind::Try(..) => ExprPrecedence::Try,
1222 ExprKind::Yield(..) => ExprPrecedence::Yield,
1223 ExprKind::Err => ExprPrecedence::Err,
1228 /// Limit types of a range (inclusive or exclusive)
1229 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1230 pub enum RangeLimits {
1231 /// Inclusive at the beginning, exclusive at the end
1233 /// Inclusive at the beginning and end
1237 #[derive(Clone, Encodable, Decodable, Debug)]
1238 pub enum StructRest {
1243 /// No trailing `..` or expression.
1247 #[derive(Clone, Encodable, Decodable, Debug)]
1248 pub struct StructExpr {
1250 pub fields: Vec<ExprField>,
1251 pub rest: StructRest,
1254 #[derive(Clone, Encodable, Decodable, Debug)]
1256 /// A `box x` expression.
1258 /// An array (`[a, b, c, d]`)
1259 Array(Vec<P<Expr>>),
1260 /// Allow anonymous constants from an inline `const` block
1261 ConstBlock(AnonConst),
1264 /// The first field resolves to the function itself,
1265 /// and the second field is the list of arguments.
1266 /// This also represents calling the constructor of
1267 /// tuple-like ADTs such as tuple structs and enum variants.
1268 Call(P<Expr>, Vec<P<Expr>>),
1269 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1271 /// The `PathSegment` represents the method name and its generic arguments
1272 /// (within the angle brackets).
1273 /// The first element of the vector of an `Expr` is the expression that evaluates
1274 /// to the object on which the method is being called on (the receiver),
1275 /// and the remaining elements are the rest of the arguments.
1276 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1277 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1278 /// This `Span` is the span of the function, without the dot and receiver
1279 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1280 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1281 /// A tuple (e.g., `(a, b, c, d)`).
1283 /// A binary operation (e.g., `a + b`, `a * b`).
1284 Binary(BinOp, P<Expr>, P<Expr>),
1285 /// A unary operation (e.g., `!x`, `*x`).
1286 Unary(UnOp, P<Expr>),
1287 /// A literal (e.g., `1`, `"foo"`).
1289 /// A cast (e.g., `foo as f64`).
1290 Cast(P<Expr>, P<Ty>),
1291 /// A type ascription (e.g., `42: usize`).
1292 Type(P<Expr>, P<Ty>),
1293 /// A `let pat = expr` expression that is only semantically allowed in the condition
1294 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1295 Let(P<Pat>, P<Expr>),
1296 /// An `if` block, with an optional `else` block.
1298 /// `if expr { block } else { expr }`
1299 If(P<Expr>, P<Block>, Option<P<Expr>>),
1300 /// A while loop, with an optional label.
1302 /// `'label: while expr { block }`
1303 While(P<Expr>, P<Block>, Option<Label>),
1304 /// A `for` loop, with an optional label.
1306 /// `'label: for pat in expr { block }`
1308 /// This is desugared to a combination of `loop` and `match` expressions.
1309 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1310 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1312 /// `'label: loop { block }`
1313 Loop(P<Block>, Option<Label>),
1314 /// A `match` block.
1315 Match(P<Expr>, Vec<Arm>),
1316 /// A closure (e.g., `move |a, b, c| a + b + c`).
1318 /// The final span is the span of the argument block `|...|`.
1319 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1320 /// A block (`'label: { ... }`).
1321 Block(P<Block>, Option<Label>),
1322 /// An async block (`async move { ... }`).
1324 /// The `NodeId` is the `NodeId` for the closure that results from
1325 /// desugaring an async block, just like the NodeId field in the
1326 /// `Async::Yes` variant. This is necessary in order to create a def for the
1327 /// closure which can be used as a parent of any child defs. Defs
1328 /// created during lowering cannot be made the parent of any other
1329 /// preexisting defs.
1330 Async(CaptureBy, NodeId, P<Block>),
1331 /// An await expression (`my_future.await`).
1334 /// A try block (`try { ... }`).
1337 /// An assignment (`a = foo()`).
1338 /// The `Span` argument is the span of the `=` token.
1339 Assign(P<Expr>, P<Expr>, Span),
1340 /// An assignment with an operator.
1343 AssignOp(BinOp, P<Expr>, P<Expr>),
1344 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1345 Field(P<Expr>, Ident),
1346 /// An indexing operation (e.g., `foo[2]`).
1347 Index(P<Expr>, P<Expr>),
1348 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assingment).
1349 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1350 /// An underscore, used in destructuring assignment to ignore a value.
1353 /// Variable reference, possibly containing `::` and/or type
1354 /// parameters (e.g., `foo::bar::<baz>`).
1356 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1357 Path(Option<QSelf>, Path),
1359 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1360 AddrOf(BorrowKind, Mutability, P<Expr>),
1361 /// A `break`, with an optional label to break, and an optional expression.
1362 Break(Option<Label>, Option<P<Expr>>),
1363 /// A `continue`, with an optional label.
1364 Continue(Option<Label>),
1365 /// A `return`, with an optional value to be returned.
1366 Ret(Option<P<Expr>>),
1368 /// Output of the `asm!()` macro.
1369 InlineAsm(P<InlineAsm>),
1370 /// Output of the `llvm_asm!()` macro.
1371 LlvmInlineAsm(P<LlvmInlineAsm>),
1373 /// A macro invocation; pre-expansion.
1376 /// A struct literal expression.
1378 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1379 Struct(P<StructExpr>),
1381 /// An array literal constructed from one repeated element.
1383 /// E.g., `[1; 5]`. The expression is the element to be
1384 /// repeated; the constant is the number of times to repeat it.
1385 Repeat(P<Expr>, AnonConst),
1387 /// No-op: used solely so we can pretty-print faithfully.
1390 /// A try expression (`expr?`).
1393 /// A `yield`, with an optional value to be yielded.
1394 Yield(Option<P<Expr>>),
1396 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1400 /// The explicit `Self` type in a "qualified path". The actual
1401 /// path, including the trait and the associated item, is stored
1402 /// separately. `position` represents the index of the associated
1403 /// item qualified with this `Self` type.
1405 /// ```ignore (only-for-syntax-highlight)
1406 /// <Vec<T> as a::b::Trait>::AssociatedItem
1407 /// ^~~~~ ~~~~~~~~~~~~~~^
1410 /// <Vec<T>>::AssociatedItem
1414 #[derive(Clone, Encodable, Decodable, Debug)]
1418 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1419 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1420 /// 0`, this is an empty span.
1421 pub path_span: Span,
1422 pub position: usize,
1425 /// A capture clause used in closures and `async` blocks.
1426 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1427 pub enum CaptureBy {
1428 /// `move |x| y + x`.
1430 /// `move` keyword was not specified.
1434 /// The movability of a generator / closure literal:
1435 /// whether a generator contains self-references, causing it to be `!Unpin`.
1436 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1437 #[derive(HashStable_Generic)]
1438 pub enum Movability {
1439 /// May contain self-references, `!Unpin`.
1441 /// Must not contain self-references, `Unpin`.
1445 /// Represents a macro invocation. The `path` indicates which macro
1446 /// is being invoked, and the `args` are arguments passed to it.
1447 #[derive(Clone, Encodable, Decodable, Debug)]
1448 pub struct MacCall {
1450 pub args: P<MacArgs>,
1451 pub prior_type_ascription: Option<(Span, bool)>,
1455 pub fn span(&self) -> Span {
1456 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1460 /// Arguments passed to an attribute or a function-like macro.
1461 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1463 /// No arguments - `#[attr]`.
1465 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1466 Delimited(DelimSpan, MacDelimiter, TokenStream),
1467 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1469 /// Span of the `=` token.
1471 /// "value" as a nonterminal token.
1477 pub fn delim(&self) -> DelimToken {
1479 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1480 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1484 pub fn span(&self) -> Option<Span> {
1486 MacArgs::Empty => None,
1487 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1488 MacArgs::Eq(eq_span, token) => Some(eq_span.to(token.span)),
1492 /// Tokens inside the delimiters or after `=`.
1493 /// Proc macros see these tokens, for example.
1494 pub fn inner_tokens(&self) -> TokenStream {
1496 MacArgs::Empty => TokenStream::default(),
1497 MacArgs::Delimited(.., tokens) => tokens.clone(),
1498 MacArgs::Eq(.., token) => TokenTree::Token(token.clone()).into(),
1502 /// Whether a macro with these arguments needs a semicolon
1503 /// when used as a standalone item or statement.
1504 pub fn need_semicolon(&self) -> bool {
1505 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1509 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1510 pub enum MacDelimiter {
1517 pub fn to_token(self) -> DelimToken {
1519 MacDelimiter::Parenthesis => DelimToken::Paren,
1520 MacDelimiter::Bracket => DelimToken::Bracket,
1521 MacDelimiter::Brace => DelimToken::Brace,
1525 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1527 token::Paren => Some(MacDelimiter::Parenthesis),
1528 token::Bracket => Some(MacDelimiter::Bracket),
1529 token::Brace => Some(MacDelimiter::Brace),
1530 token::NoDelim => None,
1535 /// Represents a macro definition.
1536 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1537 pub struct MacroDef {
1538 pub body: P<MacArgs>,
1539 /// `true` if macro was defined with `macro_rules`.
1540 pub macro_rules: bool,
1543 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1544 #[derive(HashStable_Generic)]
1546 /// A regular string, like `"foo"`.
1548 /// A raw string, like `r##"foo"##`.
1550 /// The value is the number of `#` symbols used.
1555 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1557 /// The original literal token as written in source code.
1558 pub token: token::Lit,
1559 /// The "semantic" representation of the literal lowered from the original tokens.
1560 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1561 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1566 /// Same as `Lit`, but restricted to string literals.
1567 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1569 /// The original literal token as written in source code.
1570 pub style: StrStyle,
1572 pub suffix: Option<Symbol>,
1574 /// The unescaped "semantic" representation of the literal lowered from the original token.
1575 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1576 pub symbol_unescaped: Symbol,
1580 pub fn as_lit(&self) -> Lit {
1581 let token_kind = match self.style {
1582 StrStyle::Cooked => token::Str,
1583 StrStyle::Raw(n) => token::StrRaw(n),
1586 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1588 kind: LitKind::Str(self.symbol_unescaped, self.style),
1593 /// Type of the integer literal based on provided suffix.
1594 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1595 #[derive(HashStable_Generic)]
1596 pub enum LitIntType {
1605 /// Type of the float literal based on provided suffix.
1606 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1607 #[derive(HashStable_Generic)]
1608 pub enum LitFloatType {
1609 /// A float literal with a suffix (`1f32` or `1E10f32`).
1611 /// A float literal without a suffix (`1.0 or 1.0E10`).
1617 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1618 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1620 /// A string literal (`"foo"`).
1621 Str(Symbol, StrStyle),
1622 /// A byte string (`b"foo"`).
1624 /// A byte char (`b'f'`).
1626 /// A character literal (`'a'`).
1628 /// An integer literal (`1`).
1629 Int(u128, LitIntType),
1630 /// A float literal (`1f64` or `1E10f64`).
1631 Float(Symbol, LitFloatType),
1632 /// A boolean literal.
1634 /// Placeholder for a literal that wasn't well-formed in some way.
1639 /// Returns `true` if this literal is a string.
1640 pub fn is_str(&self) -> bool {
1641 matches!(self, LitKind::Str(..))
1644 /// Returns `true` if this literal is byte literal string.
1645 pub fn is_bytestr(&self) -> bool {
1646 matches!(self, LitKind::ByteStr(_))
1649 /// Returns `true` if this is a numeric literal.
1650 pub fn is_numeric(&self) -> bool {
1651 matches!(self, LitKind::Int(..) | LitKind::Float(..))
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,
1719 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1720 #[derive(Encodable, Decodable, HashStable_Generic)]
1731 pub fn name_str(&self) -> &'static str {
1733 IntTy::Isize => "isize",
1735 IntTy::I16 => "i16",
1736 IntTy::I32 => "i32",
1737 IntTy::I64 => "i64",
1738 IntTy::I128 => "i128",
1742 pub fn name(&self) -> Symbol {
1744 IntTy::Isize => sym::isize,
1745 IntTy::I8 => sym::i8,
1746 IntTy::I16 => sym::i16,
1747 IntTy::I32 => sym::i32,
1748 IntTy::I64 => sym::i64,
1749 IntTy::I128 => sym::i128,
1754 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1755 #[derive(Encodable, Decodable, HashStable_Generic)]
1766 pub fn name_str(&self) -> &'static str {
1768 UintTy::Usize => "usize",
1770 UintTy::U16 => "u16",
1771 UintTy::U32 => "u32",
1772 UintTy::U64 => "u64",
1773 UintTy::U128 => "u128",
1777 pub fn name(&self) -> Symbol {
1779 UintTy::Usize => sym::usize,
1780 UintTy::U8 => sym::u8,
1781 UintTy::U16 => sym::u16,
1782 UintTy::U32 => sym::u32,
1783 UintTy::U64 => sym::u64,
1784 UintTy::U128 => sym::u128,
1789 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1790 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1791 #[derive(Clone, Encodable, Decodable, Debug)]
1792 pub struct AssocTyConstraint {
1795 pub gen_args: Option<GenericArgs>,
1796 pub kind: AssocTyConstraintKind,
1800 /// The kinds of an `AssocTyConstraint`.
1801 #[derive(Clone, Encodable, Decodable, Debug)]
1802 pub enum AssocTyConstraintKind {
1803 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1804 Equality { ty: P<Ty> },
1805 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1806 Bound { bounds: GenericBounds },
1809 #[derive(Encodable, Decodable, Debug)]
1814 pub tokens: Option<LazyTokenStream>,
1818 fn clone(&self) -> Self {
1819 ensure_sufficient_stack(|| Self {
1821 kind: self.kind.clone(),
1823 tokens: self.tokens.clone(),
1829 pub fn peel_refs(&self) -> &Self {
1830 let mut final_ty = self;
1831 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1838 #[derive(Clone, Encodable, Decodable, Debug)]
1839 pub struct BareFnTy {
1840 pub unsafety: Unsafe,
1842 pub generic_params: Vec<GenericParam>,
1843 pub decl: P<FnDecl>,
1846 /// The various kinds of type recognized by the compiler.
1847 #[derive(Clone, Encodable, Decodable, Debug)]
1849 /// A variable-length slice (`[T]`).
1851 /// A fixed length array (`[T; n]`).
1852 Array(P<Ty>, AnonConst),
1853 /// A raw pointer (`*const T` or `*mut T`).
1855 /// A reference (`&'a T` or `&'a mut T`).
1856 Rptr(Option<Lifetime>, MutTy),
1857 /// A bare function (e.g., `fn(usize) -> bool`).
1858 BareFn(P<BareFnTy>),
1859 /// The never type (`!`).
1861 /// A tuple (`(A, B, C, D,...)`).
1863 /// A path (`module::module::...::Type`), optionally
1864 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1866 /// Type parameters are stored in the `Path` itself.
1867 Path(Option<QSelf>, Path),
1868 /// A trait object type `Bound1 + Bound2 + Bound3`
1869 /// where `Bound` is a trait or a lifetime.
1870 TraitObject(GenericBounds, TraitObjectSyntax),
1871 /// An `impl Bound1 + Bound2 + Bound3` type
1872 /// where `Bound` is a trait or a lifetime.
1874 /// The `NodeId` exists to prevent lowering from having to
1875 /// generate `NodeId`s on the fly, which would complicate
1876 /// the generation of opaque `type Foo = impl Trait` items significantly.
1877 ImplTrait(NodeId, GenericBounds),
1878 /// No-op; kept solely so that we can pretty-print faithfully.
1882 /// This means the type should be inferred instead of it having been
1883 /// specified. This can appear anywhere in a type.
1885 /// Inferred type of a `self` or `&self` argument in a method.
1887 /// A macro in the type position.
1889 /// Placeholder for a kind that has failed to be defined.
1891 /// Placeholder for a `va_list`.
1896 pub fn is_implicit_self(&self) -> bool {
1897 matches!(self, TyKind::ImplicitSelf)
1900 pub fn is_unit(&self) -> bool {
1901 matches!(self, TyKind::Tup(tys) if tys.is_empty())
1905 /// Syntax used to declare a trait object.
1906 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1907 pub enum TraitObjectSyntax {
1912 /// Inline assembly operand explicit register or register class.
1914 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1915 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1916 pub enum InlineAsmRegOrRegClass {
1921 bitflags::bitflags! {
1922 #[derive(Encodable, Decodable, HashStable_Generic)]
1923 pub struct InlineAsmOptions: u8 {
1924 const PURE = 1 << 0;
1925 const NOMEM = 1 << 1;
1926 const READONLY = 1 << 2;
1927 const PRESERVES_FLAGS = 1 << 3;
1928 const NORETURN = 1 << 4;
1929 const NOSTACK = 1 << 5;
1930 const ATT_SYNTAX = 1 << 6;
1934 #[derive(Clone, PartialEq, PartialOrd, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
1935 pub enum InlineAsmTemplatePiece {
1937 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1940 impl fmt::Display for InlineAsmTemplatePiece {
1941 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1943 Self::String(s) => {
1944 for c in s.chars() {
1946 '{' => f.write_str("{{")?,
1947 '}' => f.write_str("}}")?,
1953 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1954 write!(f, "{{{}:{}}}", operand_idx, modifier)
1956 Self::Placeholder { operand_idx, modifier: None, .. } => {
1957 write!(f, "{{{}}}", operand_idx)
1963 impl InlineAsmTemplatePiece {
1964 /// Rebuilds the asm template string from its pieces.
1965 pub fn to_string(s: &[Self]) -> String {
1967 let mut out = String::new();
1969 let _ = write!(out, "{}", p);
1975 /// Inline assembly operand.
1977 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
1978 #[derive(Clone, Encodable, Decodable, Debug)]
1979 pub enum InlineAsmOperand {
1981 reg: InlineAsmRegOrRegClass,
1985 reg: InlineAsmRegOrRegClass,
1987 expr: Option<P<Expr>>,
1990 reg: InlineAsmRegOrRegClass,
1995 reg: InlineAsmRegOrRegClass,
1998 out_expr: Option<P<Expr>>,
2001 anon_const: AnonConst,
2008 /// Inline assembly.
2010 /// E.g., `asm!("NOP");`.
2011 #[derive(Clone, Encodable, Decodable, Debug)]
2012 pub struct InlineAsm {
2013 pub template: Vec<InlineAsmTemplatePiece>,
2014 pub operands: Vec<(InlineAsmOperand, Span)>,
2015 pub options: InlineAsmOptions,
2016 pub line_spans: Vec<Span>,
2019 /// Inline assembly dialect.
2021 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2022 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Hash, HashStable_Generic)]
2023 pub enum LlvmAsmDialect {
2028 /// LLVM-style inline assembly.
2030 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2031 #[derive(Clone, Encodable, Decodable, Debug)]
2032 pub struct LlvmInlineAsmOutput {
2033 pub constraint: Symbol,
2036 pub is_indirect: bool,
2039 /// LLVM-style inline assembly.
2041 /// E.g., `llvm_asm!("NOP");`.
2042 #[derive(Clone, Encodable, Decodable, Debug)]
2043 pub struct LlvmInlineAsm {
2045 pub asm_str_style: StrStyle,
2046 pub outputs: Vec<LlvmInlineAsmOutput>,
2047 pub inputs: Vec<(Symbol, P<Expr>)>,
2048 pub clobbers: Vec<Symbol>,
2050 pub alignstack: bool,
2051 pub dialect: LlvmAsmDialect,
2054 /// A parameter in a function header.
2056 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2057 #[derive(Clone, Encodable, Decodable, Debug)]
2064 pub is_placeholder: bool,
2067 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2069 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2070 #[derive(Clone, Encodable, Decodable, Debug)]
2072 /// `self`, `mut self`
2074 /// `&'lt self`, `&'lt mut self`
2075 Region(Option<Lifetime>, Mutability),
2076 /// `self: TYPE`, `mut self: TYPE`
2077 Explicit(P<Ty>, Mutability),
2080 pub type ExplicitSelf = Spanned<SelfKind>;
2083 /// Attempts to cast parameter to `ExplicitSelf`.
2084 pub fn to_self(&self) -> Option<ExplicitSelf> {
2085 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2086 if ident.name == kw::SelfLower {
2087 return match self.ty.kind {
2088 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2089 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2090 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2093 self.pat.span.to(self.ty.span),
2094 SelfKind::Explicit(self.ty.clone(), mutbl),
2102 /// Returns `true` if parameter is `self`.
2103 pub fn is_self(&self) -> bool {
2104 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2105 ident.name == kw::SelfLower
2111 /// Builds a `Param` object from `ExplicitSelf`.
2112 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2113 let span = eself.span.to(eself_ident.span);
2114 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2115 let param = |mutbl, ty| Param {
2119 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2126 is_placeholder: false,
2129 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2130 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2131 SelfKind::Region(lt, mutbl) => param(
2135 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2144 /// A signature (not the body) of a function declaration.
2146 /// E.g., `fn foo(bar: baz)`.
2148 /// Please note that it's different from `FnHeader` structure
2149 /// which contains metadata about function safety, asyncness, constness and ABI.
2150 #[derive(Clone, Encodable, Decodable, Debug)]
2152 pub inputs: Vec<Param>,
2153 pub output: FnRetTy,
2157 pub fn has_self(&self) -> bool {
2158 self.inputs.get(0).map_or(false, Param::is_self)
2160 pub fn c_variadic(&self) -> bool {
2161 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2165 /// Is the trait definition an auto trait?
2166 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2172 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2173 #[derive(HashStable_Generic)]
2179 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2181 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2186 pub fn is_async(self) -> bool {
2187 matches!(self, Async::Yes { .. })
2190 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2191 pub fn opt_return_id(self) -> Option<NodeId> {
2193 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2199 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2200 #[derive(HashStable_Generic)]
2206 /// Item defaultness.
2207 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2208 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2209 pub enum Defaultness {
2214 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2215 pub enum ImplPolarity {
2216 /// `impl Trait for Type`
2218 /// `impl !Trait for Type`
2222 impl fmt::Debug for ImplPolarity {
2223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2225 ImplPolarity::Positive => "positive".fmt(f),
2226 ImplPolarity::Negative(_) => "negative".fmt(f),
2231 #[derive(Clone, Encodable, Decodable, Debug)]
2233 /// Returns type is not specified.
2235 /// Functions default to `()` and closures default to inference.
2236 /// Span points to where return type would be inserted.
2238 /// Everything else.
2243 pub fn span(&self) -> Span {
2245 FnRetTy::Default(span) => span,
2246 FnRetTy::Ty(ref ty) => ty.span,
2251 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2257 /// Module item kind.
2258 #[derive(Clone, Encodable, Decodable, Debug)]
2260 /// Module with inlined definition `mod foo { ... }`,
2261 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2262 /// The inner span is from the first token past `{` to the last token until `}`,
2263 /// or from the first to the last token in the loaded file.
2264 Loaded(Vec<P<Item>>, Inline, Span),
2265 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2269 /// Foreign module declaration.
2271 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2272 #[derive(Clone, Encodable, Decodable, Debug)]
2273 pub struct ForeignMod {
2274 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2275 /// semantically by Rust.
2276 pub unsafety: Unsafe,
2277 pub abi: Option<StrLit>,
2278 pub items: Vec<P<ForeignItem>>,
2281 /// Global inline assembly.
2283 /// Also known as "module-level assembly" or "file-scoped assembly".
2284 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2285 pub struct GlobalAsm {
2289 #[derive(Clone, Encodable, Decodable, Debug)]
2290 pub struct EnumDef {
2291 pub variants: Vec<Variant>,
2294 #[derive(Clone, Encodable, Decodable, Debug)]
2295 pub struct Variant {
2296 /// Attributes of the variant.
2297 pub attrs: Vec<Attribute>,
2298 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2302 /// The visibility of the variant. Syntactically accepted but not semantically.
2303 pub vis: Visibility,
2304 /// Name of the variant.
2307 /// Fields and constructor id of the variant.
2308 pub data: VariantData,
2309 /// Explicit discriminant, e.g., `Foo = 1`.
2310 pub disr_expr: Option<AnonConst>,
2311 /// Is a macro placeholder
2312 pub is_placeholder: bool,
2315 /// Part of `use` item to the right of its prefix.
2316 #[derive(Clone, Encodable, Decodable, Debug)]
2317 pub enum UseTreeKind {
2318 /// `use prefix` or `use prefix as rename`
2320 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2322 Simple(Option<Ident>, NodeId, NodeId),
2323 /// `use prefix::{...}`
2324 Nested(Vec<(UseTree, NodeId)>),
2329 /// A tree of paths sharing common prefixes.
2330 /// Used in `use` items both at top-level and inside of braces in import groups.
2331 #[derive(Clone, Encodable, Decodable, Debug)]
2332 pub struct UseTree {
2334 pub kind: UseTreeKind,
2339 pub fn ident(&self) -> Ident {
2341 UseTreeKind::Simple(Some(rename), ..) => rename,
2342 UseTreeKind::Simple(None, ..) => {
2343 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2345 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2350 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2351 /// are contained as statements within items. These two cases need to be
2352 /// distinguished for pretty-printing.
2353 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2354 pub enum AttrStyle {
2359 rustc_index::newtype_index! {
2362 DEBUG_FORMAT = "AttrId({})"
2366 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2367 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2372 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2373 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2374 d.read_nil().map(|_| crate::attr::mk_attr_id())
2378 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2379 pub struct AttrItem {
2382 pub tokens: Option<LazyTokenStream>,
2385 /// A list of attributes.
2386 pub type AttrVec = ThinVec<Attribute>;
2388 /// Metadata associated with an item.
2389 #[derive(Clone, Encodable, Decodable, Debug)]
2390 pub struct Attribute {
2393 /// Denotes if the attribute decorates the following construct (outer)
2394 /// or the construct this attribute is contained within (inner).
2395 pub style: AttrStyle,
2399 #[derive(Clone, Encodable, Decodable, Debug)]
2401 /// A normal attribute.
2402 Normal(AttrItem, Option<LazyTokenStream>),
2404 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2405 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2406 /// variant (which is much less compact and thus more expensive).
2407 DocComment(CommentKind, Symbol),
2410 /// `TraitRef`s appear in impls.
2412 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2413 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2414 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2415 /// same as the impl's `NodeId`).
2416 #[derive(Clone, Encodable, Decodable, Debug)]
2417 pub struct TraitRef {
2422 #[derive(Clone, Encodable, Decodable, Debug)]
2423 pub struct PolyTraitRef {
2424 /// The `'a` in `<'a> Foo<&'a T>`.
2425 pub bound_generic_params: Vec<GenericParam>,
2427 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2428 pub trait_ref: TraitRef,
2434 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2436 bound_generic_params: generic_params,
2437 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2443 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2444 pub enum CrateSugar {
2445 /// Source is `pub(crate)`.
2448 /// Source is (just) `crate`.
2452 #[derive(Clone, Encodable, Decodable, Debug)]
2453 pub struct Visibility {
2454 pub kind: VisibilityKind,
2456 pub tokens: Option<LazyTokenStream>,
2459 #[derive(Clone, Encodable, Decodable, Debug)]
2460 pub enum VisibilityKind {
2463 Restricted { path: P<Path>, id: NodeId },
2467 impl VisibilityKind {
2468 pub fn is_pub(&self) -> bool {
2469 matches!(self, VisibilityKind::Public)
2473 /// Field definition in a struct, variant or union.
2475 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2476 #[derive(Clone, Encodable, Decodable, Debug)]
2477 pub struct FieldDef {
2478 pub attrs: Vec<Attribute>,
2481 pub vis: Visibility,
2482 pub ident: Option<Ident>,
2485 pub is_placeholder: bool,
2488 /// Fields and constructor ids of enum variants and structs.
2489 #[derive(Clone, Encodable, Decodable, Debug)]
2490 pub enum VariantData {
2493 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2494 Struct(Vec<FieldDef>, bool),
2497 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2498 Tuple(Vec<FieldDef>, NodeId),
2501 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2506 /// Return the fields of this variant.
2507 pub fn fields(&self) -> &[FieldDef] {
2509 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2514 /// Return the `NodeId` of this variant's constructor, if it has one.
2515 pub fn ctor_id(&self) -> Option<NodeId> {
2517 VariantData::Struct(..) => None,
2518 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2523 /// An item definition.
2524 #[derive(Clone, Encodable, Decodable, Debug)]
2525 pub struct Item<K = ItemKind> {
2526 pub attrs: Vec<Attribute>,
2529 pub vis: Visibility,
2530 /// The name of the item.
2531 /// It might be a dummy name in case of anonymous items.
2536 /// Original tokens this item was parsed from. This isn't necessarily
2537 /// available for all items, although over time more and more items should
2538 /// have this be `Some`. Right now this is primarily used for procedural
2539 /// macros, notably custom attributes.
2541 /// Note that the tokens here do not include the outer attributes, but will
2542 /// include inner attributes.
2543 pub tokens: Option<LazyTokenStream>,
2547 /// Return the span that encompasses the attributes.
2548 pub fn span_with_attributes(&self) -> Span {
2549 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2553 impl<K: Into<ItemKind>> Item<K> {
2554 pub fn into_item(self) -> Item {
2555 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2556 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2560 /// `extern` qualifier on a function item or function type.
2561 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2569 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2570 abi.map_or(Extern::Implicit, Extern::Explicit)
2574 /// A function header.
2576 /// All the information between the visibility and the name of the function is
2577 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2578 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2579 pub struct FnHeader {
2580 pub unsafety: Unsafe,
2581 pub asyncness: Async,
2582 pub constness: Const,
2587 /// Does this function header have any qualifiers or is it empty?
2588 pub fn has_qualifiers(&self) -> bool {
2589 let Self { unsafety, asyncness, constness, ext } = self;
2590 matches!(unsafety, Unsafe::Yes(_))
2591 || asyncness.is_async()
2592 || matches!(constness, Const::Yes(_))
2593 || !matches!(ext, Extern::None)
2597 impl Default for FnHeader {
2598 fn default() -> FnHeader {
2600 unsafety: Unsafe::No,
2601 asyncness: Async::No,
2602 constness: Const::No,
2608 #[derive(Clone, Encodable, Decodable, Debug)]
2609 pub struct TraitKind(
2614 pub Vec<P<AssocItem>>,
2617 #[derive(Clone, Encodable, Decodable, Debug)]
2618 pub struct TyAliasKind(pub Defaultness, pub Generics, pub GenericBounds, pub Option<P<Ty>>);
2620 #[derive(Clone, Encodable, Decodable, Debug)]
2621 pub struct ImplKind {
2622 pub unsafety: Unsafe,
2623 pub polarity: ImplPolarity,
2624 pub defaultness: Defaultness,
2625 pub constness: Const,
2626 pub generics: Generics,
2628 /// The trait being implemented, if any.
2629 pub of_trait: Option<TraitRef>,
2632 pub items: Vec<P<AssocItem>>,
2635 #[derive(Clone, Encodable, Decodable, Debug)]
2636 pub struct FnKind(pub Defaultness, pub FnSig, pub Generics, pub Option<P<Block>>);
2638 #[derive(Clone, Encodable, Decodable, Debug)]
2640 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2642 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2643 ExternCrate(Option<Symbol>),
2644 /// A use declaration item (`use`).
2646 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2648 /// A static item (`static`).
2650 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2651 Static(P<Ty>, Mutability, Option<P<Expr>>),
2652 /// A constant item (`const`).
2654 /// E.g., `const FOO: i32 = 42;`.
2655 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2656 /// A function declaration (`fn`).
2658 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2660 /// A module declaration (`mod`).
2662 /// E.g., `mod foo;` or `mod foo { .. }`.
2663 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2664 /// semantically by Rust.
2665 Mod(Unsafe, ModKind),
2666 /// An external module (`extern`).
2668 /// E.g., `extern {}` or `extern "C" {}`.
2669 ForeignMod(ForeignMod),
2670 /// Module-level inline assembly (from `global_asm!()`).
2671 GlobalAsm(GlobalAsm),
2672 /// A type alias (`type`).
2674 /// E.g., `type Foo = Bar<u8>;`.
2675 TyAlias(Box<TyAliasKind>),
2676 /// An enum definition (`enum`).
2678 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2679 Enum(EnumDef, Generics),
2680 /// A struct definition (`struct`).
2682 /// E.g., `struct Foo<A> { x: A }`.
2683 Struct(VariantData, Generics),
2684 /// A union definition (`union`).
2686 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2687 Union(VariantData, Generics),
2688 /// A trait declaration (`trait`).
2690 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2691 Trait(Box<TraitKind>),
2694 /// E.g., `trait Foo = Bar + Quux;`.
2695 TraitAlias(Generics, GenericBounds),
2696 /// An implementation.
2698 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2699 Impl(Box<ImplKind>),
2700 /// A macro invocation.
2702 /// E.g., `foo!(..)`.
2705 /// A macro definition.
2709 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2710 rustc_data_structures::static_assert_size!(ItemKind, 112);
2713 pub fn article(&self) -> &str {
2716 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2717 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2718 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2722 pub fn descr(&self) -> &str {
2724 ItemKind::ExternCrate(..) => "extern crate",
2725 ItemKind::Use(..) => "`use` import",
2726 ItemKind::Static(..) => "static item",
2727 ItemKind::Const(..) => "constant item",
2728 ItemKind::Fn(..) => "function",
2729 ItemKind::Mod(..) => "module",
2730 ItemKind::ForeignMod(..) => "extern block",
2731 ItemKind::GlobalAsm(..) => "global asm item",
2732 ItemKind::TyAlias(..) => "type alias",
2733 ItemKind::Enum(..) => "enum",
2734 ItemKind::Struct(..) => "struct",
2735 ItemKind::Union(..) => "union",
2736 ItemKind::Trait(..) => "trait",
2737 ItemKind::TraitAlias(..) => "trait alias",
2738 ItemKind::MacCall(..) => "item macro invocation",
2739 ItemKind::MacroDef(..) => "macro definition",
2740 ItemKind::Impl { .. } => "implementation",
2744 pub fn generics(&self) -> Option<&Generics> {
2746 Self::Fn(box FnKind(_, _, generics, _))
2747 | Self::TyAlias(box TyAliasKind(_, generics, ..))
2748 | Self::Enum(_, generics)
2749 | Self::Struct(_, generics)
2750 | Self::Union(_, generics)
2751 | Self::Trait(box TraitKind(_, _, generics, ..))
2752 | Self::TraitAlias(generics, _)
2753 | Self::Impl(box ImplKind { generics, .. }) => Some(generics),
2759 /// Represents associated items.
2760 /// These include items in `impl` and `trait` definitions.
2761 pub type AssocItem = Item<AssocItemKind>;
2763 /// Represents associated item kinds.
2765 /// The term "provided" in the variants below refers to the item having a default
2766 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2767 /// In an implementation, all items must be provided.
2768 /// The `Option`s below denote the bodies, where `Some(_)`
2769 /// means "provided" and conversely `None` means "required".
2770 #[derive(Clone, Encodable, Decodable, Debug)]
2771 pub enum AssocItemKind {
2772 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2773 /// If `def` is parsed, then the constant is provided, and otherwise required.
2774 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2775 /// An associated function.
2777 /// An associated type.
2778 TyAlias(Box<TyAliasKind>),
2779 /// A macro expanding to associated items.
2783 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2784 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2786 impl AssocItemKind {
2787 pub fn defaultness(&self) -> Defaultness {
2789 Self::Const(def, ..)
2790 | Self::Fn(box FnKind(def, ..))
2791 | Self::TyAlias(box TyAliasKind(def, ..)) => def,
2792 Self::MacCall(..) => Defaultness::Final,
2797 impl From<AssocItemKind> for ItemKind {
2798 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2799 match assoc_item_kind {
2800 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2801 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2802 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2803 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2808 impl TryFrom<ItemKind> for AssocItemKind {
2809 type Error = ItemKind;
2811 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2812 Ok(match item_kind {
2813 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2814 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2815 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2816 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2817 _ => return Err(item_kind),
2822 /// An item in `extern` block.
2823 #[derive(Clone, Encodable, Decodable, Debug)]
2824 pub enum ForeignItemKind {
2825 /// A foreign static item (`static FOO: u8`).
2826 Static(P<Ty>, Mutability, Option<P<Expr>>),
2827 /// An foreign function.
2829 /// An foreign type.
2830 TyAlias(Box<TyAliasKind>),
2831 /// A macro expanding to foreign items.
2835 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2836 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
2838 impl From<ForeignItemKind> for ItemKind {
2839 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2840 match foreign_item_kind {
2841 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2842 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2843 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2844 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2849 impl TryFrom<ItemKind> for ForeignItemKind {
2850 type Error = ItemKind;
2852 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2853 Ok(match item_kind {
2854 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2855 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
2856 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
2857 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2858 _ => return Err(item_kind),
2863 pub type ForeignItem = Item<ForeignItemKind>;