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::source_map::{dummy_spanned, respan, Spanned};
29 use crate::token::{self, DelimToken};
30 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
32 use rustc_span::symbol::{kw, sym, Symbol};
33 use rustc_span::{Span, DUMMY_SP};
35 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
36 use rustc_data_structures::sync::Lrc;
37 use rustc_data_structures::thin_vec::ThinVec;
38 use rustc_index::vec::Idx;
39 use rustc_macros::HashStable_Generic;
40 use rustc_serialize::{self, Decoder, Encoder};
48 /// A "Label" is an identifier of some point in sources,
49 /// e.g. in the following code:
57 /// `'outer` is a label.
58 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable_Generic)]
63 impl fmt::Debug for Label {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 write!(f, "label({:?})", self.ident)
69 /// A "Lifetime" is an annotation of the scope in which variable
70 /// can be used, e.g. `'a` in `&'a i32`.
71 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
77 impl fmt::Debug for Lifetime {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 write!(f, "lifetime({}: {})", self.id, self)
83 impl fmt::Display for Lifetime {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 write!(f, "{}", self.ident.name)
89 /// A "Path" is essentially Rust's notion of a name.
91 /// It's represented as a sequence of identifiers,
92 /// along with a bunch of supporting information.
94 /// E.g., `std::cmp::PartialEq`.
95 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
98 /// The segments in the path: the things separated by `::`.
99 /// Global paths begin with `kw::PathRoot`.
100 pub segments: Vec<PathSegment>,
103 impl PartialEq<Symbol> for Path {
104 fn eq(&self, symbol: &Symbol) -> bool {
105 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
109 impl<CTX> HashStable<CTX> for Path {
110 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
111 self.segments.len().hash_stable(hcx, hasher);
112 for segment in &self.segments {
113 segment.ident.name.hash_stable(hcx, hasher);
119 // Convert a span and an identifier to the corresponding
121 pub fn from_ident(ident: Ident) -> Path {
122 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
125 pub fn is_global(&self) -> bool {
126 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
130 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
132 /// E.g., `std`, `String` or `Box<T>`.
133 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
134 pub struct PathSegment {
135 /// The identifier portion of this path segment.
140 /// Type/lifetime parameters attached to this path. They come in
141 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
142 /// `None` means that no parameter list is supplied (`Path`),
143 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
144 /// but it can be empty (`Path<>`).
145 /// `P` is used as a size optimization for the common case with no parameters.
146 pub args: Option<P<GenericArgs>>,
150 pub fn from_ident(ident: Ident) -> Self {
151 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
153 pub fn path_root(span: Span) -> Self {
154 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
158 /// The arguments of a path segment.
160 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
161 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
162 pub enum GenericArgs {
163 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
164 AngleBracketed(AngleBracketedArgs),
165 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
166 Parenthesized(ParenthesizedArgs),
170 pub fn is_parenthesized(&self) -> bool {
172 Parenthesized(..) => true,
177 pub fn is_angle_bracketed(&self) -> bool {
179 AngleBracketed(..) => true,
184 pub fn span(&self) -> Span {
186 AngleBracketed(ref data) => data.span,
187 Parenthesized(ref data) => data.span,
192 /// Concrete argument in the sequence of generic args.
193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
194 pub enum GenericArg {
195 /// `'a` in `Foo<'a>`
197 /// `Bar` in `Foo<Bar>`
204 pub fn span(&self) -> Span {
206 GenericArg::Lifetime(lt) => lt.ident.span,
207 GenericArg::Type(ty) => ty.span,
208 GenericArg::Const(ct) => ct.value.span,
213 /// A path like `Foo<'a, T>`.
214 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
215 pub struct AngleBracketedArgs {
216 /// The overall span.
218 /// The arguments for this path segment.
219 pub args: Vec<GenericArg>,
220 /// Constraints on associated types, if any.
221 /// E.g., `Foo<A = Bar, B: Baz>`.
222 pub constraints: Vec<AssocTyConstraint>,
225 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
226 fn into(self) -> Option<P<GenericArgs>> {
227 Some(P(GenericArgs::AngleBracketed(self)))
231 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
232 fn into(self) -> Option<P<GenericArgs>> {
233 Some(P(GenericArgs::Parenthesized(self)))
237 /// A path like `Foo(A, B) -> C`.
238 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
239 pub struct ParenthesizedArgs {
244 pub inputs: Vec<P<Ty>>,
247 pub output: FunctionRetTy,
250 impl ParenthesizedArgs {
251 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
254 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
260 pub use rustc_session::node_id::NodeId;
262 /// `NodeId` used to represent the root of the crate.
263 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
265 /// When parsing and doing expansions, we initially give all AST nodes this AST
266 /// node value. Then later, in the renumber pass, we renumber them to have
267 /// small, positive ids.
268 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
270 /// A modifier on a bound, currently this is only used for `?Sized`, where the
271 /// modifier is `Maybe`. Negative bounds should also be handled here.
272 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
273 pub enum TraitBoundModifier {
278 /// The AST represents all type param bounds as types.
279 /// `typeck::collect::compute_bounds` matches these against
280 /// the "special" built-in traits (see `middle::lang_items`) and
281 /// detects `Copy`, `Send` and `Sync`.
282 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
283 pub enum GenericBound {
284 Trait(PolyTraitRef, TraitBoundModifier),
289 pub fn span(&self) -> Span {
291 &GenericBound::Trait(ref t, ..) => t.span,
292 &GenericBound::Outlives(ref l) => l.ident.span,
297 pub type GenericBounds = Vec<GenericBound>;
299 /// Specifies the enforced ordering for generic parameters. In the future,
300 /// if we wanted to relax this order, we could override `PartialEq` and
301 /// `PartialOrd`, to allow the kinds to be unordered.
302 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
303 pub enum ParamKindOrd {
309 impl fmt::Display for ParamKindOrd {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 ParamKindOrd::Lifetime => "lifetime".fmt(f),
313 ParamKindOrd::Type => "type".fmt(f),
314 ParamKindOrd::Const => "const".fmt(f),
319 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
320 pub enum GenericParamKind {
321 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
324 default: Option<P<Ty>>,
331 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
332 pub struct GenericParam {
336 pub bounds: GenericBounds,
337 pub is_placeholder: bool,
338 pub kind: GenericParamKind,
341 /// Represents lifetime, type and const parameters attached to a declaration of
342 /// a function, enum, trait, etc.
343 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
344 pub struct Generics {
345 pub params: Vec<GenericParam>,
346 pub where_clause: WhereClause,
350 impl Default for Generics {
351 /// Creates an instance of `Generics`.
352 fn default() -> Generics {
355 where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP },
361 /// A where-clause in a definition.
362 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
363 pub struct WhereClause {
364 pub predicates: Vec<WherePredicate>,
368 /// A single predicate in a where-clause.
369 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
370 pub enum WherePredicate {
371 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
372 BoundPredicate(WhereBoundPredicate),
373 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
374 RegionPredicate(WhereRegionPredicate),
375 /// An equality predicate (unsupported).
376 EqPredicate(WhereEqPredicate),
379 impl WherePredicate {
380 pub fn span(&self) -> Span {
382 &WherePredicate::BoundPredicate(ref p) => p.span,
383 &WherePredicate::RegionPredicate(ref p) => p.span,
384 &WherePredicate::EqPredicate(ref p) => p.span,
391 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
392 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
393 pub struct WhereBoundPredicate {
395 /// Any generics from a `for` binding.
396 pub bound_generic_params: Vec<GenericParam>,
397 /// The type being bounded.
398 pub bounded_ty: P<Ty>,
399 /// Trait and lifetime bounds (`Clone + Send + 'static`).
400 pub bounds: GenericBounds,
403 /// A lifetime predicate.
405 /// E.g., `'a: 'b + 'c`.
406 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
407 pub struct WhereRegionPredicate {
409 pub lifetime: Lifetime,
410 pub bounds: GenericBounds,
413 /// An equality predicate (unsupported).
416 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
417 pub struct WhereEqPredicate {
424 pub use rustc_session::parse::CrateConfig;
426 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
429 pub attrs: Vec<Attribute>,
433 /// Possible values inside of compile-time attribute lists.
435 /// E.g., the '..' in `#[name(..)]`.
436 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
437 pub enum NestedMetaItem {
438 /// A full MetaItem, for recursive meta items.
442 /// E.g., `"foo"`, `64`, `true`.
446 /// A spanned compile-time attribute item.
448 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
449 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
450 pub struct MetaItem {
452 pub kind: MetaItemKind,
456 /// A compile-time attribute item.
458 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
459 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
460 pub enum MetaItemKind {
463 /// E.g., `test` as in `#[test]`.
467 /// E.g., `derive(..)` as in `#[derive(..)]`.
468 List(Vec<NestedMetaItem>),
469 /// Name value meta item.
471 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
475 /// A block (`{ .. }`).
477 /// E.g., `{ .. }` as in `fn foo() { .. }`.
478 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
480 /// The statements in the block.
481 pub stmts: Vec<Stmt>,
483 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
484 pub rules: BlockCheckMode,
488 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
496 /// Attempt reparsing the pattern as a type.
497 /// This is intended for use by diagnostics.
498 pub fn to_ty(&self) -> Option<P<Ty>> {
499 let kind = match &self.kind {
500 // In a type expression `_` is an inference variable.
501 PatKind::Wild => TyKind::Infer,
502 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
503 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
504 TyKind::Path(None, Path::from_ident(*ident))
506 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
507 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
508 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
509 PatKind::Ref(pat, mutbl) => {
510 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
512 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
513 // when `P` can be reparsed as a type `T`.
514 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
515 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
516 // assuming `T0` to `Tn` are all syntactically valid as types.
517 PatKind::Tuple(pats) => {
518 let mut tys = Vec::with_capacity(pats.len());
519 // FIXME(#48994) - could just be collected into an Option<Vec>
521 tys.push(pat.to_ty()?);
528 Some(P(Ty { kind, id: self.id, span: self.span }))
531 /// Walk top-down and call `it` in each place where a pattern occurs
532 /// starting with the root pattern `walk` is called on. If `it` returns
533 /// false then we will descend no further but siblings will be processed.
534 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
540 // Walk into the pattern associated with `Ident` (if any).
541 PatKind::Ident(_, _, Some(p)) => p.walk(it),
543 // Walk into each field of struct.
544 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
546 // Sequence of patterns.
547 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
548 s.iter().for_each(|p| p.walk(it))
551 // Trivial wrappers over inner patterns.
552 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
554 // These patterns do not contain subpatterns, skip.
561 | PatKind::Mac(_) => {}
565 /// Is this a `..` pattern?
566 pub fn is_rest(&self) -> bool {
568 PatKind::Rest => true,
574 /// A single field in a struct pattern
576 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
577 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
578 /// except is_shorthand is true
579 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
580 pub struct FieldPat {
581 /// The identifier for the field
583 /// The pattern the field is destructured to
585 pub is_shorthand: bool,
589 pub is_placeholder: bool,
592 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
593 pub enum BindingMode {
598 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
600 Included(RangeSyntax),
604 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
605 pub enum RangeSyntax {
612 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
614 /// Represents a wildcard pattern (`_`).
617 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
618 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
619 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
620 /// during name resolution.
621 Ident(BindingMode, Ident, Option<P<Pat>>),
623 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
624 /// The `bool` is `true` in the presence of a `..`.
625 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
627 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
628 TupleStruct(Path, Vec<P<Pat>>),
630 /// An or-pattern `A | B | C`.
631 /// Invariant: `pats.len() >= 2`.
634 /// A possibly qualified path pattern.
635 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
636 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
637 /// only legally refer to associated constants.
638 Path(Option<QSelf>, Path),
640 /// A tuple pattern (`(a, b)`).
646 /// A reference pattern (e.g., `&mut (a, b)`).
647 Ref(P<Pat>, Mutability),
652 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
653 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
655 /// A slice pattern `[a, b, c]`.
658 /// A rest pattern `..`.
660 /// Syntactically it is valid anywhere.
662 /// Semantically however, it only has meaning immediately inside:
663 /// - a slice pattern: `[a, .., b]`,
664 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
665 /// - a tuple pattern: `(a, .., b)`,
666 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
668 /// In all of these cases, an additional restriction applies,
669 /// only one rest pattern may occur in the pattern sequences.
672 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
675 /// A macro pattern; pre-expansion.
692 pub enum Mutability {
698 /// Returns `MutMutable` only if both `self` and `other` are mutable.
699 pub fn and(self, other: Self) -> Self {
701 Mutability::Mut => other,
702 Mutability::Not => Mutability::Not,
706 pub fn invert(self) -> Self {
708 Mutability::Mut => Mutability::Not,
709 Mutability::Not => Mutability::Mut,
713 pub fn prefix_str(&self) -> &'static str {
715 Mutability::Mut => "mut ",
716 Mutability::Not => "",
721 /// The kind of borrow in an `AddrOf` expression,
722 /// e.g., `&place` or `&raw const place`.
723 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
724 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
725 pub enum BorrowKind {
726 /// A normal borrow, `&$expr` or `&mut $expr`.
727 /// The resulting type is either `&'a T` or `&'a mut T`
728 /// where `T = typeof($expr)` and `'a` is some lifetime.
730 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
731 /// The resulting type is either `*const T` or `*mut T`
732 /// where `T = typeof($expr)`.
736 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
738 /// The `+` operator (addition)
740 /// The `-` operator (subtraction)
742 /// The `*` operator (multiplication)
744 /// The `/` operator (division)
746 /// The `%` operator (modulus)
748 /// The `&&` operator (logical and)
750 /// The `||` operator (logical or)
752 /// The `^` operator (bitwise xor)
754 /// The `&` operator (bitwise and)
756 /// The `|` operator (bitwise or)
758 /// The `<<` operator (shift left)
760 /// The `>>` operator (shift right)
762 /// The `==` operator (equality)
764 /// The `<` operator (less than)
766 /// The `<=` operator (less than or equal to)
768 /// The `!=` operator (not equal to)
770 /// The `>=` operator (greater than or equal to)
772 /// The `>` operator (greater than)
777 pub fn to_string(&self) -> &'static str {
800 pub fn lazy(&self) -> bool {
802 BinOpKind::And | BinOpKind::Or => true,
807 pub fn is_shift(&self) -> bool {
809 BinOpKind::Shl | BinOpKind::Shr => true,
814 pub fn is_comparison(&self) -> bool {
816 // Note for developers: please keep this as is;
817 // we want compilation to fail if another variant is added.
819 Eq | Lt | Le | Ne | Gt | Ge => true,
820 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
824 /// Returns `true` if the binary operator takes its arguments by value
825 pub fn is_by_value(&self) -> bool {
826 !self.is_comparison()
830 pub type BinOp = Spanned<BinOpKind>;
834 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
835 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
837 /// The `*` operator for dereferencing
839 /// The `!` operator for logical inversion
841 /// The `-` operator for negation
846 /// Returns `true` if the unary operator takes its argument by value
847 pub fn is_by_value(u: UnOp) -> bool {
849 UnOp::Neg | UnOp::Not => true,
854 pub fn to_string(op: UnOp) -> &'static str {
864 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
872 pub fn add_trailing_semicolon(mut self) -> Self {
873 self.kind = match self.kind {
874 StmtKind::Expr(expr) => StmtKind::Semi(expr),
875 StmtKind::Mac(mac) => {
876 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
883 pub fn is_item(&self) -> bool {
885 StmtKind::Item(_) => true,
890 pub fn is_expr(&self) -> bool {
892 StmtKind::Expr(_) => true,
898 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
900 /// A local (let) binding.
902 /// An item definition.
904 /// Expr without trailing semi-colon.
906 /// Expr with a trailing semi-colon.
909 Mac(P<(Mac, MacStmtStyle, AttrVec)>),
912 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
913 pub enum MacStmtStyle {
914 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
915 /// `foo!(...);`, `foo![...];`).
917 /// The macro statement had braces (e.g., `foo! { ... }`).
919 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
920 /// `foo!(...)`). All of these will end up being converted into macro
925 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
926 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
930 pub ty: Option<P<Ty>>,
931 /// Initializer expression to set the value, if any.
932 pub init: Option<P<Expr>>,
937 /// An arm of a 'match'.
939 /// E.g., `0..=10 => { println!("match!") }` as in
943 /// 0..=10 => { println!("match!") },
944 /// _ => { println!("no match!") },
947 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
949 pub attrs: Vec<Attribute>,
950 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
952 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
953 pub guard: Option<P<Expr>>,
958 pub is_placeholder: bool,
961 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
962 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
969 pub is_shorthand: bool,
970 pub is_placeholder: bool,
973 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
974 pub enum BlockCheckMode {
976 Unsafe(UnsafeSource),
979 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
980 pub enum UnsafeSource {
985 /// A constant (expression) that's not an item or associated item,
986 /// but needs its own `DefId` for type-checking, const-eval, etc.
987 /// These are usually found nested inside types (e.g., array lengths)
988 /// or expressions (e.g., repeat counts), and also used to define
989 /// explicit discriminant values for enum variants.
990 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
991 pub struct AnonConst {
997 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1005 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1006 #[cfg(target_arch = "x86_64")]
1007 rustc_data_structures::static_assert_size!(Expr, 96);
1010 /// Returns `true` if this expression would be valid somewhere that expects a value;
1011 /// for example, an `if` condition.
1012 pub fn returns(&self) -> bool {
1013 if let ExprKind::Block(ref block, _) = self.kind {
1014 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1016 Some(&StmtKind::Expr(_)) => true,
1017 Some(&StmtKind::Semi(ref expr)) => {
1018 if let ExprKind::Ret(_) = expr.kind {
1019 // Last statement is explicit return.
1025 // This is a block that doesn't end in either an implicit or explicit return.
1029 // This is not a block, it is a value.
1034 pub fn to_bound(&self) -> Option<GenericBound> {
1036 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1037 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1038 TraitBoundModifier::None,
1044 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1045 pub fn to_ty(&self) -> Option<P<Ty>> {
1046 let kind = match &self.kind {
1047 // Trivial conversions.
1048 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1049 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1051 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1053 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1054 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1057 ExprKind::Repeat(expr, expr_len) => {
1058 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1061 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1063 ExprKind::Tup(exprs) => {
1064 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1068 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1069 // then type of result is trait object.
1070 // Othewise we don't assume the result type.
1071 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1072 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1073 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1079 // This expression doesn't look like a type syntactically.
1083 Some(P(Ty { kind, id: self.id, span: self.span }))
1086 pub fn precedence(&self) -> ExprPrecedence {
1088 ExprKind::Box(_) => ExprPrecedence::Box,
1089 ExprKind::Array(_) => ExprPrecedence::Array,
1090 ExprKind::Call(..) => ExprPrecedence::Call,
1091 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1092 ExprKind::Tup(_) => ExprPrecedence::Tup,
1093 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1094 ExprKind::Unary(..) => ExprPrecedence::Unary,
1095 ExprKind::Lit(_) => ExprPrecedence::Lit,
1096 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1097 ExprKind::Let(..) => ExprPrecedence::Let,
1098 ExprKind::If(..) => ExprPrecedence::If,
1099 ExprKind::While(..) => ExprPrecedence::While,
1100 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1101 ExprKind::Loop(..) => ExprPrecedence::Loop,
1102 ExprKind::Match(..) => ExprPrecedence::Match,
1103 ExprKind::Closure(..) => ExprPrecedence::Closure,
1104 ExprKind::Block(..) => ExprPrecedence::Block,
1105 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1106 ExprKind::Async(..) => ExprPrecedence::Async,
1107 ExprKind::Await(..) => ExprPrecedence::Await,
1108 ExprKind::Assign(..) => ExprPrecedence::Assign,
1109 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1110 ExprKind::Field(..) => ExprPrecedence::Field,
1111 ExprKind::Index(..) => ExprPrecedence::Index,
1112 ExprKind::Range(..) => ExprPrecedence::Range,
1113 ExprKind::Path(..) => ExprPrecedence::Path,
1114 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1115 ExprKind::Break(..) => ExprPrecedence::Break,
1116 ExprKind::Continue(..) => ExprPrecedence::Continue,
1117 ExprKind::Ret(..) => ExprPrecedence::Ret,
1118 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1119 ExprKind::Mac(..) => ExprPrecedence::Mac,
1120 ExprKind::Struct(..) => ExprPrecedence::Struct,
1121 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1122 ExprKind::Paren(..) => ExprPrecedence::Paren,
1123 ExprKind::Try(..) => ExprPrecedence::Try,
1124 ExprKind::Yield(..) => ExprPrecedence::Yield,
1125 ExprKind::Err => ExprPrecedence::Err,
1130 /// Limit types of a range (inclusive or exclusive)
1131 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1132 pub enum RangeLimits {
1133 /// Inclusive at the beginning, exclusive at the end
1135 /// Inclusive at the beginning and end
1139 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1141 /// A `box x` expression.
1143 /// An array (`[a, b, c, d]`)
1144 Array(Vec<P<Expr>>),
1147 /// The first field resolves to the function itself,
1148 /// and the second field is the list of arguments.
1149 /// This also represents calling the constructor of
1150 /// tuple-like ADTs such as tuple structs and enum variants.
1151 Call(P<Expr>, Vec<P<Expr>>),
1152 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1154 /// The `PathSegment` represents the method name and its generic arguments
1155 /// (within the angle brackets).
1156 /// The first element of the vector of an `Expr` is the expression that evaluates
1157 /// to the object on which the method is being called on (the receiver),
1158 /// and the remaining elements are the rest of the arguments.
1159 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1160 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1161 MethodCall(PathSegment, Vec<P<Expr>>),
1162 /// A tuple (e.g., `(a, b, c, d)`).
1164 /// A binary operation (e.g., `a + b`, `a * b`).
1165 Binary(BinOp, P<Expr>, P<Expr>),
1166 /// A unary operation (e.g., `!x`, `*x`).
1167 Unary(UnOp, P<Expr>),
1168 /// A literal (e.g., `1`, `"foo"`).
1170 /// A cast (e.g., `foo as f64`).
1171 Cast(P<Expr>, P<Ty>),
1172 /// A type ascription (e.g., `42: usize`).
1173 Type(P<Expr>, P<Ty>),
1174 /// A `let pat = expr` expression that is only semantically allowed in the condition
1175 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1176 Let(P<Pat>, P<Expr>),
1177 /// An `if` block, with an optional `else` block.
1179 /// `if expr { block } else { expr }`
1180 If(P<Expr>, P<Block>, Option<P<Expr>>),
1181 /// A while loop, with an optional label.
1183 /// `'label: while expr { block }`
1184 While(P<Expr>, P<Block>, Option<Label>),
1185 /// A `for` loop, with an optional label.
1187 /// `'label: for pat in expr { block }`
1189 /// This is desugared to a combination of `loop` and `match` expressions.
1190 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1191 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1193 /// `'label: loop { block }`
1194 Loop(P<Block>, Option<Label>),
1195 /// A `match` block.
1196 Match(P<Expr>, Vec<Arm>),
1197 /// A closure (e.g., `move |a, b, c| a + b + c`).
1199 /// The final span is the span of the argument block `|...|`.
1200 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1201 /// A block (`'label: { ... }`).
1202 Block(P<Block>, Option<Label>),
1203 /// An async block (`async move { ... }`).
1205 /// The `NodeId` is the `NodeId` for the closure that results from
1206 /// desugaring an async block, just like the NodeId field in the
1207 /// `IsAsync` enum. This is necessary in order to create a def for the
1208 /// closure which can be used as a parent of any child defs. Defs
1209 /// created during lowering cannot be made the parent of any other
1210 /// preexisting defs.
1211 Async(CaptureBy, NodeId, P<Block>),
1212 /// An await expression (`my_future.await`).
1215 /// A try block (`try { ... }`).
1218 /// An assignment (`a = foo()`).
1219 /// The `Span` argument is the span of the `=` token.
1220 Assign(P<Expr>, P<Expr>, Span),
1221 /// An assignment with an operator.
1224 AssignOp(BinOp, P<Expr>, P<Expr>),
1225 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1226 Field(P<Expr>, Ident),
1227 /// An indexing operation (e.g., `foo[2]`).
1228 Index(P<Expr>, P<Expr>),
1229 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1230 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1232 /// Variable reference, possibly containing `::` and/or type
1233 /// parameters (e.g., `foo::bar::<baz>`).
1235 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1236 Path(Option<QSelf>, Path),
1238 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1239 AddrOf(BorrowKind, Mutability, P<Expr>),
1240 /// A `break`, with an optional label to break, and an optional expression.
1241 Break(Option<Label>, Option<P<Expr>>),
1242 /// A `continue`, with an optional label.
1243 Continue(Option<Label>),
1244 /// A `return`, with an optional value to be returned.
1245 Ret(Option<P<Expr>>),
1247 /// Output of the `asm!()` macro.
1248 InlineAsm(P<InlineAsm>),
1250 /// A macro invocation; pre-expansion.
1253 /// A struct literal expression.
1255 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1256 /// where `base` is the `Option<Expr>`.
1257 Struct(Path, Vec<Field>, Option<P<Expr>>),
1259 /// An array literal constructed from one repeated element.
1261 /// E.g., `[1; 5]`. The expression is the element to be
1262 /// repeated; the constant is the number of times to repeat it.
1263 Repeat(P<Expr>, AnonConst),
1265 /// No-op: used solely so we can pretty-print faithfully.
1268 /// A try expression (`expr?`).
1271 /// A `yield`, with an optional value to be yielded.
1272 Yield(Option<P<Expr>>),
1274 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1278 /// The explicit `Self` type in a "qualified path". The actual
1279 /// path, including the trait and the associated item, is stored
1280 /// separately. `position` represents the index of the associated
1281 /// item qualified with this `Self` type.
1283 /// ```ignore (only-for-syntax-highlight)
1284 /// <Vec<T> as a::b::Trait>::AssociatedItem
1285 /// ^~~~~ ~~~~~~~~~~~~~~^
1288 /// <Vec<T>>::AssociatedItem
1292 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1296 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1297 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1298 /// 0`, this is an empty span.
1299 pub path_span: Span,
1300 pub position: usize,
1303 /// A capture clause used in closures and `async` blocks.
1304 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1305 pub enum CaptureBy {
1306 /// `move |x| y + x`.
1308 /// `move` keyword was not specified.
1312 /// The movability of a generator / closure literal:
1313 /// whether a generator contains self-references, causing it to be `!Unpin`.
1327 pub enum Movability {
1328 /// May contain self-references, `!Unpin`.
1330 /// Must not contain self-references, `Unpin`.
1334 /// Represents a macro invocation. The `path` indicates which macro
1335 /// is being invoked, and the `args` are arguments passed to it.
1336 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1339 pub args: P<MacArgs>,
1340 pub prior_type_ascription: Option<(Span, bool)>,
1344 pub fn span(&self) -> Span {
1345 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1349 /// Arguments passed to an attribute or a function-like macro.
1350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1352 /// No arguments - `#[attr]`.
1354 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1355 Delimited(DelimSpan, MacDelimiter, TokenStream),
1356 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1358 /// Span of the `=` token.
1360 /// Token stream of the "value".
1366 pub fn delim(&self) -> DelimToken {
1368 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1369 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1373 pub fn span(&self) -> Option<Span> {
1375 MacArgs::Empty => None,
1376 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1377 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1381 /// Tokens inside the delimiters or after `=`.
1382 /// Proc macros see these tokens, for example.
1383 pub fn inner_tokens(&self) -> TokenStream {
1385 MacArgs::Empty => TokenStream::default(),
1386 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1390 /// Tokens together with the delimiters or `=`.
1391 /// Use of this method generally means that something suboptimal or hacky is happening.
1392 pub fn outer_tokens(&self) -> TokenStream {
1394 MacArgs::Empty => TokenStream::default(),
1395 MacArgs::Delimited(dspan, delim, ref tokens) => {
1396 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1398 MacArgs::Eq(eq_span, ref tokens) => {
1399 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1404 /// Whether a macro with these arguments needs a semicolon
1405 /// when used as a standalone item or statement.
1406 pub fn need_semicolon(&self) -> bool {
1407 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1411 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1412 pub enum MacDelimiter {
1419 crate fn to_token(self) -> DelimToken {
1421 MacDelimiter::Parenthesis => DelimToken::Paren,
1422 MacDelimiter::Bracket => DelimToken::Bracket,
1423 MacDelimiter::Brace => DelimToken::Brace,
1427 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1429 token::Paren => Some(MacDelimiter::Parenthesis),
1430 token::Bracket => Some(MacDelimiter::Bracket),
1431 token::Brace => Some(MacDelimiter::Brace),
1432 token::NoDelim => None,
1437 /// Represents a macro definition.
1438 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1439 pub struct MacroDef {
1440 pub body: P<MacArgs>,
1441 /// `true` if macro was defined with `macro_rules`.
1445 // Clippy uses Hash and PartialEq
1446 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
1448 /// A regular string, like `"foo"`.
1450 /// A raw string, like `r##"foo"##`.
1452 /// The value is the number of `#` symbols used.
1457 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1459 /// The original literal token as written in source code.
1460 pub token: token::Lit,
1461 /// The "semantic" representation of the literal lowered from the original tokens.
1462 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1463 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1468 /// Same as `Lit`, but restricted to string literals.
1469 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1471 /// The original literal token as written in source code.
1472 pub style: StrStyle,
1474 pub suffix: Option<Symbol>,
1476 /// The unescaped "semantic" representation of the literal lowered from the original token.
1477 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1478 pub symbol_unescaped: Symbol,
1482 crate fn as_lit(&self) -> Lit {
1483 let token_kind = match self.style {
1484 StrStyle::Cooked => token::Str,
1485 StrStyle::Raw(n) => token::StrRaw(n),
1488 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1490 kind: LitKind::Str(self.symbol_unescaped, self.style),
1495 // Clippy uses Hash and PartialEq
1496 /// Type of the integer literal based on provided suffix.
1497 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1498 pub enum LitIntType {
1507 /// Type of the float literal based on provided suffix.
1508 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1509 pub enum LitFloatType {
1510 /// A float literal with a suffix (`1f32` or `1E10f32`).
1512 /// A float literal without a suffix (`1.0 or 1.0E10`).
1518 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1519 // Clippy uses Hash and PartialEq
1520 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1522 /// A string literal (`"foo"`).
1523 Str(Symbol, StrStyle),
1524 /// A byte string (`b"foo"`).
1525 ByteStr(Lrc<Vec<u8>>),
1526 /// A byte char (`b'f'`).
1528 /// A character literal (`'a'`).
1530 /// An integer literal (`1`).
1531 Int(u128, LitIntType),
1532 /// A float literal (`1f64` or `1E10f64`).
1533 Float(Symbol, LitFloatType),
1534 /// A boolean literal.
1536 /// Placeholder for a literal that wasn't well-formed in some way.
1541 /// Returns `true` if this literal is a string.
1542 pub fn is_str(&self) -> bool {
1544 LitKind::Str(..) => true,
1549 /// Returns `true` if this literal is byte literal string.
1550 pub fn is_bytestr(&self) -> bool {
1552 LitKind::ByteStr(_) => true,
1557 /// Returns `true` if this is a numeric literal.
1558 pub fn is_numeric(&self) -> bool {
1560 LitKind::Int(..) | LitKind::Float(..) => true,
1565 /// Returns `true` if this literal has no suffix.
1566 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1567 pub fn is_unsuffixed(&self) -> bool {
1571 /// Returns `true` if this literal has a suffix.
1572 pub fn is_suffixed(&self) -> bool {
1574 // suffixed variants
1575 LitKind::Int(_, LitIntType::Signed(..))
1576 | LitKind::Int(_, LitIntType::Unsigned(..))
1577 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1578 // unsuffixed variants
1580 | LitKind::ByteStr(..)
1583 | LitKind::Int(_, LitIntType::Unsuffixed)
1584 | LitKind::Float(_, LitFloatType::Unsuffixed)
1586 | LitKind::Err(..) => false,
1591 // N.B., If you change this, you'll probably want to change the corresponding
1592 // type structure in `middle/ty.rs` as well.
1593 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1596 pub mutbl: Mutability,
1599 /// Represents a function's signature in a trait declaration,
1600 /// trait implementation, or free function.
1601 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1603 pub header: FnHeader,
1604 pub decl: P<FnDecl>,
1607 /// Represents associated items.
1608 /// These include items in `impl` and `trait` definitions.
1609 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1610 pub struct AssocItem {
1611 pub attrs: Vec<Attribute>,
1614 pub vis: Visibility,
1617 pub defaultness: Defaultness,
1618 pub generics: Generics,
1619 pub kind: AssocItemKind,
1620 /// See `Item::tokens` for what this is.
1621 pub tokens: Option<TokenStream>,
1624 /// Represents various kinds of content within an `impl`.
1626 /// The term "provided" in the variants below refers to the item having a default
1627 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
1628 /// In an implementation, all items must be provided.
1629 /// The `Option`s below denote the bodies, where `Some(_)`
1630 /// means "provided" and conversely `None` means "required".
1631 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1632 pub enum AssocItemKind {
1633 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
1634 /// If `def` is parsed, then the associated constant is provided, and otherwise required.
1635 Const(P<Ty>, Option<P<Expr>>),
1637 /// An associated function.
1638 Fn(FnSig, Option<P<Block>>),
1640 /// An associated type.
1641 TyAlias(GenericBounds, Option<P<Ty>>),
1643 /// A macro expanding to an associated item.
1666 pub fn name_str(self) -> &'static str {
1668 FloatTy::F32 => "f32",
1669 FloatTy::F64 => "f64",
1673 pub fn name(self) -> Symbol {
1675 FloatTy::F32 => sym::f32,
1676 FloatTy::F64 => sym::f64,
1680 pub fn bit_width(self) -> usize {
1711 pub fn name_str(&self) -> &'static str {
1713 IntTy::Isize => "isize",
1715 IntTy::I16 => "i16",
1716 IntTy::I32 => "i32",
1717 IntTy::I64 => "i64",
1718 IntTy::I128 => "i128",
1722 pub fn name(&self) -> Symbol {
1724 IntTy::Isize => sym::isize,
1725 IntTy::I8 => sym::i8,
1726 IntTy::I16 => sym::i16,
1727 IntTy::I32 => sym::i32,
1728 IntTy::I64 => sym::i64,
1729 IntTy::I128 => sym::i128,
1733 pub fn val_to_string(&self, val: i128) -> String {
1734 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1735 // are parsed as `u128`, so we wouldn't want to print an extra negative
1737 format!("{}{}", val as u128, self.name_str())
1740 pub fn bit_width(&self) -> Option<usize> {
1742 IntTy::Isize => return None,
1751 pub fn normalize(&self, target_width: u32) -> Self {
1753 IntTy::Isize => match target_width {
1757 _ => unreachable!(),
1787 pub fn name_str(&self) -> &'static str {
1789 UintTy::Usize => "usize",
1791 UintTy::U16 => "u16",
1792 UintTy::U32 => "u32",
1793 UintTy::U64 => "u64",
1794 UintTy::U128 => "u128",
1798 pub fn name(&self) -> Symbol {
1800 UintTy::Usize => sym::usize,
1801 UintTy::U8 => sym::u8,
1802 UintTy::U16 => sym::u16,
1803 UintTy::U32 => sym::u32,
1804 UintTy::U64 => sym::u64,
1805 UintTy::U128 => sym::u128,
1809 pub fn val_to_string(&self, val: u128) -> String {
1810 format!("{}{}", val, self.name_str())
1813 pub fn bit_width(&self) -> Option<usize> {
1815 UintTy::Usize => return None,
1820 UintTy::U128 => 128,
1824 pub fn normalize(&self, target_width: u32) -> Self {
1826 UintTy::Usize => match target_width {
1830 _ => unreachable!(),
1837 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1838 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1839 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1840 pub struct AssocTyConstraint {
1843 pub kind: AssocTyConstraintKind,
1847 /// The kinds of an `AssocTyConstraint`.
1848 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1849 pub enum AssocTyConstraintKind {
1850 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1851 Equality { ty: P<Ty> },
1852 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1853 Bound { bounds: GenericBounds },
1856 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1863 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1864 pub struct BareFnTy {
1865 pub unsafety: Unsafety,
1867 pub generic_params: Vec<GenericParam>,
1868 pub decl: P<FnDecl>,
1871 /// The various kinds of type recognized by the compiler.
1872 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1874 /// A variable-length slice (`[T]`).
1876 /// A fixed length array (`[T; n]`).
1877 Array(P<Ty>, AnonConst),
1878 /// A raw pointer (`*const T` or `*mut T`).
1880 /// A reference (`&'a T` or `&'a mut T`).
1881 Rptr(Option<Lifetime>, MutTy),
1882 /// A bare function (e.g., `fn(usize) -> bool`).
1883 BareFn(P<BareFnTy>),
1884 /// The never type (`!`).
1886 /// A tuple (`(A, B, C, D,...)`).
1888 /// A path (`module::module::...::Type`), optionally
1889 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1891 /// Type parameters are stored in the `Path` itself.
1892 Path(Option<QSelf>, Path),
1893 /// A trait object type `Bound1 + Bound2 + Bound3`
1894 /// where `Bound` is a trait or a lifetime.
1895 TraitObject(GenericBounds, TraitObjectSyntax),
1896 /// An `impl Bound1 + Bound2 + Bound3` type
1897 /// where `Bound` is a trait or a lifetime.
1899 /// The `NodeId` exists to prevent lowering from having to
1900 /// generate `NodeId`s on the fly, which would complicate
1901 /// the generation of opaque `type Foo = impl Trait` items significantly.
1902 ImplTrait(NodeId, GenericBounds),
1903 /// No-op; kept solely so that we can pretty-print faithfully.
1907 /// This means the type should be inferred instead of it having been
1908 /// specified. This can appear anywhere in a type.
1910 /// Inferred type of a `self` or `&self` argument in a method.
1912 /// A macro in the type position.
1914 /// Placeholder for a kind that has failed to be defined.
1916 /// Placeholder for a `va_list`.
1921 pub fn is_implicit_self(&self) -> bool {
1922 if let TyKind::ImplicitSelf = *self { true } else { false }
1925 pub fn is_unit(&self) -> bool {
1926 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1929 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1930 /// in lowering to avoid making larger changes there and beyond.
1931 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1933 Self::ImplTrait(_, bounds) => Some(bounds),
1939 /// Syntax used to declare a trait object.
1940 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1941 pub enum TraitObjectSyntax {
1946 /// Inline assembly dialect.
1948 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1949 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1950 pub enum AsmDialect {
1955 /// Inline assembly.
1957 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1958 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1959 pub struct InlineAsmOutput {
1960 pub constraint: Symbol,
1963 pub is_indirect: bool,
1966 /// Inline assembly.
1968 /// E.g., `asm!("NOP");`.
1969 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1970 pub struct InlineAsm {
1972 pub asm_str_style: StrStyle,
1973 pub outputs: Vec<InlineAsmOutput>,
1974 pub inputs: Vec<(Symbol, P<Expr>)>,
1975 pub clobbers: Vec<Symbol>,
1977 pub alignstack: bool,
1978 pub dialect: AsmDialect,
1981 /// A parameter in a function header.
1983 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1984 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1991 pub is_placeholder: bool,
1994 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1996 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1997 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1999 /// `self`, `mut self`
2001 /// `&'lt self`, `&'lt mut self`
2002 Region(Option<Lifetime>, Mutability),
2003 /// `self: TYPE`, `mut self: TYPE`
2004 Explicit(P<Ty>, Mutability),
2007 pub type ExplicitSelf = Spanned<SelfKind>;
2010 /// Attempts to cast parameter to `ExplicitSelf`.
2011 pub fn to_self(&self) -> Option<ExplicitSelf> {
2012 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2013 if ident.name == kw::SelfLower {
2014 return match self.ty.kind {
2015 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2016 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2017 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2020 self.pat.span.to(self.ty.span),
2021 SelfKind::Explicit(self.ty.clone(), mutbl),
2029 /// Returns `true` if parameter is `self`.
2030 pub fn is_self(&self) -> bool {
2031 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2032 ident.name == kw::SelfLower
2038 /// Builds a `Param` object from `ExplicitSelf`.
2039 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2040 let span = eself.span.to(eself_ident.span);
2041 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2042 let param = |mutbl, ty| Param {
2046 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2052 is_placeholder: false,
2055 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2056 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2057 SelfKind::Region(lt, mutbl) => param(
2061 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2069 /// A signature (not the body) of a function declaration.
2071 /// E.g., `fn foo(bar: baz)`.
2073 /// Please note that it's different from `FnHeader` structure
2074 /// which contains metadata about function safety, asyncness, constness and ABI.
2075 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2077 pub inputs: Vec<Param>,
2078 pub output: FunctionRetTy,
2082 pub fn get_self(&self) -> Option<ExplicitSelf> {
2083 self.inputs.get(0).and_then(Param::to_self)
2085 pub fn has_self(&self) -> bool {
2086 self.inputs.get(0).map_or(false, Param::is_self)
2088 pub fn c_variadic(&self) -> bool {
2089 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2090 TyKind::CVarArgs => true,
2096 /// Is the trait definition an auto trait?
2097 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2122 pub fn prefix_str(&self) -> &'static str {
2124 Unsafety::Unsafe => "unsafe ",
2125 Unsafety::Normal => "",
2130 impl fmt::Display for Unsafety {
2131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2134 Unsafety::Normal => "normal",
2135 Unsafety::Unsafe => "unsafe",
2142 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2144 Async { closure_id: NodeId, return_impl_trait_id: NodeId },
2149 pub fn is_async(self) -> bool {
2150 if let IsAsync::Async { .. } = self { true } else { false }
2153 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2154 pub fn opt_return_id(self) -> Option<NodeId> {
2156 IsAsync::Async { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2157 IsAsync::NotAsync => None,
2162 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2163 pub enum Constness {
2168 /// Item defaultness.
2169 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2170 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2171 pub enum Defaultness {
2176 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2177 pub enum ImplPolarity {
2178 /// `impl Trait for Type`
2180 /// `impl !Trait for Type`
2184 impl fmt::Debug for ImplPolarity {
2185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2187 ImplPolarity::Positive => "positive".fmt(f),
2188 ImplPolarity::Negative => "negative".fmt(f),
2193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2194 pub enum FunctionRetTy {
2195 // FIXME(Centril): Rename to `FnRetTy` and in HIR also.
2196 /// Returns type is not specified.
2198 /// Functions default to `()` and closures default to inference.
2199 /// Span points to where return type would be inserted.
2201 /// Everything else.
2205 impl FunctionRetTy {
2206 pub fn span(&self) -> Span {
2208 FunctionRetTy::Default(span) => span,
2209 FunctionRetTy::Ty(ref ty) => ty.span,
2214 /// Module declaration.
2216 /// E.g., `mod foo;` or `mod foo { .. }`.
2217 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2219 /// A span from the first token past `{` to the last token until `}`.
2220 /// For `mod foo;`, the inner span ranges from the first token
2221 /// to the last token in the external file.
2223 pub items: Vec<P<Item>>,
2224 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2228 /// Foreign module declaration.
2230 /// E.g., `extern { .. }` or `extern C { .. }`.
2231 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2232 pub struct ForeignMod {
2233 pub abi: Option<StrLit>,
2234 pub items: Vec<ForeignItem>,
2237 /// Global inline assembly.
2239 /// Also known as "module-level assembly" or "file-scoped assembly".
2240 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2241 pub struct GlobalAsm {
2245 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2246 pub struct EnumDef {
2247 pub variants: Vec<Variant>,
2250 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2251 pub struct Variant {
2252 /// Attributes of the variant.
2253 pub attrs: Vec<Attribute>,
2254 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2258 /// The visibility of the variant. Syntactically accepted but not semantically.
2259 pub vis: Visibility,
2260 /// Name of the variant.
2263 /// Fields and constructor id of the variant.
2264 pub data: VariantData,
2265 /// Explicit discriminant, e.g., `Foo = 1`.
2266 pub disr_expr: Option<AnonConst>,
2267 /// Is a macro placeholder
2268 pub is_placeholder: bool,
2271 /// Part of `use` item to the right of its prefix.
2272 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2273 pub enum UseTreeKind {
2274 /// `use prefix` or `use prefix as rename`
2276 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2278 Simple(Option<Ident>, NodeId, NodeId),
2279 /// `use prefix::{...}`
2280 Nested(Vec<(UseTree, NodeId)>),
2285 /// A tree of paths sharing common prefixes.
2286 /// Used in `use` items both at top-level and inside of braces in import groups.
2287 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2288 pub struct UseTree {
2290 pub kind: UseTreeKind,
2295 pub fn ident(&self) -> Ident {
2297 UseTreeKind::Simple(Some(rename), ..) => rename,
2298 UseTreeKind::Simple(None, ..) => {
2299 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2301 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2306 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2307 /// are contained as statements within items. These two cases need to be
2308 /// distinguished for pretty-printing.
2309 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2310 pub enum AttrStyle {
2315 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2316 pub struct AttrId(pub usize);
2318 impl Idx for AttrId {
2319 fn new(idx: usize) -> Self {
2322 fn index(self) -> usize {
2327 impl rustc_serialize::Encodable for AttrId {
2328 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2333 impl rustc_serialize::Decodable for AttrId {
2334 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2335 d.read_nil().map(|_| crate::attr::mk_attr_id())
2339 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2340 pub struct AttrItem {
2345 /// A list of attributes.
2346 pub type AttrVec = ThinVec<Attribute>;
2348 /// Metadata associated with an item.
2349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2350 pub struct Attribute {
2353 /// Denotes if the attribute decorates the following construct (outer)
2354 /// or the construct this attribute is contained within (inner).
2355 pub style: AttrStyle,
2359 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2361 /// A normal attribute.
2364 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2365 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2366 /// variant (which is much less compact and thus more expensive).
2370 /// `TraitRef`s appear in impls.
2372 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2373 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2374 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2375 /// same as the impl's `NodeId`).
2376 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2377 pub struct TraitRef {
2382 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2383 pub struct PolyTraitRef {
2384 /// The `'a` in `<'a> Foo<&'a T>`.
2385 pub bound_generic_params: Vec<GenericParam>,
2387 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2388 pub trait_ref: TraitRef,
2394 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2396 bound_generic_params: generic_params,
2397 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2403 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2404 pub enum CrateSugar {
2405 /// Source is `pub(crate)`.
2408 /// Source is (just) `crate`.
2412 pub type Visibility = Spanned<VisibilityKind>;
2414 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2415 pub enum VisibilityKind {
2418 Restricted { path: P<Path>, id: NodeId },
2422 impl VisibilityKind {
2423 pub fn is_pub(&self) -> bool {
2424 if let VisibilityKind::Public = *self { true } else { false }
2428 /// Field of a struct.
2430 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2431 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2432 pub struct StructField {
2433 pub attrs: Vec<Attribute>,
2436 pub vis: Visibility,
2437 pub ident: Option<Ident>,
2440 pub is_placeholder: bool,
2443 /// Fields and constructor ids of enum variants and structs.
2444 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2445 pub enum VariantData {
2448 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2449 Struct(Vec<StructField>, bool),
2452 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2453 Tuple(Vec<StructField>, NodeId),
2456 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2461 /// Return the fields of this variant.
2462 pub fn fields(&self) -> &[StructField] {
2464 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2469 /// Return the `NodeId` of this variant's constructor, if it has one.
2470 pub fn ctor_id(&self) -> Option<NodeId> {
2472 VariantData::Struct(..) => None,
2473 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2480 /// The name might be a dummy name in case of anonymous items.
2481 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2482 pub struct Item<K = ItemKind> {
2483 pub attrs: Vec<Attribute>,
2486 pub vis: Visibility,
2491 /// Original tokens this item was parsed from. This isn't necessarily
2492 /// available for all items, although over time more and more items should
2493 /// have this be `Some`. Right now this is primarily used for procedural
2494 /// macros, notably custom attributes.
2496 /// Note that the tokens here do not include the outer attributes, but will
2497 /// include inner attributes.
2498 pub tokens: Option<TokenStream>,
2502 /// Return the span that encompasses the attributes.
2503 pub fn span_with_attributes(&self) -> Span {
2504 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2508 /// `extern` qualifier on a function item or function type.
2509 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2517 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2518 abi.map_or(Extern::Implicit, Extern::Explicit)
2522 /// A function header.
2524 /// All the information between the visibility and the name of the function is
2525 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2526 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2527 pub struct FnHeader {
2528 pub unsafety: Unsafety,
2529 pub asyncness: Spanned<IsAsync>,
2530 pub constness: Spanned<Constness>,
2534 impl Default for FnHeader {
2535 fn default() -> FnHeader {
2537 unsafety: Unsafety::Normal,
2538 asyncness: dummy_spanned(IsAsync::NotAsync),
2539 constness: dummy_spanned(Constness::NotConst),
2545 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2547 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2549 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2550 ExternCrate(Option<Name>),
2551 /// A use declaration item (`use`).
2553 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2555 /// A static item (`static`).
2557 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2558 Static(P<Ty>, Mutability, P<Expr>),
2559 /// A constant item (`const`).
2561 /// E.g., `const FOO: i32 = 42;`.
2562 Const(P<Ty>, P<Expr>),
2563 /// A function declaration (`fn`).
2565 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2566 Fn(FnSig, Generics, P<Block>),
2567 /// A module declaration (`mod`).
2569 /// E.g., `mod foo;` or `mod foo { .. }`.
2571 /// An external module (`extern`).
2573 /// E.g., `extern {}` or `extern "C" {}`.
2574 ForeignMod(ForeignMod),
2575 /// Module-level inline assembly (from `global_asm!()`).
2576 GlobalAsm(P<GlobalAsm>),
2577 /// A type alias (`type`).
2579 /// E.g., `type Foo = Bar<u8>;`.
2580 TyAlias(P<Ty>, Generics),
2581 /// An enum definition (`enum`).
2583 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2584 Enum(EnumDef, Generics),
2585 /// A struct definition (`struct`).
2587 /// E.g., `struct Foo<A> { x: A }`.
2588 Struct(VariantData, Generics),
2589 /// A union definition (`union`).
2591 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2592 Union(VariantData, Generics),
2593 /// A trait declaration (`trait`).
2595 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2596 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<AssocItem>),
2599 /// E.g., `trait Foo = Bar + Quux;`.
2600 TraitAlias(Generics, GenericBounds),
2601 /// An implementation.
2603 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2609 Option<TraitRef>, // (optional) trait this impl implements
2613 /// A macro invocation.
2615 /// E.g., `foo!(..)`.
2618 /// A macro definition.
2623 pub fn descriptive_variant(&self) -> &str {
2625 ItemKind::ExternCrate(..) => "extern crate",
2626 ItemKind::Use(..) => "use",
2627 ItemKind::Static(..) => "static item",
2628 ItemKind::Const(..) => "constant item",
2629 ItemKind::Fn(..) => "function",
2630 ItemKind::Mod(..) => "module",
2631 ItemKind::ForeignMod(..) => "foreign module",
2632 ItemKind::GlobalAsm(..) => "global asm",
2633 ItemKind::TyAlias(..) => "type alias",
2634 ItemKind::Enum(..) => "enum",
2635 ItemKind::Struct(..) => "struct",
2636 ItemKind::Union(..) => "union",
2637 ItemKind::Trait(..) => "trait",
2638 ItemKind::TraitAlias(..) => "trait alias",
2639 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2644 pub type ForeignItem = Item<ForeignItemKind>;
2646 /// An item within an `extern` block.
2647 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2648 pub enum ForeignItemKind {
2649 /// A foreign function.
2650 Fn(P<FnDecl>, Generics),
2651 /// A foreign static item (`static ext: u8`).
2652 Static(P<Ty>, Mutability),
2655 /// A macro invocation.
2659 impl ForeignItemKind {
2660 pub fn descriptive_variant(&self) -> &str {
2662 ForeignItemKind::Fn(..) => "foreign function",
2663 ForeignItemKind::Static(..) => "foreign static item",
2664 ForeignItemKind::Ty => "foreign type",
2665 ForeignItemKind::Macro(..) => "macro in foreign module",