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
;
47 /// A "Label" is an identifier of some point in sources,
48 /// e.g. in the following code:
56 /// `'outer` is a label.
57 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
62 impl fmt
::Debug
for Label
{
63 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
64 write
!(f
, "label({:?})", self.ident
)
68 /// A "Lifetime" is an annotation of the scope in which variable
69 /// can be used, e.g. `'a` in `&'a i32`.
70 #[derive(Clone, Encodable, Decodable, Copy)]
76 impl fmt
::Debug
for Lifetime
{
77 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
78 write
!(f
, "lifetime({}: {})", self.id
, self)
82 impl fmt
::Display
for Lifetime
{
83 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
84 write
!(f
, "{}", self.ident
.name
)
88 /// A "Path" is essentially Rust's notion of a name.
90 /// It's represented as a sequence of identifiers,
91 /// along with a bunch of supporting information.
93 /// E.g., `std::cmp::PartialEq`.
94 #[derive(Clone, Encodable, Decodable, Debug)]
97 /// The segments in the path: the things separated by `::`.
98 /// Global paths begin with `kw::PathRoot`.
99 pub segments
: Vec
<PathSegment
>,
100 pub tokens
: Option
<LazyTokenStream
>,
103 impl PartialEq
<Symbol
> for Path
{
105 fn eq(&self, symbol
: &Symbol
) -> bool
{
106 self.segments
.len() == 1 && { self.segments[0].ident.name == *symbol }
110 impl<CTX
> HashStable
<CTX
> for Path
{
111 fn hash_stable(&self, hcx
: &mut CTX
, hasher
: &mut StableHasher
) {
112 self.segments
.len().hash_stable(hcx
, hasher
);
113 for segment
in &self.segments
{
114 segment
.ident
.name
.hash_stable(hcx
, hasher
);
120 // Convert a span and an identifier to the corresponding
122 pub fn from_ident(ident
: Ident
) -> Path
{
123 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
126 pub fn is_global(&self) -> bool
{
127 !self.segments
.is_empty() && self.segments
[0].ident
.name
== kw
::PathRoot
131 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
133 /// E.g., `std`, `String` or `Box<T>`.
134 #[derive(Clone, Encodable, Decodable, Debug)]
135 pub struct PathSegment
{
136 /// The identifier portion of this path segment.
141 /// Type/lifetime parameters attached to this path. They come in
142 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
143 /// `None` means that no parameter list is supplied (`Path`),
144 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
145 /// but it can be empty (`Path<>`).
146 /// `P` is used as a size optimization for the common case with no parameters.
147 pub args
: Option
<P
<GenericArgs
>>,
151 pub fn from_ident(ident
: Ident
) -> Self {
152 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
155 pub fn path_root(span
: Span
) -> Self {
156 PathSegment
::from_ident(Ident
::new(kw
::PathRoot
, span
))
159 pub fn span(&self) -> Span
{
161 Some(args
) => self.ident
.span
.to(args
.span()),
162 None
=> self.ident
.span
,
167 /// The arguments of a path segment.
169 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
170 #[derive(Clone, Encodable, Decodable, Debug)]
171 pub enum GenericArgs
{
172 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
173 AngleBracketed(AngleBracketedArgs
),
174 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
175 Parenthesized(ParenthesizedArgs
),
179 pub fn is_angle_bracketed(&self) -> bool
{
180 matches
!(self, AngleBracketed(..))
183 pub fn span(&self) -> Span
{
185 AngleBracketed(ref data
) => data
.span
,
186 Parenthesized(ref data
) => data
.span
,
191 /// Concrete argument in the sequence of generic args.
192 #[derive(Clone, Encodable, Decodable, Debug)]
193 pub enum GenericArg
{
194 /// `'a` in `Foo<'a>`
196 /// `Bar` in `Foo<Bar>`
203 pub fn span(&self) -> Span
{
205 GenericArg
::Lifetime(lt
) => lt
.ident
.span
,
206 GenericArg
::Type(ty
) => ty
.span
,
207 GenericArg
::Const(ct
) => ct
.value
.span
,
212 /// A path like `Foo<'a, T>`.
213 #[derive(Clone, Encodable, Decodable, Debug, Default)]
214 pub struct AngleBracketedArgs
{
215 /// The overall span.
217 /// The comma separated parts in the `<...>`.
218 pub args
: Vec
<AngleBracketedArg
>,
221 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
222 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
223 #[derive(Clone, Encodable, Decodable, Debug)]
224 pub enum AngleBracketedArg
{
225 /// Argument for a generic parameter.
227 /// Constraint for an associated item.
228 Constraint(AssocConstraint
),
231 impl AngleBracketedArg
{
232 pub fn span(&self) -> Span
{
234 AngleBracketedArg
::Arg(arg
) => arg
.span(),
235 AngleBracketedArg
::Constraint(constraint
) => constraint
.span
,
240 impl Into
<Option
<P
<GenericArgs
>>> for AngleBracketedArgs
{
241 fn into(self) -> Option
<P
<GenericArgs
>> {
242 Some(P(GenericArgs
::AngleBracketed(self)))
246 impl Into
<Option
<P
<GenericArgs
>>> for ParenthesizedArgs
{
247 fn into(self) -> Option
<P
<GenericArgs
>> {
248 Some(P(GenericArgs
::Parenthesized(self)))
252 /// A path like `Foo(A, B) -> C`.
253 #[derive(Clone, Encodable, Decodable, Debug)]
254 pub struct ParenthesizedArgs
{
262 pub inputs
: Vec
<P
<Ty
>>,
268 pub inputs_span
: Span
,
274 impl ParenthesizedArgs
{
275 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs
{
280 .map(|input
| AngleBracketedArg
::Arg(GenericArg
::Type(input
)))
282 AngleBracketedArgs { span: self.inputs_span, args }
286 pub use crate::node_id
::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID}
;
288 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
290 /// Negative bounds should also be handled here.
291 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
292 pub enum TraitBoundModifier
{
304 // This parses but will be rejected during AST validation.
308 /// The AST represents all type param bounds as types.
309 /// `typeck::collect::compute_bounds` matches these against
310 /// the "special" built-in traits (see `middle::lang_items`) and
311 /// detects `Copy`, `Send` and `Sync`.
312 #[derive(Clone, Encodable, Decodable, Debug)]
313 pub enum GenericBound
{
314 Trait(PolyTraitRef
, TraitBoundModifier
),
319 pub fn span(&self) -> Span
{
321 GenericBound
::Trait(ref t
, ..) => t
.span
,
322 GenericBound
::Outlives(ref l
) => l
.ident
.span
,
327 pub type GenericBounds
= Vec
<GenericBound
>;
329 /// Specifies the enforced ordering for generic parameters. In the future,
330 /// if we wanted to relax this order, we could override `PartialEq` and
331 /// `PartialOrd`, to allow the kinds to be unordered.
332 #[derive(Hash, Clone, Copy)]
333 pub enum ParamKindOrd
{
337 // `Infer` is not actually constructed directly from the AST, but is implicitly constructed
338 // during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last.
342 impl Ord
for ParamKindOrd
{
343 fn cmp(&self, other
: &Self) -> Ordering
{
345 let to_int
= |v
| match v
{
347 Infer
| Type
| Const
=> 1,
350 to_int(*self).cmp(&to_int(*other
))
353 impl PartialOrd
for ParamKindOrd
{
354 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
355 Some(self.cmp(other
))
358 impl PartialEq
for ParamKindOrd
{
359 fn eq(&self, other
: &Self) -> bool
{
360 self.cmp(other
) == Ordering
::Equal
363 impl Eq
for ParamKindOrd {}
365 impl fmt
::Display
for ParamKindOrd
{
366 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
368 ParamKindOrd
::Lifetime
=> "lifetime".fmt(f
),
369 ParamKindOrd
::Type
=> "type".fmt(f
),
370 ParamKindOrd
::Const { .. }
=> "const".fmt(f
),
371 ParamKindOrd
::Infer
=> "infer".fmt(f
),
376 #[derive(Clone, Encodable, Decodable, Debug)]
377 pub enum GenericParamKind
{
378 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
381 default: Option
<P
<Ty
>>,
385 /// Span of the `const` keyword.
387 /// Optional default value for the const generic param
388 default: Option
<AnonConst
>,
392 #[derive(Clone, Encodable, Decodable, Debug)]
393 pub struct GenericParam
{
397 pub bounds
: GenericBounds
,
398 pub is_placeholder
: bool
,
399 pub kind
: GenericParamKind
,
403 pub fn span(&self) -> Span
{
405 GenericParamKind
::Lifetime
| GenericParamKind
::Type { default: None }
=> {
408 GenericParamKind
::Type { default: Some(ty) }
=> self.ident
.span
.to(ty
.span
),
409 GenericParamKind
::Const { kw_span, default: Some(default), .. }
=> {
410 kw_span
.to(default.value
.span
)
412 GenericParamKind
::Const { kw_span, default: None, ty }
=> kw_span
.to(ty
.span
),
417 /// Represents lifetime, type and const parameters attached to a declaration of
418 /// a function, enum, trait, etc.
419 #[derive(Clone, Encodable, Decodable, Debug)]
420 pub struct Generics
{
421 pub params
: Vec
<GenericParam
>,
422 pub where_clause
: WhereClause
,
426 impl Default
for Generics
{
427 /// Creates an instance of `Generics`.
428 fn default() -> Generics
{
431 where_clause
: WhereClause
{
432 has_where_token
: false,
433 predicates
: Vec
::new(),
441 /// A where-clause in a definition.
442 #[derive(Clone, Encodable, Decodable, Debug)]
443 pub struct WhereClause
{
444 /// `true` if we ate a `where` token: this can happen
445 /// if we parsed no predicates (e.g. `struct Foo where {}`).
446 /// This allows us to accurately pretty-print
447 /// in `nt_to_tokenstream`
448 pub has_where_token
: bool
,
449 pub predicates
: Vec
<WherePredicate
>,
453 /// A single predicate in a where-clause.
454 #[derive(Clone, Encodable, Decodable, Debug)]
455 pub enum WherePredicate
{
456 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
457 BoundPredicate(WhereBoundPredicate
),
458 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
459 RegionPredicate(WhereRegionPredicate
),
460 /// An equality predicate (unsupported).
461 EqPredicate(WhereEqPredicate
),
464 impl WherePredicate
{
465 pub fn span(&self) -> Span
{
467 WherePredicate
::BoundPredicate(p
) => p
.span
,
468 WherePredicate
::RegionPredicate(p
) => p
.span
,
469 WherePredicate
::EqPredicate(p
) => p
.span
,
476 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
477 #[derive(Clone, Encodable, Decodable, Debug)]
478 pub struct WhereBoundPredicate
{
480 /// Any generics from a `for` binding.
481 pub bound_generic_params
: Vec
<GenericParam
>,
482 /// The type being bounded.
483 pub bounded_ty
: P
<Ty
>,
484 /// Trait and lifetime bounds (`Clone + Send + 'static`).
485 pub bounds
: GenericBounds
,
488 /// A lifetime predicate.
490 /// E.g., `'a: 'b + 'c`.
491 #[derive(Clone, Encodable, Decodable, Debug)]
492 pub struct WhereRegionPredicate
{
494 pub lifetime
: Lifetime
,
495 pub bounds
: GenericBounds
,
498 /// An equality predicate (unsupported).
501 #[derive(Clone, Encodable, Decodable, Debug)]
502 pub struct WhereEqPredicate
{
509 #[derive(Clone, Encodable, Decodable, Debug)]
511 pub attrs
: Vec
<Attribute
>,
512 pub items
: Vec
<P
<Item
>>,
514 /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
515 /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
517 pub is_placeholder
: bool
,
520 /// Possible values inside of compile-time attribute lists.
522 /// E.g., the '..' in `#[name(..)]`.
523 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
524 pub enum NestedMetaItem
{
525 /// A full MetaItem, for recursive meta items.
529 /// E.g., `"foo"`, `64`, `true`.
533 /// A spanned compile-time attribute item.
535 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
536 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
537 pub struct MetaItem
{
539 pub kind
: MetaItemKind
,
543 /// A compile-time attribute item.
545 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
546 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
547 pub enum MetaItemKind
{
550 /// E.g., `test` as in `#[test]`.
554 /// E.g., `derive(..)` as in `#[derive(..)]`.
555 List(Vec
<NestedMetaItem
>),
556 /// Name value meta item.
558 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
562 /// A block (`{ .. }`).
564 /// E.g., `{ .. }` as in `fn foo() { .. }`.
565 #[derive(Clone, Encodable, Decodable, Debug)]
567 /// The statements in the block.
568 pub stmts
: Vec
<Stmt
>,
570 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
571 pub rules
: BlockCheckMode
,
573 pub tokens
: Option
<LazyTokenStream
>,
574 /// The following *isn't* a parse error, but will cause multiple errors in following stages.
581 pub could_be_bare_literal
: bool
,
586 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
587 #[derive(Clone, Encodable, Decodable, Debug)]
592 pub tokens
: Option
<LazyTokenStream
>,
596 /// Attempt reparsing the pattern as a type.
597 /// This is intended for use by diagnostics.
598 pub fn to_ty(&self) -> Option
<P
<Ty
>> {
599 let kind
= match &self.kind
{
600 // In a type expression `_` is an inference variable.
601 PatKind
::Wild
=> TyKind
::Infer
,
602 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
603 PatKind
::Ident(BindingMode
::ByValue(Mutability
::Not
), ident
, None
) => {
604 TyKind
::Path(None
, Path
::from_ident(*ident
))
606 PatKind
::Path(qself
, path
) => TyKind
::Path(qself
.clone(), path
.clone()),
607 PatKind
::MacCall(mac
) => TyKind
::MacCall(mac
.clone()),
608 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
609 PatKind
::Ref(pat
, mutbl
) => {
610 pat
.to_ty().map(|ty
| TyKind
::Rptr(None
, MutTy { ty, mutbl: *mutbl }
))?
612 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
613 // when `P` can be reparsed as a type `T`.
614 PatKind
::Slice(pats
) if pats
.len() == 1 => pats
[0].to_ty().map(TyKind
::Slice
)?
,
615 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
616 // assuming `T0` to `Tn` are all syntactically valid as types.
617 PatKind
::Tuple(pats
) => {
618 let mut tys
= Vec
::with_capacity(pats
.len());
619 // FIXME(#48994) - could just be collected into an Option<Vec>
621 tys
.push(pat
.to_ty()?
);
628 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }
))
631 /// Walk top-down and call `it` in each place where a pattern occurs
632 /// starting with the root pattern `walk` is called on. If `it` returns
633 /// false then we will descend no further but siblings will be processed.
634 pub fn walk(&self, it
: &mut impl FnMut(&Pat
) -> bool
) {
640 // Walk into the pattern associated with `Ident` (if any).
641 PatKind
::Ident(_
, _
, Some(p
)) => p
.walk(it
),
643 // Walk into each field of struct.
644 PatKind
::Struct(_
, _
, fields
, _
) => fields
.iter().for_each(|field
| field
.pat
.walk(it
)),
646 // Sequence of patterns.
647 PatKind
::TupleStruct(_
, _
, s
)
650 | PatKind
::Or(s
) => s
.iter().for_each(|p
| p
.walk(it
)),
652 // Trivial wrappers over inner patterns.
653 PatKind
::Box(s
) | PatKind
::Ref(s
, _
) | PatKind
::Paren(s
) => s
.walk(it
),
655 // These patterns do not contain subpatterns, skip.
662 | PatKind
::MacCall(_
) => {}
666 /// Is this a `..` pattern?
667 pub fn is_rest(&self) -> bool
{
668 matches
!(self.kind
, PatKind
::Rest
)
672 /// A single field in a struct pattern.
674 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
675 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
676 /// except when `is_shorthand` is true.
677 #[derive(Clone, Encodable, Decodable, Debug)]
678 pub struct PatField
{
679 /// The identifier for the field.
681 /// The pattern the field is destructured to.
683 pub is_shorthand
: bool
,
687 pub is_placeholder
: bool
,
690 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
691 pub enum BindingMode
{
696 #[derive(Clone, Encodable, Decodable, Debug)]
699 Included(RangeSyntax
),
704 #[derive(Clone, Encodable, Decodable, Debug)]
705 pub enum RangeSyntax
{
712 /// All the different flavors of pattern that Rust recognizes.
713 #[derive(Clone, Encodable, Decodable, Debug)]
715 /// Represents a wildcard pattern (`_`).
718 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
719 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
720 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
721 /// during name resolution.
722 Ident(BindingMode
, Ident
, Option
<P
<Pat
>>),
724 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
725 /// The `bool` is `true` in the presence of a `..`.
726 Struct(Option
<QSelf
>, Path
, Vec
<PatField
>, /* recovered */ bool
),
728 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
729 TupleStruct(Option
<QSelf
>, Path
, Vec
<P
<Pat
>>),
731 /// An or-pattern `A | B | C`.
732 /// Invariant: `pats.len() >= 2`.
735 /// A possibly qualified path pattern.
736 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
737 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
738 /// only legally refer to associated constants.
739 Path(Option
<QSelf
>, Path
),
741 /// A tuple pattern (`(a, b)`).
747 /// A reference pattern (e.g., `&mut (a, b)`).
748 Ref(P
<Pat
>, Mutability
),
753 /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
754 Range(Option
<P
<Expr
>>, Option
<P
<Expr
>>, Spanned
<RangeEnd
>),
756 /// A slice pattern `[a, b, c]`.
759 /// A rest pattern `..`.
761 /// Syntactically it is valid anywhere.
763 /// Semantically however, it only has meaning immediately inside:
764 /// - a slice pattern: `[a, .., b]`,
765 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
766 /// - a tuple pattern: `(a, .., b)`,
767 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
769 /// In all of these cases, an additional restriction applies,
770 /// only one rest pattern may occur in the pattern sequences.
773 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
776 /// A macro pattern; pre-expansion.
780 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
781 #[derive(HashStable_Generic, Encodable, Decodable)]
782 pub enum Mutability
{
788 pub fn invert(self) -> Self {
790 Mutability
::Mut
=> Mutability
::Not
,
791 Mutability
::Not
=> Mutability
::Mut
,
795 pub fn prefix_str(&self) -> &'
static str {
797 Mutability
::Mut
=> "mut ",
798 Mutability
::Not
=> "",
803 /// The kind of borrow in an `AddrOf` expression,
804 /// e.g., `&place` or `&raw const place`.
805 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
806 #[derive(Encodable, Decodable, HashStable_Generic)]
807 pub enum BorrowKind
{
808 /// A normal borrow, `&$expr` or `&mut $expr`.
809 /// The resulting type is either `&'a T` or `&'a mut T`
810 /// where `T = typeof($expr)` and `'a` is some lifetime.
812 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
813 /// The resulting type is either `*const T` or `*mut T`
814 /// where `T = typeof($expr)`.
818 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
820 /// The `+` operator (addition)
822 /// The `-` operator (subtraction)
824 /// The `*` operator (multiplication)
826 /// The `/` operator (division)
828 /// The `%` operator (modulus)
830 /// The `&&` operator (logical and)
832 /// The `||` operator (logical or)
834 /// The `^` operator (bitwise xor)
836 /// The `&` operator (bitwise and)
838 /// The `|` operator (bitwise or)
840 /// The `<<` operator (shift left)
842 /// The `>>` operator (shift right)
844 /// The `==` operator (equality)
846 /// The `<` operator (less than)
848 /// The `<=` operator (less than or equal to)
850 /// The `!=` operator (not equal to)
852 /// The `>=` operator (greater than or equal to)
854 /// The `>` operator (greater than)
859 pub fn to_string(&self) -> &'
static str {
882 pub fn lazy(&self) -> bool
{
883 matches
!(self, BinOpKind
::And
| BinOpKind
::Or
)
886 pub fn is_comparison(&self) -> bool
{
888 // Note for developers: please keep this as is;
889 // we want compilation to fail if another variant is added.
891 Eq
| Lt
| Le
| Ne
| Gt
| Ge
=> true,
892 And
| Or
| Add
| Sub
| Mul
| Div
| Rem
| BitXor
| BitAnd
| BitOr
| Shl
| Shr
=> false,
897 pub type BinOp
= Spanned
<BinOpKind
>;
901 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
902 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
904 /// The `*` operator for dereferencing
906 /// The `!` operator for logical inversion
908 /// The `-` operator for negation
913 pub fn to_string(op
: UnOp
) -> &'
static str {
923 #[derive(Clone, Encodable, Decodable, Debug)]
931 pub fn tokens(&self) -> Option
<&LazyTokenStream
> {
933 StmtKind
::Local(ref local
) => local
.tokens
.as_ref(),
934 StmtKind
::Item(ref item
) => item
.tokens
.as_ref(),
935 StmtKind
::Expr(ref expr
) | StmtKind
::Semi(ref expr
) => expr
.tokens
.as_ref(),
936 StmtKind
::Empty
=> None
,
937 StmtKind
::MacCall(ref mac
) => mac
.tokens
.as_ref(),
941 pub fn has_trailing_semicolon(&self) -> bool
{
943 StmtKind
::Semi(_
) => true,
944 StmtKind
::MacCall(mac
) => matches
!(mac
.style
, MacStmtStyle
::Semicolon
),
949 /// Converts a parsed `Stmt` to a `Stmt` with
950 /// a trailing semicolon.
952 /// This only modifies the parsed AST struct, not the attached
953 /// `LazyTokenStream`. The parser is responsible for calling
954 /// `CreateTokenStream::add_trailing_semi` when there is actually
955 /// a semicolon in the tokenstream.
956 pub fn add_trailing_semicolon(mut self) -> Self {
957 self.kind
= match self.kind
{
958 StmtKind
::Expr(expr
) => StmtKind
::Semi(expr
),
959 StmtKind
::MacCall(mac
) => {
960 StmtKind
::MacCall(mac
.map(|MacCallStmt { mac, style: _, attrs, tokens }
| {
961 MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
970 pub fn is_item(&self) -> bool
{
971 matches
!(self.kind
, StmtKind
::Item(_
))
974 pub fn is_expr(&self) -> bool
{
975 matches
!(self.kind
, StmtKind
::Expr(_
))
979 #[derive(Clone, Encodable, Decodable, Debug)]
981 /// A local (let) binding.
983 /// An item definition.
985 /// Expr without trailing semi-colon.
987 /// Expr with a trailing semi-colon.
989 /// Just a trailing semi-colon.
992 MacCall(P
<MacCallStmt
>),
995 #[derive(Clone, Encodable, Decodable, Debug)]
996 pub struct MacCallStmt
{
998 pub style
: MacStmtStyle
,
1000 pub tokens
: Option
<LazyTokenStream
>,
1003 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
1004 pub enum MacStmtStyle
{
1005 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
1006 /// `foo!(...);`, `foo![...];`).
1008 /// The macro statement had braces (e.g., `foo! { ... }`).
1010 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
1011 /// `foo!(...)`). All of these will end up being converted into macro
1016 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1017 #[derive(Clone, Encodable, Decodable, Debug)]
1021 pub ty
: Option
<P
<Ty
>>,
1022 pub kind
: LocalKind
,
1025 pub tokens
: Option
<LazyTokenStream
>,
1028 #[derive(Clone, Encodable, Decodable, Debug)]
1029 pub enum LocalKind
{
1030 /// Local declaration.
1031 /// Example: `let x;`
1033 /// Local declaration with an initializer.
1034 /// Example: `let x = y;`
1036 /// Local declaration with an initializer and an `else` clause.
1037 /// Example: `let Some(x) = y else { return };`
1038 InitElse(P
<Expr
>, P
<Block
>),
1042 pub fn init(&self) -> Option
<&Expr
> {
1045 Self::Init(i
) | Self::InitElse(i
, _
) => Some(i
),
1049 pub fn init_else_opt(&self) -> Option
<(&Expr
, Option
<&Block
>)> {
1052 Self::Init(init
) => Some((init
, None
)),
1053 Self::InitElse(init
, els
) => Some((init
, Some(els
))),
1058 /// An arm of a 'match'.
1060 /// E.g., `0..=10 => { println!("match!") }` as in
1064 /// 0..=10 => { println!("match!") },
1065 /// _ => { println!("no match!") },
1068 #[derive(Clone, Encodable, Decodable, Debug)]
1071 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1073 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1074 pub guard
: Option
<P
<Expr
>>,
1079 pub is_placeholder
: bool
,
1082 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1083 #[derive(Clone, Encodable, Decodable, Debug)]
1084 pub struct ExprField
{
1090 pub is_shorthand
: bool
,
1091 pub is_placeholder
: bool
,
1094 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1095 pub enum BlockCheckMode
{
1097 Unsafe(UnsafeSource
),
1100 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1101 pub enum UnsafeSource
{
1106 /// A constant (expression) that's not an item or associated item,
1107 /// but needs its own `DefId` for type-checking, const-eval, etc.
1108 /// These are usually found nested inside types (e.g., array lengths)
1109 /// or expressions (e.g., repeat counts), and also used to define
1110 /// explicit discriminant values for enum variants.
1111 #[derive(Clone, Encodable, Decodable, Debug)]
1112 pub struct AnonConst
{
1118 #[derive(Clone, Encodable, Decodable, Debug)]
1124 pub tokens
: Option
<LazyTokenStream
>,
1127 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1128 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1129 rustc_data_structures
::static_assert_size
!(Expr
, 104);
1132 /// Returns `true` if this expression would be valid somewhere that expects a value;
1133 /// for example, an `if` condition.
1134 pub fn returns(&self) -> bool
{
1135 if let ExprKind
::Block(ref block
, _
) = self.kind
{
1136 match block
.stmts
.last().map(|last_stmt
| &last_stmt
.kind
) {
1138 Some(StmtKind
::Expr(_
)) => true,
1139 // Last statement is an explicit return?
1140 Some(StmtKind
::Semi(expr
)) => matches
!(expr
.kind
, ExprKind
::Ret(_
)),
1141 // This is a block that doesn't end in either an implicit or explicit return.
1145 // This is not a block, it is a value.
1150 /// Is this expr either `N`, or `{ N }`.
1152 /// If this is not the case, name resolution does not resolve `N` when using
1153 /// `min_const_generics` as more complex expressions are not supported.
1154 pub fn is_potential_trivial_const_param(&self) -> bool
{
1155 let this
= if let ExprKind
::Block(ref block
, None
) = self.kind
{
1156 if block
.stmts
.len() == 1 {
1157 if let StmtKind
::Expr(ref expr
) = block
.stmts
[0].kind { expr }
else { self }
1165 if let ExprKind
::Path(None
, ref path
) = this
.kind
{
1166 if path
.segments
.len() == 1 && path
.segments
[0].args
.is_none() {
1174 pub fn to_bound(&self) -> Option
<GenericBound
> {
1176 ExprKind
::Path(None
, path
) => Some(GenericBound
::Trait(
1177 PolyTraitRef
::new(Vec
::new(), path
.clone(), self.span
),
1178 TraitBoundModifier
::None
,
1184 pub fn peel_parens(&self) -> &Expr
{
1185 let mut expr
= self;
1186 while let ExprKind
::Paren(inner
) = &expr
.kind
{
1192 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1193 pub fn to_ty(&self) -> Option
<P
<Ty
>> {
1194 let kind
= match &self.kind
{
1195 // Trivial conversions.
1196 ExprKind
::Path(qself
, path
) => TyKind
::Path(qself
.clone(), path
.clone()),
1197 ExprKind
::MacCall(mac
) => TyKind
::MacCall(mac
.clone()),
1199 ExprKind
::Paren(expr
) => expr
.to_ty().map(TyKind
::Paren
)?
,
1201 ExprKind
::AddrOf(BorrowKind
::Ref
, mutbl
, expr
) => {
1202 expr
.to_ty().map(|ty
| TyKind
::Rptr(None
, MutTy { ty, mutbl: *mutbl }
))?
1205 ExprKind
::Repeat(expr
, expr_len
) => {
1206 expr
.to_ty().map(|ty
| TyKind
::Array(ty
, expr_len
.clone()))?
1209 ExprKind
::Array(exprs
) if exprs
.len() == 1 => exprs
[0].to_ty().map(TyKind
::Slice
)?
,
1211 ExprKind
::Tup(exprs
) => {
1212 let tys
= exprs
.iter().map(|expr
| expr
.to_ty()).collect
::<Option
<Vec
<_
>>>()?
;
1216 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1217 // then type of result is trait object.
1218 // Otherwise we don't assume the result type.
1219 ExprKind
::Binary(binop
, lhs
, rhs
) if binop
.node
== BinOpKind
::Add
=> {
1220 if let (Some(lhs
), Some(rhs
)) = (lhs
.to_bound(), rhs
.to_bound()) {
1221 TyKind
::TraitObject(vec
![lhs
, rhs
], TraitObjectSyntax
::None
)
1227 ExprKind
::Underscore
=> TyKind
::Infer
,
1229 // This expression doesn't look like a type syntactically.
1233 Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }
))
1236 pub fn precedence(&self) -> ExprPrecedence
{
1238 ExprKind
::Box(_
) => ExprPrecedence
::Box
,
1239 ExprKind
::Array(_
) => ExprPrecedence
::Array
,
1240 ExprKind
::ConstBlock(_
) => ExprPrecedence
::ConstBlock
,
1241 ExprKind
::Call(..) => ExprPrecedence
::Call
,
1242 ExprKind
::MethodCall(..) => ExprPrecedence
::MethodCall
,
1243 ExprKind
::Tup(_
) => ExprPrecedence
::Tup
,
1244 ExprKind
::Binary(op
, ..) => ExprPrecedence
::Binary(op
.node
),
1245 ExprKind
::Unary(..) => ExprPrecedence
::Unary
,
1246 ExprKind
::Lit(_
) => ExprPrecedence
::Lit
,
1247 ExprKind
::Type(..) | ExprKind
::Cast(..) => ExprPrecedence
::Cast
,
1248 ExprKind
::Let(..) => ExprPrecedence
::Let
,
1249 ExprKind
::If(..) => ExprPrecedence
::If
,
1250 ExprKind
::While(..) => ExprPrecedence
::While
,
1251 ExprKind
::ForLoop(..) => ExprPrecedence
::ForLoop
,
1252 ExprKind
::Loop(..) => ExprPrecedence
::Loop
,
1253 ExprKind
::Match(..) => ExprPrecedence
::Match
,
1254 ExprKind
::Closure(..) => ExprPrecedence
::Closure
,
1255 ExprKind
::Block(..) => ExprPrecedence
::Block
,
1256 ExprKind
::TryBlock(..) => ExprPrecedence
::TryBlock
,
1257 ExprKind
::Async(..) => ExprPrecedence
::Async
,
1258 ExprKind
::Await(..) => ExprPrecedence
::Await
,
1259 ExprKind
::Assign(..) => ExprPrecedence
::Assign
,
1260 ExprKind
::AssignOp(..) => ExprPrecedence
::AssignOp
,
1261 ExprKind
::Field(..) => ExprPrecedence
::Field
,
1262 ExprKind
::Index(..) => ExprPrecedence
::Index
,
1263 ExprKind
::Range(..) => ExprPrecedence
::Range
,
1264 ExprKind
::Underscore
=> ExprPrecedence
::Path
,
1265 ExprKind
::Path(..) => ExprPrecedence
::Path
,
1266 ExprKind
::AddrOf(..) => ExprPrecedence
::AddrOf
,
1267 ExprKind
::Break(..) => ExprPrecedence
::Break
,
1268 ExprKind
::Continue(..) => ExprPrecedence
::Continue
,
1269 ExprKind
::Ret(..) => ExprPrecedence
::Ret
,
1270 ExprKind
::InlineAsm(..) => ExprPrecedence
::InlineAsm
,
1271 ExprKind
::MacCall(..) => ExprPrecedence
::Mac
,
1272 ExprKind
::Struct(..) => ExprPrecedence
::Struct
,
1273 ExprKind
::Repeat(..) => ExprPrecedence
::Repeat
,
1274 ExprKind
::Paren(..) => ExprPrecedence
::Paren
,
1275 ExprKind
::Try(..) => ExprPrecedence
::Try
,
1276 ExprKind
::Yield(..) => ExprPrecedence
::Yield
,
1277 ExprKind
::Err
=> ExprPrecedence
::Err
,
1281 pub fn take(&mut self) -> Self {
1286 kind
: ExprKind
::Err
,
1288 attrs
: ThinVec
::new(),
1295 /// Limit types of a range (inclusive or exclusive)
1296 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1297 pub enum RangeLimits
{
1298 /// Inclusive at the beginning, exclusive at the end
1300 /// Inclusive at the beginning and end
1304 #[derive(Clone, Encodable, Decodable, Debug)]
1305 pub enum StructRest
{
1310 /// No trailing `..` or expression.
1314 #[derive(Clone, Encodable, Decodable, Debug)]
1315 pub struct StructExpr
{
1316 pub qself
: Option
<QSelf
>,
1318 pub fields
: Vec
<ExprField
>,
1319 pub rest
: StructRest
,
1322 #[derive(Clone, Encodable, Decodable, Debug)]
1324 /// A `box x` expression.
1326 /// An array (`[a, b, c, d]`)
1327 Array(Vec
<P
<Expr
>>),
1328 /// Allow anonymous constants from an inline `const` block
1329 ConstBlock(AnonConst
),
1332 /// The first field resolves to the function itself,
1333 /// and the second field is the list of arguments.
1334 /// This also represents calling the constructor of
1335 /// tuple-like ADTs such as tuple structs and enum variants.
1336 Call(P
<Expr
>, Vec
<P
<Expr
>>),
1337 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1339 /// The `PathSegment` represents the method name and its generic arguments
1340 /// (within the angle brackets).
1341 /// The first element of the vector of an `Expr` is the expression that evaluates
1342 /// to the object on which the method is being called on (the receiver),
1343 /// and the remaining elements are the rest of the arguments.
1344 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1345 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1346 /// This `Span` is the span of the function, without the dot and receiver
1347 /// (e.g. `foo(a, b)` in `x.foo(a, b)`
1348 MethodCall(PathSegment
, Vec
<P
<Expr
>>, Span
),
1349 /// A tuple (e.g., `(a, b, c, d)`).
1351 /// A binary operation (e.g., `a + b`, `a * b`).
1352 Binary(BinOp
, P
<Expr
>, P
<Expr
>),
1353 /// A unary operation (e.g., `!x`, `*x`).
1354 Unary(UnOp
, P
<Expr
>),
1355 /// A literal (e.g., `1`, `"foo"`).
1357 /// A cast (e.g., `foo as f64`).
1358 Cast(P
<Expr
>, P
<Ty
>),
1359 /// A type ascription (e.g., `42: usize`).
1360 Type(P
<Expr
>, P
<Ty
>),
1361 /// A `let pat = expr` expression that is only semantically allowed in the condition
1362 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1364 /// `Span` represents the whole `let pat = expr` statement.
1365 Let(P
<Pat
>, P
<Expr
>, Span
),
1366 /// An `if` block, with an optional `else` block.
1368 /// `if expr { block } else { expr }`
1369 If(P
<Expr
>, P
<Block
>, Option
<P
<Expr
>>),
1370 /// A while loop, with an optional label.
1372 /// `'label: while expr { block }`
1373 While(P
<Expr
>, P
<Block
>, Option
<Label
>),
1374 /// A `for` loop, with an optional label.
1376 /// `'label: for pat in expr { block }`
1378 /// This is desugared to a combination of `loop` and `match` expressions.
1379 ForLoop(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<Label
>),
1380 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1382 /// `'label: loop { block }`
1383 Loop(P
<Block
>, Option
<Label
>),
1384 /// A `match` block.
1385 Match(P
<Expr
>, Vec
<Arm
>),
1386 /// A closure (e.g., `move |a, b, c| a + b + c`).
1388 /// The final span is the span of the argument block `|...|`.
1389 Closure(CaptureBy
, Async
, Movability
, P
<FnDecl
>, P
<Expr
>, Span
),
1390 /// A block (`'label: { ... }`).
1391 Block(P
<Block
>, Option
<Label
>),
1392 /// An async block (`async move { ... }`).
1394 /// The `NodeId` is the `NodeId` for the closure that results from
1395 /// desugaring an async block, just like the NodeId field in the
1396 /// `Async::Yes` variant. This is necessary in order to create a def for the
1397 /// closure which can be used as a parent of any child defs. Defs
1398 /// created during lowering cannot be made the parent of any other
1399 /// preexisting defs.
1400 Async(CaptureBy
, NodeId
, P
<Block
>),
1401 /// An await expression (`my_future.await`).
1404 /// A try block (`try { ... }`).
1407 /// An assignment (`a = foo()`).
1408 /// The `Span` argument is the span of the `=` token.
1409 Assign(P
<Expr
>, P
<Expr
>, Span
),
1410 /// An assignment with an operator.
1413 AssignOp(BinOp
, P
<Expr
>, P
<Expr
>),
1414 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1415 Field(P
<Expr
>, Ident
),
1416 /// An indexing operation (e.g., `foo[2]`).
1417 Index(P
<Expr
>, P
<Expr
>),
1418 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1419 Range(Option
<P
<Expr
>>, Option
<P
<Expr
>>, RangeLimits
),
1420 /// An underscore, used in destructuring assignment to ignore a value.
1423 /// Variable reference, possibly containing `::` and/or type
1424 /// parameters (e.g., `foo::bar::<baz>`).
1426 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1427 Path(Option
<QSelf
>, Path
),
1429 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1430 AddrOf(BorrowKind
, Mutability
, P
<Expr
>),
1431 /// A `break`, with an optional label to break, and an optional expression.
1432 Break(Option
<Label
>, Option
<P
<Expr
>>),
1433 /// A `continue`, with an optional label.
1434 Continue(Option
<Label
>),
1435 /// A `return`, with an optional value to be returned.
1436 Ret(Option
<P
<Expr
>>),
1438 /// Output of the `asm!()` macro.
1439 InlineAsm(P
<InlineAsm
>),
1441 /// A macro invocation; pre-expansion.
1444 /// A struct literal expression.
1446 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1447 Struct(P
<StructExpr
>),
1449 /// An array literal constructed from one repeated element.
1451 /// E.g., `[1; 5]`. The expression is the element to be
1452 /// repeated; the constant is the number of times to repeat it.
1453 Repeat(P
<Expr
>, AnonConst
),
1455 /// No-op: used solely so we can pretty-print faithfully.
1458 /// A try expression (`expr?`).
1461 /// A `yield`, with an optional value to be yielded.
1462 Yield(Option
<P
<Expr
>>),
1464 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1468 /// The explicit `Self` type in a "qualified path". The actual
1469 /// path, including the trait and the associated item, is stored
1470 /// separately. `position` represents the index of the associated
1471 /// item qualified with this `Self` type.
1473 /// ```ignore (only-for-syntax-highlight)
1474 /// <Vec<T> as a::b::Trait>::AssociatedItem
1475 /// ^~~~~ ~~~~~~~~~~~~~~^
1478 /// <Vec<T>>::AssociatedItem
1482 #[derive(Clone, Encodable, Decodable, Debug)]
1486 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1487 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1488 /// 0`, this is an empty span.
1489 pub path_span
: Span
,
1490 pub position
: usize,
1493 /// A capture clause used in closures and `async` blocks.
1494 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1495 pub enum CaptureBy
{
1496 /// `move |x| y + x`.
1498 /// `move` keyword was not specified.
1502 /// The movability of a generator / closure literal:
1503 /// whether a generator contains self-references, causing it to be `!Unpin`.
1504 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1505 #[derive(HashStable_Generic)]
1506 pub enum Movability
{
1507 /// May contain self-references, `!Unpin`.
1509 /// Must not contain self-references, `Unpin`.
1513 /// Represents a macro invocation. The `path` indicates which macro
1514 /// is being invoked, and the `args` are arguments passed to it.
1515 #[derive(Clone, Encodable, Decodable, Debug)]
1516 pub struct MacCall
{
1518 pub args
: P
<MacArgs
>,
1519 pub prior_type_ascription
: Option
<(Span
, bool
)>,
1523 pub fn span(&self) -> Span
{
1524 self.path
.span
.to(self.args
.span().unwrap_or(self.path
.span
))
1528 /// Arguments passed to an attribute or a function-like macro.
1529 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1531 /// No arguments - `#[attr]`.
1533 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1534 Delimited(DelimSpan
, MacDelimiter
, TokenStream
),
1535 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1537 /// Span of the `=` token.
1539 /// "value" as a nonterminal token.
1545 pub fn delim(&self) -> DelimToken
{
1547 MacArgs
::Delimited(_
, delim
, _
) => delim
.to_token(),
1548 MacArgs
::Empty
| MacArgs
::Eq(..) => token
::NoDelim
,
1552 pub fn span(&self) -> Option
<Span
> {
1554 MacArgs
::Empty
=> None
,
1555 MacArgs
::Delimited(dspan
, ..) => Some(dspan
.entire()),
1556 MacArgs
::Eq(eq_span
, token
) => Some(eq_span
.to(token
.span
)),
1560 /// Tokens inside the delimiters or after `=`.
1561 /// Proc macros see these tokens, for example.
1562 pub fn inner_tokens(&self) -> TokenStream
{
1564 MacArgs
::Empty
=> TokenStream
::default(),
1565 MacArgs
::Delimited(.., tokens
) => tokens
.clone(),
1566 MacArgs
::Eq(.., token
) => TokenTree
::Token(token
.clone()).into(),
1570 /// Whether a macro with these arguments needs a semicolon
1571 /// when used as a standalone item or statement.
1572 pub fn need_semicolon(&self) -> bool
{
1573 !matches
!(self, MacArgs
::Delimited(_
, MacDelimiter
::Brace
, _
))
1577 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1578 pub enum MacDelimiter
{
1585 pub fn to_token(self) -> DelimToken
{
1587 MacDelimiter
::Parenthesis
=> DelimToken
::Paren
,
1588 MacDelimiter
::Bracket
=> DelimToken
::Bracket
,
1589 MacDelimiter
::Brace
=> DelimToken
::Brace
,
1593 pub fn from_token(delim
: DelimToken
) -> Option
<MacDelimiter
> {
1595 token
::Paren
=> Some(MacDelimiter
::Parenthesis
),
1596 token
::Bracket
=> Some(MacDelimiter
::Bracket
),
1597 token
::Brace
=> Some(MacDelimiter
::Brace
),
1598 token
::NoDelim
=> None
,
1603 /// Represents a macro definition.
1604 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1605 pub struct MacroDef
{
1606 pub body
: P
<MacArgs
>,
1607 /// `true` if macro was defined with `macro_rules`.
1608 pub macro_rules
: bool
,
1611 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1612 #[derive(HashStable_Generic)]
1614 /// A regular string, like `"foo"`.
1616 /// A raw string, like `r##"foo"##`.
1618 /// The value is the number of `#` symbols used.
1623 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1625 /// The original literal token as written in source code.
1626 pub token
: token
::Lit
,
1627 /// The "semantic" representation of the literal lowered from the original tokens.
1628 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1629 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1634 /// Same as `Lit`, but restricted to string literals.
1635 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1637 /// The original literal token as written in source code.
1638 pub style
: StrStyle
,
1640 pub suffix
: Option
<Symbol
>,
1642 /// The unescaped "semantic" representation of the literal lowered from the original token.
1643 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1644 pub symbol_unescaped
: Symbol
,
1648 pub fn as_lit(&self) -> Lit
{
1649 let token_kind
= match self.style
{
1650 StrStyle
::Cooked
=> token
::Str
,
1651 StrStyle
::Raw(n
) => token
::StrRaw(n
),
1654 token
: token
::Lit
::new(token_kind
, self.symbol
, self.suffix
),
1656 kind
: LitKind
::Str(self.symbol_unescaped
, self.style
),
1661 /// Type of the integer literal based on provided suffix.
1662 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1663 #[derive(HashStable_Generic)]
1664 pub enum LitIntType
{
1673 /// Type of the float literal based on provided suffix.
1674 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1675 #[derive(HashStable_Generic)]
1676 pub enum LitFloatType
{
1677 /// A float literal with a suffix (`1f32` or `1E10f32`).
1679 /// A float literal without a suffix (`1.0 or 1.0E10`).
1685 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1686 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1688 /// A string literal (`"foo"`).
1689 Str(Symbol
, StrStyle
),
1690 /// A byte string (`b"foo"`).
1692 /// A byte char (`b'f'`).
1694 /// A character literal (`'a'`).
1696 /// An integer literal (`1`).
1697 Int(u128
, LitIntType
),
1698 /// A float literal (`1f64` or `1E10f64`).
1699 Float(Symbol
, LitFloatType
),
1700 /// A boolean literal.
1702 /// Placeholder for a literal that wasn't well-formed in some way.
1707 /// Returns `true` if this literal is a string.
1708 pub fn is_str(&self) -> bool
{
1709 matches
!(self, LitKind
::Str(..))
1712 /// Returns `true` if this literal is byte literal string.
1713 pub fn is_bytestr(&self) -> bool
{
1714 matches
!(self, LitKind
::ByteStr(_
))
1717 /// Returns `true` if this is a numeric literal.
1718 pub fn is_numeric(&self) -> bool
{
1719 matches
!(self, LitKind
::Int(..) | LitKind
::Float(..))
1722 /// Returns `true` if this literal has no suffix.
1723 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1724 pub fn is_unsuffixed(&self) -> bool
{
1728 /// Returns `true` if this literal has a suffix.
1729 pub fn is_suffixed(&self) -> bool
{
1731 // suffixed variants
1732 LitKind
::Int(_
, LitIntType
::Signed(..) | LitIntType
::Unsigned(..))
1733 | LitKind
::Float(_
, LitFloatType
::Suffixed(..)) => true,
1734 // unsuffixed variants
1736 | LitKind
::ByteStr(..)
1739 | LitKind
::Int(_
, LitIntType
::Unsuffixed
)
1740 | LitKind
::Float(_
, LitFloatType
::Unsuffixed
)
1742 | LitKind
::Err(..) => false,
1747 // N.B., If you change this, you'll probably want to change the corresponding
1748 // type structure in `middle/ty.rs` as well.
1749 #[derive(Clone, Encodable, Decodable, Debug)]
1752 pub mutbl
: Mutability
,
1755 /// Represents a function's signature in a trait declaration,
1756 /// trait implementation, or free function.
1757 #[derive(Clone, Encodable, Decodable, Debug)]
1759 pub header
: FnHeader
,
1760 pub decl
: P
<FnDecl
>,
1764 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1765 #[derive(Encodable, Decodable, HashStable_Generic)]
1772 pub fn name_str(self) -> &'
static str {
1774 FloatTy
::F32
=> "f32",
1775 FloatTy
::F64
=> "f64",
1779 pub fn name(self) -> Symbol
{
1781 FloatTy
::F32
=> sym
::f32,
1782 FloatTy
::F64
=> sym
::f64,
1787 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1788 #[derive(Encodable, Decodable, HashStable_Generic)]
1799 pub fn name_str(&self) -> &'
static str {
1801 IntTy
::Isize
=> "isize",
1803 IntTy
::I16
=> "i16",
1804 IntTy
::I32
=> "i32",
1805 IntTy
::I64
=> "i64",
1806 IntTy
::I128
=> "i128",
1810 pub fn name(&self) -> Symbol
{
1812 IntTy
::Isize
=> sym
::isize,
1813 IntTy
::I8
=> sym
::i8,
1814 IntTy
::I16
=> sym
::i16,
1815 IntTy
::I32
=> sym
::i32,
1816 IntTy
::I64
=> sym
::i64,
1817 IntTy
::I128
=> sym
::i128
,
1822 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1823 #[derive(Encodable, Decodable, HashStable_Generic)]
1834 pub fn name_str(&self) -> &'
static str {
1836 UintTy
::Usize
=> "usize",
1838 UintTy
::U16
=> "u16",
1839 UintTy
::U32
=> "u32",
1840 UintTy
::U64
=> "u64",
1841 UintTy
::U128
=> "u128",
1845 pub fn name(&self) -> Symbol
{
1847 UintTy
::Usize
=> sym
::usize,
1848 UintTy
::U8
=> sym
::u8,
1849 UintTy
::U16
=> sym
::u16,
1850 UintTy
::U32
=> sym
::u32,
1851 UintTy
::U64
=> sym
::u64,
1852 UintTy
::U128
=> sym
::u128
,
1857 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1858 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1859 #[derive(Clone, Encodable, Decodable, Debug)]
1860 pub struct AssocConstraint
{
1863 pub gen_args
: Option
<GenericArgs
>,
1864 pub kind
: AssocConstraintKind
,
1868 /// The kinds of an `AssocConstraint`.
1869 #[derive(Clone, Encodable, Decodable, Debug)]
1875 impl From
<P
<Ty
>> for Term
{
1876 fn from(v
: P
<Ty
>) -> Self {
1881 impl From
<AnonConst
> for Term
{
1882 fn from(v
: AnonConst
) -> Self {
1887 /// The kinds of an `AssocConstraint`.
1888 #[derive(Clone, Encodable, Decodable, Debug)]
1889 pub enum AssocConstraintKind
{
1890 /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1891 Equality { term: Term }
,
1892 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1893 Bound { bounds: GenericBounds }
,
1896 #[derive(Encodable, Decodable, Debug)]
1901 pub tokens
: Option
<LazyTokenStream
>,
1905 fn clone(&self) -> Self {
1906 ensure_sufficient_stack(|| Self {
1908 kind
: self.kind
.clone(),
1910 tokens
: self.tokens
.clone(),
1916 pub fn peel_refs(&self) -> &Self {
1917 let mut final_ty
= self;
1918 while let TyKind
::Rptr(_
, MutTy { ty, .. }
) = &final_ty
.kind
{
1925 #[derive(Clone, Encodable, Decodable, Debug)]
1926 pub struct BareFnTy
{
1927 pub unsafety
: Unsafe
,
1929 pub generic_params
: Vec
<GenericParam
>,
1930 pub decl
: P
<FnDecl
>,
1933 /// The various kinds of type recognized by the compiler.
1934 #[derive(Clone, Encodable, Decodable, Debug)]
1936 /// A variable-length slice (`[T]`).
1938 /// A fixed length array (`[T; n]`).
1939 Array(P
<Ty
>, AnonConst
),
1940 /// A raw pointer (`*const T` or `*mut T`).
1942 /// A reference (`&'a T` or `&'a mut T`).
1943 Rptr(Option
<Lifetime
>, MutTy
),
1944 /// A bare function (e.g., `fn(usize) -> bool`).
1945 BareFn(P
<BareFnTy
>),
1946 /// The never type (`!`).
1948 /// A tuple (`(A, B, C, D,...)`).
1950 /// A path (`module::module::...::Type`), optionally
1951 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1953 /// Type parameters are stored in the `Path` itself.
1954 Path(Option
<QSelf
>, Path
),
1955 /// A trait object type `Bound1 + Bound2 + Bound3`
1956 /// where `Bound` is a trait or a lifetime.
1957 TraitObject(GenericBounds
, TraitObjectSyntax
),
1958 /// An `impl Bound1 + Bound2 + Bound3` type
1959 /// where `Bound` is a trait or a lifetime.
1961 /// The `NodeId` exists to prevent lowering from having to
1962 /// generate `NodeId`s on the fly, which would complicate
1963 /// the generation of opaque `type Foo = impl Trait` items significantly.
1964 ImplTrait(NodeId
, GenericBounds
),
1965 /// No-op; kept solely so that we can pretty-print faithfully.
1969 /// This means the type should be inferred instead of it having been
1970 /// specified. This can appear anywhere in a type.
1972 /// Inferred type of a `self` or `&self` argument in a method.
1974 /// A macro in the type position.
1976 /// Placeholder for a kind that has failed to be defined.
1978 /// Placeholder for a `va_list`.
1983 pub fn is_implicit_self(&self) -> bool
{
1984 matches
!(self, TyKind
::ImplicitSelf
)
1987 pub fn is_unit(&self) -> bool
{
1988 matches
!(self, TyKind
::Tup(tys
) if tys
.is_empty())
1992 /// Syntax used to declare a trait object.
1993 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1994 pub enum TraitObjectSyntax
{
1999 /// Inline assembly operand explicit register or register class.
2001 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2002 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2003 pub enum InlineAsmRegOrRegClass
{
2008 bitflags
::bitflags
! {
2009 #[derive(Encodable, Decodable, HashStable_Generic)]
2010 pub struct InlineAsmOptions
: u16 {
2011 const PURE
= 1 << 0;
2012 const NOMEM
= 1 << 1;
2013 const READONLY
= 1 << 2;
2014 const PRESERVES_FLAGS
= 1 << 3;
2015 const NORETURN
= 1 << 4;
2016 const NOSTACK
= 1 << 5;
2017 const ATT_SYNTAX
= 1 << 6;
2019 const MAY_UNWIND
= 1 << 8;
2023 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2024 pub enum InlineAsmTemplatePiece
{
2026 Placeholder { operand_idx: usize, modifier: Option<char>, span: Span }
,
2029 impl fmt
::Display
for InlineAsmTemplatePiece
{
2030 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2032 Self::String(s
) => {
2033 for c
in s
.chars() {
2035 '
{'
=> f
.write_str("{{")?
,
2036 '
}'
=> f
.write_str("}}")?
,
2042 Self::Placeholder { operand_idx, modifier: Some(modifier), .. }
=> {
2043 write
!(f
, "{{{}:{}}}", operand_idx
, modifier
)
2045 Self::Placeholder { operand_idx, modifier: None, .. }
=> {
2046 write
!(f
, "{{{}}}", operand_idx
)
2052 impl InlineAsmTemplatePiece
{
2053 /// Rebuilds the asm template string from its pieces.
2054 pub fn to_string(s
: &[Self]) -> String
{
2056 let mut out
= String
::new();
2058 let _
= write
!(out
, "{}", p
);
2064 /// Inline assembly operand.
2066 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2067 #[derive(Clone, Encodable, Decodable, Debug)]
2068 pub enum InlineAsmOperand
{
2070 reg
: InlineAsmRegOrRegClass
,
2074 reg
: InlineAsmRegOrRegClass
,
2076 expr
: Option
<P
<Expr
>>,
2079 reg
: InlineAsmRegOrRegClass
,
2084 reg
: InlineAsmRegOrRegClass
,
2087 out_expr
: Option
<P
<Expr
>>,
2090 anon_const
: AnonConst
,
2097 /// Inline assembly.
2099 /// E.g., `asm!("NOP");`.
2100 #[derive(Clone, Encodable, Decodable, Debug)]
2101 pub struct InlineAsm
{
2102 pub template
: Vec
<InlineAsmTemplatePiece
>,
2103 pub template_strs
: Box
<[(Symbol
, Option
<Symbol
>, Span
)]>,
2104 pub operands
: Vec
<(InlineAsmOperand
, Span
)>,
2105 pub clobber_abis
: Vec
<(Symbol
, Span
)>,
2106 pub options
: InlineAsmOptions
,
2107 pub line_spans
: Vec
<Span
>,
2110 /// A parameter in a function header.
2112 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2113 #[derive(Clone, Encodable, Decodable, Debug)]
2120 pub is_placeholder
: bool
,
2123 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2125 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2126 #[derive(Clone, Encodable, Decodable, Debug)]
2128 /// `self`, `mut self`
2130 /// `&'lt self`, `&'lt mut self`
2131 Region(Option
<Lifetime
>, Mutability
),
2132 /// `self: TYPE`, `mut self: TYPE`
2133 Explicit(P
<Ty
>, Mutability
),
2136 pub type ExplicitSelf
= Spanned
<SelfKind
>;
2139 /// Attempts to cast parameter to `ExplicitSelf`.
2140 pub fn to_self(&self) -> Option
<ExplicitSelf
> {
2141 if let PatKind
::Ident(BindingMode
::ByValue(mutbl
), ident
, _
) = self.pat
.kind
{
2142 if ident
.name
== kw
::SelfLower
{
2143 return match self.ty
.kind
{
2144 TyKind
::ImplicitSelf
=> Some(respan(self.pat
.span
, SelfKind
::Value(mutbl
))),
2145 TyKind
::Rptr(lt
, MutTy { ref ty, mutbl }
) if ty
.kind
.is_implicit_self() => {
2146 Some(respan(self.pat
.span
, SelfKind
::Region(lt
, mutbl
)))
2149 self.pat
.span
.to(self.ty
.span
),
2150 SelfKind
::Explicit(self.ty
.clone(), mutbl
),
2158 /// Returns `true` if parameter is `self`.
2159 pub fn is_self(&self) -> bool
{
2160 if let PatKind
::Ident(_
, ident
, _
) = self.pat
.kind
{
2161 ident
.name
== kw
::SelfLower
2167 /// Builds a `Param` object from `ExplicitSelf`.
2168 pub fn from_self(attrs
: AttrVec
, eself
: ExplicitSelf
, eself_ident
: Ident
) -> Param
{
2169 let span
= eself
.span
.to(eself_ident
.span
);
2170 let infer_ty
= P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None }
);
2171 let param
= |mutbl
, ty
| Param
{
2175 kind
: PatKind
::Ident(BindingMode
::ByValue(mutbl
), eself_ident
, None
),
2182 is_placeholder
: false,
2185 SelfKind
::Explicit(ty
, mutbl
) => param(mutbl
, ty
),
2186 SelfKind
::Value(mutbl
) => param(mutbl
, infer_ty
),
2187 SelfKind
::Region(lt
, mutbl
) => param(
2191 kind
: TyKind
::Rptr(lt
, MutTy { ty: infer_ty, mutbl }
),
2200 /// A signature (not the body) of a function declaration.
2202 /// E.g., `fn foo(bar: baz)`.
2204 /// Please note that it's different from `FnHeader` structure
2205 /// which contains metadata about function safety, asyncness, constness and ABI.
2206 #[derive(Clone, Encodable, Decodable, Debug)]
2208 pub inputs
: Vec
<Param
>,
2209 pub output
: FnRetTy
,
2213 pub fn has_self(&self) -> bool
{
2214 self.inputs
.get(0).map_or(false, Param
::is_self
)
2216 pub fn c_variadic(&self) -> bool
{
2217 self.inputs
.last().map_or(false, |arg
| matches
!(arg
.ty
.kind
, TyKind
::CVarArgs
))
2221 /// Is the trait definition an auto trait?
2222 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2228 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2229 #[derive(HashStable_Generic)]
2235 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2237 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId }
,
2242 pub fn is_async(self) -> bool
{
2243 matches
!(self, Async
::Yes { .. }
)
2246 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2247 pub fn opt_return_id(self) -> Option
<NodeId
> {
2249 Async
::Yes { return_impl_trait_id, .. }
=> Some(return_impl_trait_id
),
2255 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2256 #[derive(HashStable_Generic)]
2262 /// Item defaultness.
2263 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2264 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2265 pub enum Defaultness
{
2270 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2271 pub enum ImplPolarity
{
2272 /// `impl Trait for Type`
2274 /// `impl !Trait for Type`
2278 impl fmt
::Debug
for ImplPolarity
{
2279 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2281 ImplPolarity
::Positive
=> "positive".fmt(f
),
2282 ImplPolarity
::Negative(_
) => "negative".fmt(f
),
2287 #[derive(Clone, Encodable, Decodable, Debug)]
2289 /// Returns type is not specified.
2291 /// Functions default to `()` and closures default to inference.
2292 /// Span points to where return type would be inserted.
2294 /// Everything else.
2299 pub fn span(&self) -> Span
{
2301 FnRetTy
::Default(span
) => span
,
2302 FnRetTy
::Ty(ref ty
) => ty
.span
,
2307 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2313 /// Module item kind.
2314 #[derive(Clone, Encodable, Decodable, Debug)]
2316 /// Module with inlined definition `mod foo { ... }`,
2317 /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2318 /// The inner span is from the first token past `{` to the last token until `}`,
2319 /// or from the first to the last token in the loaded file.
2320 Loaded(Vec
<P
<Item
>>, Inline
, ModSpans
),
2321 /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2325 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2326 pub struct ModSpans
{
2327 /// `inner_span` covers the body of the module; for a file module, its the whole file.
2328 /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2329 pub inner_span
: Span
,
2330 pub inject_use_span
: Span
,
2333 impl Default
for ModSpans
{
2334 fn default() -> ModSpans
{
2335 ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2339 /// Foreign module declaration.
2341 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2342 #[derive(Clone, Encodable, Decodable, Debug)]
2343 pub struct ForeignMod
{
2344 /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2345 /// semantically by Rust.
2346 pub unsafety
: Unsafe
,
2347 pub abi
: Option
<StrLit
>,
2348 pub items
: Vec
<P
<ForeignItem
>>,
2351 #[derive(Clone, Encodable, Decodable, Debug)]
2352 pub struct EnumDef
{
2353 pub variants
: Vec
<Variant
>,
2356 #[derive(Clone, Encodable, Decodable, Debug)]
2357 pub struct Variant
{
2358 /// Attributes of the variant.
2360 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2364 /// The visibility of the variant. Syntactically accepted but not semantically.
2365 pub vis
: Visibility
,
2366 /// Name of the variant.
2369 /// Fields and constructor id of the variant.
2370 pub data
: VariantData
,
2371 /// Explicit discriminant, e.g., `Foo = 1`.
2372 pub disr_expr
: Option
<AnonConst
>,
2373 /// Is a macro placeholder
2374 pub is_placeholder
: bool
,
2377 /// Part of `use` item to the right of its prefix.
2378 #[derive(Clone, Encodable, Decodable, Debug)]
2379 pub enum UseTreeKind
{
2380 /// `use prefix` or `use prefix as rename`
2382 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2384 Simple(Option
<Ident
>, NodeId
, NodeId
),
2385 /// `use prefix::{...}`
2386 Nested(Vec
<(UseTree
, NodeId
)>),
2391 /// A tree of paths sharing common prefixes.
2392 /// Used in `use` items both at top-level and inside of braces in import groups.
2393 #[derive(Clone, Encodable, Decodable, Debug)]
2394 pub struct UseTree
{
2396 pub kind
: UseTreeKind
,
2401 pub fn ident(&self) -> Ident
{
2403 UseTreeKind
::Simple(Some(rename
), ..) => rename
,
2404 UseTreeKind
::Simple(None
, ..) => {
2405 self.prefix
.segments
.last().expect("empty prefix in a simple import").ident
2407 _
=> panic
!("`UseTree::ident` can only be used on a simple import"),
2412 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2413 /// are contained as statements within items. These two cases need to be
2414 /// distinguished for pretty-printing.
2415 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2416 pub enum AttrStyle
{
2421 rustc_index
::newtype_index
! {
2424 DEBUG_FORMAT
= "AttrId({})"
2428 impl<S
: Encoder
> rustc_serialize
::Encodable
<S
> for AttrId
{
2429 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
2434 impl<D
: Decoder
> rustc_serialize
::Decodable
<D
> for AttrId
{
2435 fn decode(_
: &mut D
) -> AttrId
{
2436 crate::attr
::mk_attr_id()
2440 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2441 pub struct AttrItem
{
2444 pub tokens
: Option
<LazyTokenStream
>,
2447 /// A list of attributes.
2448 pub type AttrVec
= ThinVec
<Attribute
>;
2450 /// Metadata associated with an item.
2451 #[derive(Clone, Encodable, Decodable, Debug)]
2452 pub struct Attribute
{
2455 /// Denotes if the attribute decorates the following construct (outer)
2456 /// or the construct this attribute is contained within (inner).
2457 pub style
: AttrStyle
,
2461 #[derive(Clone, Encodable, Decodable, Debug)]
2463 /// A normal attribute.
2464 Normal(AttrItem
, Option
<LazyTokenStream
>),
2466 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2467 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2468 /// variant (which is much less compact and thus more expensive).
2469 DocComment(CommentKind
, Symbol
),
2472 /// `TraitRef`s appear in impls.
2474 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2475 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2476 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2477 /// same as the impl's `NodeId`).
2478 #[derive(Clone, Encodable, Decodable, Debug)]
2479 pub struct TraitRef
{
2484 #[derive(Clone, Encodable, Decodable, Debug)]
2485 pub struct PolyTraitRef
{
2486 /// The `'a` in `<'a> Foo<&'a T>`.
2487 pub bound_generic_params
: Vec
<GenericParam
>,
2489 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2490 pub trait_ref
: TraitRef
,
2496 pub fn new(generic_params
: Vec
<GenericParam
>, path
: Path
, span
: Span
) -> Self {
2498 bound_generic_params
: generic_params
,
2499 trait_ref
: TraitRef { path, ref_id: DUMMY_NODE_ID }
,
2505 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2506 pub enum CrateSugar
{
2507 /// Source is `pub(crate)`.
2510 /// Source is (just) `crate`.
2514 #[derive(Clone, Encodable, Decodable, Debug)]
2515 pub struct Visibility
{
2516 pub kind
: VisibilityKind
,
2518 pub tokens
: Option
<LazyTokenStream
>,
2521 #[derive(Clone, Encodable, Decodable, Debug)]
2522 pub enum VisibilityKind
{
2525 Restricted { path: P<Path>, id: NodeId }
,
2529 impl VisibilityKind
{
2530 pub fn is_pub(&self) -> bool
{
2531 matches
!(self, VisibilityKind
::Public
)
2535 /// Field definition in a struct, variant or union.
2537 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2538 #[derive(Clone, Encodable, Decodable, Debug)]
2539 pub struct FieldDef
{
2543 pub vis
: Visibility
,
2544 pub ident
: Option
<Ident
>,
2547 pub is_placeholder
: bool
,
2550 /// Fields and constructor ids of enum variants and structs.
2551 #[derive(Clone, Encodable, Decodable, Debug)]
2552 pub enum VariantData
{
2555 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2556 Struct(Vec
<FieldDef
>, bool
),
2559 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2560 Tuple(Vec
<FieldDef
>, NodeId
),
2563 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2568 /// Return the fields of this variant.
2569 pub fn fields(&self) -> &[FieldDef
] {
2571 VariantData
::Struct(ref fields
, ..) | VariantData
::Tuple(ref fields
, _
) => fields
,
2576 /// Return the `NodeId` of this variant's constructor, if it has one.
2577 pub fn ctor_id(&self) -> Option
<NodeId
> {
2579 VariantData
::Struct(..) => None
,
2580 VariantData
::Tuple(_
, id
) | VariantData
::Unit(id
) => Some(id
),
2585 /// An item definition.
2586 #[derive(Clone, Encodable, Decodable, Debug)]
2587 pub struct Item
<K
= ItemKind
> {
2588 pub attrs
: Vec
<Attribute
>,
2591 pub vis
: Visibility
,
2592 /// The name of the item.
2593 /// It might be a dummy name in case of anonymous items.
2598 /// Original tokens this item was parsed from. This isn't necessarily
2599 /// available for all items, although over time more and more items should
2600 /// have this be `Some`. Right now this is primarily used for procedural
2601 /// macros, notably custom attributes.
2603 /// Note that the tokens here do not include the outer attributes, but will
2604 /// include inner attributes.
2605 pub tokens
: Option
<LazyTokenStream
>,
2609 /// Return the span that encompasses the attributes.
2610 pub fn span_with_attributes(&self) -> Span
{
2611 self.attrs
.iter().fold(self.span
, |acc
, attr
| acc
.to(attr
.span
))
2615 impl<K
: Into
<ItemKind
>> Item
<K
> {
2616 pub fn into_item(self) -> Item
{
2617 let Item { attrs, id, span, vis, ident, kind, tokens }
= self;
2618 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2622 /// `extern` qualifier on a function item or function type.
2623 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2631 pub fn from_abi(abi
: Option
<StrLit
>) -> Extern
{
2632 abi
.map_or(Extern
::Implicit
, Extern
::Explicit
)
2636 /// A function header.
2638 /// All the information between the visibility and the name of the function is
2639 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2640 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2641 pub struct FnHeader
{
2642 pub unsafety
: Unsafe
,
2643 pub asyncness
: Async
,
2644 pub constness
: Const
,
2649 /// Does this function header have any qualifiers or is it empty?
2650 pub fn has_qualifiers(&self) -> bool
{
2651 let Self { unsafety, asyncness, constness, ext }
= self;
2652 matches
!(unsafety
, Unsafe
::Yes(_
))
2653 || asyncness
.is_async()
2654 || matches
!(constness
, Const
::Yes(_
))
2655 || !matches
!(ext
, Extern
::None
)
2659 impl Default
for FnHeader
{
2660 fn default() -> FnHeader
{
2662 unsafety
: Unsafe
::No
,
2663 asyncness
: Async
::No
,
2664 constness
: Const
::No
,
2670 #[derive(Clone, Encodable, Decodable, Debug)]
2672 pub unsafety
: Unsafe
,
2673 pub is_auto
: IsAuto
,
2674 pub generics
: Generics
,
2675 pub bounds
: GenericBounds
,
2676 pub items
: Vec
<P
<AssocItem
>>,
2679 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2680 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2681 /// are two locations for where clause on type aliases, but their predicates
2682 /// are concatenated together.
2684 /// Take this example:
2685 /// ```ignore (only-for-syntax-highlight)
2687 /// type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2689 /// impl Foo for () {
2690 /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2691 /// // ^^^^^^^^^^^^^^ first where clause
2692 /// // ^^^^^^^^^^^^^^ second where clause
2696 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2697 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2698 pub struct TyAliasWhereClause(pub bool
, pub Span
);
2700 #[derive(Clone, Encodable, Decodable, Debug)]
2701 pub struct TyAlias
{
2702 pub defaultness
: Defaultness
,
2703 pub generics
: Generics
,
2704 /// The span information for the two where clauses (before equals, after equals)
2705 pub where_clauses
: (TyAliasWhereClause
, TyAliasWhereClause
),
2706 /// The index in `generics.where_clause.predicates` that would split into
2707 /// predicates from the where clause before the equals and the predicates
2708 /// from the where clause after the equals
2709 pub where_predicates_split
: usize,
2710 pub bounds
: GenericBounds
,
2711 pub ty
: Option
<P
<Ty
>>,
2714 #[derive(Clone, Encodable, Decodable, Debug)]
2716 pub defaultness
: Defaultness
,
2717 pub unsafety
: Unsafe
,
2718 pub generics
: Generics
,
2719 pub constness
: Const
,
2720 pub polarity
: ImplPolarity
,
2721 /// The trait being implemented, if any.
2722 pub of_trait
: Option
<TraitRef
>,
2724 pub items
: Vec
<P
<AssocItem
>>,
2727 #[derive(Clone, Encodable, Decodable, Debug)]
2729 pub defaultness
: Defaultness
,
2730 pub generics
: Generics
,
2732 pub body
: Option
<P
<Block
>>,
2735 #[derive(Clone, Encodable, Decodable, Debug)]
2737 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2739 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2740 ExternCrate(Option
<Symbol
>),
2741 /// A use declaration item (`use`).
2743 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2745 /// A static item (`static`).
2747 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2748 Static(P
<Ty
>, Mutability
, Option
<P
<Expr
>>),
2749 /// A constant item (`const`).
2751 /// E.g., `const FOO: i32 = 42;`.
2752 Const(Defaultness
, P
<Ty
>, Option
<P
<Expr
>>),
2753 /// A function declaration (`fn`).
2755 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2757 /// A module declaration (`mod`).
2759 /// E.g., `mod foo;` or `mod foo { .. }`.
2760 /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2761 /// semantically by Rust.
2762 Mod(Unsafe
, ModKind
),
2763 /// An external module (`extern`).
2765 /// E.g., `extern {}` or `extern "C" {}`.
2766 ForeignMod(ForeignMod
),
2767 /// Module-level inline assembly (from `global_asm!()`).
2768 GlobalAsm(Box
<InlineAsm
>),
2769 /// A type alias (`type`).
2771 /// E.g., `type Foo = Bar<u8>;`.
2772 TyAlias(Box
<TyAlias
>),
2773 /// An enum definition (`enum`).
2775 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2776 Enum(EnumDef
, Generics
),
2777 /// A struct definition (`struct`).
2779 /// E.g., `struct Foo<A> { x: A }`.
2780 Struct(VariantData
, Generics
),
2781 /// A union definition (`union`).
2783 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2784 Union(VariantData
, Generics
),
2785 /// A trait declaration (`trait`).
2787 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2791 /// E.g., `trait Foo = Bar + Quux;`.
2792 TraitAlias(Generics
, GenericBounds
),
2793 /// An implementation.
2795 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2797 /// A macro invocation.
2799 /// E.g., `foo!(..)`.
2802 /// A macro definition.
2806 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2807 rustc_data_structures
::static_assert_size
!(ItemKind
, 112);
2810 pub fn article(&self) -> &str {
2813 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2814 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2815 ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. }
=> "an",
2819 pub fn descr(&self) -> &str {
2821 ItemKind
::ExternCrate(..) => "extern crate",
2822 ItemKind
::Use(..) => "`use` import",
2823 ItemKind
::Static(..) => "static item",
2824 ItemKind
::Const(..) => "constant item",
2825 ItemKind
::Fn(..) => "function",
2826 ItemKind
::Mod(..) => "module",
2827 ItemKind
::ForeignMod(..) => "extern block",
2828 ItemKind
::GlobalAsm(..) => "global asm item",
2829 ItemKind
::TyAlias(..) => "type alias",
2830 ItemKind
::Enum(..) => "enum",
2831 ItemKind
::Struct(..) => "struct",
2832 ItemKind
::Union(..) => "union",
2833 ItemKind
::Trait(..) => "trait",
2834 ItemKind
::TraitAlias(..) => "trait alias",
2835 ItemKind
::MacCall(..) => "item macro invocation",
2836 ItemKind
::MacroDef(..) => "macro definition",
2837 ItemKind
::Impl { .. }
=> "implementation",
2841 pub fn generics(&self) -> Option
<&Generics
> {
2843 Self::Fn(box Fn { generics, .. }
)
2844 | Self::TyAlias(box TyAlias { generics, .. }
)
2845 | Self::Enum(_
, generics
)
2846 | Self::Struct(_
, generics
)
2847 | Self::Union(_
, generics
)
2848 | Self::Trait(box Trait { generics, .. }
)
2849 | Self::TraitAlias(generics
, _
)
2850 | Self::Impl(box Impl { generics, .. }
) => Some(generics
),
2856 /// Represents associated items.
2857 /// These include items in `impl` and `trait` definitions.
2858 pub type AssocItem
= Item
<AssocItemKind
>;
2860 /// Represents associated item kinds.
2862 /// The term "provided" in the variants below refers to the item having a default
2863 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2864 /// In an implementation, all items must be provided.
2865 /// The `Option`s below denote the bodies, where `Some(_)`
2866 /// means "provided" and conversely `None` means "required".
2867 #[derive(Clone, Encodable, Decodable, Debug)]
2868 pub enum AssocItemKind
{
2869 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2870 /// If `def` is parsed, then the constant is provided, and otherwise required.
2871 Const(Defaultness
, P
<Ty
>, Option
<P
<Expr
>>),
2872 /// An associated function.
2874 /// An associated type.
2875 TyAlias(Box
<TyAlias
>),
2876 /// A macro expanding to associated items.
2880 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2881 rustc_data_structures
::static_assert_size
!(AssocItemKind
, 72);
2883 impl AssocItemKind
{
2884 pub fn defaultness(&self) -> Defaultness
{
2886 Self::Const(defaultness
, ..)
2887 | Self::Fn(box Fn { defaultness, .. }
)
2888 | Self::TyAlias(box TyAlias { defaultness, .. }
) => defaultness
,
2889 Self::MacCall(..) => Defaultness
::Final
,
2894 impl From
<AssocItemKind
> for ItemKind
{
2895 fn from(assoc_item_kind
: AssocItemKind
) -> ItemKind
{
2896 match assoc_item_kind
{
2897 AssocItemKind
::Const(a
, b
, c
) => ItemKind
::Const(a
, b
, c
),
2898 AssocItemKind
::Fn(fn_kind
) => ItemKind
::Fn(fn_kind
),
2899 AssocItemKind
::TyAlias(ty_alias_kind
) => ItemKind
::TyAlias(ty_alias_kind
),
2900 AssocItemKind
::MacCall(a
) => ItemKind
::MacCall(a
),
2905 impl TryFrom
<ItemKind
> for AssocItemKind
{
2906 type Error
= ItemKind
;
2908 fn try_from(item_kind
: ItemKind
) -> Result
<AssocItemKind
, ItemKind
> {
2909 Ok(match item_kind
{
2910 ItemKind
::Const(a
, b
, c
) => AssocItemKind
::Const(a
, b
, c
),
2911 ItemKind
::Fn(fn_kind
) => AssocItemKind
::Fn(fn_kind
),
2912 ItemKind
::TyAlias(ty_alias_kind
) => AssocItemKind
::TyAlias(ty_alias_kind
),
2913 ItemKind
::MacCall(a
) => AssocItemKind
::MacCall(a
),
2914 _
=> return Err(item_kind
),
2919 /// An item in `extern` block.
2920 #[derive(Clone, Encodable, Decodable, Debug)]
2921 pub enum ForeignItemKind
{
2922 /// A foreign static item (`static FOO: u8`).
2923 Static(P
<Ty
>, Mutability
, Option
<P
<Expr
>>),
2924 /// An foreign function.
2926 /// An foreign type.
2927 TyAlias(Box
<TyAlias
>),
2928 /// A macro expanding to foreign items.
2932 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2933 rustc_data_structures
::static_assert_size
!(ForeignItemKind
, 72);
2935 impl From
<ForeignItemKind
> for ItemKind
{
2936 fn from(foreign_item_kind
: ForeignItemKind
) -> ItemKind
{
2937 match foreign_item_kind
{
2938 ForeignItemKind
::Static(a
, b
, c
) => ItemKind
::Static(a
, b
, c
),
2939 ForeignItemKind
::Fn(fn_kind
) => ItemKind
::Fn(fn_kind
),
2940 ForeignItemKind
::TyAlias(ty_alias_kind
) => ItemKind
::TyAlias(ty_alias_kind
),
2941 ForeignItemKind
::MacCall(a
) => ItemKind
::MacCall(a
),
2946 impl TryFrom
<ItemKind
> for ForeignItemKind
{
2947 type Error
= ItemKind
;
2949 fn try_from(item_kind
: ItemKind
) -> Result
<ForeignItemKind
, ItemKind
> {
2950 Ok(match item_kind
{
2951 ItemKind
::Static(a
, b
, c
) => ForeignItemKind
::Static(a
, b
, c
),
2952 ItemKind
::Fn(fn_kind
) => ForeignItemKind
::Fn(fn_kind
),
2953 ItemKind
::TyAlias(ty_alias_kind
) => ForeignItemKind
::TyAlias(ty_alias_kind
),
2954 ItemKind
::MacCall(a
) => ForeignItemKind
::MacCall(a
),
2955 _
=> return Err(item_kind
),
2960 pub type ForeignItem
= Item
<ForeignItemKind
>;