1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
26 use crate::token::{self, CommentKind, DelimToken, Token};
27 use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree};
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable_Generic;
34 use rustc_serialize::{self, Decoder, Encoder};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
39 use std::cmp::Ordering;
40 use std::convert::TryFrom;
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
55 /// `'outer` is a label.
56 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)]
61 impl fmt::Debug for Label {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "label({:?})", self.ident)
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, Encodable, Decodable, Copy)]
75 impl fmt::Debug for Lifetime {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "lifetime({}: {})", self.id, self)
81 impl fmt::Display for Lifetime {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "{}", self.ident.name)
87 /// A "Path" is essentially Rust's notion of a name.
89 /// It's represented as a sequence of identifiers,
90 /// along with a bunch of supporting information.
92 /// E.g., `std::cmp::PartialEq`.
93 #[derive(Clone, Encodable, Decodable, Debug)]
96 /// The segments in the path: the things separated by `::`.
97 /// Global paths begin with `kw::PathRoot`.
98 pub segments: Vec<PathSegment>,
99 pub tokens: Option<LazyTokenStream>,
102 impl PartialEq<Symbol> for Path {
104 fn eq(&self, symbol: &Symbol) -> bool {
105 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
109 impl<CTX> HashStable<CTX> for Path {
110 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
111 self.segments.len().hash_stable(hcx, hasher);
112 for segment in &self.segments {
113 segment.ident.name.hash_stable(hcx, hasher);
119 // Convert a span and an identifier to the corresponding
121 pub fn from_ident(ident: Ident) -> Path {
122 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
125 pub fn is_global(&self) -> bool {
126 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
130 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
132 /// E.g., `std`, `String` or `Box<T>`.
133 #[derive(Clone, Encodable, Decodable, Debug)]
134 pub struct PathSegment {
135 /// The identifier portion of this path segment.
140 /// Type/lifetime parameters attached to this path. They come in
141 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
142 /// `None` means that no parameter list is supplied (`Path`),
143 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
144 /// but it can be empty (`Path<>`).
145 /// `P` is used as a size optimization for the common case with no parameters.
146 pub args: Option<P<GenericArgs>>,
150 pub fn from_ident(ident: Ident) -> Self {
151 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
154 pub fn path_root(span: Span) -> Self {
155 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
158 pub fn span(&self) -> Span {
160 Some(args) => self.ident.span.to(args.span()),
161 None => self.ident.span,
166 /// The arguments of a path segment.
168 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
169 #[derive(Clone, Encodable, Decodable, Debug)]
170 pub enum GenericArgs {
171 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
172 AngleBracketed(AngleBracketedArgs),
173 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
174 Parenthesized(ParenthesizedArgs),
178 pub fn is_angle_bracketed(&self) -> bool {
179 matches!(self, AngleBracketed(..))
182 pub fn span(&self) -> Span {
184 AngleBracketed(ref data) => data.span,
185 Parenthesized(ref data) => data.span,
190 /// Concrete argument in the sequence of generic args.
191 #[derive(Clone, Encodable, Decodable, Debug)]
192 pub enum GenericArg {
193 /// `'a` in `Foo<'a>`
195 /// `Bar` in `Foo<Bar>`
202 pub fn span(&self) -> Span {
204 GenericArg::Lifetime(lt) => lt.ident.span,
205 GenericArg::Type(ty) => ty.span,
206 GenericArg::Const(ct) => ct.value.span,
211 /// A path like `Foo<'a, T>`.
212 #[derive(Clone, Encodable, Decodable, Debug, Default)]
213 pub struct AngleBracketedArgs {
214 /// The overall span.
216 /// The comma separated parts in the `<...>`.
217 pub args: Vec<AngleBracketedArg>,
220 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
221 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
222 #[derive(Clone, Encodable, Decodable, Debug)]
223 pub enum AngleBracketedArg {
224 /// Argument for a generic parameter.
226 /// Constraint for an associated item.
227 Constraint(AssocTyConstraint),
230 impl AngleBracketedArg {
231 pub fn span(&self) -> Span {
233 AngleBracketedArg::Arg(arg) => arg.span(),
234 AngleBracketedArg::Constraint(constraint) => constraint.span,
239 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
240 fn into(self) -> Option<P<GenericArgs>> {
241 Some(P(GenericArgs::AngleBracketed(self)))
245 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
246 fn into(self) -> Option<P<GenericArgs>> {
247 Some(P(GenericArgs::Parenthesized(self)))
251 /// A path like `Foo(A, B) -> C`.
252 #[derive(Clone, Encodable, Decodable, Debug)]
253 pub struct ParenthesizedArgs {
261 pub inputs: Vec<P<Ty>>,
267 pub inputs_span: Span,
273 impl ParenthesizedArgs {
274 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
279 .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
281 AngleBracketedArgs { span: self.span, args }
285 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
287 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
289 /// Negative bounds should also be handled here.
290 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
291 pub enum TraitBoundModifier {
303 // This parses but will be rejected during AST validation.
307 /// The AST represents all type param bounds as types.
308 /// `typeck::collect::compute_bounds` matches these against
309 /// the "special" built-in traits (see `middle::lang_items`) and
310 /// detects `Copy`, `Send` and `Sync`.
311 #[derive(Clone, Encodable, Decodable, Debug)]
312 pub enum GenericBound {
313 Trait(PolyTraitRef, TraitBoundModifier),
318 pub fn span(&self) -> Span {
320 GenericBound::Trait(ref t, ..) => t.span,
321 GenericBound::Outlives(ref l) => l.ident.span,
326 pub type GenericBounds = Vec<GenericBound>;
328 /// Specifies the enforced ordering for generic parameters. In the future,
329 /// if we wanted to relax this order, we could override `PartialEq` and
330 /// `PartialOrd`, to allow the kinds to be unordered.
331 #[derive(Hash, Clone, Copy)]
332 pub enum ParamKindOrd {
335 // `unordered` is only `true` if `sess.has_features().const_generics`
336 // is active. Specifically, if it's only `min_const_generics`, it will still require
337 // ordering consts after types.
338 Const { unordered: bool },
341 impl Ord for ParamKindOrd {
342 fn cmp(&self, other: &Self) -> Ordering {
344 let to_int = |v| match v {
346 Type | Const { unordered: true } => 1,
347 // technically both consts should be ordered equally,
348 // but only one is ever encountered at a time, so this is
350 Const { unordered: false } => 2,
353 to_int(*self).cmp(&to_int(*other))
356 impl PartialOrd for ParamKindOrd {
357 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
358 Some(self.cmp(other))
361 impl PartialEq for ParamKindOrd {
362 fn eq(&self, other: &Self) -> bool {
363 self.cmp(other) == Ordering::Equal
366 impl Eq for ParamKindOrd {}
368 impl fmt::Display for ParamKindOrd {
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 ParamKindOrd::Lifetime => "lifetime".fmt(f),
372 ParamKindOrd::Type => "type".fmt(f),
373 ParamKindOrd::Const { .. } => "const".fmt(f),
378 #[derive(Clone, Encodable, Decodable, Debug)]
379 pub enum GenericParamKind {
380 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
383 default: Option<P<Ty>>,
387 /// Span of the `const` keyword.
389 /// Optional default value for the const generic param
390 default: Option<AnonConst>,
394 #[derive(Clone, Encodable, Decodable, Debug)]
395 pub struct GenericParam {
399 pub bounds: GenericBounds,
400 pub is_placeholder: bool,
401 pub kind: GenericParamKind,
404 /// Represents lifetime, type and const parameters attached to a declaration of
405 /// a function, enum, trait, etc.
406 #[derive(Clone, Encodable, Decodable, Debug)]
407 pub struct Generics {
408 pub params: Vec<GenericParam>,
409 pub where_clause: WhereClause,
413 impl Default for Generics {
414 /// Creates an instance of `Generics`.
415 fn default() -> Generics {
418 where_clause: WhereClause {
419 has_where_token: false,
420 predicates: Vec::new(),
428 /// A where-clause in a definition.
429 #[derive(Clone, Encodable, Decodable, Debug)]
430 pub struct WhereClause {
431 /// `true` if we ate a `where` token: this can happen
432 /// if we parsed no predicates (e.g. `struct Foo where {}`).
433 /// This allows us to accurately pretty-print
434 /// in `nt_to_tokenstream`
435 pub has_where_token: bool,
436 pub predicates: Vec<WherePredicate>,
440 /// A single predicate in a where-clause.
441 #[derive(Clone, Encodable, Decodable, Debug)]
442 pub enum WherePredicate {
443 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
444 BoundPredicate(WhereBoundPredicate),
445 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
446 RegionPredicate(WhereRegionPredicate),
447 /// An equality predicate (unsupported).
448 EqPredicate(WhereEqPredicate),
451 impl WherePredicate {
452 pub fn span(&self) -> Span {
454 WherePredicate::BoundPredicate(p) => p.span,
455 WherePredicate::RegionPredicate(p) => p.span,
456 WherePredicate::EqPredicate(p) => p.span,
463 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
464 #[derive(Clone, Encodable, Decodable, Debug)]
465 pub struct WhereBoundPredicate {
467 /// Any generics from a `for` binding.
468 pub bound_generic_params: Vec<GenericParam>,
469 /// The type being bounded.
470 pub bounded_ty: P<Ty>,
471 /// Trait and lifetime bounds (`Clone + Send + 'static`).
472 pub bounds: GenericBounds,
475 /// A lifetime predicate.
477 /// E.g., `'a: 'b + 'c`.
478 #[derive(Clone, Encodable, Decodable, Debug)]
479 pub struct WhereRegionPredicate {
481 pub lifetime: Lifetime,
482 pub bounds: GenericBounds,
485 /// An equality predicate (unsupported).
488 #[derive(Clone, Encodable, Decodable, Debug)]
489 pub struct WhereEqPredicate {
496 #[derive(Clone, Encodable, Decodable, Debug)]
498 pub attrs: Vec<Attribute>,
499 pub items: Vec<P<Item>>,
501 /// The order of items in the HIR is unrelated to the order of
502 /// items in the AST. However, we generate proc macro harnesses
503 /// based on the AST order, and later refer to these harnesses
504 /// from the HIR. This field keeps track of the order in which
505 /// we generated proc macros harnesses, so that we can map
506 /// HIR proc macros items back to their harness items.
507 pub proc_macros: Vec<NodeId>,
510 /// Possible values inside of compile-time attribute lists.
512 /// E.g., the '..' in `#[name(..)]`.
513 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
514 pub enum NestedMetaItem {
515 /// A full MetaItem, for recursive meta items.
519 /// E.g., `"foo"`, `64`, `true`.
523 /// A spanned compile-time attribute item.
525 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
526 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
527 pub struct MetaItem {
529 pub kind: MetaItemKind,
533 /// A compile-time attribute item.
535 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
536 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
537 pub enum MetaItemKind {
540 /// E.g., `test` as in `#[test]`.
544 /// E.g., `derive(..)` as in `#[derive(..)]`.
545 List(Vec<NestedMetaItem>),
546 /// Name value meta item.
548 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
552 /// A block (`{ .. }`).
554 /// E.g., `{ .. }` as in `fn foo() { .. }`.
555 #[derive(Clone, Encodable, Decodable, Debug)]
557 /// The statements in the block.
558 pub stmts: Vec<Stmt>,
560 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
561 pub rules: BlockCheckMode,
563 pub tokens: Option<LazyTokenStream>,
568 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
569 #[derive(Clone, Encodable, Decodable, Debug)]
574 pub tokens: Option<LazyTokenStream>,
578 /// Attempt reparsing the pattern as a type.
579 /// This is intended for use by diagnostics.
580 pub fn to_ty(&self) -> Option<P<Ty>> {
581 let kind = match &self.kind {
582 // In a type expression `_` is an inference variable.
583 PatKind::Wild => TyKind::Infer,
584 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
585 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
586 TyKind::Path(None, Path::from_ident(*ident))
588 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
589 PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
590 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
591 PatKind::Ref(pat, mutbl) => {
592 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
594 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
595 // when `P` can be reparsed as a type `T`.
596 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
597 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
598 // assuming `T0` to `Tn` are all syntactically valid as types.
599 PatKind::Tuple(pats) => {
600 let mut tys = Vec::with_capacity(pats.len());
601 // FIXME(#48994) - could just be collected into an Option<Vec>
603 tys.push(pat.to_ty()?);
610 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
613 /// Walk top-down and call `it` in each place where a pattern occurs
614 /// starting with the root pattern `walk` is called on. If `it` returns
615 /// false then we will descend no further but siblings will be processed.
616 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
622 // Walk into the pattern associated with `Ident` (if any).
623 PatKind::Ident(_, _, Some(p)) => p.walk(it),
625 // Walk into each field of struct.
626 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
628 // Sequence of patterns.
629 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
630 s.iter().for_each(|p| p.walk(it))
633 // Trivial wrappers over inner patterns.
634 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
636 // These patterns do not contain subpatterns, skip.
643 | PatKind::MacCall(_) => {}
647 /// Is this a `..` pattern?
648 pub fn is_rest(&self) -> bool {
649 matches!(self.kind, PatKind::Rest)
653 /// A single field in a struct pattern.
655 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
656 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
657 /// except when `is_shorthand` is true.
658 #[derive(Clone, Encodable, Decodable, Debug)]
659 pub struct PatField {
660 /// The identifier for the field.
662 /// The pattern the field is destructured to.
664 pub is_shorthand: bool,
668 pub is_placeholder: bool,
671 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
672 pub enum BindingMode {
677 #[derive(Clone, Encodable, Decodable, Debug)]
679 Included(RangeSyntax),
683 #[derive(Clone, Encodable, Decodable, Debug)]
684 pub enum RangeSyntax {
691 #[derive(Clone, Encodable, Decodable, Debug)]
693 /// Represents a wildcard pattern (`_`).
696 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
697 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
698 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
699 /// during name resolution.
700 Ident(BindingMode, Ident, Option<P<Pat>>),
702 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
703 /// The `bool` is `true` in the presence of a `..`.
704 Struct(Path, Vec<PatField>, /* recovered */ bool),
706 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
707 TupleStruct(Path, Vec<P<Pat>>),
709 /// An or-pattern `A | B | C`.
710 /// Invariant: `pats.len() >= 2`.
713 /// A possibly qualified path pattern.
714 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
715 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
716 /// only legally refer to associated constants.
717 Path(Option<QSelf>, Path),
719 /// A tuple pattern (`(a, b)`).
725 /// A reference pattern (e.g., `&mut (a, b)`).
726 Ref(P<Pat>, Mutability),
731 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
732 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
734 /// A slice pattern `[a, b, c]`.
737 /// A rest pattern `..`.
739 /// Syntactically it is valid anywhere.
741 /// Semantically however, it only has meaning immediately inside:
742 /// - a slice pattern: `[a, .., b]`,
743 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
744 /// - a tuple pattern: `(a, .., b)`,
745 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
747 /// In all of these cases, an additional restriction applies,
748 /// only one rest pattern may occur in the pattern sequences.
751 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
754 /// A macro pattern; pre-expansion.
758 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
759 #[derive(HashStable_Generic, Encodable, Decodable)]
760 pub enum Mutability {
766 pub fn invert(self) -> Self {
768 Mutability::Mut => Mutability::Not,
769 Mutability::Not => Mutability::Mut,
773 pub fn prefix_str(&self) -> &'static str {
775 Mutability::Mut => "mut ",
776 Mutability::Not => "",
781 /// The kind of borrow in an `AddrOf` expression,
782 /// e.g., `&place` or `&raw const place`.
783 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
784 #[derive(Encodable, Decodable, HashStable_Generic)]
785 pub enum BorrowKind {
786 /// A normal borrow, `&$expr` or `&mut $expr`.
787 /// The resulting type is either `&'a T` or `&'a mut T`
788 /// where `T = typeof($expr)` and `'a` is some lifetime.
790 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
791 /// The resulting type is either `*const T` or `*mut T`
792 /// where `T = typeof($expr)`.
796 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
798 /// The `+` operator (addition)
800 /// The `-` operator (subtraction)
802 /// The `*` operator (multiplication)
804 /// The `/` operator (division)
806 /// The `%` operator (modulus)
808 /// The `&&` operator (logical and)
810 /// The `||` operator (logical or)
812 /// The `^` operator (bitwise xor)
814 /// The `&` operator (bitwise and)
816 /// The `|` operator (bitwise or)
818 /// The `<<` operator (shift left)
820 /// The `>>` operator (shift right)
822 /// The `==` operator (equality)
824 /// The `<` operator (less than)
826 /// The `<=` operator (less than or equal to)
828 /// The `!=` operator (not equal to)
830 /// The `>=` operator (greater than or equal to)
832 /// The `>` operator (greater than)
837 pub fn to_string(&self) -> &'static str {
860 pub fn lazy(&self) -> bool {
861 matches!(self, BinOpKind::And | BinOpKind::Or)
864 pub fn is_comparison(&self) -> bool {
866 // Note for developers: please keep this as is;
867 // we want compilation to fail if another variant is added.
869 Eq | Lt | Le | Ne | Gt | Ge => true,
870 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
875 pub type BinOp = Spanned<BinOpKind>;
879 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
880 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
882 /// The `*` operator for dereferencing
884 /// The `!` operator for logical inversion
886 /// The `-` operator for negation
891 pub fn to_string(op: UnOp) -> &'static str {
901 #[derive(Clone, Encodable, Decodable, Debug)]
909 pub fn tokens(&self) -> Option<&LazyTokenStream> {
911 StmtKind::Local(ref local) => local.tokens.as_ref(),
912 StmtKind::Item(ref item) => item.tokens.as_ref(),
913 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(),
914 StmtKind::Empty => None,
915 StmtKind::MacCall(ref mac) => mac.tokens.as_ref(),
919 pub fn has_trailing_semicolon(&self) -> bool {
921 StmtKind::Semi(_) => true,
922 StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
927 /// Converts a parsed `Stmt` to a `Stmt` with
928 /// a trailing semicolon.
930 /// This only modifies the parsed AST struct, not the attached
931 /// `LazyTokenStream`. The parser is responsible for calling
932 /// `CreateTokenStream::add_trailing_semi` when there is actually
933 /// a semicolon in the tokenstream.
934 pub fn add_trailing_semicolon(mut self) -> Self {
935 self.kind = match self.kind {
936 StmtKind::Expr(expr) => StmtKind::Semi(expr),
937 StmtKind::MacCall(mac) => {
938 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
939 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
948 pub fn is_item(&self) -> bool {
949 matches!(self.kind, StmtKind::Item(_))
952 pub fn is_expr(&self) -> bool {
953 matches!(self.kind, StmtKind::Expr(_))
957 #[derive(Clone, Encodable, Decodable, Debug)]
959 /// A local (let) binding.
961 /// An item definition.
963 /// Expr without trailing semi-colon.
965 /// Expr with a trailing semi-colon.
967 /// Just a trailing semi-colon.
970 MacCall(P<MacCallStmt>),
973 #[derive(Clone, Encodable, Decodable, Debug)]
974 pub struct MacCallStmt {
976 pub style: MacStmtStyle,
978 pub tokens: Option<LazyTokenStream>,
981 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
982 pub enum MacStmtStyle {
983 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
984 /// `foo!(...);`, `foo![...];`).
986 /// The macro statement had braces (e.g., `foo! { ... }`).
988 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
989 /// `foo!(...)`). All of these will end up being converted into macro
994 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
995 #[derive(Clone, Encodable, Decodable, Debug)]
999 pub ty: Option<P<Ty>>,
1000 /// Initializer expression to set the value, if any.
1001 pub init: Option<P<Expr>>,
1004 pub tokens: Option<LazyTokenStream>,
1007 /// An arm of a 'match'.
1009 /// E.g., `0..=10 => { println!("match!") }` as in
1013 /// 0..=10 => { println!("match!") },
1014 /// _ => { println!("no match!") },
1017 #[derive(Clone, Encodable, Decodable, Debug)]
1019 pub attrs: Vec<Attribute>,
1020 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1022 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1023 pub guard: Option<P<Expr>>,
1028 pub is_placeholder: bool,
1031 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1032 #[derive(Clone, Encodable, Decodable, Debug)]
1033 pub struct ExprField {
1039 pub is_shorthand: bool,
1040 pub is_placeholder: bool,
1043 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1044 pub enum BlockCheckMode {
1046 Unsafe(UnsafeSource),
1049 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1050 pub enum UnsafeSource {
1055 /// A constant (expression) that's not an item or associated item,
1056 /// but needs its own `DefId` for type-checking, const-eval, etc.
1057 /// These are usually found nested inside types (e.g., array lengths)
1058 /// or expressions (e.g., repeat counts), and also used to define
1059 /// explicit discriminant values for enum variants.
1060 #[derive(Clone, Encodable, Decodable, Debug)]
1061 pub struct AnonConst {
1067 #[derive(Clone, Encodable, Decodable, Debug)]
1073 pub tokens: Option<LazyTokenStream>,
1076 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1077 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1078 rustc_data_structures::static_assert_size!(Expr, 104);
1081 /// Returns `true` if this expression would be valid somewhere that expects a value;
1082 /// for example, an `if` condition.
1083 pub fn returns(&self) -> bool {
1084 if let ExprKind::Block(ref block, _) = self.kind {
1085 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1087 Some(StmtKind::Expr(_)) => true,
1088 // Last statement is an explicit return?
1089 Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)),
1090 // This is a block that doesn't end in either an implicit or explicit return.
1094 // This is not a block, it is a value.
1099 /// Is this expr either `N`, or `{ N }`.
1101 /// If this is not the case, name resolution does not resolve `N` when using
1102 /// `min_const_generics` as more complex expressions are not supported.
1103 pub fn is_potential_trivial_const_param(&self) -> bool {
1104 let this = if let ExprKind::Block(ref block, None) = self.kind {
1105 if block.stmts.len() == 1 {
1106 if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
1114 if let ExprKind::Path(None, ref path) = this.kind {
1115 if path.segments.len() == 1 && path.segments[0].args.is_none() {
1123 pub fn to_bound(&self) -> Option<GenericBound> {
1125 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1126 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1127 TraitBoundModifier::None,
1133 pub fn peel_parens(&self) -> &Expr {
1134 let mut expr = self;
1135 while let ExprKind::Paren(inner) = &expr.kind {
1141 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1142 pub fn to_ty(&self) -> Option<P<Ty>> {
1143 let kind = match &self.kind {
1144 // Trivial conversions.
1145 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1146 ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1148 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1150 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1151 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1154 ExprKind::Repeat(expr, expr_len) => {
1155 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1158 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1160 ExprKind::Tup(exprs) => {
1161 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1165 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1166 // then type of result is trait object.
1167 // Otherwise we don't assume the result type.
1168 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1169 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1170 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1176 // This expression doesn't look like a type syntactically.
1180 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1183 pub fn precedence(&self) -> ExprPrecedence {
1185 ExprKind::Box(_) => ExprPrecedence::Box,
1186 ExprKind::Array(_) => ExprPrecedence::Array,
1187 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1188 ExprKind::Call(..) => ExprPrecedence::Call,
1189 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1190 ExprKind::Tup(_) => ExprPrecedence::Tup,
1191 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1192 ExprKind::Unary(..) => ExprPrecedence::Unary,
1193 ExprKind::Lit(_) => ExprPrecedence::Lit,
1194 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1195 ExprKind::Let(..) => ExprPrecedence::Let,
1196 ExprKind::If(..) => ExprPrecedence::If,
1197 ExprKind::While(..) => ExprPrecedence::While,
1198 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1199 ExprKind::Loop(..) => ExprPrecedence::Loop,
1200 ExprKind::Match(..) => ExprPrecedence::Match,
1201 ExprKind::Closure(..) => ExprPrecedence::Closure,
1202 ExprKind::Block(..) => ExprPrecedence::Block,
1203 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1204 ExprKind::Async(..) => ExprPrecedence::Async,
1205 ExprKind::Await(..) => ExprPrecedence::Await,
1206 ExprKind::Assign(..) => ExprPrecedence::Assign,
1207 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1208 ExprKind::Field(..) => ExprPrecedence::Field,
1209 ExprKind::Index(..) => ExprPrecedence::Index,
1210 ExprKind::Range(..) => ExprPrecedence::Range,
1211 ExprKind::Underscore => ExprPrecedence::Path,
1212 ExprKind::Path(..) => ExprPrecedence::Path,
1213 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1214 ExprKind::Break(..) => ExprPrecedence::Break,
1215 ExprKind::Continue(..) => ExprPrecedence::Continue,
1216 ExprKind::Ret(..) => ExprPrecedence::Ret,
1217 ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1218 ExprKind::MacCall(..) => ExprPrecedence::Mac,
1219 ExprKind::Struct(..) => ExprPrecedence::Struct,
1220 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1221 ExprKind::Paren(..) => ExprPrecedence::Paren,
1222 ExprKind::Try(..) => ExprPrecedence::Try,
1223 ExprKind::Yield(..) => ExprPrecedence::Yield,
1224 ExprKind::Err => ExprPrecedence::Err,
1229 /// Limit types of a range (inclusive or exclusive)
1230 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1231 pub enum RangeLimits {
1232 /// Inclusive at the beginning, exclusive at the end
1234 /// Inclusive at the beginning and end
1238 #[derive(Clone, Encodable, Decodable, Debug)]
1239 pub enum StructRest {
1244 /// No trailing `..` or expression.
1248 #[derive(Clone, Encodable, Decodable, Debug)]
1249 pub struct StructExpr {
1251 pub fields: Vec<ExprField>,
1252 pub rest: StructRest,
1255 #[derive(Clone, Encodable, Decodable, Debug)]
1257 /// A `box x` expression.
1259 /// An array (`[a, b, c, d]`)
1260 Array(Vec<P<Expr>>),
1261 /// Allow anonymous constants from an inline `const` block
1262 ConstBlock(AnonConst),
1265 /// The first field resolves to the function itself,
1266 /// and the second field is the list of arguments.
1267 /// This also represents calling the constructor of
1268 /// tuple-like ADTs such as tuple structs and enum variants.
1269 Call(P<Expr>, Vec<P<Expr>>),
1270 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1272 /// The `PathSegment` represents the method name and its generic arguments
1273 /// (within the angle brackets).
1274 /// The first element of the vector of an `Expr` is the expression that evaluates
1275 /// to the object on which the method is being called on (the receiver),
1276 /// and the remaining elements are the rest of the arguments.
1277 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1278 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1279 /// This `Span` is the span of the function, without the dot and receiver
1280 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1281 MethodCall(PathSegment, Vec<P<Expr>>, Span),
1282 /// A tuple (e.g., `(a, b, c, d)`).
1284 /// A binary operation (e.g., `a + b`, `a * b`).
1285 Binary(BinOp, P<Expr>, P<Expr>),
1286 /// A unary operation (e.g., `!x`, `*x`).
1287 Unary(UnOp, P<Expr>),
1288 /// A literal (e.g., `1`, `"foo"`).
1290 /// A cast (e.g., `foo as f64`).
1291 Cast(P<Expr>, P<Ty>),
1292 /// A type ascription (e.g., `42: usize`).
1293 Type(P<Expr>, P<Ty>),
1294 /// A `let pat = expr` expression that is only semantically allowed in the condition
1295 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1296 Let(P<Pat>, P<Expr>),
1297 /// An `if` block, with an optional `else` block.
1299 /// `if expr { block } else { expr }`
1300 If(P<Expr>, P<Block>, Option<P<Expr>>),
1301 /// A while loop, with an optional label.
1303 /// `'label: while expr { block }`
1304 While(P<Expr>, P<Block>, Option<Label>),
1305 /// A `for` loop, with an optional label.
1307 /// `'label: for pat in expr { block }`
1309 /// This is desugared to a combination of `loop` and `match` expressions.
1310 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1311 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1313 /// `'label: loop { block }`
1314 Loop(P<Block>, Option<Label>),
1315 /// A `match` block.
1316 Match(P<Expr>, Vec<Arm>),
1317 /// A closure (e.g., `move |a, b, c| a + b + c`).
1319 /// The final span is the span of the argument block `|...|`.
1320 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1321 /// A block (`'label: { ... }`).
1322 Block(P<Block>, Option<Label>),
1323 /// An async block (`async move { ... }`).
1325 /// The `NodeId` is the `NodeId` for the closure that results from
1326 /// desugaring an async block, just like the NodeId field in the
1327 /// `Async::Yes` variant. This is necessary in order to create a def for the
1328 /// closure which can be used as a parent of any child defs. Defs
1329 /// created during lowering cannot be made the parent of any other
1330 /// preexisting defs.
1331 Async(CaptureBy, NodeId, P<Block>),
1332 /// An await expression (`my_future.await`).
1335 /// A try block (`try { ... }`).
1338 /// An assignment (`a = foo()`).
1339 /// The `Span` argument is the span of the `=` token.
1340 Assign(P<Expr>, P<Expr>, Span),
1341 /// An assignment with an operator.
1344 AssignOp(BinOp, P<Expr>, P<Expr>),
1345 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1346 Field(P<Expr>, Ident),
1347 /// An indexing operation (e.g., `foo[2]`).
1348 Index(P<Expr>, P<Expr>),
1349 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1350 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1351 /// An underscore, used in destructuring assignment to ignore a value.
1354 /// Variable reference, possibly containing `::` and/or type
1355 /// parameters (e.g., `foo::bar::<baz>`).
1357 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1358 Path(Option<QSelf>, Path),
1360 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1361 AddrOf(BorrowKind, Mutability, P<Expr>),
1362 /// A `break`, with an optional label to break, and an optional expression.
1363 Break(Option<Label>, Option<P<Expr>>),
1364 /// A `continue`, with an optional label.
1365 Continue(Option<Label>),
1366 /// A `return`, with an optional value to be returned.
1367 Ret(Option<P<Expr>>),
1369 /// Output of the `asm!()` macro.
1370 InlineAsm(P<InlineAsm>),
1371 /// Output of the `llvm_asm!()` macro.
1372 LlvmInlineAsm(P<LlvmInlineAsm>),
1374 /// A macro invocation; pre-expansion.
1377 /// A struct literal expression.
1379 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1380 Struct(P<StructExpr>),
1382 /// An array literal constructed from one repeated element.
1384 /// E.g., `[1; 5]`. The expression is the element to be
1385 /// repeated; the constant is the number of times to repeat it.
1386 Repeat(P<Expr>, AnonConst),
1388 /// No-op: used solely so we can pretty-print faithfully.
1391 /// A try expression (`expr?`).
1394 /// A `yield`, with an optional value to be yielded.
1395 Yield(Option<P<Expr>>),
1397 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1401 /// The explicit `Self` type in a "qualified path". The actual
1402 /// path, including the trait and the associated item, is stored
1403 /// separately. `position` represents the index of the associated
1404 /// item qualified with this `Self` type.
1406 /// ```ignore (only-for-syntax-highlight)
1407 /// <Vec<T> as a::b::Trait>::AssociatedItem
1408 /// ^~~~~ ~~~~~~~~~~~~~~^
1411 /// <Vec<T>>::AssociatedItem
1415 #[derive(Clone, Encodable, Decodable, Debug)]
1419 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1420 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1421 /// 0`, this is an empty span.
1422 pub path_span: Span,
1423 pub position: usize,
1426 /// A capture clause used in closures and `async` blocks.
1427 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1428 pub enum CaptureBy {
1429 /// `move |x| y + x`.
1431 /// `move` keyword was not specified.
1435 /// The movability of a generator / closure literal:
1436 /// whether a generator contains self-references, causing it to be `!Unpin`.
1437 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1438 #[derive(HashStable_Generic)]
1439 pub enum Movability {
1440 /// May contain self-references, `!Unpin`.
1442 /// Must not contain self-references, `Unpin`.
1446 /// Represents a macro invocation. The `path` indicates which macro
1447 /// is being invoked, and the `args` are arguments passed to it.
1448 #[derive(Clone, Encodable, Decodable, Debug)]
1449 pub struct MacCall {
1451 pub args: P<MacArgs>,
1452 pub prior_type_ascription: Option<(Span, bool)>,
1456 pub fn span(&self) -> Span {
1457 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1461 /// Arguments passed to an attribute or a function-like macro.
1462 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1464 /// No arguments - `#[attr]`.
1466 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1467 Delimited(DelimSpan, MacDelimiter, TokenStream),
1468 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1470 /// Span of the `=` token.
1472 /// "value" as a nonterminal token.
1478 pub fn delim(&self) -> DelimToken {
1480 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1481 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1485 pub fn span(&self) -> Option<Span> {
1487 MacArgs::Empty => None,
1488 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1489 MacArgs::Eq(eq_span, token) => Some(eq_span.to(token.span)),
1493 /// Tokens inside the delimiters or after `=`.
1494 /// Proc macros see these tokens, for example.
1495 pub fn inner_tokens(&self) -> TokenStream {
1497 MacArgs::Empty => TokenStream::default(),
1498 MacArgs::Delimited(.., tokens) => tokens.clone(),
1499 MacArgs::Eq(.., token) => TokenTree::Token(token.clone()).into(),
1503 /// Whether a macro with these arguments needs a semicolon
1504 /// when used as a standalone item or statement.
1505 pub fn need_semicolon(&self) -> bool {
1506 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1510 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1511 pub enum MacDelimiter {
1518 pub fn to_token(self) -> DelimToken {
1520 MacDelimiter::Parenthesis => DelimToken::Paren,
1521 MacDelimiter::Bracket => DelimToken::Bracket,
1522 MacDelimiter::Brace => DelimToken::Brace,
1526 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1528 token::Paren => Some(MacDelimiter::Parenthesis),
1529 token::Bracket => Some(MacDelimiter::Bracket),
1530 token::Brace => Some(MacDelimiter::Brace),
1531 token::NoDelim => None,
1536 /// Represents a macro definition.
1537 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1538 pub struct MacroDef {
1539 pub body: P<MacArgs>,
1540 /// `true` if macro was defined with `macro_rules`.
1541 pub macro_rules: bool,
1544 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1545 #[derive(HashStable_Generic)]
1547 /// A regular string, like `"foo"`.
1549 /// A raw string, like `r##"foo"##`.
1551 /// The value is the number of `#` symbols used.
1556 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1558 /// The original literal token as written in source code.
1559 pub token: token::Lit,
1560 /// The "semantic" representation of the literal lowered from the original tokens.
1561 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1562 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1567 /// Same as `Lit`, but restricted to string literals.
1568 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1570 /// The original literal token as written in source code.
1571 pub style: StrStyle,
1573 pub suffix: Option<Symbol>,
1575 /// The unescaped "semantic" representation of the literal lowered from the original token.
1576 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1577 pub symbol_unescaped: Symbol,
1581 pub fn as_lit(&self) -> Lit {
1582 let token_kind = match self.style {
1583 StrStyle::Cooked => token::Str,
1584 StrStyle::Raw(n) => token::StrRaw(n),
1587 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1589 kind: LitKind::Str(self.symbol_unescaped, self.style),
1594 /// Type of the integer literal based on provided suffix.
1595 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1596 #[derive(HashStable_Generic)]
1597 pub enum LitIntType {
1606 /// Type of the float literal based on provided suffix.
1607 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1608 #[derive(HashStable_Generic)]
1609 pub enum LitFloatType {
1610 /// A float literal with a suffix (`1f32` or `1E10f32`).
1612 /// A float literal without a suffix (`1.0 or 1.0E10`).
1618 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1619 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1621 /// A string literal (`"foo"`).
1622 Str(Symbol, StrStyle),
1623 /// A byte string (`b"foo"`).
1625 /// A byte char (`b'f'`).
1627 /// A character literal (`'a'`).
1629 /// An integer literal (`1`).
1630 Int(u128, LitIntType),
1631 /// A float literal (`1f64` or `1E10f64`).
1632 Float(Symbol, LitFloatType),
1633 /// A boolean literal.
1635 /// Placeholder for a literal that wasn't well-formed in some way.
1640 /// Returns `true` if this literal is a string.
1641 pub fn is_str(&self) -> bool {
1642 matches!(self, LitKind::Str(..))
1645 /// Returns `true` if this literal is byte literal string.
1646 pub fn is_bytestr(&self) -> bool {
1647 matches!(self, LitKind::ByteStr(_))
1650 /// Returns `true` if this is a numeric literal.
1651 pub fn is_numeric(&self) -> bool {
1652 matches!(self, LitKind::Int(..) | LitKind::Float(..))
1655 /// Returns `true` if this literal has no suffix.
1656 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1657 pub fn is_unsuffixed(&self) -> bool {
1661 /// Returns `true` if this literal has a suffix.
1662 pub fn is_suffixed(&self) -> bool {
1664 // suffixed variants
1665 LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1666 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1667 // unsuffixed variants
1669 | LitKind::ByteStr(..)
1672 | LitKind::Int(_, LitIntType::Unsuffixed)
1673 | LitKind::Float(_, LitFloatType::Unsuffixed)
1675 | LitKind::Err(..) => false,
1680 // N.B., If you change this, you'll probably want to change the corresponding
1681 // type structure in `middle/ty.rs` as well.
1682 #[derive(Clone, Encodable, Decodable, Debug)]
1685 pub mutbl: Mutability,
1688 /// Represents a function's signature in a trait declaration,
1689 /// trait implementation, or free function.
1690 #[derive(Clone, Encodable, Decodable, Debug)]
1692 pub header: FnHeader,
1693 pub decl: P<FnDecl>,
1697 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1698 #[derive(Encodable, Decodable, HashStable_Generic)]
1705 pub fn name_str(self) -> &'static str {
1707 FloatTy::F32 => "f32",
1708 FloatTy::F64 => "f64",
1712 pub fn name(self) -> Symbol {
1714 FloatTy::F32 => sym::f32,
1715 FloatTy::F64 => sym::f64,
1720 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1721 #[derive(Encodable, Decodable, HashStable_Generic)]
1732 pub fn name_str(&self) -> &'static str {
1734 IntTy::Isize => "isize",
1736 IntTy::I16 => "i16",
1737 IntTy::I32 => "i32",
1738 IntTy::I64 => "i64",
1739 IntTy::I128 => "i128",
1743 pub fn name(&self) -> Symbol {
1745 IntTy::Isize => sym::isize,
1746 IntTy::I8 => sym::i8,
1747 IntTy::I16 => sym::i16,
1748 IntTy::I32 => sym::i32,
1749 IntTy::I64 => sym::i64,
1750 IntTy::I128 => sym::i128,
1755 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1756 #[derive(Encodable, Decodable, HashStable_Generic)]
1767 pub fn name_str(&self) -> &'static str {
1769 UintTy::Usize => "usize",
1771 UintTy::U16 => "u16",
1772 UintTy::U32 => "u32",
1773 UintTy::U64 => "u64",
1774 UintTy::U128 => "u128",
1778 pub fn name(&self) -> Symbol {
1780 UintTy::Usize => sym::usize,
1781 UintTy::U8 => sym::u8,
1782 UintTy::U16 => sym::u16,
1783 UintTy::U32 => sym::u32,
1784 UintTy::U64 => sym::u64,
1785 UintTy::U128 => sym::u128,
1790 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1791 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1792 #[derive(Clone, Encodable, Decodable, Debug)]
1793 pub struct AssocTyConstraint {
1796 pub gen_args: Option<GenericArgs>,
1797 pub kind: AssocTyConstraintKind,
1801 /// The kinds of an `AssocTyConstraint`.
1802 #[derive(Clone, Encodable, Decodable, Debug)]
1803 pub enum AssocTyConstraintKind {
1804 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1805 Equality { ty: P<Ty> },
1806 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1807 Bound { bounds: GenericBounds },
1810 #[derive(Encodable, Decodable, Debug)]
1815 pub tokens: Option<LazyTokenStream>,
1819 fn clone(&self) -> Self {
1820 ensure_sufficient_stack(|| Self {
1822 kind: self.kind.clone(),
1824 tokens: self.tokens.clone(),
1830 pub fn peel_refs(&self) -> &Self {
1831 let mut final_ty = self;
1832 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1839 #[derive(Clone, Encodable, Decodable, Debug)]
1840 pub struct BareFnTy {
1841 pub unsafety: Unsafe,
1843 pub generic_params: Vec<GenericParam>,
1844 pub decl: P<FnDecl>,
1847 /// The various kinds of type recognized by the compiler.
1848 #[derive(Clone, Encodable, Decodable, Debug)]
1850 /// A variable-length slice (`[T]`).
1852 /// A fixed length array (`[T; n]`).
1853 Array(P<Ty>, AnonConst),
1854 /// A raw pointer (`*const T` or `*mut T`).
1856 /// A reference (`&'a T` or `&'a mut T`).
1857 Rptr(Option<Lifetime>, MutTy),
1858 /// A bare function (e.g., `fn(usize) -> bool`).
1859 BareFn(P<BareFnTy>),
1860 /// The never type (`!`).
1862 /// A tuple (`(A, B, C, D,...)`).
1864 /// A path (`module::module::...::Type`), optionally
1865 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1867 /// Type parameters are stored in the `Path` itself.
1868 Path(Option<QSelf>, Path),
1869 /// A trait object type `Bound1 + Bound2 + Bound3`
1870 /// where `Bound` is a trait or a lifetime.
1871 TraitObject(GenericBounds, TraitObjectSyntax),
1872 /// An `impl Bound1 + Bound2 + Bound3` type
1873 /// where `Bound` is a trait or a lifetime.
1875 /// The `NodeId` exists to prevent lowering from having to
1876 /// generate `NodeId`s on the fly, which would complicate
1877 /// the generation of opaque `type Foo = impl Trait` items significantly.
1878 ImplTrait(NodeId, GenericBounds),
1879 /// No-op; kept solely so that we can pretty-print faithfully.
1883 /// This means the type should be inferred instead of it having been
1884 /// specified. This can appear anywhere in a type.
1886 /// Inferred type of a `self` or `&self` argument in a method.
1888 /// A macro in the type position.
1890 /// Placeholder for a kind that has failed to be defined.
1892 /// Placeholder for a `va_list`.
1897 pub fn is_implicit_self(&self) -> bool {
1898 matches!(self, TyKind::ImplicitSelf)
1901 pub fn is_unit(&self) -> bool {
1902 matches!(self, TyKind::Tup(tys) if tys.is_empty())
1906 /// Syntax used to declare a trait object.
1907 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1908 pub enum TraitObjectSyntax {
1913 /// Inline assembly operand explicit register or register class.
1915 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
1916 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1917 pub enum InlineAsmRegOrRegClass {
1922 bitflags::bitflags! {
1923 #[derive(Encodable, Decodable, HashStable_Generic)]
1924 pub struct InlineAsmOptions: u8 {
1925 const PURE = 1 << 0;
1926 const NOMEM = 1 << 1;
1927 const READONLY = 1 << 2;
1928 const PRESERVES_FLAGS = 1 << 3;
1929 const NORETURN = 1 << 4;
1930 const NOSTACK = 1 << 5;
1931 const ATT_SYNTAX = 1 << 6;
1935 #[derive(Clone, PartialEq, PartialOrd, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
1936 pub enum InlineAsmTemplatePiece {
1938 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
1941 impl fmt::Display for InlineAsmTemplatePiece {
1942 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1944 Self::String(s) => {
1945 for c in s.chars() {
1947 '{' => f.write_str("{{")?,
1948 '}' => f.write_str("}}")?,
1954 Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
1955 write!(f, "{{{}:{}}}", operand_idx, modifier)
1957 Self::Placeholder { operand_idx, modifier: None, .. } => {
1958 write!(f, "{{{}}}", operand_idx)
1964 impl InlineAsmTemplatePiece {
1965 /// Rebuilds the asm template string from its pieces.
1966 pub fn to_string(s: &[Self]) -> String {
1968 let mut out = String::new();
1970 let _ = write!(out, "{}", p);
1976 /// Inline assembly operand.
1978 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
1979 #[derive(Clone, Encodable, Decodable, Debug)]
1980 pub enum InlineAsmOperand {
1982 reg: InlineAsmRegOrRegClass,
1986 reg: InlineAsmRegOrRegClass,
1988 expr: Option<P<Expr>>,
1991 reg: InlineAsmRegOrRegClass,
1996 reg: InlineAsmRegOrRegClass,
1999 out_expr: Option<P<Expr>>,
2002 anon_const: AnonConst,
2009 /// Inline assembly.
2011 /// E.g., `asm!("NOP");`.
2012 #[derive(Clone, Encodable, Decodable, Debug)]
2013 pub struct InlineAsm {
2014 pub template: Vec<InlineAsmTemplatePiece>,
2015 pub operands: Vec<(InlineAsmOperand, Span)>,
2016 pub options: InlineAsmOptions,
2017 pub line_spans: Vec<Span>,
2020 /// Inline assembly dialect.
2022 /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2023 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, Hash, HashStable_Generic)]
2024 pub enum LlvmAsmDialect {
2029 /// LLVM-style inline assembly.
2031 /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
2032 #[derive(Clone, Encodable, Decodable, Debug)]
2033 pub struct LlvmInlineAsmOutput {
2034 pub constraint: Symbol,
2037 pub is_indirect: bool,
2040 /// LLVM-style inline assembly.
2042 /// E.g., `llvm_asm!("NOP");`.
2043 #[derive(Clone, Encodable, Decodable, Debug)]
2044 pub struct LlvmInlineAsm {
2046 pub asm_str_style: StrStyle,
2047 pub outputs: Vec<LlvmInlineAsmOutput>,
2048 pub inputs: Vec<(Symbol, P<Expr>)>,
2049 pub clobbers: Vec<Symbol>,
2051 pub alignstack: bool,
2052 pub dialect: LlvmAsmDialect,
2055 /// A parameter in a function header.
2057 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2058 #[derive(Clone, Encodable, Decodable, Debug)]
2065 pub is_placeholder: bool,
2068 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2070 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2071 #[derive(Clone, Encodable, Decodable, Debug)]
2073 /// `self`, `mut self`
2075 /// `&'lt self`, `&'lt mut self`
2076 Region(Option<Lifetime>, Mutability),
2077 /// `self: TYPE`, `mut self: TYPE`
2078 Explicit(P<Ty>, Mutability),
2081 pub type ExplicitSelf = Spanned<SelfKind>;
2084 /// Attempts to cast parameter to `ExplicitSelf`.
2085 pub fn to_self(&self) -> Option<ExplicitSelf> {
2086 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2087 if ident.name == kw::SelfLower {
2088 return match self.ty.kind {
2089 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2090 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2091 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2094 self.pat.span.to(self.ty.span),
2095 SelfKind::Explicit(self.ty.clone(), mutbl),
2103 /// Returns `true` if parameter is `self`.
2104 pub fn is_self(&self) -> bool {
2105 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2106 ident.name == kw::SelfLower
2112 /// Builds a `Param` object from `ExplicitSelf`.
2113 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2114 let span = eself.span.to(eself_ident.span);
2115 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2116 let param = |mutbl, ty| Param {
2120 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2127 is_placeholder: false,
2130 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2131 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2132 SelfKind::Region(lt, mutbl) => param(
2136 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2145 /// A signature (not the body) of a function declaration.
2147 /// E.g., `fn foo(bar: baz)`.
2149 /// Please note that it's different from `FnHeader` structure
2150 /// which contains metadata about function safety, asyncness, constness and ABI.
2151 #[derive(Clone, Encodable, Decodable, Debug)]
2153 pub inputs: Vec<Param>,
2154 pub output: FnRetTy,
2158 pub fn has_self(&self) -> bool {
2159 self.inputs.get(0).map_or(false, Param::is_self)
2161 pub fn c_variadic(&self) -> bool {
2162 self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2166 /// Is the trait definition an auto trait?
2167 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2173 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)]
2174 #[derive(HashStable_Generic)]
2180 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2182 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2187 pub fn is_async(self) -> bool {
2188 matches!(self, Async::Yes { .. })
2191 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2192 pub fn opt_return_id(self) -> Option<NodeId> {
2194 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2200 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2201 #[derive(HashStable_Generic)]
2207 /// Item defaultness.
2208 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2209 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2210 pub enum Defaultness {
2215 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2216 pub enum ImplPolarity {
2217 /// `impl Trait for Type`
2219 /// `impl !Trait for Type`
2223 impl fmt::Debug for ImplPolarity {
2224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2226 ImplPolarity::Positive => "positive".fmt(f),
2227 ImplPolarity::Negative(_) => "negative".fmt(f),
2232 #[derive(Clone, Encodable, Decodable, Debug)]
2234 /// Returns type is not specified.
2236 /// Functions default to `()` and closures default to inference.
2237 /// Span points to where return type would be inserted.
2239 /// Everything else.
2244 pub fn span(&self) -> Span {
2246 FnRetTy::Default(span) => span,
2247 FnRetTy::Ty(ref ty) => ty.span,
2252 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2258 /// Module item kind.
2259 #[derive(Clone, Encodable, Decodable, Debug)]
2261 /// Module with inlined definition `mod foo { ... }`,
2262 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2263 /// The inner span is from the first token past `{` to the last token until `}`,
2264 /// or from the first to the last token in the loaded file.
2265 Loaded(Vec<P<Item>>, Inline, Span),
2266 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2270 /// Foreign module declaration.
2272 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2273 #[derive(Clone, Encodable, Decodable, Debug)]
2274 pub struct ForeignMod {
2275 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2276 /// semantically by Rust.
2277 pub unsafety: Unsafe,
2278 pub abi: Option<StrLit>,
2279 pub items: Vec<P<ForeignItem>>,
2282 /// Global inline assembly.
2284 /// Also known as "module-level assembly" or "file-scoped assembly".
2285 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
2286 pub struct GlobalAsm {
2290 #[derive(Clone, Encodable, Decodable, Debug)]
2291 pub struct EnumDef {
2292 pub variants: Vec<Variant>,
2295 #[derive(Clone, Encodable, Decodable, Debug)]
2296 pub struct Variant {
2297 /// Attributes of the variant.
2298 pub attrs: Vec<Attribute>,
2299 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2303 /// The visibility of the variant. Syntactically accepted but not semantically.
2304 pub vis: Visibility,
2305 /// Name of the variant.
2308 /// Fields and constructor id of the variant.
2309 pub data: VariantData,
2310 /// Explicit discriminant, e.g., `Foo = 1`.
2311 pub disr_expr: Option<AnonConst>,
2312 /// Is a macro placeholder
2313 pub is_placeholder: bool,
2316 /// Part of `use` item to the right of its prefix.
2317 #[derive(Clone, Encodable, Decodable, Debug)]
2318 pub enum UseTreeKind {
2319 /// `use prefix` or `use prefix as rename`
2321 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2323 Simple(Option<Ident>, NodeId, NodeId),
2324 /// `use prefix::{...}`
2325 Nested(Vec<(UseTree, NodeId)>),
2330 /// A tree of paths sharing common prefixes.
2331 /// Used in `use` items both at top-level and inside of braces in import groups.
2332 #[derive(Clone, Encodable, Decodable, Debug)]
2333 pub struct UseTree {
2335 pub kind: UseTreeKind,
2340 pub fn ident(&self) -> Ident {
2342 UseTreeKind::Simple(Some(rename), ..) => rename,
2343 UseTreeKind::Simple(None, ..) => {
2344 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2346 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2351 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2352 /// are contained as statements within items. These two cases need to be
2353 /// distinguished for pretty-printing.
2354 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2355 pub enum AttrStyle {
2360 rustc_index::newtype_index! {
2363 DEBUG_FORMAT = "AttrId({})"
2367 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2368 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2373 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2374 fn decode(d: &mut D) -> Result<AttrId, D::Error> {
2375 d.read_nil().map(|_| crate::attr::mk_attr_id())
2379 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2380 pub struct AttrItem {
2383 pub tokens: Option<LazyTokenStream>,
2386 /// A list of attributes.
2387 pub type AttrVec = ThinVec<Attribute>;
2389 /// Metadata associated with an item.
2390 #[derive(Clone, Encodable, Decodable, Debug)]
2391 pub struct Attribute {
2394 /// Denotes if the attribute decorates the following construct (outer)
2395 /// or the construct this attribute is contained within (inner).
2396 pub style: AttrStyle,
2400 #[derive(Clone, Encodable, Decodable, Debug)]
2402 /// A normal attribute.
2403 Normal(AttrItem, Option<LazyTokenStream>),
2405 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2406 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2407 /// variant (which is much less compact and thus more expensive).
2408 DocComment(CommentKind, Symbol),
2411 /// `TraitRef`s appear in impls.
2413 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2414 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2415 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2416 /// same as the impl's `NodeId`).
2417 #[derive(Clone, Encodable, Decodable, Debug)]
2418 pub struct TraitRef {
2423 #[derive(Clone, Encodable, Decodable, Debug)]
2424 pub struct PolyTraitRef {
2425 /// The `'a` in `<'a> Foo<&'a T>`.
2426 pub bound_generic_params: Vec<GenericParam>,
2428 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2429 pub trait_ref: TraitRef,
2435 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2437 bound_generic_params: generic_params,
2438 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2444 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2445 pub enum CrateSugar {
2446 /// Source is `pub(crate)`.
2449 /// Source is (just) `crate`.
2453 #[derive(Clone, Encodable, Decodable, Debug)]
2454 pub struct Visibility {
2455 pub kind: VisibilityKind,
2457 pub tokens: Option<LazyTokenStream>,
2460 #[derive(Clone, Encodable, Decodable, Debug)]
2461 pub enum VisibilityKind {
2464 Restricted { path: P<Path>, id: NodeId },
2468 impl VisibilityKind {
2469 pub fn is_pub(&self) -> bool {
2470 matches!(self, VisibilityKind::Public)
2474 /// Field definition in a struct, variant or union.
2476 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2477 #[derive(Clone, Encodable, Decodable, Debug)]
2478 pub struct FieldDef {
2479 pub attrs: Vec<Attribute>,
2482 pub vis: Visibility,
2483 pub ident: Option<Ident>,
2486 pub is_placeholder: bool,
2489 /// Fields and constructor ids of enum variants and structs.
2490 #[derive(Clone, Encodable, Decodable, Debug)]
2491 pub enum VariantData {
2494 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2495 Struct(Vec<FieldDef>, bool),
2498 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2499 Tuple(Vec<FieldDef>, NodeId),
2502 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2507 /// Return the fields of this variant.
2508 pub fn fields(&self) -> &[FieldDef] {
2510 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2515 /// Return the `NodeId` of this variant's constructor, if it has one.
2516 pub fn ctor_id(&self) -> Option<NodeId> {
2518 VariantData::Struct(..) => None,
2519 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2524 /// An item definition.
2525 #[derive(Clone, Encodable, Decodable, Debug)]
2526 pub struct Item<K = ItemKind> {
2527 pub attrs: Vec<Attribute>,
2530 pub vis: Visibility,
2531 /// The name of the item.
2532 /// It might be a dummy name in case of anonymous items.
2537 /// Original tokens this item was parsed from. This isn't necessarily
2538 /// available for all items, although over time more and more items should
2539 /// have this be `Some`. Right now this is primarily used for procedural
2540 /// macros, notably custom attributes.
2542 /// Note that the tokens here do not include the outer attributes, but will
2543 /// include inner attributes.
2544 pub tokens: Option<LazyTokenStream>,
2548 /// Return the span that encompasses the attributes.
2549 pub fn span_with_attributes(&self) -> Span {
2550 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2554 impl<K: Into<ItemKind>> Item<K> {
2555 pub fn into_item(self) -> Item {
2556 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2557 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2561 /// `extern` qualifier on a function item or function type.
2562 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2570 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2571 abi.map_or(Extern::Implicit, Extern::Explicit)
2575 /// A function header.
2577 /// All the information between the visibility and the name of the function is
2578 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2579 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2580 pub struct FnHeader {
2581 pub unsafety: Unsafe,
2582 pub asyncness: Async,
2583 pub constness: Const,
2588 /// Does this function header have any qualifiers or is it empty?
2589 pub fn has_qualifiers(&self) -> bool {
2590 let Self { unsafety, asyncness, constness, ext } = self;
2591 matches!(unsafety, Unsafe::Yes(_))
2592 || asyncness.is_async()
2593 || matches!(constness, Const::Yes(_))
2594 || !matches!(ext, Extern::None)
2598 impl Default for FnHeader {
2599 fn default() -> FnHeader {
2601 unsafety: Unsafe::No,
2602 asyncness: Async::No,
2603 constness: Const::No,
2609 #[derive(Clone, Encodable, Decodable, Debug)]
2610 pub struct TraitKind(
2615 pub Vec<P<AssocItem>>,
2618 #[derive(Clone, Encodable, Decodable, Debug)]
2619 pub struct TyAliasKind(pub Defaultness, pub Generics, pub GenericBounds, pub Option<P<Ty>>);
2621 #[derive(Clone, Encodable, Decodable, Debug)]
2622 pub struct ImplKind {
2623 pub unsafety: Unsafe,
2624 pub polarity: ImplPolarity,
2625 pub defaultness: Defaultness,
2626 pub constness: Const,
2627 pub generics: Generics,
2629 /// The trait being implemented, if any.
2630 pub of_trait: Option<TraitRef>,
2633 pub items: Vec<P<AssocItem>>,
2636 #[derive(Clone, Encodable, Decodable, Debug)]
2637 pub struct FnKind(pub Defaultness, pub FnSig, pub Generics, pub Option<P<Block>>);
2639 #[derive(Clone, Encodable, Decodable, Debug)]
2641 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2643 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2644 ExternCrate(Option<Symbol>),
2645 /// A use declaration item (`use`).
2647 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2649 /// A static item (`static`).
2651 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2652 Static(P<Ty>, Mutability, Option<P<Expr>>),
2653 /// A constant item (`const`).
2655 /// E.g., `const FOO: i32 = 42;`.
2656 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2657 /// A function declaration (`fn`).
2659 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2661 /// A module declaration (`mod`).
2663 /// E.g., `mod foo;` or `mod foo { .. }`.
2664 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2665 /// semantically by Rust.
2666 Mod(Unsafe, ModKind),
2667 /// An external module (`extern`).
2669 /// E.g., `extern {}` or `extern "C" {}`.
2670 ForeignMod(ForeignMod),
2671 /// Module-level inline assembly (from `global_asm!()`).
2672 GlobalAsm(GlobalAsm),
2673 /// A type alias (`type`).
2675 /// E.g., `type Foo = Bar<u8>;`.
2676 TyAlias(Box<TyAliasKind>),
2677 /// An enum definition (`enum`).
2679 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2680 Enum(EnumDef, Generics),
2681 /// A struct definition (`struct`).
2683 /// E.g., `struct Foo<A> { x: A }`.
2684 Struct(VariantData, Generics),
2685 /// A union definition (`union`).
2687 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2688 Union(VariantData, Generics),
2689 /// A trait declaration (`trait`).
2691 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2692 Trait(Box<TraitKind>),
2695 /// E.g., `trait Foo = Bar + Quux;`.
2696 TraitAlias(Generics, GenericBounds),
2697 /// An implementation.
2699 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2700 Impl(Box<ImplKind>),
2701 /// A macro invocation.
2703 /// E.g., `foo!(..)`.
2706 /// A macro definition.
2710 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2711 rustc_data_structures::static_assert_size!(ItemKind, 112);
2714 pub fn article(&self) -> &str {
2717 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2718 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2719 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2723 pub fn descr(&self) -> &str {
2725 ItemKind::ExternCrate(..) => "extern crate",
2726 ItemKind::Use(..) => "`use` import",
2727 ItemKind::Static(..) => "static item",
2728 ItemKind::Const(..) => "constant item",
2729 ItemKind::Fn(..) => "function",
2730 ItemKind::Mod(..) => "module",
2731 ItemKind::ForeignMod(..) => "extern block",
2732 ItemKind::GlobalAsm(..) => "global asm item",
2733 ItemKind::TyAlias(..) => "type alias",
2734 ItemKind::Enum(..) => "enum",
2735 ItemKind::Struct(..) => "struct",
2736 ItemKind::Union(..) => "union",
2737 ItemKind::Trait(..) => "trait",
2738 ItemKind::TraitAlias(..) => "trait alias",
2739 ItemKind::MacCall(..) => "item macro invocation",
2740 ItemKind::MacroDef(..) => "macro definition",
2741 ItemKind::Impl { .. } => "implementation",
2745 pub fn generics(&self) -> Option<&Generics> {
2747 Self::Fn(box FnKind(_, _, generics, _))
2748 | Self::TyAlias(box TyAliasKind(_, generics, ..))
2749 | Self::Enum(_, generics)
2750 | Self::Struct(_, generics)
2751 | Self::Union(_, generics)
2752 | Self::Trait(box TraitKind(_, _, generics, ..))
2753 | Self::TraitAlias(generics, _)
2754 | Self::Impl(box ImplKind { generics, .. }) => Some(generics),
2760 /// Represents associated items.
2761 /// These include items in `impl` and `trait` definitions.
2762 pub type AssocItem = Item<AssocItemKind>;
2764 /// Represents associated item kinds.
2766 /// The term "provided" in the variants below refers to the item having a default
2767 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2768 /// In an implementation, all items must be provided.
2769 /// The `Option`s below denote the bodies, where `Some(_)`
2770 /// means "provided" and conversely `None` means "required".
2771 #[derive(Clone, Encodable, Decodable, Debug)]
2772 pub enum AssocItemKind {
2773 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2774 /// If `def` is parsed, then the constant is provided, and otherwise required.
2775 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2776 /// An associated function.
2778 /// An associated type.
2779 TyAlias(Box<TyAliasKind>),
2780 /// A macro expanding to associated items.
2784 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2785 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2787 impl AssocItemKind {
2788 pub fn defaultness(&self) -> Defaultness {
2790 Self::Const(def, ..)
2791 | Self::Fn(box FnKind(def, ..))
2792 | Self::TyAlias(box TyAliasKind(def, ..)) => def,
2793 Self::MacCall(..) => Defaultness::Final,
2798 impl From<AssocItemKind> for ItemKind {
2799 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2800 match assoc_item_kind {
2801 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2802 AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2803 AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2804 AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2809 impl TryFrom<ItemKind> for AssocItemKind {
2810 type Error = ItemKind;
2812 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2813 Ok(match item_kind {
2814 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2815 ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2816 ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2817 ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2818 _ => return Err(item_kind),
2823 /// An item in `extern` block.
2824 #[derive(Clone, Encodable, Decodable, Debug)]
2825 pub enum ForeignItemKind {
2826 /// A foreign static item (`static FOO: u8`).
2827 Static(P<Ty>, Mutability, Option<P<Expr>>),
2828 /// An foreign function.
2830 /// An foreign type.
2831 TyAlias(Box<TyAliasKind>),
2832 /// A macro expanding to foreign items.
2836 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2837 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
2839 impl From<ForeignItemKind> for ItemKind {
2840 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2841 match foreign_item_kind {
2842 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2843 ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2844 ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2845 ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
2850 impl TryFrom<ItemKind> for ForeignItemKind {
2851 type Error = ItemKind;
2853 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2854 Ok(match item_kind {
2855 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2856 ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
2857 ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
2858 ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
2859 _ => return Err(item_kind),
2864 pub type ForeignItem = Item<ForeignItemKind>;