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 GenericArgs::*;
22 pub use UnsafeSource::*;
23 pub use crate::util::parser::ExprPrecedence;
25 pub use syntax_pos::symbol::{Ident, Symbol as Name};
28 use crate::source_map::{dummy_spanned, respan, Spanned};
29 use crate::token::{self, DelimToken};
30 use crate::tokenstream::{TokenStream, TokenTree, DelimSpan};
32 use syntax_pos::symbol::{kw, sym, Symbol};
33 use syntax_pos::{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_serialize::{self, Decoder, Encoder};
40 use rustc_macros::HashStable_Generic;
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 {
88 impl fmt::Display for Lifetime {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 write!(f, "{}", self.ident.name)
94 /// A "Path" is essentially Rust's notion of a name.
96 /// It's represented as a sequence of identifiers,
97 /// along with a bunch of supporting information.
99 /// E.g., `std::cmp::PartialEq`.
100 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
103 /// The segments in the path: the things separated by `::`.
104 /// Global paths begin with `kw::PathRoot`.
105 pub segments: Vec<PathSegment>,
108 impl PartialEq<Symbol> for Path {
109 fn eq(&self, symbol: &Symbol) -> bool {
110 self.segments.len() == 1 && {
111 self.segments[0].ident.name == *symbol
116 impl<CTX> HashStable<CTX> for Path {
117 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
118 self.segments.len().hash_stable(hcx, hasher);
119 for segment in &self.segments {
120 segment.ident.name.hash_stable(hcx, hasher);
126 // Convert a span and an identifier to the corresponding
128 pub fn from_ident(ident: Ident) -> Path {
130 segments: vec![PathSegment::from_ident(ident)],
135 pub fn is_global(&self) -> bool {
136 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
140 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
142 /// E.g., `std`, `String` or `Box<T>`.
143 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
144 pub struct PathSegment {
145 /// The identifier portion of this path segment.
150 /// Type/lifetime parameters attached to this path. They come in
151 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
152 /// `None` means that no parameter list is supplied (`Path`),
153 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
154 /// but it can be empty (`Path<>`).
155 /// `P` is used as a size optimization for the common case with no parameters.
156 pub args: Option<P<GenericArgs>>,
160 pub fn from_ident(ident: Ident) -> Self {
161 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
163 pub fn path_root(span: Span) -> Self {
164 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
168 /// The arguments of a path segment.
170 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
171 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
172 pub enum GenericArgs {
173 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
174 AngleBracketed(AngleBracketedArgs),
175 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
176 Parenthesized(ParenthesizedArgs),
180 pub fn is_parenthesized(&self) -> bool {
182 Parenthesized(..) => true,
187 pub fn is_angle_bracketed(&self) -> bool {
189 AngleBracketed(..) => true,
194 pub fn span(&self) -> Span {
196 AngleBracketed(ref data) => data.span,
197 Parenthesized(ref data) => data.span,
202 /// Concrete argument in the sequence of generic args.
203 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
204 pub enum GenericArg {
205 /// `'a` in `Foo<'a>`
207 /// `Bar` in `Foo<Bar>`
214 pub fn span(&self) -> Span {
216 GenericArg::Lifetime(lt) => lt.ident.span,
217 GenericArg::Type(ty) => ty.span,
218 GenericArg::Const(ct) => ct.value.span,
223 /// A path like `Foo<'a, T>`.
224 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
225 pub struct AngleBracketedArgs {
226 /// The overall span.
228 /// The arguments for this path segment.
229 pub args: Vec<GenericArg>,
230 /// Constraints on associated types, if any.
231 /// E.g., `Foo<A = Bar, B: Baz>`.
232 pub constraints: Vec<AssocTyConstraint>,
235 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
236 fn into(self) -> Option<P<GenericArgs>> {
237 Some(P(GenericArgs::AngleBracketed(self)))
241 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
242 fn into(self) -> Option<P<GenericArgs>> {
243 Some(P(GenericArgs::Parenthesized(self)))
247 /// A path like `Foo(A, B) -> C`.
248 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
249 pub struct ParenthesizedArgs {
254 pub inputs: Vec<P<Ty>>,
257 pub output: Option<P<Ty>>,
260 impl ParenthesizedArgs {
261 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
264 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
270 pub use rustc_session::node_id::NodeId;
272 /// `NodeId` used to represent the root of the crate.
273 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
275 /// When parsing and doing expansions, we initially give all AST nodes this AST
276 /// node value. Then later, in the renumber pass, we renumber them to have
277 /// small, positive ids.
278 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
280 /// A modifier on a bound, currently this is only used for `?Sized`, where the
281 /// modifier is `Maybe`. Negative bounds should also be handled here.
282 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
283 pub enum TraitBoundModifier {
288 /// The AST represents all type param bounds as types.
289 /// `typeck::collect::compute_bounds` matches these against
290 /// the "special" built-in traits (see `middle::lang_items`) and
291 /// detects `Copy`, `Send` and `Sync`.
292 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
293 pub enum GenericBound {
294 Trait(PolyTraitRef, TraitBoundModifier),
299 pub fn span(&self) -> Span {
301 &GenericBound::Trait(ref t, ..) => t.span,
302 &GenericBound::Outlives(ref l) => l.ident.span,
307 pub type GenericBounds = Vec<GenericBound>;
309 /// Specifies the enforced ordering for generic parameters. In the future,
310 /// if we wanted to relax this order, we could override `PartialEq` and
311 /// `PartialOrd`, to allow the kinds to be unordered.
312 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
313 pub enum ParamKindOrd {
319 impl fmt::Display for ParamKindOrd {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 ParamKindOrd::Lifetime => "lifetime".fmt(f),
323 ParamKindOrd::Type => "type".fmt(f),
324 ParamKindOrd::Const => "const".fmt(f),
329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
330 pub enum GenericParamKind {
331 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
333 Type { default: Option<P<Ty>> },
337 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
338 pub struct GenericParam {
341 pub attrs: ThinVec<Attribute>,
342 pub bounds: GenericBounds,
343 pub is_placeholder: bool,
344 pub kind: GenericParamKind,
347 /// Represents lifetime, type and const parameters attached to a declaration of
348 /// a function, enum, trait, etc.
349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
350 pub struct Generics {
351 pub params: Vec<GenericParam>,
352 pub where_clause: WhereClause,
356 impl Default for Generics {
357 /// Creates an instance of `Generics`.
358 fn default() -> Generics {
361 where_clause: WhereClause {
362 predicates: Vec::new(),
370 /// A where-clause in a definition.
371 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
372 pub struct WhereClause {
373 pub predicates: Vec<WherePredicate>,
377 /// A single predicate in a where-clause.
378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
379 pub enum WherePredicate {
380 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
381 BoundPredicate(WhereBoundPredicate),
382 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
383 RegionPredicate(WhereRegionPredicate),
384 /// An equality predicate (unsupported).
385 EqPredicate(WhereEqPredicate),
388 impl WherePredicate {
389 pub fn span(&self) -> Span {
391 &WherePredicate::BoundPredicate(ref p) => p.span,
392 &WherePredicate::RegionPredicate(ref p) => p.span,
393 &WherePredicate::EqPredicate(ref p) => p.span,
400 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
401 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
402 pub struct WhereBoundPredicate {
404 /// Any generics from a `for` binding.
405 pub bound_generic_params: Vec<GenericParam>,
406 /// The type being bounded.
407 pub bounded_ty: P<Ty>,
408 /// Trait and lifetime bounds (`Clone + Send + 'static`).
409 pub bounds: GenericBounds,
412 /// A lifetime predicate.
414 /// E.g., `'a: 'b + 'c`.
415 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
416 pub struct WhereRegionPredicate {
418 pub lifetime: Lifetime,
419 pub bounds: GenericBounds,
422 /// An equality predicate (unsupported).
425 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
426 pub struct WhereEqPredicate {
433 pub use rustc_session::parse::CrateConfig;
435 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
438 pub attrs: Vec<Attribute>,
442 /// Possible values inside of compile-time attribute lists.
444 /// E.g., the '..' in `#[name(..)]`.
445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
446 pub enum NestedMetaItem {
447 /// A full MetaItem, for recursive meta items.
451 /// E.g., `"foo"`, `64`, `true`.
455 /// A spanned compile-time attribute item.
457 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
458 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
459 pub struct MetaItem {
461 pub kind: MetaItemKind,
465 /// A compile-time attribute item.
467 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
468 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
469 pub enum MetaItemKind {
472 /// E.g., `test` as in `#[test]`.
476 /// E.g., `derive(..)` as in `#[derive(..)]`.
477 List(Vec<NestedMetaItem>),
478 /// Name value meta item.
480 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
484 /// A block (`{ .. }`).
486 /// E.g., `{ .. }` as in `fn foo() { .. }`.
487 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
489 /// The statements in the block.
490 pub stmts: Vec<Stmt>,
492 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
493 pub rules: BlockCheckMode,
497 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
505 /// Attempt reparsing the pattern as a type.
506 /// This is intended for use by diagnostics.
507 pub fn to_ty(&self) -> Option<P<Ty>> {
508 let kind = match &self.kind {
509 // In a type expression `_` is an inference variable.
510 PatKind::Wild => TyKind::Infer,
511 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
512 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
513 TyKind::Path(None, Path::from_ident(*ident))
515 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
516 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
517 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
518 PatKind::Ref(pat, mutbl) => pat
520 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
521 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
522 // when `P` can be reparsed as a type `T`.
523 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
524 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
525 // assuming `T0` to `Tn` are all syntactically valid as types.
526 PatKind::Tuple(pats) => {
527 let mut tys = Vec::with_capacity(pats.len());
528 // FIXME(#48994) - could just be collected into an Option<Vec>
530 tys.push(pat.to_ty()?);
544 /// Walk top-down and call `it` in each place where a pattern occurs
545 /// starting with the root pattern `walk` is called on. If `it` returns
546 /// false then we will descend no further but siblings will be processed.
547 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
553 // Walk into the pattern associated with `Ident` (if any).
554 PatKind::Ident(_, _, Some(p)) => p.walk(it),
556 // Walk into each field of struct.
557 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
559 // Sequence of patterns.
560 PatKind::TupleStruct(_, s)
563 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
565 // Trivial wrappers over inner patterns.
568 | PatKind::Paren(s) => s.walk(it),
570 // These patterns do not contain subpatterns, skip.
577 | PatKind::Mac(_) => {},
581 /// Is this a `..` pattern?
582 pub fn is_rest(&self) -> bool {
584 PatKind::Rest => true,
590 /// A single field in a struct pattern
592 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
593 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
594 /// except is_shorthand is true
595 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
596 pub struct FieldPat {
597 /// The identifier for the field
599 /// The pattern the field is destructured to
601 pub is_shorthand: bool,
602 pub attrs: ThinVec<Attribute>,
605 pub is_placeholder: bool,
608 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
609 pub enum BindingMode {
614 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
616 Included(RangeSyntax),
620 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
621 pub enum RangeSyntax {
628 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
630 /// Represents a wildcard pattern (`_`).
633 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
634 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
635 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
636 /// during name resolution.
637 Ident(BindingMode, Ident, Option<P<Pat>>),
639 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
640 /// The `bool` is `true` in the presence of a `..`.
641 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
643 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
644 TupleStruct(Path, Vec<P<Pat>>),
646 /// An or-pattern `A | B | C`.
647 /// Invariant: `pats.len() >= 2`.
650 /// A possibly qualified path pattern.
651 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
652 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
653 /// only legally refer to associated constants.
654 Path(Option<QSelf>, Path),
656 /// A tuple pattern (`(a, b)`).
662 /// A reference pattern (e.g., `&mut (a, b)`).
663 Ref(P<Pat>, Mutability),
668 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
669 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
671 /// A slice pattern `[a, b, c]`.
674 /// A rest pattern `..`.
676 /// Syntactically it is valid anywhere.
678 /// Semantically however, it only has meaning immediately inside:
679 /// - a slice pattern: `[a, .., b]`,
680 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
681 /// - a tuple pattern: `(a, .., b)`,
682 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
684 /// In all of these cases, an additional restriction applies,
685 /// only one rest pattern may occur in the pattern sequences.
688 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
691 /// A macro pattern; pre-expansion.
695 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
696 RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
697 pub enum Mutability {
703 /// Returns `MutMutable` only if both `self` and `other` are mutable.
704 pub fn and(self, other: Self) -> Self {
706 Mutability::Mutable => other,
707 Mutability::Immutable => Mutability::Immutable,
711 pub fn invert(self) -> Self {
713 Mutability::Mutable => Mutability::Immutable,
714 Mutability::Immutable => Mutability::Mutable,
718 pub fn prefix_str(&self) -> &'static str {
720 Mutability::Mutable => "mut ",
721 Mutability::Immutable => "",
726 /// The kind of borrow in an `AddrOf` expression,
727 /// e.g., `&place` or `&raw const place`.
728 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
729 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
730 pub enum BorrowKind {
731 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
732 /// The resulting type is either `*const T` or `*mut T`
733 /// where `T = typeof($expr)`.
735 /// A normal borrow, `&$expr` or `&mut $expr`.
736 /// The resulting type is either `&'a T` or `&'a mut T`
737 /// where `T = typeof($expr)` and `'a` is some lifetime.
741 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
743 /// The `+` operator (addition)
745 /// The `-` operator (subtraction)
747 /// The `*` operator (multiplication)
749 /// The `/` operator (division)
751 /// The `%` operator (modulus)
753 /// The `&&` operator (logical and)
755 /// The `||` operator (logical or)
757 /// The `^` operator (bitwise xor)
759 /// The `&` operator (bitwise and)
761 /// The `|` operator (bitwise or)
763 /// The `<<` operator (shift left)
765 /// The `>>` operator (shift right)
767 /// The `==` operator (equality)
769 /// The `<` operator (less than)
771 /// The `<=` operator (less than or equal to)
773 /// The `!=` operator (not equal to)
775 /// The `>=` operator (greater than or equal to)
777 /// The `>` operator (greater than)
782 pub fn to_string(&self) -> &'static str {
805 pub fn lazy(&self) -> bool {
807 BinOpKind::And | BinOpKind::Or => true,
812 pub fn is_shift(&self) -> bool {
814 BinOpKind::Shl | BinOpKind::Shr => true,
819 pub fn is_comparison(&self) -> bool {
821 // Note for developers: please keep this as is;
822 // we want compilation to fail if another variant is added.
824 Eq | Lt | Le | Ne | Gt | Ge => true,
825 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
829 /// Returns `true` if the binary operator takes its arguments by value
830 pub fn is_by_value(&self) -> bool {
831 !self.is_comparison()
835 pub type BinOp = Spanned<BinOpKind>;
839 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
840 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
842 /// The `*` operator for dereferencing
844 /// The `!` operator for logical inversion
846 /// The `-` operator for negation
851 /// Returns `true` if the unary operator takes its argument by value
852 pub fn is_by_value(u: UnOp) -> bool {
854 UnOp::Neg | UnOp::Not => true,
859 pub fn to_string(op: UnOp) -> &'static str {
869 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
877 pub fn add_trailing_semicolon(mut self) -> Self {
878 self.kind = match self.kind {
879 StmtKind::Expr(expr) => StmtKind::Semi(expr),
880 StmtKind::Mac(mac) => {
881 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
888 pub fn is_item(&self) -> bool {
890 StmtKind::Item(_) => true,
895 pub fn is_expr(&self) -> bool {
897 StmtKind::Expr(_) => true,
903 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
905 /// A local (let) binding.
907 /// An item definition.
909 /// Expr without trailing semi-colon.
911 /// Expr with a trailing semi-colon.
914 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
917 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
918 pub enum MacStmtStyle {
919 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
920 /// `foo!(...);`, `foo![...];`).
922 /// The macro statement had braces (e.g., `foo! { ... }`).
924 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
925 /// `foo!(...)`). All of these will end up being converted into macro
930 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
931 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
935 pub ty: Option<P<Ty>>,
936 /// Initializer expression to set the value, if any.
937 pub init: Option<P<Expr>>,
939 pub attrs: ThinVec<Attribute>,
942 /// An arm of a 'match'.
944 /// E.g., `0..=10 => { println!("match!") }` as in
948 /// 0..=10 => { println!("match!") },
949 /// _ => { println!("no match!") },
952 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
954 pub attrs: Vec<Attribute>,
955 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
957 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
958 pub guard: Option<P<Expr>>,
963 pub is_placeholder: bool,
966 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
967 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
969 pub attrs: ThinVec<Attribute>,
974 pub is_shorthand: bool,
975 pub is_placeholder: bool,
978 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
979 pub enum BlockCheckMode {
981 Unsafe(UnsafeSource),
984 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
985 pub enum UnsafeSource {
990 /// A constant (expression) that's not an item or associated item,
991 /// but needs its own `DefId` for type-checking, const-eval, etc.
992 /// These are usually found nested inside types (e.g., array lengths)
993 /// or expressions (e.g., repeat counts), and also used to define
994 /// explicit discriminant values for enum variants.
995 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
996 pub struct AnonConst {
1002 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1007 pub attrs: ThinVec<Attribute>,
1010 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1011 #[cfg(target_arch = "x86_64")]
1012 rustc_data_structures::static_assert_size!(Expr, 96);
1015 /// Returns `true` if this expression would be valid somewhere that expects a value;
1016 /// for example, an `if` condition.
1017 pub fn returns(&self) -> bool {
1018 if let ExprKind::Block(ref block, _) = self.kind {
1019 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1021 Some(&StmtKind::Expr(_)) => true,
1022 Some(&StmtKind::Semi(ref expr)) => {
1023 if let ExprKind::Ret(_) = expr.kind {
1024 // Last statement is explicit return.
1030 // This is a block that doesn't end in either an implicit or explicit return.
1034 // This is not a block, it is a value.
1039 pub fn to_bound(&self) -> Option<GenericBound> {
1041 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1042 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1043 TraitBoundModifier::None,
1049 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1050 pub fn to_ty(&self) -> Option<P<Ty>> {
1051 let kind = match &self.kind {
1052 // Trivial conversions.
1053 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1054 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1056 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1058 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => expr
1060 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1062 ExprKind::Repeat(expr, expr_len) => {
1063 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1066 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1068 ExprKind::Tup(exprs) => {
1071 .map(|expr| expr.to_ty())
1072 .collect::<Option<Vec<_>>>()?;
1076 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1077 // then type of result is trait object.
1078 // Othewise we don't assume the result type.
1079 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1080 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1081 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1087 // This expression doesn't look like a type syntactically.
1098 pub fn precedence(&self) -> ExprPrecedence {
1100 ExprKind::Box(_) => ExprPrecedence::Box,
1101 ExprKind::Array(_) => ExprPrecedence::Array,
1102 ExprKind::Call(..) => ExprPrecedence::Call,
1103 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1104 ExprKind::Tup(_) => ExprPrecedence::Tup,
1105 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1106 ExprKind::Unary(..) => ExprPrecedence::Unary,
1107 ExprKind::Lit(_) => ExprPrecedence::Lit,
1108 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1109 ExprKind::Let(..) => ExprPrecedence::Let,
1110 ExprKind::If(..) => ExprPrecedence::If,
1111 ExprKind::While(..) => ExprPrecedence::While,
1112 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1113 ExprKind::Loop(..) => ExprPrecedence::Loop,
1114 ExprKind::Match(..) => ExprPrecedence::Match,
1115 ExprKind::Closure(..) => ExprPrecedence::Closure,
1116 ExprKind::Block(..) => ExprPrecedence::Block,
1117 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1118 ExprKind::Async(..) => ExprPrecedence::Async,
1119 ExprKind::Await(..) => ExprPrecedence::Await,
1120 ExprKind::Assign(..) => ExprPrecedence::Assign,
1121 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1122 ExprKind::Field(..) => ExprPrecedence::Field,
1123 ExprKind::Index(..) => ExprPrecedence::Index,
1124 ExprKind::Range(..) => ExprPrecedence::Range,
1125 ExprKind::Path(..) => ExprPrecedence::Path,
1126 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1127 ExprKind::Break(..) => ExprPrecedence::Break,
1128 ExprKind::Continue(..) => ExprPrecedence::Continue,
1129 ExprKind::Ret(..) => ExprPrecedence::Ret,
1130 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1131 ExprKind::Mac(..) => ExprPrecedence::Mac,
1132 ExprKind::Struct(..) => ExprPrecedence::Struct,
1133 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1134 ExprKind::Paren(..) => ExprPrecedence::Paren,
1135 ExprKind::Try(..) => ExprPrecedence::Try,
1136 ExprKind::Yield(..) => ExprPrecedence::Yield,
1137 ExprKind::Err => ExprPrecedence::Err,
1142 /// Limit types of a range (inclusive or exclusive)
1143 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1144 pub enum RangeLimits {
1145 /// Inclusive at the beginning, exclusive at the end
1147 /// Inclusive at the beginning and end
1151 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1153 /// A `box x` expression.
1155 /// An array (`[a, b, c, d]`)
1156 Array(Vec<P<Expr>>),
1159 /// The first field resolves to the function itself,
1160 /// and the second field is the list of arguments.
1161 /// This also represents calling the constructor of
1162 /// tuple-like ADTs such as tuple structs and enum variants.
1163 Call(P<Expr>, Vec<P<Expr>>),
1164 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1166 /// The `PathSegment` represents the method name and its generic arguments
1167 /// (within the angle brackets).
1168 /// The first element of the vector of an `Expr` is the expression that evaluates
1169 /// to the object on which the method is being called on (the receiver),
1170 /// and the remaining elements are the rest of the arguments.
1171 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1172 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1173 MethodCall(PathSegment, Vec<P<Expr>>),
1174 /// A tuple (e.g., `(a, b, c, d)`).
1176 /// A binary operation (e.g., `a + b`, `a * b`).
1177 Binary(BinOp, P<Expr>, P<Expr>),
1178 /// A unary operation (e.g., `!x`, `*x`).
1179 Unary(UnOp, P<Expr>),
1180 /// A literal (e.g., `1`, `"foo"`).
1182 /// A cast (e.g., `foo as f64`).
1183 Cast(P<Expr>, P<Ty>),
1184 /// A type ascription (e.g., `42: usize`).
1185 Type(P<Expr>, P<Ty>),
1186 /// A `let pat = expr` expression that is only semantically allowed in the condition
1187 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1188 Let(P<Pat>, P<Expr>),
1189 /// An `if` block, with an optional `else` block.
1191 /// `if expr { block } else { expr }`
1192 If(P<Expr>, P<Block>, Option<P<Expr>>),
1193 /// A while loop, with an optional label.
1195 /// `'label: while expr { block }`
1196 While(P<Expr>, P<Block>, Option<Label>),
1197 /// A `for` loop, with an optional label.
1199 /// `'label: for pat in expr { block }`
1201 /// This is desugared to a combination of `loop` and `match` expressions.
1202 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1203 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1205 /// `'label: loop { block }`
1206 Loop(P<Block>, Option<Label>),
1207 /// A `match` block.
1208 Match(P<Expr>, Vec<Arm>),
1209 /// A closure (e.g., `move |a, b, c| a + b + c`).
1211 /// The final span is the span of the argument block `|...|`.
1212 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1213 /// A block (`'label: { ... }`).
1214 Block(P<Block>, Option<Label>),
1215 /// An async block (`async move { ... }`).
1217 /// The `NodeId` is the `NodeId` for the closure that results from
1218 /// desugaring an async block, just like the NodeId field in the
1219 /// `IsAsync` enum. This is necessary in order to create a def for the
1220 /// closure which can be used as a parent of any child defs. Defs
1221 /// created during lowering cannot be made the parent of any other
1222 /// preexisting defs.
1223 Async(CaptureBy, NodeId, P<Block>),
1224 /// An await expression (`my_future.await`).
1227 /// A try block (`try { ... }`).
1230 /// An assignment (`a = foo()`).
1231 Assign(P<Expr>, P<Expr>),
1232 /// An assignment with an operator.
1235 AssignOp(BinOp, P<Expr>, P<Expr>),
1236 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1237 Field(P<Expr>, Ident),
1238 /// An indexing operation (e.g., `foo[2]`).
1239 Index(P<Expr>, P<Expr>),
1240 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1241 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1243 /// Variable reference, possibly containing `::` and/or type
1244 /// parameters (e.g., `foo::bar::<baz>`).
1246 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1247 Path(Option<QSelf>, Path),
1249 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1250 AddrOf(BorrowKind, Mutability, P<Expr>),
1251 /// A `break`, with an optional label to break, and an optional expression.
1252 Break(Option<Label>, Option<P<Expr>>),
1253 /// A `continue`, with an optional label.
1254 Continue(Option<Label>),
1255 /// A `return`, with an optional value to be returned.
1256 Ret(Option<P<Expr>>),
1258 /// Output of the `asm!()` macro.
1259 InlineAsm(P<InlineAsm>),
1261 /// A macro invocation; pre-expansion.
1264 /// A struct literal expression.
1266 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1267 /// where `base` is the `Option<Expr>`.
1268 Struct(Path, Vec<Field>, Option<P<Expr>>),
1270 /// An array literal constructed from one repeated element.
1272 /// E.g., `[1; 5]`. The expression is the element to be
1273 /// repeated; the constant is the number of times to repeat it.
1274 Repeat(P<Expr>, AnonConst),
1276 /// No-op: used solely so we can pretty-print faithfully.
1279 /// A try expression (`expr?`).
1282 /// A `yield`, with an optional value to be yielded.
1283 Yield(Option<P<Expr>>),
1285 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1289 /// The explicit `Self` type in a "qualified path". The actual
1290 /// path, including the trait and the associated item, is stored
1291 /// separately. `position` represents the index of the associated
1292 /// item qualified with this `Self` type.
1294 /// ```ignore (only-for-syntax-highlight)
1295 /// <Vec<T> as a::b::Trait>::AssociatedItem
1296 /// ^~~~~ ~~~~~~~~~~~~~~^
1299 /// <Vec<T>>::AssociatedItem
1303 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1307 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1308 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1309 /// 0`, this is an empty span.
1310 pub path_span: Span,
1311 pub position: usize,
1314 /// A capture clause used in closures and `async` blocks.
1315 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1316 pub enum CaptureBy {
1317 /// `move |x| y + x`.
1319 /// `move` keyword was not specified.
1323 /// The movability of a generator / closure literal:
1324 /// whether a generator contains self-references, causing it to be `!Unpin`.
1325 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
1326 RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
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) |
1387 MacArgs::Eq(.., tokens) => tokens.clone(),
1391 /// Tokens together with the delimiters or `=`.
1392 /// Use of this method generally means that something suboptimal or hacky is happening.
1393 pub fn outer_tokens(&self) -> TokenStream {
1395 MacArgs::Empty => TokenStream::default(),
1396 MacArgs::Delimited(dspan, delim, ref tokens) =>
1397 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into(),
1398 MacArgs::Eq(eq_span, ref tokens) => iter::once(TokenTree::token(token::Eq, eq_span))
1399 .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 an item declaration within a trait declaration,
1607 /// possibly including a default implementation. A trait item is
1608 /// either required (meaning it doesn't have an implementation, just a
1609 /// signature) or provided (meaning it has a default implementation).
1610 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1611 pub struct TraitItem {
1612 pub attrs: Vec<Attribute>,
1615 pub vis: Visibility,
1618 pub generics: Generics,
1619 pub kind: TraitItemKind,
1620 /// See `Item::tokens` for what this is.
1621 pub tokens: Option<TokenStream>,
1624 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1625 pub enum TraitItemKind {
1626 Const(P<Ty>, Option<P<Expr>>),
1627 Method(FnSig, Option<P<Block>>),
1628 Type(GenericBounds, Option<P<Ty>>),
1632 /// Represents anything within an `impl` block.
1633 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1634 pub struct ImplItem {
1635 pub attrs: Vec<Attribute>,
1638 pub vis: Visibility,
1641 pub defaultness: Defaultness,
1642 pub generics: Generics,
1643 pub kind: ImplItemKind,
1644 /// See `Item::tokens` for what this is.
1645 pub tokens: Option<TokenStream>,
1648 /// Represents various kinds of content within an `impl`.
1649 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1650 pub enum ImplItemKind {
1651 Const(P<Ty>, P<Expr>),
1652 Method(FnSig, P<Block>),
1657 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1658 RustcEncodable, RustcDecodable, Debug)]
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 {
1687 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1688 RustcEncodable, RustcDecodable, Debug)]
1699 pub fn name_str(&self) -> &'static str {
1701 IntTy::Isize => "isize",
1703 IntTy::I16 => "i16",
1704 IntTy::I32 => "i32",
1705 IntTy::I64 => "i64",
1706 IntTy::I128 => "i128",
1710 pub fn name(&self) -> Symbol {
1712 IntTy::Isize => sym::isize,
1713 IntTy::I8 => sym::i8,
1714 IntTy::I16 => sym::i16,
1715 IntTy::I32 => sym::i32,
1716 IntTy::I64 => sym::i64,
1717 IntTy::I128 => sym::i128,
1721 pub fn val_to_string(&self, val: i128) -> String {
1722 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1723 // are parsed as `u128`, so we wouldn't want to print an extra negative
1725 format!("{}{}", val as u128, self.name_str())
1728 pub fn bit_width(&self) -> Option<usize> {
1730 IntTy::Isize => return None,
1739 pub fn normalize(&self, target_width: u32) -> Self {
1741 IntTy::Isize => match target_width {
1745 _ => unreachable!(),
1752 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1753 RustcEncodable, RustcDecodable, Copy, Debug)]
1764 pub fn name_str(&self) -> &'static str {
1766 UintTy::Usize => "usize",
1768 UintTy::U16 => "u16",
1769 UintTy::U32 => "u32",
1770 UintTy::U64 => "u64",
1771 UintTy::U128 => "u128",
1775 pub fn name(&self) -> Symbol {
1777 UintTy::Usize => sym::usize,
1778 UintTy::U8 => sym::u8,
1779 UintTy::U16 => sym::u16,
1780 UintTy::U32 => sym::u32,
1781 UintTy::U64 => sym::u64,
1782 UintTy::U128 => sym::u128,
1786 pub fn val_to_string(&self, val: u128) -> String {
1787 format!("{}{}", val, self.name_str())
1790 pub fn bit_width(&self) -> Option<usize> {
1792 UintTy::Usize => return None,
1797 UintTy::U128 => 128,
1801 pub fn normalize(&self, target_width: u32) -> Self {
1803 UintTy::Usize => match target_width {
1807 _ => unreachable!(),
1814 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1815 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1816 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1817 pub struct AssocTyConstraint {
1820 pub kind: AssocTyConstraintKind,
1824 /// The kinds of an `AssocTyConstraint`.
1825 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1826 pub enum AssocTyConstraintKind {
1827 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1831 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1833 bounds: GenericBounds,
1837 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1844 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1845 pub struct BareFnTy {
1846 pub unsafety: Unsafety,
1848 pub generic_params: Vec<GenericParam>,
1849 pub decl: P<FnDecl>,
1852 /// The various kinds of type recognized by the compiler.
1853 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1855 /// A variable-length slice (`[T]`).
1857 /// A fixed length array (`[T; n]`).
1858 Array(P<Ty>, AnonConst),
1859 /// A raw pointer (`*const T` or `*mut T`).
1861 /// A reference (`&'a T` or `&'a mut T`).
1862 Rptr(Option<Lifetime>, MutTy),
1863 /// A bare function (e.g., `fn(usize) -> bool`).
1864 BareFn(P<BareFnTy>),
1865 /// The never type (`!`).
1867 /// A tuple (`(A, B, C, D,...)`).
1869 /// A path (`module::module::...::Type`), optionally
1870 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1872 /// Type parameters are stored in the `Path` itself.
1873 Path(Option<QSelf>, Path),
1874 /// A trait object type `Bound1 + Bound2 + Bound3`
1875 /// where `Bound` is a trait or a lifetime.
1876 TraitObject(GenericBounds, TraitObjectSyntax),
1877 /// An `impl Bound1 + Bound2 + Bound3` type
1878 /// where `Bound` is a trait or a lifetime.
1880 /// The `NodeId` exists to prevent lowering from having to
1881 /// generate `NodeId`s on the fly, which would complicate
1882 /// the generation of opaque `type Foo = impl Trait` items significantly.
1883 ImplTrait(NodeId, GenericBounds),
1884 /// No-op; kept solely so that we can pretty-print faithfully.
1888 /// This means the type should be inferred instead of it having been
1889 /// specified. This can appear anywhere in a type.
1891 /// Inferred type of a `self` or `&self` argument in a method.
1893 /// A macro in the type position.
1895 /// Placeholder for a kind that has failed to be defined.
1897 /// Placeholder for a `va_list`.
1902 pub fn is_implicit_self(&self) -> bool {
1903 if let TyKind::ImplicitSelf = *self {
1910 pub fn is_unit(&self) -> bool {
1911 if let TyKind::Tup(ref tys) = *self {
1918 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1919 /// in lowering to avoid making larger changes there and beyond.
1920 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1922 Self::ImplTrait(_, bounds) => Some(bounds),
1928 /// Syntax used to declare a trait object.
1929 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1930 pub enum TraitObjectSyntax {
1935 /// Inline assembly dialect.
1937 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1938 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1939 pub enum AsmDialect {
1944 /// Inline assembly.
1946 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1947 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1948 pub struct InlineAsmOutput {
1949 pub constraint: Symbol,
1952 pub is_indirect: bool,
1955 /// Inline assembly.
1957 /// E.g., `asm!("NOP");`.
1958 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1959 pub struct InlineAsm {
1961 pub asm_str_style: StrStyle,
1962 pub outputs: Vec<InlineAsmOutput>,
1963 pub inputs: Vec<(Symbol, P<Expr>)>,
1964 pub clobbers: Vec<Symbol>,
1966 pub alignstack: bool,
1967 pub dialect: AsmDialect,
1970 /// A parameter in a function header.
1972 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1973 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1975 pub attrs: ThinVec<Attribute>,
1980 pub is_placeholder: bool,
1983 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1985 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1986 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1988 /// `self`, `mut self`
1990 /// `&'lt self`, `&'lt mut self`
1991 Region(Option<Lifetime>, Mutability),
1992 /// `self: TYPE`, `mut self: TYPE`
1993 Explicit(P<Ty>, Mutability),
1996 pub type ExplicitSelf = Spanned<SelfKind>;
1999 /// Attempts to cast parameter to `ExplicitSelf`.
2000 pub fn to_self(&self) -> Option<ExplicitSelf> {
2001 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2002 if ident.name == kw::SelfLower {
2003 return match self.ty.kind {
2004 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2005 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2006 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2009 self.pat.span.to(self.ty.span),
2010 SelfKind::Explicit(self.ty.clone(), mutbl),
2018 /// Returns `true` if parameter is `self`.
2019 pub fn is_self(&self) -> bool {
2020 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2021 ident.name == kw::SelfLower
2027 /// Builds a `Param` object from `ExplicitSelf`.
2028 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2029 let span = eself.span.to(eself_ident.span);
2030 let infer_ty = P(Ty {
2032 kind: TyKind::ImplicitSelf,
2035 let param = |mutbl, ty| Param {
2039 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2045 is_placeholder: false
2048 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2049 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2050 SelfKind::Region(lt, mutbl) => param(
2051 Mutability::Immutable,
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)]
2102 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2103 RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2110 pub fn prefix_str(&self) -> &'static str {
2112 Unsafety::Unsafe => "unsafe ",
2113 Unsafety::Normal => "",
2118 impl fmt::Display for Unsafety {
2119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2122 Unsafety::Normal => "normal",
2123 Unsafety::Unsafe => "unsafe",
2130 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2134 return_impl_trait_id: NodeId,
2140 pub fn is_async(self) -> bool {
2141 if let IsAsync::Async { .. } = self {
2148 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2149 pub fn opt_return_id(self) -> Option<NodeId> {
2152 return_impl_trait_id,
2154 } => Some(return_impl_trait_id),
2155 IsAsync::NotAsync => None,
2160 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2161 pub enum Constness {
2166 /// Item defaultness.
2167 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2168 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2169 pub enum Defaultness {
2174 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2175 pub enum ImplPolarity {
2176 /// `impl Trait for Type`
2178 /// `impl !Trait for Type`
2182 impl fmt::Debug for ImplPolarity {
2183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2185 ImplPolarity::Positive => "positive".fmt(f),
2186 ImplPolarity::Negative => "negative".fmt(f),
2191 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2192 pub enum FunctionRetTy {
2193 /// Returns type is not specified.
2195 /// Functions default to `()` and closures default to inference.
2196 /// Span points to where return type would be inserted.
2198 /// Everything else.
2202 impl FunctionRetTy {
2203 pub fn span(&self) -> Span {
2205 FunctionRetTy::Default(span) => span,
2206 FunctionRetTy::Ty(ref ty) => ty.span,
2211 /// Module declaration.
2213 /// E.g., `mod foo;` or `mod foo { .. }`.
2214 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2216 /// A span from the first token past `{` to the last token until `}`.
2217 /// For `mod foo;`, the inner span ranges from the first token
2218 /// to the last token in the external file.
2220 pub items: Vec<P<Item>>,
2221 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2225 /// Foreign module declaration.
2227 /// E.g., `extern { .. }` or `extern C { .. }`.
2228 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2229 pub struct ForeignMod {
2230 pub abi: Option<StrLit>,
2231 pub items: Vec<ForeignItem>,
2234 /// Global inline assembly.
2236 /// Also known as "module-level assembly" or "file-scoped assembly".
2237 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2238 pub struct GlobalAsm {
2242 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2243 pub struct EnumDef {
2244 pub variants: Vec<Variant>,
2247 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2248 pub struct Variant {
2249 /// Attributes of the variant.
2250 pub attrs: Vec<Attribute>,
2251 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2255 /// The visibility of the variant. Syntactically accepted but not semantically.
2256 pub vis: Visibility,
2257 /// Name of the variant.
2260 /// Fields and constructor id of the variant.
2261 pub data: VariantData,
2262 /// Explicit discriminant, e.g., `Foo = 1`.
2263 pub disr_expr: Option<AnonConst>,
2264 /// Is a macro placeholder
2265 pub is_placeholder: bool,
2268 /// Part of `use` item to the right of its prefix.
2269 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2270 pub enum UseTreeKind {
2271 /// `use prefix` or `use prefix as rename`
2273 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2275 Simple(Option<Ident>, NodeId, NodeId),
2276 /// `use prefix::{...}`
2277 Nested(Vec<(UseTree, NodeId)>),
2282 /// A tree of paths sharing common prefixes.
2283 /// Used in `use` items both at top-level and inside of braces in import groups.
2284 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2285 pub struct UseTree {
2287 pub kind: UseTreeKind,
2292 pub fn ident(&self) -> Ident {
2294 UseTreeKind::Simple(Some(rename), ..) => rename,
2295 UseTreeKind::Simple(None, ..) => {
2299 .expect("empty prefix in a simple import")
2302 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2307 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2308 /// are contained as statements within items. These two cases need to be
2309 /// distinguished for pretty-printing.
2310 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2311 pub enum AttrStyle {
2316 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2317 pub struct AttrId(pub usize);
2319 impl Idx for AttrId {
2320 fn new(idx: usize) -> Self {
2323 fn index(self) -> usize {
2328 impl rustc_serialize::Encodable for AttrId {
2329 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2334 impl rustc_serialize::Decodable for AttrId {
2335 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2336 d.read_nil().map(|_| crate::attr::mk_attr_id())
2340 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2341 pub struct AttrItem {
2346 /// Metadata associated with an item.
2347 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2348 pub struct Attribute {
2351 /// Denotes if the attribute decorates the following construct (outer)
2352 /// or the construct this attribute is contained within (inner).
2353 pub style: AttrStyle,
2357 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2359 /// A normal attribute.
2362 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2363 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2364 /// variant (which is much less compact and thus more expensive).
2366 /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2367 /// for this variant, but this may change in the future.
2372 /// `TraitRef`s appear in impls.
2374 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2375 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2376 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2377 /// same as the impl's `NodeId`).
2378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2379 pub struct TraitRef {
2384 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2385 pub struct PolyTraitRef {
2386 /// The `'a` in `<'a> Foo<&'a T>`.
2387 pub bound_generic_params: Vec<GenericParam>,
2389 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2390 pub trait_ref: TraitRef,
2396 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2398 bound_generic_params: generic_params,
2399 trait_ref: TraitRef {
2401 ref_id: DUMMY_NODE_ID,
2408 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2409 pub enum CrateSugar {
2410 /// Source is `pub(crate)`.
2413 /// Source is (just) `crate`.
2417 pub type Visibility = Spanned<VisibilityKind>;
2419 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2420 pub enum VisibilityKind {
2423 Restricted { path: P<Path>, id: NodeId },
2427 impl VisibilityKind {
2428 pub fn is_pub(&self) -> bool {
2429 if let VisibilityKind::Public = *self {
2437 /// Field of a struct.
2439 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2440 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2441 pub struct StructField {
2442 pub attrs: Vec<Attribute>,
2445 pub vis: Visibility,
2446 pub ident: Option<Ident>,
2449 pub is_placeholder: bool,
2452 /// Fields and constructor ids of enum variants and structs.
2453 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2454 pub enum VariantData {
2457 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2458 Struct(Vec<StructField>, bool),
2461 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2462 Tuple(Vec<StructField>, NodeId),
2465 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2470 /// Return the fields of this variant.
2471 pub fn fields(&self) -> &[StructField] {
2473 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2478 /// Return the `NodeId` of this variant's constructor, if it has one.
2479 pub fn ctor_id(&self) -> Option<NodeId> {
2481 VariantData::Struct(..) => None,
2482 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2489 /// The name might be a dummy name in case of anonymous items.
2490 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2491 pub struct Item<K = ItemKind> {
2492 pub attrs: Vec<Attribute>,
2495 pub vis: Visibility,
2500 /// Original tokens this item was parsed from. This isn't necessarily
2501 /// available for all items, although over time more and more items should
2502 /// have this be `Some`. Right now this is primarily used for procedural
2503 /// macros, notably custom attributes.
2505 /// Note that the tokens here do not include the outer attributes, but will
2506 /// include inner attributes.
2507 pub tokens: Option<TokenStream>,
2511 /// Return the span that encompasses the attributes.
2512 pub fn span_with_attributes(&self) -> Span {
2513 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2517 /// `extern` qualifier on a function item or function type.
2518 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2526 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2527 abi.map_or(Extern::Implicit, Extern::Explicit)
2531 /// A function header.
2533 /// All the information between the visibility and the name of the function is
2534 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2535 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2536 pub struct FnHeader {
2537 pub unsafety: Unsafety,
2538 pub asyncness: Spanned<IsAsync>,
2539 pub constness: Spanned<Constness>,
2543 impl Default for FnHeader {
2544 fn default() -> FnHeader {
2546 unsafety: Unsafety::Normal,
2547 asyncness: dummy_spanned(IsAsync::NotAsync),
2548 constness: dummy_spanned(Constness::NotConst),
2554 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2556 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2558 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2559 ExternCrate(Option<Name>),
2560 /// A use declaration item (`use`).
2562 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2564 /// A static item (`static`).
2566 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2567 Static(P<Ty>, Mutability, P<Expr>),
2568 /// A constant item (`const`).
2570 /// E.g., `const FOO: i32 = 42;`.
2571 Const(P<Ty>, P<Expr>),
2572 /// A function declaration (`fn`).
2574 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2575 Fn(FnSig, Generics, P<Block>),
2576 /// A module declaration (`mod`).
2578 /// E.g., `mod foo;` or `mod foo { .. }`.
2580 /// An external module (`extern`).
2582 /// E.g., `extern {}` or `extern "C" {}`.
2583 ForeignMod(ForeignMod),
2584 /// Module-level inline assembly (from `global_asm!()`).
2585 GlobalAsm(P<GlobalAsm>),
2586 /// A type alias (`type`).
2588 /// E.g., `type Foo = Bar<u8>;`.
2589 TyAlias(P<Ty>, Generics),
2590 /// An enum definition (`enum`).
2592 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2593 Enum(EnumDef, Generics),
2594 /// A struct definition (`struct`).
2596 /// E.g., `struct Foo<A> { x: A }`.
2597 Struct(VariantData, Generics),
2598 /// A union definition (`union`).
2600 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2601 Union(VariantData, Generics),
2602 /// A trait declaration (`trait`).
2604 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2605 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2608 /// E.g., `trait Foo = Bar + Quux;`.
2609 TraitAlias(Generics, GenericBounds),
2610 /// An implementation.
2612 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2618 Option<TraitRef>, // (optional) trait this impl implements
2622 /// A macro invocation.
2624 /// E.g., `foo!(..)`.
2627 /// A macro definition.
2632 pub fn descriptive_variant(&self) -> &str {
2634 ItemKind::ExternCrate(..) => "extern crate",
2635 ItemKind::Use(..) => "use",
2636 ItemKind::Static(..) => "static item",
2637 ItemKind::Const(..) => "constant item",
2638 ItemKind::Fn(..) => "function",
2639 ItemKind::Mod(..) => "module",
2640 ItemKind::ForeignMod(..) => "foreign module",
2641 ItemKind::GlobalAsm(..) => "global asm",
2642 ItemKind::TyAlias(..) => "type alias",
2643 ItemKind::Enum(..) => "enum",
2644 ItemKind::Struct(..) => "struct",
2645 ItemKind::Union(..) => "union",
2646 ItemKind::Trait(..) => "trait",
2647 ItemKind::TraitAlias(..) => "trait alias",
2648 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2653 pub type ForeignItem = Item<ForeignItemKind>;
2655 /// An item within an `extern` block.
2656 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2657 pub enum ForeignItemKind {
2658 /// A foreign function.
2659 Fn(P<FnDecl>, Generics),
2660 /// A foreign static item (`static ext: u8`).
2661 Static(P<Ty>, Mutability),
2664 /// A macro invocation.
2668 impl ForeignItemKind {
2669 pub fn descriptive_variant(&self) -> &str {
2671 ForeignItemKind::Fn(..) => "foreign function",
2672 ForeignItemKind::Static(..) => "foreign static item",
2673 ForeignItemKind::Ty => "foreign type",
2674 ForeignItemKind::Macro(..) => "macro in foreign module",