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 that 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`], [`Mac`], [`MacDelimeter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`UnOpKind`], [`BinOp`], [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
25 pub use rustc_span::symbol::{Ident, Symbol as Name};
28 use crate::token::{self, DelimToken};
29 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
31 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
32 use rustc_data_structures::sync::Lrc;
33 use rustc_data_structures::thin_vec::ThinVec;
34 use rustc_index::vec::Idx;
35 use rustc_macros::HashStable_Generic;
36 use rustc_serialize::{self, Decoder, Encoder};
37 use rustc_span::source_map::{dummy_spanned, respan, Spanned};
38 use rustc_span::symbol::{kw, sym, Symbol};
39 use rustc_span::{Span, DUMMY_SP};
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, RustcEncodable, RustcDecodable, Copy, HashStable_Generic)]
62 impl fmt::Debug for Label {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "label({:?})", self.ident)
68 /// A "Lifetime" is an annotation of the scope in which variable
69 /// can be used, e.g. `'a` in `&'a i32`.
70 #[derive(Clone, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, Debug)]
97 /// The segments in the path: the things separated by `::`.
98 /// Global paths begin with `kw::PathRoot`.
99 pub segments: Vec<PathSegment>,
102 impl PartialEq<Symbol> for Path {
103 fn eq(&self, symbol: &Symbol) -> bool {
104 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
108 impl<CTX> HashStable<CTX> for Path {
109 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
110 self.segments.len().hash_stable(hcx, hasher);
111 for segment in &self.segments {
112 segment.ident.name.hash_stable(hcx, hasher);
118 // Convert a span and an identifier to the corresponding
120 pub fn from_ident(ident: Ident) -> Path {
121 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
124 pub fn is_global(&self) -> bool {
125 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
129 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
131 /// E.g., `std`, `String` or `Box<T>`.
132 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
133 pub struct PathSegment {
134 /// The identifier portion of this path segment.
139 /// Type/lifetime parameters attached to this path. They come in
140 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
141 /// `None` means that no parameter list is supplied (`Path`),
142 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
143 /// but it can be empty (`Path<>`).
144 /// `P` is used as a size optimization for the common case with no parameters.
145 pub args: Option<P<GenericArgs>>,
149 pub fn from_ident(ident: Ident) -> Self {
150 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
152 pub fn path_root(span: Span) -> Self {
153 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
157 /// The arguments of a path segment.
159 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
160 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
161 pub enum GenericArgs {
162 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
163 AngleBracketed(AngleBracketedArgs),
164 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
165 Parenthesized(ParenthesizedArgs),
169 pub fn is_parenthesized(&self) -> bool {
171 Parenthesized(..) => true,
176 pub fn is_angle_bracketed(&self) -> bool {
178 AngleBracketed(..) => true,
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, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, Debug, Default)]
214 pub struct AngleBracketedArgs {
215 /// The overall span.
217 /// The arguments for this path segment.
218 pub args: Vec<GenericArg>,
219 /// Constraints on associated types, if any.
220 /// E.g., `Foo<A = Bar, B: Baz>`.
221 pub constraints: Vec<AssocTyConstraint>,
224 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
225 fn into(self) -> Option<P<GenericArgs>> {
226 Some(P(GenericArgs::AngleBracketed(self)))
230 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
231 fn into(self) -> Option<P<GenericArgs>> {
232 Some(P(GenericArgs::Parenthesized(self)))
236 /// A path like `Foo(A, B) -> C`.
237 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
238 pub struct ParenthesizedArgs {
243 pub inputs: Vec<P<Ty>>,
246 pub output: FunctionRetTy,
249 impl ParenthesizedArgs {
250 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
253 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
259 pub use rustc_session::node_id::NodeId;
261 /// `NodeId` used to represent the root of the crate.
262 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
264 /// When parsing and doing expansions, we initially give all AST nodes this AST
265 /// node value. Then later, in the renumber pass, we renumber them to have
266 /// small, positive ids.
267 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
269 /// A modifier on a bound, currently this is only used for `?Sized`, where the
270 /// modifier is `Maybe`. Negative bounds should also be handled here.
271 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
272 pub enum TraitBoundModifier {
277 /// The AST represents all type param bounds as types.
278 /// `typeck::collect::compute_bounds` matches these against
279 /// the "special" built-in traits (see `middle::lang_items`) and
280 /// detects `Copy`, `Send` and `Sync`.
281 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
282 pub enum GenericBound {
283 Trait(PolyTraitRef, TraitBoundModifier),
288 pub fn span(&self) -> Span {
290 &GenericBound::Trait(ref t, ..) => t.span,
291 &GenericBound::Outlives(ref l) => l.ident.span,
296 pub type GenericBounds = Vec<GenericBound>;
298 /// Specifies the enforced ordering for generic parameters. In the future,
299 /// if we wanted to relax this order, we could override `PartialEq` and
300 /// `PartialOrd`, to allow the kinds to be unordered.
301 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
302 pub enum ParamKindOrd {
308 impl fmt::Display for ParamKindOrd {
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 ParamKindOrd::Lifetime => "lifetime".fmt(f),
312 ParamKindOrd::Type => "type".fmt(f),
313 ParamKindOrd::Const => "const".fmt(f),
318 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
319 pub enum GenericParamKind {
320 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
323 default: Option<P<Ty>>,
330 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
331 pub struct GenericParam {
335 pub bounds: GenericBounds,
336 pub is_placeholder: bool,
337 pub kind: GenericParamKind,
340 /// Represents lifetime, type and const parameters attached to a declaration of
341 /// a function, enum, trait, etc.
342 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
343 pub struct Generics {
344 pub params: Vec<GenericParam>,
345 pub where_clause: WhereClause,
349 impl Default for Generics {
350 /// Creates an instance of `Generics`.
351 fn default() -> Generics {
354 where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP },
360 /// A where-clause in a definition.
361 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
362 pub struct WhereClause {
363 pub predicates: Vec<WherePredicate>,
367 /// A single predicate in a where-clause.
368 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
369 pub enum WherePredicate {
370 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
371 BoundPredicate(WhereBoundPredicate),
372 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
373 RegionPredicate(WhereRegionPredicate),
374 /// An equality predicate (unsupported).
375 EqPredicate(WhereEqPredicate),
378 impl WherePredicate {
379 pub fn span(&self) -> Span {
381 &WherePredicate::BoundPredicate(ref p) => p.span,
382 &WherePredicate::RegionPredicate(ref p) => p.span,
383 &WherePredicate::EqPredicate(ref p) => p.span,
390 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
391 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
392 pub struct WhereBoundPredicate {
394 /// Any generics from a `for` binding.
395 pub bound_generic_params: Vec<GenericParam>,
396 /// The type being bounded.
397 pub bounded_ty: P<Ty>,
398 /// Trait and lifetime bounds (`Clone + Send + 'static`).
399 pub bounds: GenericBounds,
402 /// A lifetime predicate.
404 /// E.g., `'a: 'b + 'c`.
405 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
406 pub struct WhereRegionPredicate {
408 pub lifetime: Lifetime,
409 pub bounds: GenericBounds,
412 /// An equality predicate (unsupported).
415 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
416 pub struct WhereEqPredicate {
423 pub use rustc_session::parse::CrateConfig;
425 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
428 pub attrs: Vec<Attribute>,
432 /// Possible values inside of compile-time attribute lists.
434 /// E.g., the '..' in `#[name(..)]`.
435 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
436 pub enum NestedMetaItem {
437 /// A full MetaItem, for recursive meta items.
441 /// E.g., `"foo"`, `64`, `true`.
445 /// A spanned compile-time attribute item.
447 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
448 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
449 pub struct MetaItem {
451 pub kind: MetaItemKind,
455 /// A compile-time attribute item.
457 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
458 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
459 pub enum MetaItemKind {
462 /// E.g., `test` as in `#[test]`.
466 /// E.g., `derive(..)` as in `#[derive(..)]`.
467 List(Vec<NestedMetaItem>),
468 /// Name value meta item.
470 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
474 /// A block (`{ .. }`).
476 /// E.g., `{ .. }` as in `fn foo() { .. }`.
477 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
479 /// The statements in the block.
480 pub stmts: Vec<Stmt>,
482 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
483 pub rules: BlockCheckMode,
487 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
495 /// Attempt reparsing the pattern as a type.
496 /// This is intended for use by diagnostics.
497 pub fn to_ty(&self) -> Option<P<Ty>> {
498 let kind = match &self.kind {
499 // In a type expression `_` is an inference variable.
500 PatKind::Wild => TyKind::Infer,
501 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
502 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
503 TyKind::Path(None, Path::from_ident(*ident))
505 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
506 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
507 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
508 PatKind::Ref(pat, mutbl) => {
509 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
511 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
512 // when `P` can be reparsed as a type `T`.
513 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
514 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
515 // assuming `T0` to `Tn` are all syntactically valid as types.
516 PatKind::Tuple(pats) => {
517 let mut tys = Vec::with_capacity(pats.len());
518 // FIXME(#48994) - could just be collected into an Option<Vec>
520 tys.push(pat.to_ty()?);
527 Some(P(Ty { kind, id: self.id, span: self.span }))
530 /// Walk top-down and call `it` in each place where a pattern occurs
531 /// starting with the root pattern `walk` is called on. If `it` returns
532 /// false then we will descend no further but siblings will be processed.
533 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
539 // Walk into the pattern associated with `Ident` (if any).
540 PatKind::Ident(_, _, Some(p)) => p.walk(it),
542 // Walk into each field of struct.
543 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
545 // Sequence of patterns.
546 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
547 s.iter().for_each(|p| p.walk(it))
550 // Trivial wrappers over inner patterns.
551 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
553 // These patterns do not contain subpatterns, skip.
560 | PatKind::Mac(_) => {}
564 /// Is this a `..` pattern?
565 pub fn is_rest(&self) -> bool {
567 PatKind::Rest => true,
573 /// A single field in a struct pattern
575 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
576 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
577 /// except is_shorthand is true
578 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
579 pub struct FieldPat {
580 /// The identifier for the field
582 /// The pattern the field is destructured to
584 pub is_shorthand: bool,
588 pub is_placeholder: bool,
591 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
592 pub enum BindingMode {
597 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
599 Included(RangeSyntax),
603 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
604 pub enum RangeSyntax {
611 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
613 /// Represents a wildcard pattern (`_`).
616 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
617 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
618 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
619 /// during name resolution.
620 Ident(BindingMode, Ident, Option<P<Pat>>),
622 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
623 /// The `bool` is `true` in the presence of a `..`.
624 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
626 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
627 TupleStruct(Path, Vec<P<Pat>>),
629 /// An or-pattern `A | B | C`.
630 /// Invariant: `pats.len() >= 2`.
633 /// A possibly qualified path pattern.
634 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
635 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
636 /// only legally refer to associated constants.
637 Path(Option<QSelf>, Path),
639 /// A tuple pattern (`(a, b)`).
645 /// A reference pattern (e.g., `&mut (a, b)`).
646 Ref(P<Pat>, Mutability),
651 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
652 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
654 /// A slice pattern `[a, b, c]`.
657 /// A rest pattern `..`.
659 /// Syntactically it is valid anywhere.
661 /// Semantically however, it only has meaning immediately inside:
662 /// - a slice pattern: `[a, .., b]`,
663 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
664 /// - a tuple pattern: `(a, .., b)`,
665 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
667 /// In all of these cases, an additional restriction applies,
668 /// only one rest pattern may occur in the pattern sequences.
671 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
674 /// A macro pattern; pre-expansion.
691 pub enum Mutability {
697 /// Returns `MutMutable` only if both `self` and `other` are mutable.
698 pub fn and(self, other: Self) -> Self {
700 Mutability::Mut => other,
701 Mutability::Not => Mutability::Not,
705 pub fn invert(self) -> Self {
707 Mutability::Mut => Mutability::Not,
708 Mutability::Not => Mutability::Mut,
712 pub fn prefix_str(&self) -> &'static str {
714 Mutability::Mut => "mut ",
715 Mutability::Not => "",
720 /// The kind of borrow in an `AddrOf` expression,
721 /// e.g., `&place` or `&raw const place`.
722 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
723 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
724 pub enum BorrowKind {
725 /// A normal borrow, `&$expr` or `&mut $expr`.
726 /// The resulting type is either `&'a T` or `&'a mut T`
727 /// where `T = typeof($expr)` and `'a` is some lifetime.
729 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
730 /// The resulting type is either `*const T` or `*mut T`
731 /// where `T = typeof($expr)`.
735 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
737 /// The `+` operator (addition)
739 /// The `-` operator (subtraction)
741 /// The `*` operator (multiplication)
743 /// The `/` operator (division)
745 /// The `%` operator (modulus)
747 /// The `&&` operator (logical and)
749 /// The `||` operator (logical or)
751 /// The `^` operator (bitwise xor)
753 /// The `&` operator (bitwise and)
755 /// The `|` operator (bitwise or)
757 /// The `<<` operator (shift left)
759 /// The `>>` operator (shift right)
761 /// The `==` operator (equality)
763 /// The `<` operator (less than)
765 /// The `<=` operator (less than or equal to)
767 /// The `!=` operator (not equal to)
769 /// The `>=` operator (greater than or equal to)
771 /// The `>` operator (greater than)
776 pub fn to_string(&self) -> &'static str {
799 pub fn lazy(&self) -> bool {
801 BinOpKind::And | BinOpKind::Or => true,
806 pub fn is_shift(&self) -> bool {
808 BinOpKind::Shl | BinOpKind::Shr => true,
813 pub fn is_comparison(&self) -> bool {
815 // Note for developers: please keep this as is;
816 // we want compilation to fail if another variant is added.
818 Eq | Lt | Le | Ne | Gt | Ge => true,
819 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
823 /// Returns `true` if the binary operator takes its arguments by value
824 pub fn is_by_value(&self) -> bool {
825 !self.is_comparison()
829 pub type BinOp = Spanned<BinOpKind>;
833 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
834 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
836 /// The `*` operator for dereferencing
838 /// The `!` operator for logical inversion
840 /// The `-` operator for negation
845 /// Returns `true` if the unary operator takes its argument by value
846 pub fn is_by_value(u: UnOp) -> bool {
848 UnOp::Neg | UnOp::Not => true,
853 pub fn to_string(op: UnOp) -> &'static str {
863 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
871 pub fn add_trailing_semicolon(mut self) -> Self {
872 self.kind = match self.kind {
873 StmtKind::Expr(expr) => StmtKind::Semi(expr),
874 StmtKind::Mac(mac) => {
875 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
882 pub fn is_item(&self) -> bool {
884 StmtKind::Item(_) => true,
889 pub fn is_expr(&self) -> bool {
891 StmtKind::Expr(_) => true,
897 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
899 /// A local (let) binding.
901 /// An item definition.
903 /// Expr without trailing semi-colon.
905 /// Expr with a trailing semi-colon.
908 Mac(P<(Mac, MacStmtStyle, AttrVec)>),
911 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
912 pub enum MacStmtStyle {
913 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
914 /// `foo!(...);`, `foo![...];`).
916 /// The macro statement had braces (e.g., `foo! { ... }`).
918 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
919 /// `foo!(...)`). All of these will end up being converted into macro
924 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
925 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
929 pub ty: Option<P<Ty>>,
930 /// Initializer expression to set the value, if any.
931 pub init: Option<P<Expr>>,
936 /// An arm of a 'match'.
938 /// E.g., `0..=10 => { println!("match!") }` as in
942 /// 0..=10 => { println!("match!") },
943 /// _ => { println!("no match!") },
946 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
948 pub attrs: Vec<Attribute>,
949 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
951 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
952 pub guard: Option<P<Expr>>,
957 pub is_placeholder: bool,
960 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
961 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
968 pub is_shorthand: bool,
969 pub is_placeholder: bool,
972 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
973 pub enum BlockCheckMode {
975 Unsafe(UnsafeSource),
978 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
979 pub enum UnsafeSource {
984 /// A constant (expression) that's not an item or associated item,
985 /// but needs its own `DefId` for type-checking, const-eval, etc.
986 /// These are usually found nested inside types (e.g., array lengths)
987 /// or expressions (e.g., repeat counts), and also used to define
988 /// explicit discriminant values for enum variants.
989 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
990 pub struct AnonConst {
996 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1004 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1005 #[cfg(target_arch = "x86_64")]
1006 rustc_data_structures::static_assert_size!(Expr, 96);
1009 /// Returns `true` if this expression would be valid somewhere that expects a value;
1010 /// for example, an `if` condition.
1011 pub fn returns(&self) -> bool {
1012 if let ExprKind::Block(ref block, _) = self.kind {
1013 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1015 Some(&StmtKind::Expr(_)) => true,
1016 Some(&StmtKind::Semi(ref expr)) => {
1017 if let ExprKind::Ret(_) = expr.kind {
1018 // Last statement is explicit return.
1024 // This is a block that doesn't end in either an implicit or explicit return.
1028 // This is not a block, it is a value.
1033 pub fn to_bound(&self) -> Option<GenericBound> {
1035 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1036 PolyTraitRef::new(Vec::new(), path.clone(), None, self.span),
1037 TraitBoundModifier::None,
1043 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1044 pub fn to_ty(&self) -> Option<P<Ty>> {
1045 let kind = match &self.kind {
1046 // Trivial conversions.
1047 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1048 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1050 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1052 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1053 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1056 ExprKind::Repeat(expr, expr_len) => {
1057 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1060 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1062 ExprKind::Tup(exprs) => {
1063 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1067 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1068 // then type of result is trait object.
1069 // Othewise we don't assume the result type.
1070 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1071 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1072 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1078 // This expression doesn't look like a type syntactically.
1082 Some(P(Ty { kind, id: self.id, span: self.span }))
1085 pub fn precedence(&self) -> ExprPrecedence {
1087 ExprKind::Box(_) => ExprPrecedence::Box,
1088 ExprKind::Array(_) => ExprPrecedence::Array,
1089 ExprKind::Call(..) => ExprPrecedence::Call,
1090 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1091 ExprKind::Tup(_) => ExprPrecedence::Tup,
1092 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1093 ExprKind::Unary(..) => ExprPrecedence::Unary,
1094 ExprKind::Lit(_) => ExprPrecedence::Lit,
1095 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1096 ExprKind::Let(..) => ExprPrecedence::Let,
1097 ExprKind::If(..) => ExprPrecedence::If,
1098 ExprKind::While(..) => ExprPrecedence::While,
1099 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1100 ExprKind::Loop(..) => ExprPrecedence::Loop,
1101 ExprKind::Match(..) => ExprPrecedence::Match,
1102 ExprKind::Closure(..) => ExprPrecedence::Closure,
1103 ExprKind::Block(..) => ExprPrecedence::Block,
1104 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1105 ExprKind::Async(..) => ExprPrecedence::Async,
1106 ExprKind::Await(..) => ExprPrecedence::Await,
1107 ExprKind::Assign(..) => ExprPrecedence::Assign,
1108 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1109 ExprKind::Field(..) => ExprPrecedence::Field,
1110 ExprKind::Index(..) => ExprPrecedence::Index,
1111 ExprKind::Range(..) => ExprPrecedence::Range,
1112 ExprKind::Path(..) => ExprPrecedence::Path,
1113 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1114 ExprKind::Break(..) => ExprPrecedence::Break,
1115 ExprKind::Continue(..) => ExprPrecedence::Continue,
1116 ExprKind::Ret(..) => ExprPrecedence::Ret,
1117 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1118 ExprKind::Mac(..) => ExprPrecedence::Mac,
1119 ExprKind::Struct(..) => ExprPrecedence::Struct,
1120 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1121 ExprKind::Paren(..) => ExprPrecedence::Paren,
1122 ExprKind::Try(..) => ExprPrecedence::Try,
1123 ExprKind::Yield(..) => ExprPrecedence::Yield,
1124 ExprKind::Err => ExprPrecedence::Err,
1129 /// Limit types of a range (inclusive or exclusive)
1130 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1131 pub enum RangeLimits {
1132 /// Inclusive at the beginning, exclusive at the end
1134 /// Inclusive at the beginning and end
1138 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1140 /// A `box x` expression.
1142 /// An array (`[a, b, c, d]`)
1143 Array(Vec<P<Expr>>),
1146 /// The first field resolves to the function itself,
1147 /// and the second field is the list of arguments.
1148 /// This also represents calling the constructor of
1149 /// tuple-like ADTs such as tuple structs and enum variants.
1150 Call(P<Expr>, Vec<P<Expr>>),
1151 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1153 /// The `PathSegment` represents the method name and its generic arguments
1154 /// (within the angle brackets).
1155 /// The first element of the vector of an `Expr` is the expression that evaluates
1156 /// to the object on which the method is being called on (the receiver),
1157 /// and the remaining elements are the rest of the arguments.
1158 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1159 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1160 MethodCall(PathSegment, Vec<P<Expr>>),
1161 /// A tuple (e.g., `(a, b, c, d)`).
1163 /// A binary operation (e.g., `a + b`, `a * b`).
1164 Binary(BinOp, P<Expr>, P<Expr>),
1165 /// A unary operation (e.g., `!x`, `*x`).
1166 Unary(UnOp, P<Expr>),
1167 /// A literal (e.g., `1`, `"foo"`).
1169 /// A cast (e.g., `foo as f64`).
1170 Cast(P<Expr>, P<Ty>),
1171 /// A type ascription (e.g., `42: usize`).
1172 Type(P<Expr>, P<Ty>),
1173 /// A `let pat = expr` expression that is only semantically allowed in the condition
1174 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1175 Let(P<Pat>, P<Expr>),
1176 /// An `if` block, with an optional `else` block.
1178 /// `if expr { block } else { expr }`
1179 If(P<Expr>, P<Block>, Option<P<Expr>>),
1180 /// A while loop, with an optional label.
1182 /// `'label: while expr { block }`
1183 While(P<Expr>, P<Block>, Option<Label>),
1184 /// A `for` loop, with an optional label.
1186 /// `'label: for pat in expr { block }`
1188 /// This is desugared to a combination of `loop` and `match` expressions.
1189 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1190 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1192 /// `'label: loop { block }`
1193 Loop(P<Block>, Option<Label>),
1194 /// A `match` block.
1195 Match(P<Expr>, Vec<Arm>),
1196 /// A closure (e.g., `move |a, b, c| a + b + c`).
1198 /// The final span is the span of the argument block `|...|`.
1199 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1200 /// A block (`'label: { ... }`).
1201 Block(P<Block>, Option<Label>),
1202 /// An async block (`async move { ... }`).
1204 /// The `NodeId` is the `NodeId` for the closure that results from
1205 /// desugaring an async block, just like the NodeId field in the
1206 /// `IsAsync` enum. This is necessary in order to create a def for the
1207 /// closure which can be used as a parent of any child defs. Defs
1208 /// created during lowering cannot be made the parent of any other
1209 /// preexisting defs.
1210 Async(CaptureBy, NodeId, P<Block>),
1211 /// An await expression (`my_future.await`).
1214 /// A try block (`try { ... }`).
1217 /// An assignment (`a = foo()`).
1218 /// The `Span` argument is the span of the `=` token.
1219 Assign(P<Expr>, P<Expr>, Span),
1220 /// An assignment with an operator.
1223 AssignOp(BinOp, P<Expr>, P<Expr>),
1224 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1225 Field(P<Expr>, Ident),
1226 /// An indexing operation (e.g., `foo[2]`).
1227 Index(P<Expr>, P<Expr>),
1228 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1229 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1231 /// Variable reference, possibly containing `::` and/or type
1232 /// parameters (e.g., `foo::bar::<baz>`).
1234 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1235 Path(Option<QSelf>, Path),
1237 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1238 AddrOf(BorrowKind, Mutability, P<Expr>),
1239 /// A `break`, with an optional label to break, and an optional expression.
1240 Break(Option<Label>, Option<P<Expr>>),
1241 /// A `continue`, with an optional label.
1242 Continue(Option<Label>),
1243 /// A `return`, with an optional value to be returned.
1244 Ret(Option<P<Expr>>),
1246 /// Output of the `asm!()` macro.
1247 InlineAsm(P<InlineAsm>),
1249 /// A macro invocation; pre-expansion.
1252 /// A struct literal expression.
1254 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1255 /// where `base` is the `Option<Expr>`.
1256 Struct(Path, Vec<Field>, Option<P<Expr>>),
1258 /// An array literal constructed from one repeated element.
1260 /// E.g., `[1; 5]`. The expression is the element to be
1261 /// repeated; the constant is the number of times to repeat it.
1262 Repeat(P<Expr>, AnonConst),
1264 /// No-op: used solely so we can pretty-print faithfully.
1267 /// A try expression (`expr?`).
1270 /// A `yield`, with an optional value to be yielded.
1271 Yield(Option<P<Expr>>),
1273 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1277 /// The explicit `Self` type in a "qualified path". The actual
1278 /// path, including the trait and the associated item, is stored
1279 /// separately. `position` represents the index of the associated
1280 /// item qualified with this `Self` type.
1282 /// ```ignore (only-for-syntax-highlight)
1283 /// <Vec<T> as a::b::Trait>::AssociatedItem
1284 /// ^~~~~ ~~~~~~~~~~~~~~^
1287 /// <Vec<T>>::AssociatedItem
1291 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1295 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1296 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1297 /// 0`, this is an empty span.
1298 pub path_span: Span,
1299 pub position: usize,
1302 /// A capture clause used in closures and `async` blocks.
1303 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1304 pub enum CaptureBy {
1305 /// `move |x| y + x`.
1307 /// `move` keyword was not specified.
1311 /// The movability of a generator / closure literal:
1312 /// whether a generator contains self-references, causing it to be `!Unpin`.
1326 pub enum Movability {
1327 /// May contain self-references, `!Unpin`.
1329 /// Must not contain self-references, `Unpin`.
1333 /// Represents a macro invocation. The `path` indicates which macro
1334 /// is being invoked, and the `args` are arguments passed to it.
1335 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1338 pub args: P<MacArgs>,
1339 pub prior_type_ascription: Option<(Span, bool)>,
1343 pub fn span(&self) -> Span {
1344 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1348 /// Arguments passed to an attribute or a function-like macro.
1349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1351 /// No arguments - `#[attr]`.
1353 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1354 Delimited(DelimSpan, MacDelimiter, TokenStream),
1355 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1357 /// Span of the `=` token.
1359 /// Token stream of the "value".
1365 pub fn delim(&self) -> DelimToken {
1367 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1368 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1372 pub fn span(&self) -> Option<Span> {
1374 MacArgs::Empty => None,
1375 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1376 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1380 /// Tokens inside the delimiters or after `=`.
1381 /// Proc macros see these tokens, for example.
1382 pub fn inner_tokens(&self) -> TokenStream {
1384 MacArgs::Empty => TokenStream::default(),
1385 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1389 /// Tokens together with the delimiters or `=`.
1390 /// Use of this method generally means that something suboptimal or hacky is happening.
1391 pub fn outer_tokens(&self) -> TokenStream {
1393 MacArgs::Empty => TokenStream::default(),
1394 MacArgs::Delimited(dspan, delim, ref tokens) => {
1395 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1397 MacArgs::Eq(eq_span, ref tokens) => {
1398 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1403 /// Whether a macro with these arguments needs a semicolon
1404 /// when used as a standalone item or statement.
1405 pub fn need_semicolon(&self) -> bool {
1406 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1410 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1411 pub enum MacDelimiter {
1418 crate fn to_token(self) -> DelimToken {
1420 MacDelimiter::Parenthesis => DelimToken::Paren,
1421 MacDelimiter::Bracket => DelimToken::Bracket,
1422 MacDelimiter::Brace => DelimToken::Brace,
1426 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1428 token::Paren => Some(MacDelimiter::Parenthesis),
1429 token::Bracket => Some(MacDelimiter::Bracket),
1430 token::Brace => Some(MacDelimiter::Brace),
1431 token::NoDelim => None,
1436 /// Represents a macro definition.
1437 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1438 pub struct MacroDef {
1439 pub body: P<MacArgs>,
1440 /// `true` if macro was defined with `macro_rules`.
1444 // Clippy uses Hash and PartialEq
1445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
1447 /// A regular string, like `"foo"`.
1449 /// A raw string, like `r##"foo"##`.
1451 /// The value is the number of `#` symbols used.
1456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1458 /// The original literal token as written in source code.
1459 pub token: token::Lit,
1460 /// The "semantic" representation of the literal lowered from the original tokens.
1461 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1462 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1467 /// Same as `Lit`, but restricted to string literals.
1468 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1470 /// The original literal token as written in source code.
1471 pub style: StrStyle,
1473 pub suffix: Option<Symbol>,
1475 /// The unescaped "semantic" representation of the literal lowered from the original token.
1476 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1477 pub symbol_unescaped: Symbol,
1481 crate fn as_lit(&self) -> Lit {
1482 let token_kind = match self.style {
1483 StrStyle::Cooked => token::Str,
1484 StrStyle::Raw(n) => token::StrRaw(n),
1487 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1489 kind: LitKind::Str(self.symbol_unescaped, self.style),
1494 // Clippy uses Hash and PartialEq
1495 /// Type of the integer literal based on provided suffix.
1496 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1497 pub enum LitIntType {
1506 /// Type of the float literal based on provided suffix.
1507 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1508 pub enum LitFloatType {
1509 /// A float literal with a suffix (`1f32` or `1E10f32`).
1511 /// A float literal without a suffix (`1.0 or 1.0E10`).
1517 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1518 // Clippy uses Hash and PartialEq
1519 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1521 /// A string literal (`"foo"`).
1522 Str(Symbol, StrStyle),
1523 /// A byte string (`b"foo"`).
1524 ByteStr(Lrc<Vec<u8>>),
1525 /// A byte char (`b'f'`).
1527 /// A character literal (`'a'`).
1529 /// An integer literal (`1`).
1530 Int(u128, LitIntType),
1531 /// A float literal (`1f64` or `1E10f64`).
1532 Float(Symbol, LitFloatType),
1533 /// A boolean literal.
1535 /// Placeholder for a literal that wasn't well-formed in some way.
1540 /// Returns `true` if this literal is a string.
1541 pub fn is_str(&self) -> bool {
1543 LitKind::Str(..) => true,
1548 /// Returns `true` if this literal is byte literal string.
1549 pub fn is_bytestr(&self) -> bool {
1551 LitKind::ByteStr(_) => true,
1556 /// Returns `true` if this is a numeric literal.
1557 pub fn is_numeric(&self) -> bool {
1559 LitKind::Int(..) | LitKind::Float(..) => true,
1564 /// Returns `true` if this literal has no suffix.
1565 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1566 pub fn is_unsuffixed(&self) -> bool {
1570 /// Returns `true` if this literal has a suffix.
1571 pub fn is_suffixed(&self) -> bool {
1573 // suffixed variants
1574 LitKind::Int(_, LitIntType::Signed(..))
1575 | LitKind::Int(_, LitIntType::Unsigned(..))
1576 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1577 // unsuffixed variants
1579 | LitKind::ByteStr(..)
1582 | LitKind::Int(_, LitIntType::Unsuffixed)
1583 | LitKind::Float(_, LitFloatType::Unsuffixed)
1585 | LitKind::Err(..) => false,
1590 // N.B., If you change this, you'll probably want to change the corresponding
1591 // type structure in `middle/ty.rs` as well.
1592 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1595 pub mutbl: Mutability,
1598 /// Represents a function's signature in a trait declaration,
1599 /// trait implementation, or free function.
1600 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1602 pub header: FnHeader,
1603 pub decl: P<FnDecl>,
1606 /// Represents associated items.
1607 /// These include items in `impl` and `trait` definitions.
1608 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1609 pub struct AssocItem {
1610 pub attrs: Vec<Attribute>,
1613 pub vis: Visibility,
1616 pub defaultness: Defaultness,
1617 pub generics: Generics,
1618 pub kind: AssocItemKind,
1619 /// See `Item::tokens` for what this is.
1620 pub tokens: Option<TokenStream>,
1623 /// Represents various kinds of content within an `impl`.
1625 /// The term "provided" in the variants below refers to the item having a default
1626 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
1627 /// In an implementation, all items must be provided.
1628 /// The `Option`s below denote the bodies, where `Some(_)`
1629 /// means "provided" and conversely `None` means "required".
1630 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1631 pub enum AssocItemKind {
1632 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
1633 /// If `def` is parsed, then the associated constant is provided, and otherwise required.
1634 Const(P<Ty>, Option<P<Expr>>),
1636 /// An associated function.
1637 Fn(FnSig, Option<P<Block>>),
1639 /// An associated type.
1640 TyAlias(GenericBounds, Option<P<Ty>>),
1642 /// A macro expanding to an associated item.
1665 pub fn name_str(self) -> &'static str {
1667 FloatTy::F32 => "f32",
1668 FloatTy::F64 => "f64",
1672 pub fn name(self) -> Symbol {
1674 FloatTy::F32 => sym::f32,
1675 FloatTy::F64 => sym::f64,
1679 pub fn bit_width(self) -> usize {
1710 pub fn name_str(&self) -> &'static str {
1712 IntTy::Isize => "isize",
1714 IntTy::I16 => "i16",
1715 IntTy::I32 => "i32",
1716 IntTy::I64 => "i64",
1717 IntTy::I128 => "i128",
1721 pub fn name(&self) -> Symbol {
1723 IntTy::Isize => sym::isize,
1724 IntTy::I8 => sym::i8,
1725 IntTy::I16 => sym::i16,
1726 IntTy::I32 => sym::i32,
1727 IntTy::I64 => sym::i64,
1728 IntTy::I128 => sym::i128,
1732 pub fn val_to_string(&self, val: i128) -> String {
1733 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1734 // are parsed as `u128`, so we wouldn't want to print an extra negative
1736 format!("{}{}", val as u128, self.name_str())
1739 pub fn bit_width(&self) -> Option<usize> {
1741 IntTy::Isize => return None,
1750 pub fn normalize(&self, target_width: u32) -> Self {
1752 IntTy::Isize => match target_width {
1756 _ => unreachable!(),
1786 pub fn name_str(&self) -> &'static str {
1788 UintTy::Usize => "usize",
1790 UintTy::U16 => "u16",
1791 UintTy::U32 => "u32",
1792 UintTy::U64 => "u64",
1793 UintTy::U128 => "u128",
1797 pub fn name(&self) -> Symbol {
1799 UintTy::Usize => sym::usize,
1800 UintTy::U8 => sym::u8,
1801 UintTy::U16 => sym::u16,
1802 UintTy::U32 => sym::u32,
1803 UintTy::U64 => sym::u64,
1804 UintTy::U128 => sym::u128,
1808 pub fn val_to_string(&self, val: u128) -> String {
1809 format!("{}{}", val, self.name_str())
1812 pub fn bit_width(&self) -> Option<usize> {
1814 UintTy::Usize => return None,
1819 UintTy::U128 => 128,
1823 pub fn normalize(&self, target_width: u32) -> Self {
1825 UintTy::Usize => match target_width {
1829 _ => unreachable!(),
1836 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1837 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1838 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1839 pub struct AssocTyConstraint {
1842 pub kind: AssocTyConstraintKind,
1846 /// The kinds of an `AssocTyConstraint`.
1847 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1848 pub enum AssocTyConstraintKind {
1849 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1850 Equality { ty: P<Ty> },
1851 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1852 Bound { bounds: GenericBounds },
1855 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1862 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1863 pub struct BareFnTy {
1864 pub unsafety: Unsafety,
1866 pub generic_params: Vec<GenericParam>,
1867 pub decl: P<FnDecl>,
1870 /// The various kinds of type recognized by the compiler.
1871 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1873 /// A variable-length slice (`[T]`).
1875 /// A fixed length array (`[T; n]`).
1876 Array(P<Ty>, AnonConst),
1877 /// A raw pointer (`*const T` or `*mut T`).
1879 /// A reference (`&'a T` or `&'a mut T`).
1880 Rptr(Option<Lifetime>, MutTy),
1881 /// A bare function (e.g., `fn(usize) -> bool`).
1882 BareFn(P<BareFnTy>),
1883 /// The never type (`!`).
1885 /// A tuple (`(A, B, C, D,...)`).
1887 /// A path (`module::module::...::Type`), optionally
1888 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1890 /// Type parameters are stored in the `Path` itself.
1891 Path(Option<QSelf>, Path),
1892 /// A trait object type `Bound1 + Bound2 + Bound3`
1893 /// where `Bound` is a trait or a lifetime.
1894 TraitObject(GenericBounds, TraitObjectSyntax),
1895 /// An `impl Bound1 + Bound2 + Bound3` type
1896 /// where `Bound` is a trait or a lifetime.
1898 /// The `NodeId` exists to prevent lowering from having to
1899 /// generate `NodeId`s on the fly, which would complicate
1900 /// the generation of opaque `type Foo = impl Trait` items significantly.
1901 ImplTrait(NodeId, GenericBounds),
1902 /// No-op; kept solely so that we can pretty-print faithfully.
1906 /// This means the type should be inferred instead of it having been
1907 /// specified. This can appear anywhere in a type.
1909 /// Inferred type of a `self` or `&self` argument in a method.
1911 /// A macro in the type position.
1913 /// Placeholder for a kind that has failed to be defined.
1915 /// Placeholder for a `va_list`.
1920 pub fn is_implicit_self(&self) -> bool {
1921 if let TyKind::ImplicitSelf = *self { true } else { false }
1924 pub fn is_unit(&self) -> bool {
1925 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1928 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1929 /// in lowering to avoid making larger changes there and beyond.
1930 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1932 Self::ImplTrait(_, bounds) => Some(bounds),
1938 /// Syntax used to declare a trait object.
1939 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1940 pub enum TraitObjectSyntax {
1945 /// Inline assembly dialect.
1947 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1948 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1949 pub enum AsmDialect {
1954 /// Inline assembly.
1956 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1957 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1958 pub struct InlineAsmOutput {
1959 pub constraint: Symbol,
1962 pub is_indirect: bool,
1965 /// Inline assembly.
1967 /// E.g., `asm!("NOP");`.
1968 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1969 pub struct InlineAsm {
1971 pub asm_str_style: StrStyle,
1972 pub outputs: Vec<InlineAsmOutput>,
1973 pub inputs: Vec<(Symbol, P<Expr>)>,
1974 pub clobbers: Vec<Symbol>,
1976 pub alignstack: bool,
1977 pub dialect: AsmDialect,
1980 /// A parameter in a function header.
1982 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1983 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1990 pub is_placeholder: bool,
1993 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1995 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1996 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1998 /// `self`, `mut self`
2000 /// `&'lt self`, `&'lt mut self`
2001 Region(Option<Lifetime>, Mutability),
2002 /// `self: TYPE`, `mut self: TYPE`
2003 Explicit(P<Ty>, Mutability),
2006 pub type ExplicitSelf = Spanned<SelfKind>;
2009 /// Attempts to cast parameter to `ExplicitSelf`.
2010 pub fn to_self(&self) -> Option<ExplicitSelf> {
2011 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2012 if ident.name == kw::SelfLower {
2013 return match self.ty.kind {
2014 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2015 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2016 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2019 self.pat.span.to(self.ty.span),
2020 SelfKind::Explicit(self.ty.clone(), mutbl),
2028 /// Returns `true` if parameter is `self`.
2029 pub fn is_self(&self) -> bool {
2030 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2031 ident.name == kw::SelfLower
2037 /// Builds a `Param` object from `ExplicitSelf`.
2038 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2039 let span = eself.span.to(eself_ident.span);
2040 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2041 let param = |mutbl, ty| Param {
2045 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2051 is_placeholder: false,
2054 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2055 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2056 SelfKind::Region(lt, mutbl) => param(
2060 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2068 /// A signature (not the body) of a function declaration.
2070 /// E.g., `fn foo(bar: baz)`.
2072 /// Please note that it's different from `FnHeader` structure
2073 /// which contains metadata about function safety, asyncness, constness and ABI.
2074 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2076 pub inputs: Vec<Param>,
2077 pub output: FunctionRetTy,
2081 pub fn get_self(&self) -> Option<ExplicitSelf> {
2082 self.inputs.get(0).and_then(Param::to_self)
2084 pub fn has_self(&self) -> bool {
2085 self.inputs.get(0).map_or(false, Param::is_self)
2087 pub fn c_variadic(&self) -> bool {
2088 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2089 TyKind::CVarArgs => true,
2095 /// Is the trait definition an auto trait?
2096 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2121 pub fn prefix_str(&self) -> &'static str {
2123 Unsafety::Unsafe => "unsafe ",
2124 Unsafety::Normal => "",
2129 impl fmt::Display for Unsafety {
2130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2133 Unsafety::Normal => "normal",
2134 Unsafety::Unsafe => "unsafe",
2141 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2143 Async { closure_id: NodeId, return_impl_trait_id: NodeId },
2148 pub fn is_async(self) -> bool {
2149 if let IsAsync::Async { .. } = self { true } else { false }
2152 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2153 pub fn opt_return_id(self) -> Option<NodeId> {
2155 IsAsync::Async { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2156 IsAsync::NotAsync => None,
2161 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2162 pub enum Constness {
2167 /// Item defaultness.
2168 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2169 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2170 pub enum Defaultness {
2175 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2176 pub enum ImplPolarity {
2177 /// `impl Trait for Type`
2179 /// `impl !Trait for Type`
2183 impl fmt::Debug for ImplPolarity {
2184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2186 ImplPolarity::Positive => "positive".fmt(f),
2187 ImplPolarity::Negative => "negative".fmt(f),
2192 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2193 pub enum FunctionRetTy {
2194 // FIXME(Centril): Rename to `FnRetTy` and in HIR also.
2195 /// Returns type is not specified.
2197 /// Functions default to `()` and closures default to inference.
2198 /// Span points to where return type would be inserted.
2200 /// Everything else.
2204 impl FunctionRetTy {
2205 pub fn span(&self) -> Span {
2207 FunctionRetTy::Default(span) => span,
2208 FunctionRetTy::Ty(ref ty) => ty.span,
2213 /// Module declaration.
2215 /// E.g., `mod foo;` or `mod foo { .. }`.
2216 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2218 /// A span from the first token past `{` to the last token until `}`.
2219 /// For `mod foo;`, the inner span ranges from the first token
2220 /// to the last token in the external file.
2222 pub items: Vec<P<Item>>,
2223 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2227 /// Foreign module declaration.
2229 /// E.g., `extern { .. }` or `extern C { .. }`.
2230 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2231 pub struct ForeignMod {
2232 pub abi: Option<StrLit>,
2233 pub items: Vec<ForeignItem>,
2236 /// Global inline assembly.
2238 /// Also known as "module-level assembly" or "file-scoped assembly".
2239 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2240 pub struct GlobalAsm {
2244 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2245 pub struct EnumDef {
2246 pub variants: Vec<Variant>,
2249 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2250 pub struct Variant {
2251 /// Attributes of the variant.
2252 pub attrs: Vec<Attribute>,
2253 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2257 /// The visibility of the variant. Syntactically accepted but not semantically.
2258 pub vis: Visibility,
2259 /// Name of the variant.
2262 /// Fields and constructor id of the variant.
2263 pub data: VariantData,
2264 /// Explicit discriminant, e.g., `Foo = 1`.
2265 pub disr_expr: Option<AnonConst>,
2266 /// Is a macro placeholder
2267 pub is_placeholder: bool,
2270 /// Part of `use` item to the right of its prefix.
2271 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2272 pub enum UseTreeKind {
2273 /// `use prefix` or `use prefix as rename`
2275 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2277 Simple(Option<Ident>, NodeId, NodeId),
2278 /// `use prefix::{...}`
2279 Nested(Vec<(UseTree, NodeId)>),
2284 /// A tree of paths sharing common prefixes.
2285 /// Used in `use` items both at top-level and inside of braces in import groups.
2286 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2287 pub struct UseTree {
2289 pub kind: UseTreeKind,
2294 pub fn ident(&self) -> Ident {
2296 UseTreeKind::Simple(Some(rename), ..) => rename,
2297 UseTreeKind::Simple(None, ..) => {
2298 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2300 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2305 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2306 /// are contained as statements within items. These two cases need to be
2307 /// distinguished for pretty-printing.
2308 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2309 pub enum AttrStyle {
2314 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2315 pub struct AttrId(pub usize);
2317 impl Idx for AttrId {
2318 fn new(idx: usize) -> Self {
2321 fn index(self) -> usize {
2326 impl rustc_serialize::Encodable for AttrId {
2327 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2332 impl rustc_serialize::Decodable for AttrId {
2333 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2334 d.read_nil().map(|_| crate::attr::mk_attr_id())
2338 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2339 pub struct AttrItem {
2344 /// A list of attributes.
2345 pub type AttrVec = ThinVec<Attribute>;
2347 /// Metadata associated with an item.
2348 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2349 pub struct Attribute {
2352 /// Denotes if the attribute decorates the following construct (outer)
2353 /// or the construct this attribute is contained within (inner).
2354 pub style: AttrStyle,
2358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2360 /// A normal attribute.
2363 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2364 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2365 /// variant (which is much less compact and thus more expensive).
2369 /// `TraitRef`s appear in impls.
2371 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2372 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2373 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2374 /// same as the impl's `NodeId`).
2375 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2376 pub struct TraitRef {
2380 /// The `const` modifier, if any, that appears before this trait.
2382 /// | | `constness` |
2383 /// |----------------|-----------------------------|
2384 /// | `Trait` | `None` |
2385 /// | `const Trait` | `Some(Constness::Const)` |
2386 /// | `?const Trait` | `Some(Constness::NotConst)` |
2387 pub constness: Option<Constness>,
2390 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2391 pub struct PolyTraitRef {
2392 /// The `'a` in `<'a> Foo<&'a T>`.
2393 pub bound_generic_params: Vec<GenericParam>,
2395 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2396 pub trait_ref: TraitRef,
2403 generic_params: Vec<GenericParam>,
2405 constness: Option<Constness>,
2409 bound_generic_params: generic_params,
2410 trait_ref: TraitRef { path, constness, ref_id: DUMMY_NODE_ID },
2416 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2417 pub enum CrateSugar {
2418 /// Source is `pub(crate)`.
2421 /// Source is (just) `crate`.
2425 pub type Visibility = Spanned<VisibilityKind>;
2427 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2428 pub enum VisibilityKind {
2431 Restricted { path: P<Path>, id: NodeId },
2435 impl VisibilityKind {
2436 pub fn is_pub(&self) -> bool {
2437 if let VisibilityKind::Public = *self { true } else { false }
2441 /// Field of a struct.
2443 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2444 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2445 pub struct StructField {
2446 pub attrs: Vec<Attribute>,
2449 pub vis: Visibility,
2450 pub ident: Option<Ident>,
2453 pub is_placeholder: bool,
2456 /// Fields and constructor ids of enum variants and structs.
2457 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2458 pub enum VariantData {
2461 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2462 Struct(Vec<StructField>, bool),
2465 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2466 Tuple(Vec<StructField>, NodeId),
2469 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2474 /// Return the fields of this variant.
2475 pub fn fields(&self) -> &[StructField] {
2477 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2482 /// Return the `NodeId` of this variant's constructor, if it has one.
2483 pub fn ctor_id(&self) -> Option<NodeId> {
2485 VariantData::Struct(..) => None,
2486 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2493 /// The name might be a dummy name in case of anonymous items.
2494 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2495 pub struct Item<K = ItemKind> {
2496 pub attrs: Vec<Attribute>,
2499 pub vis: Visibility,
2504 /// Original tokens this item was parsed from. This isn't necessarily
2505 /// available for all items, although over time more and more items should
2506 /// have this be `Some`. Right now this is primarily used for procedural
2507 /// macros, notably custom attributes.
2509 /// Note that the tokens here do not include the outer attributes, but will
2510 /// include inner attributes.
2511 pub tokens: Option<TokenStream>,
2515 /// Return the span that encompasses the attributes.
2516 pub fn span_with_attributes(&self) -> Span {
2517 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2521 /// `extern` qualifier on a function item or function type.
2522 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2530 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2531 abi.map_or(Extern::Implicit, Extern::Explicit)
2535 /// A function header.
2537 /// All the information between the visibility and the name of the function is
2538 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2539 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2540 pub struct FnHeader {
2541 pub unsafety: Unsafety,
2542 pub asyncness: Spanned<IsAsync>,
2543 pub constness: Spanned<Constness>,
2547 impl Default for FnHeader {
2548 fn default() -> FnHeader {
2550 unsafety: Unsafety::Normal,
2551 asyncness: dummy_spanned(IsAsync::NotAsync),
2552 constness: dummy_spanned(Constness::NotConst),
2558 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2560 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2562 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2563 ExternCrate(Option<Name>),
2564 /// A use declaration item (`use`).
2566 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2568 /// A static item (`static`).
2570 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2571 Static(P<Ty>, Mutability, P<Expr>),
2572 /// A constant item (`const`).
2574 /// E.g., `const FOO: i32 = 42;`.
2575 Const(P<Ty>, P<Expr>),
2576 /// A function declaration (`fn`).
2578 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2579 Fn(FnSig, Generics, P<Block>),
2580 /// A module declaration (`mod`).
2582 /// E.g., `mod foo;` or `mod foo { .. }`.
2584 /// An external module (`extern`).
2586 /// E.g., `extern {}` or `extern "C" {}`.
2587 ForeignMod(ForeignMod),
2588 /// Module-level inline assembly (from `global_asm!()`).
2589 GlobalAsm(P<GlobalAsm>),
2590 /// A type alias (`type`).
2592 /// E.g., `type Foo = Bar<u8>;`.
2593 TyAlias(P<Ty>, Generics),
2594 /// An enum definition (`enum`).
2596 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2597 Enum(EnumDef, Generics),
2598 /// A struct definition (`struct`).
2600 /// E.g., `struct Foo<A> { x: A }`.
2601 Struct(VariantData, Generics),
2602 /// A union definition (`union`).
2604 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2605 Union(VariantData, Generics),
2606 /// A trait declaration (`trait`).
2608 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2609 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<AssocItem>),
2612 /// E.g., `trait Foo = Bar + Quux;`.
2613 TraitAlias(Generics, GenericBounds),
2614 /// An implementation.
2616 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2622 Option<TraitRef>, // (optional) trait this impl implements
2626 /// A macro invocation.
2628 /// E.g., `foo!(..)`.
2631 /// A macro definition.
2636 pub fn descriptive_variant(&self) -> &str {
2638 ItemKind::ExternCrate(..) => "extern crate",
2639 ItemKind::Use(..) => "use",
2640 ItemKind::Static(..) => "static item",
2641 ItemKind::Const(..) => "constant item",
2642 ItemKind::Fn(..) => "function",
2643 ItemKind::Mod(..) => "module",
2644 ItemKind::ForeignMod(..) => "foreign module",
2645 ItemKind::GlobalAsm(..) => "global asm",
2646 ItemKind::TyAlias(..) => "type alias",
2647 ItemKind::Enum(..) => "enum",
2648 ItemKind::Struct(..) => "struct",
2649 ItemKind::Union(..) => "union",
2650 ItemKind::Trait(..) => "trait",
2651 ItemKind::TraitAlias(..) => "trait alias",
2652 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2657 pub type ForeignItem = Item<ForeignItemKind>;
2659 /// An item within an `extern` block.
2660 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2661 pub enum ForeignItemKind {
2662 /// A foreign function.
2663 Fn(P<FnDecl>, Generics),
2664 /// A foreign static item (`static ext: u8`).
2665 Static(P<Ty>, Mutability),
2668 /// A macro invocation.
2672 impl ForeignItemKind {
2673 pub fn descriptive_variant(&self) -> &str {
2675 ForeignItemKind::Fn(..) => "foreign function",
2676 ForeignItemKind::Static(..) => "foreign static item",
2677 ForeignItemKind::Ty => "foreign type",
2678 ForeignItemKind::Macro(..) => "macro in foreign module",