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;
32 use syntax_pos::symbol::{kw, sym, Symbol};
33 use syntax_pos::{Span, DUMMY_SP, ExpnId};
35 use rustc_data_structures::fx::FxHashSet;
36 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
37 use rustc_data_structures::sync::Lrc;
38 use rustc_data_structures::thin_vec::ThinVec;
39 use rustc_index::vec::Idx;
40 use rustc_serialize::{self, Decoder, Encoder};
41 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 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
272 use rustc_index::vec::Idx;
273 rustc_index::newtype_index! {
276 DEBUG_FORMAT = "NodeId({})"
281 pub use node_id_inner::NodeId;
284 pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self {
285 NodeId::from_u32(expn_id.as_u32())
288 pub fn placeholder_to_expn_id(self) -> ExpnId {
289 ExpnId::from_u32(self.as_u32())
293 impl fmt::Display for NodeId {
294 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295 fmt::Display::fmt(&self.as_u32(), f)
299 impl rustc_serialize::UseSpecializedEncodable for NodeId {
300 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
301 s.emit_u32(self.as_u32())
305 impl rustc_serialize::UseSpecializedDecodable for NodeId {
306 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
307 d.read_u32().map(NodeId::from_u32)
311 /// `NodeId` used to represent the root of the crate.
312 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
314 /// When parsing and doing expansions, we initially give all AST nodes this AST
315 /// node value. Then later, in the renumber pass, we renumber them to have
316 /// small, positive ids.
317 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
319 /// A modifier on a bound, currently this is only used for `?Sized`, where the
320 /// modifier is `Maybe`. Negative bounds should also be handled here.
321 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
322 pub enum TraitBoundModifier {
327 /// The AST represents all type param bounds as types.
328 /// `typeck::collect::compute_bounds` matches these against
329 /// the "special" built-in traits (see `middle::lang_items`) and
330 /// detects `Copy`, `Send` and `Sync`.
331 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
332 pub enum GenericBound {
333 Trait(PolyTraitRef, TraitBoundModifier),
338 pub fn span(&self) -> Span {
340 &GenericBound::Trait(ref t, ..) => t.span,
341 &GenericBound::Outlives(ref l) => l.ident.span,
346 pub type GenericBounds = Vec<GenericBound>;
348 /// Specifies the enforced ordering for generic parameters. In the future,
349 /// if we wanted to relax this order, we could override `PartialEq` and
350 /// `PartialOrd`, to allow the kinds to be unordered.
351 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
352 pub enum ParamKindOrd {
358 impl fmt::Display for ParamKindOrd {
359 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 ParamKindOrd::Lifetime => "lifetime".fmt(f),
362 ParamKindOrd::Type => "type".fmt(f),
363 ParamKindOrd::Const => "const".fmt(f),
368 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
369 pub enum GenericParamKind {
370 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
372 Type { default: Option<P<Ty>> },
376 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
377 pub struct GenericParam {
380 pub attrs: ThinVec<Attribute>,
381 pub bounds: GenericBounds,
382 pub is_placeholder: bool,
383 pub kind: GenericParamKind,
386 /// Represents lifetime, type and const parameters attached to a declaration of
387 /// a function, enum, trait, etc.
388 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
389 pub struct Generics {
390 pub params: Vec<GenericParam>,
391 pub where_clause: WhereClause,
395 impl Default for Generics {
396 /// Creates an instance of `Generics`.
397 fn default() -> Generics {
400 where_clause: WhereClause {
401 predicates: Vec::new(),
409 /// A where-clause in a definition.
410 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
411 pub struct WhereClause {
412 pub predicates: Vec<WherePredicate>,
416 /// A single predicate in a where-clause.
417 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
418 pub enum WherePredicate {
419 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
420 BoundPredicate(WhereBoundPredicate),
421 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
422 RegionPredicate(WhereRegionPredicate),
423 /// An equality predicate (unsupported).
424 EqPredicate(WhereEqPredicate),
427 impl WherePredicate {
428 pub fn span(&self) -> Span {
430 &WherePredicate::BoundPredicate(ref p) => p.span,
431 &WherePredicate::RegionPredicate(ref p) => p.span,
432 &WherePredicate::EqPredicate(ref p) => p.span,
439 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
440 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
441 pub struct WhereBoundPredicate {
443 /// Any generics from a `for` binding.
444 pub bound_generic_params: Vec<GenericParam>,
445 /// The type being bounded.
446 pub bounded_ty: P<Ty>,
447 /// Trait and lifetime bounds (`Clone + Send + 'static`).
448 pub bounds: GenericBounds,
451 /// A lifetime predicate.
453 /// E.g., `'a: 'b + 'c`.
454 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
455 pub struct WhereRegionPredicate {
457 pub lifetime: Lifetime,
458 pub bounds: GenericBounds,
461 /// An equality predicate (unsupported).
464 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
465 pub struct WhereEqPredicate {
472 /// The set of `MetaItem`s that define the compilation environment of the crate,
473 /// used to drive conditional compilation.
474 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
476 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
479 pub attrs: Vec<Attribute>,
483 /// Possible values inside of compile-time attribute lists.
485 /// E.g., the '..' in `#[name(..)]`.
486 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
487 pub enum NestedMetaItem {
488 /// A full MetaItem, for recursive meta items.
492 /// E.g., `"foo"`, `64`, `true`.
496 /// A spanned compile-time attribute item.
498 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
499 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
500 pub struct MetaItem {
502 pub kind: MetaItemKind,
506 /// A compile-time attribute item.
508 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
509 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
510 pub enum MetaItemKind {
513 /// E.g., `test` as in `#[test]`.
517 /// E.g., `derive(..)` as in `#[derive(..)]`.
518 List(Vec<NestedMetaItem>),
519 /// Name value meta item.
521 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
525 /// A block (`{ .. }`).
527 /// E.g., `{ .. }` as in `fn foo() { .. }`.
528 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
530 /// The statements in the block.
531 pub stmts: Vec<Stmt>,
533 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
534 pub rules: BlockCheckMode,
538 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
546 /// Attempt reparsing the pattern as a type.
547 /// This is intended for use by diagnostics.
548 pub fn to_ty(&self) -> Option<P<Ty>> {
549 let kind = match &self.kind {
550 // In a type expression `_` is an inference variable.
551 PatKind::Wild => TyKind::Infer,
552 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
553 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
554 TyKind::Path(None, Path::from_ident(*ident))
556 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
557 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
558 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
559 PatKind::Ref(pat, mutbl) => pat
561 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
562 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
563 // when `P` can be reparsed as a type `T`.
564 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
565 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
566 // assuming `T0` to `Tn` are all syntactically valid as types.
567 PatKind::Tuple(pats) => {
568 let mut tys = Vec::with_capacity(pats.len());
569 // FIXME(#48994) - could just be collected into an Option<Vec>
571 tys.push(pat.to_ty()?);
585 /// Walk top-down and call `it` in each place where a pattern occurs
586 /// starting with the root pattern `walk` is called on. If `it` returns
587 /// false then we will descend no further but siblings will be processed.
588 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
594 // Walk into the pattern associated with `Ident` (if any).
595 PatKind::Ident(_, _, Some(p)) => p.walk(it),
597 // Walk into each field of struct.
598 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
600 // Sequence of patterns.
601 PatKind::TupleStruct(_, s)
604 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
606 // Trivial wrappers over inner patterns.
609 | PatKind::Paren(s) => s.walk(it),
611 // These patterns do not contain subpatterns, skip.
618 | PatKind::Mac(_) => {},
622 /// Is this a `..` pattern?
623 pub fn is_rest(&self) -> bool {
625 PatKind::Rest => true,
631 /// A single field in a struct pattern
633 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
634 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
635 /// except is_shorthand is true
636 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
637 pub struct FieldPat {
638 /// The identifier for the field
640 /// The pattern the field is destructured to
642 pub is_shorthand: bool,
643 pub attrs: ThinVec<Attribute>,
646 pub is_placeholder: bool,
649 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
650 pub enum BindingMode {
655 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
657 Included(RangeSyntax),
661 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
662 pub enum RangeSyntax {
669 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
671 /// Represents a wildcard pattern (`_`).
674 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
675 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
676 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
677 /// during name resolution.
678 Ident(BindingMode, Ident, Option<P<Pat>>),
680 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
681 /// The `bool` is `true` in the presence of a `..`.
682 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
684 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
685 TupleStruct(Path, Vec<P<Pat>>),
687 /// An or-pattern `A | B | C`.
688 /// Invariant: `pats.len() >= 2`.
691 /// A possibly qualified path pattern.
692 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
693 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
694 /// only legally refer to associated constants.
695 Path(Option<QSelf>, Path),
697 /// A tuple pattern (`(a, b)`).
703 /// A reference pattern (e.g., `&mut (a, b)`).
704 Ref(P<Pat>, Mutability),
709 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
710 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
712 /// A slice pattern `[a, b, c]`.
715 /// A rest pattern `..`.
717 /// Syntactically it is valid anywhere.
719 /// Semantically however, it only has meaning immediately inside:
720 /// - a slice pattern: `[a, .., b]`,
721 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
722 /// - a tuple pattern: `(a, .., b)`,
723 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
725 /// In all of these cases, an additional restriction applies,
726 /// only one rest pattern may occur in the pattern sequences.
729 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
732 /// A macro pattern; pre-expansion.
736 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
737 RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
738 pub enum Mutability {
744 /// Returns `MutMutable` only if both `self` and `other` are mutable.
745 pub fn and(self, other: Self) -> Self {
747 Mutability::Mutable => other,
748 Mutability::Immutable => Mutability::Immutable,
752 pub fn invert(self) -> Self {
754 Mutability::Mutable => Mutability::Immutable,
755 Mutability::Immutable => Mutability::Mutable,
759 pub fn prefix_str(&self) -> &'static str {
761 Mutability::Mutable => "mut ",
762 Mutability::Immutable => "",
767 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
769 /// The `+` operator (addition)
771 /// The `-` operator (subtraction)
773 /// The `*` operator (multiplication)
775 /// The `/` operator (division)
777 /// The `%` operator (modulus)
779 /// The `&&` operator (logical and)
781 /// The `||` operator (logical or)
783 /// The `^` operator (bitwise xor)
785 /// The `&` operator (bitwise and)
787 /// The `|` operator (bitwise or)
789 /// The `<<` operator (shift left)
791 /// The `>>` operator (shift right)
793 /// The `==` operator (equality)
795 /// The `<` operator (less than)
797 /// The `<=` operator (less than or equal to)
799 /// The `!=` operator (not equal to)
801 /// The `>=` operator (greater than or equal to)
803 /// The `>` operator (greater than)
808 pub fn to_string(&self) -> &'static str {
831 pub fn lazy(&self) -> bool {
833 BinOpKind::And | BinOpKind::Or => true,
838 pub fn is_shift(&self) -> bool {
840 BinOpKind::Shl | BinOpKind::Shr => true,
845 pub fn is_comparison(&self) -> bool {
847 // Note for developers: please keep this as is;
848 // we want compilation to fail if another variant is added.
850 Eq | Lt | Le | Ne | Gt | Ge => true,
851 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
855 /// Returns `true` if the binary operator takes its arguments by value
856 pub fn is_by_value(&self) -> bool {
857 !self.is_comparison()
861 pub type BinOp = Spanned<BinOpKind>;
865 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
866 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
868 /// The `*` operator for dereferencing
870 /// The `!` operator for logical inversion
872 /// The `-` operator for negation
877 /// Returns `true` if the unary operator takes its argument by value
878 pub fn is_by_value(u: UnOp) -> bool {
880 UnOp::Neg | UnOp::Not => true,
885 pub fn to_string(op: UnOp) -> &'static str {
895 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
903 pub fn add_trailing_semicolon(mut self) -> Self {
904 self.kind = match self.kind {
905 StmtKind::Expr(expr) => StmtKind::Semi(expr),
906 StmtKind::Mac(mac) => {
907 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
914 pub fn is_item(&self) -> bool {
916 StmtKind::Item(_) => true,
921 pub fn is_expr(&self) -> bool {
923 StmtKind::Expr(_) => true,
929 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
931 /// A local (let) binding.
933 /// An item definition.
935 /// Expr without trailing semi-colon.
937 /// Expr with a trailing semi-colon.
940 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
943 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
944 pub enum MacStmtStyle {
945 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
946 /// `foo!(...);`, `foo![...];`).
948 /// The macro statement had braces (e.g., `foo! { ... }`).
950 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
951 /// `foo!(...)`). All of these will end up being converted into macro
956 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
957 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
961 pub ty: Option<P<Ty>>,
962 /// Initializer expression to set the value, if any.
963 pub init: Option<P<Expr>>,
965 pub attrs: ThinVec<Attribute>,
968 /// An arm of a 'match'.
970 /// E.g., `0..=10 => { println!("match!") }` as in
974 /// 0..=10 => { println!("match!") },
975 /// _ => { println!("no match!") },
978 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
980 pub attrs: Vec<Attribute>,
981 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
983 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
984 pub guard: Option<P<Expr>>,
989 pub is_placeholder: bool,
992 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
993 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
998 pub is_shorthand: bool,
999 pub attrs: ThinVec<Attribute>,
1001 pub is_placeholder: bool,
1004 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1005 pub enum BlockCheckMode {
1007 Unsafe(UnsafeSource),
1010 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1011 pub enum UnsafeSource {
1016 /// A constant (expression) that's not an item or associated item,
1017 /// but needs its own `DefId` for type-checking, const-eval, etc.
1018 /// These are usually found nested inside types (e.g., array lengths)
1019 /// or expressions (e.g., repeat counts), and also used to define
1020 /// explicit discriminant values for enum variants.
1021 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1022 pub struct AnonConst {
1028 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1033 pub attrs: ThinVec<Attribute>,
1036 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1037 #[cfg(target_arch = "x86_64")]
1038 rustc_data_structures::static_assert_size!(Expr, 96);
1041 /// Returns `true` if this expression would be valid somewhere that expects a value;
1042 /// for example, an `if` condition.
1043 pub fn returns(&self) -> bool {
1044 if let ExprKind::Block(ref block, _) = self.kind {
1045 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1047 Some(&StmtKind::Expr(_)) => true,
1048 Some(&StmtKind::Semi(ref expr)) => {
1049 if let ExprKind::Ret(_) = expr.kind {
1050 // Last statement is explicit return.
1056 // This is a block that doesn't end in either an implicit or explicit return.
1060 // This is not a block, it is a value.
1065 pub fn to_bound(&self) -> Option<GenericBound> {
1067 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1068 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1069 TraitBoundModifier::None,
1075 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1076 pub fn to_ty(&self) -> Option<P<Ty>> {
1077 let kind = match &self.kind {
1078 // Trivial conversions.
1079 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1080 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1082 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1084 ExprKind::AddrOf(mutbl, expr) => expr
1086 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1088 ExprKind::Repeat(expr, expr_len) => {
1089 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1092 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1094 ExprKind::Tup(exprs) => {
1097 .map(|expr| expr.to_ty())
1098 .collect::<Option<Vec<_>>>()?;
1102 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1103 // then type of result is trait object.
1104 // Othewise we don't assume the result type.
1105 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1106 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1107 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1113 // This expression doesn't look like a type syntactically.
1124 pub fn precedence(&self) -> ExprPrecedence {
1126 ExprKind::Box(_) => ExprPrecedence::Box,
1127 ExprKind::Array(_) => ExprPrecedence::Array,
1128 ExprKind::Call(..) => ExprPrecedence::Call,
1129 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1130 ExprKind::Tup(_) => ExprPrecedence::Tup,
1131 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1132 ExprKind::Unary(..) => ExprPrecedence::Unary,
1133 ExprKind::Lit(_) => ExprPrecedence::Lit,
1134 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1135 ExprKind::Let(..) => ExprPrecedence::Let,
1136 ExprKind::If(..) => ExprPrecedence::If,
1137 ExprKind::While(..) => ExprPrecedence::While,
1138 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1139 ExprKind::Loop(..) => ExprPrecedence::Loop,
1140 ExprKind::Match(..) => ExprPrecedence::Match,
1141 ExprKind::Closure(..) => ExprPrecedence::Closure,
1142 ExprKind::Block(..) => ExprPrecedence::Block,
1143 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1144 ExprKind::Async(..) => ExprPrecedence::Async,
1145 ExprKind::Await(..) => ExprPrecedence::Await,
1146 ExprKind::Assign(..) => ExprPrecedence::Assign,
1147 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1148 ExprKind::Field(..) => ExprPrecedence::Field,
1149 ExprKind::Index(..) => ExprPrecedence::Index,
1150 ExprKind::Range(..) => ExprPrecedence::Range,
1151 ExprKind::Path(..) => ExprPrecedence::Path,
1152 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1153 ExprKind::Break(..) => ExprPrecedence::Break,
1154 ExprKind::Continue(..) => ExprPrecedence::Continue,
1155 ExprKind::Ret(..) => ExprPrecedence::Ret,
1156 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1157 ExprKind::Mac(..) => ExprPrecedence::Mac,
1158 ExprKind::Struct(..) => ExprPrecedence::Struct,
1159 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1160 ExprKind::Paren(..) => ExprPrecedence::Paren,
1161 ExprKind::Try(..) => ExprPrecedence::Try,
1162 ExprKind::Yield(..) => ExprPrecedence::Yield,
1163 ExprKind::Err => ExprPrecedence::Err,
1168 /// Limit types of a range (inclusive or exclusive)
1169 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1170 pub enum RangeLimits {
1171 /// Inclusive at the beginning, exclusive at the end
1173 /// Inclusive at the beginning and end
1177 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1179 /// A `box x` expression.
1181 /// An array (`[a, b, c, d]`)
1182 Array(Vec<P<Expr>>),
1185 /// The first field resolves to the function itself,
1186 /// and the second field is the list of arguments.
1187 /// This also represents calling the constructor of
1188 /// tuple-like ADTs such as tuple structs and enum variants.
1189 Call(P<Expr>, Vec<P<Expr>>),
1190 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1192 /// The `PathSegment` represents the method name and its generic arguments
1193 /// (within the angle brackets).
1194 /// The first element of the vector of an `Expr` is the expression that evaluates
1195 /// to the object on which the method is being called on (the receiver),
1196 /// and the remaining elements are the rest of the arguments.
1197 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1198 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1199 MethodCall(PathSegment, Vec<P<Expr>>),
1200 /// A tuple (e.g., `(a, b, c, d)`).
1202 /// A binary operation (e.g., `a + b`, `a * b`).
1203 Binary(BinOp, P<Expr>, P<Expr>),
1204 /// A unary operation (e.g., `!x`, `*x`).
1205 Unary(UnOp, P<Expr>),
1206 /// A literal (e.g., `1`, `"foo"`).
1208 /// A cast (e.g., `foo as f64`).
1209 Cast(P<Expr>, P<Ty>),
1210 /// A type ascription (e.g., `42: usize`).
1211 Type(P<Expr>, P<Ty>),
1212 /// A `let pat = expr` expression that is only semantically allowed in the condition
1213 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1214 Let(P<Pat>, P<Expr>),
1215 /// An `if` block, with an optional `else` block.
1217 /// `if expr { block } else { expr }`
1218 If(P<Expr>, P<Block>, Option<P<Expr>>),
1219 /// A while loop, with an optional label.
1221 /// `'label: while expr { block }`
1222 While(P<Expr>, P<Block>, Option<Label>),
1223 /// A `for` loop, with an optional label.
1225 /// `'label: for pat in expr { block }`
1227 /// This is desugared to a combination of `loop` and `match` expressions.
1228 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1229 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1231 /// `'label: loop { block }`
1232 Loop(P<Block>, Option<Label>),
1233 /// A `match` block.
1234 Match(P<Expr>, Vec<Arm>),
1235 /// A closure (e.g., `move |a, b, c| a + b + c`).
1237 /// The final span is the span of the argument block `|...|`.
1238 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1239 /// A block (`'label: { ... }`).
1240 Block(P<Block>, Option<Label>),
1241 /// An async block (`async move { ... }`).
1243 /// The `NodeId` is the `NodeId` for the closure that results from
1244 /// desugaring an async block, just like the NodeId field in the
1245 /// `IsAsync` enum. This is necessary in order to create a def for the
1246 /// closure which can be used as a parent of any child defs. Defs
1247 /// created during lowering cannot be made the parent of any other
1248 /// preexisting defs.
1249 Async(CaptureBy, NodeId, P<Block>),
1250 /// An await expression (`my_future.await`).
1253 /// A try block (`try { ... }`).
1256 /// An assignment (`a = foo()`).
1257 Assign(P<Expr>, P<Expr>),
1258 /// An assignment with an operator.
1261 AssignOp(BinOp, P<Expr>, P<Expr>),
1262 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1263 Field(P<Expr>, Ident),
1264 /// An indexing operation (e.g., `foo[2]`).
1265 Index(P<Expr>, P<Expr>),
1266 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1267 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1269 /// Variable reference, possibly containing `::` and/or type
1270 /// parameters (e.g., `foo::bar::<baz>`).
1272 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1273 Path(Option<QSelf>, Path),
1275 /// A referencing operation (`&a` or `&mut a`).
1276 AddrOf(Mutability, P<Expr>),
1277 /// A `break`, with an optional label to break, and an optional expression.
1278 Break(Option<Label>, Option<P<Expr>>),
1279 /// A `continue`, with an optional label.
1280 Continue(Option<Label>),
1281 /// A `return`, with an optional value to be returned.
1282 Ret(Option<P<Expr>>),
1284 /// Output of the `asm!()` macro.
1285 InlineAsm(P<InlineAsm>),
1287 /// A macro invocation; pre-expansion.
1290 /// A struct literal expression.
1292 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1293 /// where `base` is the `Option<Expr>`.
1294 Struct(Path, Vec<Field>, Option<P<Expr>>),
1296 /// An array literal constructed from one repeated element.
1298 /// E.g., `[1; 5]`. The expression is the element to be
1299 /// repeated; the constant is the number of times to repeat it.
1300 Repeat(P<Expr>, AnonConst),
1302 /// No-op: used solely so we can pretty-print faithfully.
1305 /// A try expression (`expr?`).
1308 /// A `yield`, with an optional value to be yielded.
1309 Yield(Option<P<Expr>>),
1311 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1315 /// The explicit `Self` type in a "qualified path". The actual
1316 /// path, including the trait and the associated item, is stored
1317 /// separately. `position` represents the index of the associated
1318 /// item qualified with this `Self` type.
1320 /// ```ignore (only-for-syntax-highlight)
1321 /// <Vec<T> as a::b::Trait>::AssociatedItem
1322 /// ^~~~~ ~~~~~~~~~~~~~~^
1325 /// <Vec<T>>::AssociatedItem
1329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1333 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1334 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1335 /// 0`, this is an empty span.
1336 pub path_span: Span,
1337 pub position: usize,
1340 /// A capture clause used in closures and `async` blocks.
1341 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1342 pub enum CaptureBy {
1343 /// `move |x| y + x`.
1345 /// `move` keyword was not specified.
1349 /// The movability of a generator / closure literal:
1350 /// whether a generator contains self-references, causing it to be `!Unpin`.
1351 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
1352 RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1353 pub enum Movability {
1354 /// May contain self-references, `!Unpin`.
1356 /// Must not contain self-references, `Unpin`.
1360 /// Represents a macro invocation. The `Path` indicates which macro
1361 /// is being invoked, and the vector of token-trees contains the source
1362 /// of the macro invocation.
1364 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1365 /// stored in the enclosing item.
1366 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1369 pub delim: MacDelimiter,
1370 pub tts: TokenStream,
1372 pub prior_type_ascription: Option<(Span, bool)>,
1375 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1376 pub enum MacDelimiter {
1383 pub fn stream(&self) -> TokenStream {
1389 crate fn to_token(self) -> DelimToken {
1391 MacDelimiter::Parenthesis => DelimToken::Paren,
1392 MacDelimiter::Bracket => DelimToken::Bracket,
1393 MacDelimiter::Brace => DelimToken::Brace,
1398 /// Represents a macro definition.
1399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1400 pub struct MacroDef {
1401 pub tokens: TokenStream,
1402 /// `true` if macro was defined with `macro_rules`.
1407 pub fn stream(&self) -> TokenStream {
1408 self.tokens.clone().into()
1412 // Clippy uses Hash and PartialEq
1413 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
1415 /// A regular string, like `"foo"`.
1417 /// A raw string, like `r##"foo"##`.
1419 /// The value is the number of `#` symbols used.
1424 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1426 /// The original literal token as written in source code.
1427 pub token: token::Lit,
1428 /// The "semantic" representation of the literal lowered from the original tokens.
1429 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1430 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1435 /// Same as `Lit`, but restricted to string literals.
1436 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1438 /// The original literal token as written in source code.
1439 pub style: StrStyle,
1441 pub suffix: Option<Symbol>,
1443 /// The unescaped "semantic" representation of the literal lowered from the original token.
1444 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1445 pub symbol_unescaped: Symbol,
1449 crate fn as_lit(&self) -> Lit {
1450 let token_kind = match self.style {
1451 StrStyle::Cooked => token::Str,
1452 StrStyle::Raw(n) => token::StrRaw(n),
1455 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1457 kind: LitKind::Str(self.symbol_unescaped, self.style),
1462 // Clippy uses Hash and PartialEq
1463 /// Type of the integer literal based on provided suffix.
1464 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1465 pub enum LitIntType {
1474 /// Type of the float literal based on provided suffix.
1475 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1476 pub enum LitFloatType {
1477 /// A float literal with a suffix (`1f32` or `1E10f32`).
1479 /// A float literal without a suffix (`1.0 or 1.0E10`).
1485 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1486 // Clippy uses Hash and PartialEq
1487 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1489 /// A string literal (`"foo"`).
1490 Str(Symbol, StrStyle),
1491 /// A byte string (`b"foo"`).
1492 ByteStr(Lrc<Vec<u8>>),
1493 /// A byte char (`b'f'`).
1495 /// A character literal (`'a'`).
1497 /// An integer literal (`1`).
1498 Int(u128, LitIntType),
1499 /// A float literal (`1f64` or `1E10f64`).
1500 Float(Symbol, LitFloatType),
1501 /// A boolean literal.
1503 /// Placeholder for a literal that wasn't well-formed in some way.
1508 /// Returns `true` if this literal is a string.
1509 pub fn is_str(&self) -> bool {
1511 LitKind::Str(..) => true,
1516 /// Returns `true` if this literal is byte literal string.
1517 pub fn is_bytestr(&self) -> bool {
1519 LitKind::ByteStr(_) => true,
1524 /// Returns `true` if this is a numeric literal.
1525 pub fn is_numeric(&self) -> bool {
1527 LitKind::Int(..) | LitKind::Float(..) => true,
1532 /// Returns `true` if this literal has no suffix.
1533 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1534 pub fn is_unsuffixed(&self) -> bool {
1538 /// Returns `true` if this literal has a suffix.
1539 pub fn is_suffixed(&self) -> bool {
1541 // suffixed variants
1542 LitKind::Int(_, LitIntType::Signed(..))
1543 | LitKind::Int(_, LitIntType::Unsigned(..))
1544 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1545 // unsuffixed variants
1547 | LitKind::ByteStr(..)
1550 | LitKind::Int(_, LitIntType::Unsuffixed)
1551 | LitKind::Float(_, LitFloatType::Unsuffixed)
1553 | LitKind::Err(..) => false,
1558 // N.B., If you change this, you'll probably want to change the corresponding
1559 // type structure in `middle/ty.rs` as well.
1560 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1563 pub mutbl: Mutability,
1566 /// Represents a function's signature in a trait declaration,
1567 /// trait implementation, or free function.
1568 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1570 pub header: FnHeader,
1571 pub decl: P<FnDecl>,
1574 /// Represents an item declaration within a trait declaration,
1575 /// possibly including a default implementation. A trait item is
1576 /// either required (meaning it doesn't have an implementation, just a
1577 /// signature) or provided (meaning it has a default implementation).
1578 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1579 pub struct TraitItem {
1582 pub attrs: Vec<Attribute>,
1583 pub generics: Generics,
1584 pub kind: TraitItemKind,
1586 /// See `Item::tokens` for what this is.
1587 pub tokens: Option<TokenStream>,
1590 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1591 pub enum TraitItemKind {
1592 Const(P<Ty>, Option<P<Expr>>),
1593 Method(FnSig, Option<P<Block>>),
1594 Type(GenericBounds, Option<P<Ty>>),
1598 /// Represents anything within an `impl` block.
1599 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1600 pub struct ImplItem {
1603 pub vis: Visibility,
1604 pub defaultness: Defaultness,
1605 pub attrs: Vec<Attribute>,
1606 pub generics: Generics,
1607 pub kind: ImplItemKind,
1609 /// See `Item::tokens` for what this is.
1610 pub tokens: Option<TokenStream>,
1613 /// Represents various kinds of content within an `impl`.
1614 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1615 pub enum ImplItemKind {
1616 Const(P<Ty>, P<Expr>),
1617 Method(FnSig, P<Block>),
1622 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1623 RustcEncodable, RustcDecodable, Debug)]
1630 pub fn name_str(self) -> &'static str {
1632 FloatTy::F32 => "f32",
1633 FloatTy::F64 => "f64",
1637 pub fn name(self) -> Symbol {
1639 FloatTy::F32 => sym::f32,
1640 FloatTy::F64 => sym::f64,
1644 pub fn bit_width(self) -> usize {
1652 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1653 RustcEncodable, RustcDecodable, Debug)]
1664 pub fn name_str(&self) -> &'static str {
1666 IntTy::Isize => "isize",
1668 IntTy::I16 => "i16",
1669 IntTy::I32 => "i32",
1670 IntTy::I64 => "i64",
1671 IntTy::I128 => "i128",
1675 pub fn name(&self) -> Symbol {
1677 IntTy::Isize => sym::isize,
1678 IntTy::I8 => sym::i8,
1679 IntTy::I16 => sym::i16,
1680 IntTy::I32 => sym::i32,
1681 IntTy::I64 => sym::i64,
1682 IntTy::I128 => sym::i128,
1686 pub fn val_to_string(&self, val: i128) -> String {
1687 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1688 // are parsed as `u128`, so we wouldn't want to print an extra negative
1690 format!("{}{}", val as u128, self.name_str())
1693 pub fn bit_width(&self) -> Option<usize> {
1695 IntTy::Isize => return None,
1705 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1706 RustcEncodable, RustcDecodable, Copy, Debug)]
1717 pub fn name_str(&self) -> &'static str {
1719 UintTy::Usize => "usize",
1721 UintTy::U16 => "u16",
1722 UintTy::U32 => "u32",
1723 UintTy::U64 => "u64",
1724 UintTy::U128 => "u128",
1728 pub fn name(&self) -> Symbol {
1730 UintTy::Usize => sym::usize,
1731 UintTy::U8 => sym::u8,
1732 UintTy::U16 => sym::u16,
1733 UintTy::U32 => sym::u32,
1734 UintTy::U64 => sym::u64,
1735 UintTy::U128 => sym::u128,
1739 pub fn val_to_string(&self, val: u128) -> String {
1740 format!("{}{}", val, self.name_str())
1743 pub fn bit_width(&self) -> Option<usize> {
1745 UintTy::Usize => return None,
1750 UintTy::U128 => 128,
1755 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1756 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1757 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1758 pub struct AssocTyConstraint {
1761 pub kind: AssocTyConstraintKind,
1765 /// The kinds of an `AssocTyConstraint`.
1766 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1767 pub enum AssocTyConstraintKind {
1768 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1772 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1774 bounds: GenericBounds,
1778 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1785 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1786 pub struct BareFnTy {
1787 pub unsafety: Unsafety,
1789 pub generic_params: Vec<GenericParam>,
1790 pub decl: P<FnDecl>,
1793 /// The various kinds of type recognized by the compiler.
1794 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1796 /// A variable-length slice (`[T]`).
1798 /// A fixed length array (`[T; n]`).
1799 Array(P<Ty>, AnonConst),
1800 /// A raw pointer (`*const T` or `*mut T`).
1802 /// A reference (`&'a T` or `&'a mut T`).
1803 Rptr(Option<Lifetime>, MutTy),
1804 /// A bare function (e.g., `fn(usize) -> bool`).
1805 BareFn(P<BareFnTy>),
1806 /// The never type (`!`).
1808 /// A tuple (`(A, B, C, D,...)`).
1810 /// A path (`module::module::...::Type`), optionally
1811 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1813 /// Type parameters are stored in the `Path` itself.
1814 Path(Option<QSelf>, Path),
1815 /// A trait object type `Bound1 + Bound2 + Bound3`
1816 /// where `Bound` is a trait or a lifetime.
1817 TraitObject(GenericBounds, TraitObjectSyntax),
1818 /// An `impl Bound1 + Bound2 + Bound3` type
1819 /// where `Bound` is a trait or a lifetime.
1821 /// The `NodeId` exists to prevent lowering from having to
1822 /// generate `NodeId`s on the fly, which would complicate
1823 /// the generation of opaque `type Foo = impl Trait` items significantly.
1824 ImplTrait(NodeId, GenericBounds),
1825 /// No-op; kept solely so that we can pretty-print faithfully.
1829 /// This means the type should be inferred instead of it having been
1830 /// specified. This can appear anywhere in a type.
1832 /// Inferred type of a `self` or `&self` argument in a method.
1834 /// A macro in the type position.
1836 /// Placeholder for a kind that has failed to be defined.
1838 /// Placeholder for a `va_list`.
1843 pub fn is_implicit_self(&self) -> bool {
1844 if let TyKind::ImplicitSelf = *self {
1851 pub fn is_unit(&self) -> bool {
1852 if let TyKind::Tup(ref tys) = *self {
1859 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1860 /// in lowering to avoid making larger changes there and beyond.
1861 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1863 Self::ImplTrait(_, bounds) => Some(bounds),
1869 /// Syntax used to declare a trait object.
1870 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1871 pub enum TraitObjectSyntax {
1876 /// Inline assembly dialect.
1878 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1879 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1880 pub enum AsmDialect {
1885 /// Inline assembly.
1887 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1888 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1889 pub struct InlineAsmOutput {
1890 pub constraint: Symbol,
1893 pub is_indirect: bool,
1896 /// Inline assembly.
1898 /// E.g., `asm!("NOP");`.
1899 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1900 pub struct InlineAsm {
1902 pub asm_str_style: StrStyle,
1903 pub outputs: Vec<InlineAsmOutput>,
1904 pub inputs: Vec<(Symbol, P<Expr>)>,
1905 pub clobbers: Vec<Symbol>,
1907 pub alignstack: bool,
1908 pub dialect: AsmDialect,
1911 /// A parameter in a function header.
1913 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1914 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1916 pub attrs: ThinVec<Attribute>,
1921 pub is_placeholder: bool,
1924 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1926 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1927 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1929 /// `self`, `mut self`
1931 /// `&'lt self`, `&'lt mut self`
1932 Region(Option<Lifetime>, Mutability),
1933 /// `self: TYPE`, `mut self: TYPE`
1934 Explicit(P<Ty>, Mutability),
1937 pub type ExplicitSelf = Spanned<SelfKind>;
1940 /// Attempts to cast parameter to `ExplicitSelf`.
1941 pub fn to_self(&self) -> Option<ExplicitSelf> {
1942 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
1943 if ident.name == kw::SelfLower {
1944 return match self.ty.kind {
1945 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1946 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
1947 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1950 self.pat.span.to(self.ty.span),
1951 SelfKind::Explicit(self.ty.clone(), mutbl),
1959 /// Returns `true` if parameter is `self`.
1960 pub fn is_self(&self) -> bool {
1961 if let PatKind::Ident(_, ident, _) = self.pat.kind {
1962 ident.name == kw::SelfLower
1968 /// Builds a `Param` object from `ExplicitSelf`.
1969 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
1970 let span = eself.span.to(eself_ident.span);
1971 let infer_ty = P(Ty {
1973 kind: TyKind::ImplicitSelf,
1976 let param = |mutbl, ty| Param {
1980 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1986 is_placeholder: false
1989 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
1990 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
1991 SelfKind::Region(lt, mutbl) => param(
1992 Mutability::Immutable,
2009 /// A signature (not the body) of a function declaration.
2011 /// E.g., `fn foo(bar: baz)`.
2013 /// Please note that it's different from `FnHeader` structure
2014 /// which contains metadata about function safety, asyncness, constness and ABI.
2015 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2017 pub inputs: Vec<Param>,
2018 pub output: FunctionRetTy,
2022 pub fn get_self(&self) -> Option<ExplicitSelf> {
2023 self.inputs.get(0).and_then(Param::to_self)
2025 pub fn has_self(&self) -> bool {
2026 self.inputs.get(0).map_or(false, Param::is_self)
2028 pub fn c_variadic(&self) -> bool {
2029 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2030 TyKind::CVarArgs => true,
2036 /// Is the trait definition an auto trait?
2037 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2043 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2044 RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2051 pub fn prefix_str(&self) -> &'static str {
2053 Unsafety::Unsafe => "unsafe ",
2054 Unsafety::Normal => "",
2059 impl fmt::Display for Unsafety {
2060 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2063 Unsafety::Normal => "normal",
2064 Unsafety::Unsafe => "unsafe",
2071 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2075 return_impl_trait_id: NodeId,
2081 pub fn is_async(self) -> bool {
2082 if let IsAsync::Async { .. } = self {
2089 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2090 pub fn opt_return_id(self) -> Option<NodeId> {
2093 return_impl_trait_id,
2095 } => Some(return_impl_trait_id),
2096 IsAsync::NotAsync => None,
2101 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2102 pub enum Constness {
2107 /// Item defaultness.
2108 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2109 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2110 pub enum Defaultness {
2115 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2116 pub enum ImplPolarity {
2117 /// `impl Trait for Type`
2119 /// `impl !Trait for Type`
2123 impl fmt::Debug for ImplPolarity {
2124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2126 ImplPolarity::Positive => "positive".fmt(f),
2127 ImplPolarity::Negative => "negative".fmt(f),
2132 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2133 pub enum FunctionRetTy {
2134 /// Returns type is not specified.
2136 /// Functions default to `()` and closures default to inference.
2137 /// Span points to where return type would be inserted.
2139 /// Everything else.
2143 impl FunctionRetTy {
2144 pub fn span(&self) -> Span {
2146 FunctionRetTy::Default(span) => span,
2147 FunctionRetTy::Ty(ref ty) => ty.span,
2152 /// Module declaration.
2154 /// E.g., `mod foo;` or `mod foo { .. }`.
2155 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2157 /// A span from the first token past `{` to the last token until `}`.
2158 /// For `mod foo;`, the inner span ranges from the first token
2159 /// to the last token in the external file.
2161 pub items: Vec<P<Item>>,
2162 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2166 /// Foreign module declaration.
2168 /// E.g., `extern { .. }` or `extern C { .. }`.
2169 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2170 pub struct ForeignMod {
2171 pub abi: Option<StrLit>,
2172 pub items: Vec<ForeignItem>,
2175 /// Global inline assembly.
2177 /// Also known as "module-level assembly" or "file-scoped assembly".
2178 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2179 pub struct GlobalAsm {
2183 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2184 pub struct EnumDef {
2185 pub variants: Vec<Variant>,
2189 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2190 pub struct Variant {
2191 /// Name of the variant.
2193 /// Attributes of the variant.
2194 pub attrs: Vec<Attribute>,
2195 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2197 /// Fields and constructor id of the variant.
2198 pub data: VariantData,
2199 /// Explicit discriminant, e.g., `Foo = 1`.
2200 pub disr_expr: Option<AnonConst>,
2203 /// Is a macro placeholder
2204 pub is_placeholder: bool,
2207 /// Part of `use` item to the right of its prefix.
2208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2209 pub enum UseTreeKind {
2210 /// `use prefix` or `use prefix as rename`
2212 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2214 Simple(Option<Ident>, NodeId, NodeId),
2215 /// `use prefix::{...}`
2216 Nested(Vec<(UseTree, NodeId)>),
2221 /// A tree of paths sharing common prefixes.
2222 /// Used in `use` items both at top-level and inside of braces in import groups.
2223 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2224 pub struct UseTree {
2226 pub kind: UseTreeKind,
2231 pub fn ident(&self) -> Ident {
2233 UseTreeKind::Simple(Some(rename), ..) => rename,
2234 UseTreeKind::Simple(None, ..) => {
2238 .expect("empty prefix in a simple import")
2241 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2246 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2247 /// are contained as statements within items. These two cases need to be
2248 /// distinguished for pretty-printing.
2249 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2250 pub enum AttrStyle {
2255 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2256 pub struct AttrId(pub usize);
2258 impl Idx for AttrId {
2259 fn new(idx: usize) -> Self {
2262 fn index(self) -> usize {
2267 impl rustc_serialize::Encodable for AttrId {
2268 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2273 impl rustc_serialize::Decodable for AttrId {
2274 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2275 d.read_nil().map(|_| crate::attr::mk_attr_id())
2279 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2280 pub struct AttrItem {
2282 pub tokens: TokenStream,
2285 /// Metadata associated with an item.
2286 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2287 pub struct Attribute {
2290 /// Denotes if the attribute decorates the following construct (outer)
2291 /// or the construct this attribute is contained within (inner).
2292 pub style: AttrStyle,
2296 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2298 /// A normal attribute.
2301 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2302 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2303 /// variant (which is much less compact and thus more expensive).
2305 /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2306 /// for this variant, but this may change in the future.
2311 /// `TraitRef`s appear in impls.
2313 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2314 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2315 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2316 /// same as the impl's `NodeId`).
2317 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2318 pub struct TraitRef {
2323 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2324 pub struct PolyTraitRef {
2325 /// The `'a` in `<'a> Foo<&'a T>`.
2326 pub bound_generic_params: Vec<GenericParam>,
2328 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2329 pub trait_ref: TraitRef,
2335 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2337 bound_generic_params: generic_params,
2338 trait_ref: TraitRef {
2340 ref_id: DUMMY_NODE_ID,
2347 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2348 pub enum CrateSugar {
2349 /// Source is `pub(crate)`.
2352 /// Source is (just) `crate`.
2356 pub type Visibility = Spanned<VisibilityKind>;
2358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2359 pub enum VisibilityKind {
2362 Restricted { path: P<Path>, id: NodeId },
2366 impl VisibilityKind {
2367 pub fn is_pub(&self) -> bool {
2368 if let VisibilityKind::Public = *self {
2376 /// Field of a struct.
2378 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2379 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2380 pub struct StructField {
2382 pub ident: Option<Ident>,
2383 pub vis: Visibility,
2386 pub attrs: Vec<Attribute>,
2387 pub is_placeholder: bool,
2390 /// Fields and constructor ids of enum variants and structs.
2391 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2392 pub enum VariantData {
2395 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2396 Struct(Vec<StructField>, bool),
2399 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2400 Tuple(Vec<StructField>, NodeId),
2403 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2408 /// Return the fields of this variant.
2409 pub fn fields(&self) -> &[StructField] {
2411 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2416 /// Return the `NodeId` of this variant's constructor, if it has one.
2417 pub fn ctor_id(&self) -> Option<NodeId> {
2419 VariantData::Struct(..) => None,
2420 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2427 /// The name might be a dummy name in case of anonymous items.
2428 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2431 pub attrs: Vec<Attribute>,
2434 pub vis: Visibility,
2437 /// Original tokens this item was parsed from. This isn't necessarily
2438 /// available for all items, although over time more and more items should
2439 /// have this be `Some`. Right now this is primarily used for procedural
2440 /// macros, notably custom attributes.
2442 /// Note that the tokens here do not include the outer attributes, but will
2443 /// include inner attributes.
2444 pub tokens: Option<TokenStream>,
2448 /// Return the span that encompasses the attributes.
2449 pub fn span_with_attributes(&self) -> Span {
2450 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2454 /// `extern` qualifier on a function item or function type.
2455 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2463 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2464 abi.map_or(Extern::Implicit, Extern::Explicit)
2468 /// A function header.
2470 /// All the information between the visibility and the name of the function is
2471 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2472 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2473 pub struct FnHeader {
2474 pub unsafety: Unsafety,
2475 pub asyncness: Spanned<IsAsync>,
2476 pub constness: Spanned<Constness>,
2480 impl Default for FnHeader {
2481 fn default() -> FnHeader {
2483 unsafety: Unsafety::Normal,
2484 asyncness: dummy_spanned(IsAsync::NotAsync),
2485 constness: dummy_spanned(Constness::NotConst),
2491 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2493 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2495 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2496 ExternCrate(Option<Name>),
2497 /// A use declaration item (`use`).
2499 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2501 /// A static item (`static`).
2503 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2504 Static(P<Ty>, Mutability, P<Expr>),
2505 /// A constant item (`const`).
2507 /// E.g., `const FOO: i32 = 42;`.
2508 Const(P<Ty>, P<Expr>),
2509 /// A function declaration (`fn`).
2511 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2512 Fn(FnSig, Generics, P<Block>),
2513 /// A module declaration (`mod`).
2515 /// E.g., `mod foo;` or `mod foo { .. }`.
2517 /// An external module (`extern`).
2519 /// E.g., `extern {}` or `extern "C" {}`.
2520 ForeignMod(ForeignMod),
2521 /// Module-level inline assembly (from `global_asm!()`).
2522 GlobalAsm(P<GlobalAsm>),
2523 /// A type alias (`type`).
2525 /// E.g., `type Foo = Bar<u8>;`.
2526 TyAlias(P<Ty>, Generics),
2527 /// An enum definition (`enum`).
2529 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2530 Enum(EnumDef, Generics),
2531 /// A struct definition (`struct`).
2533 /// E.g., `struct Foo<A> { x: A }`.
2534 Struct(VariantData, Generics),
2535 /// A union definition (`union`).
2537 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2538 Union(VariantData, Generics),
2539 /// A trait declaration (`trait`).
2541 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2542 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2545 /// E.g., `trait Foo = Bar + Quux;`.
2546 TraitAlias(Generics, GenericBounds),
2547 /// An implementation.
2549 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2555 Option<TraitRef>, // (optional) trait this impl implements
2559 /// A macro invocation.
2561 /// E.g., `foo!(..)`.
2564 /// A macro definition.
2569 pub fn descriptive_variant(&self) -> &str {
2571 ItemKind::ExternCrate(..) => "extern crate",
2572 ItemKind::Use(..) => "use",
2573 ItemKind::Static(..) => "static item",
2574 ItemKind::Const(..) => "constant item",
2575 ItemKind::Fn(..) => "function",
2576 ItemKind::Mod(..) => "module",
2577 ItemKind::ForeignMod(..) => "foreign module",
2578 ItemKind::GlobalAsm(..) => "global asm",
2579 ItemKind::TyAlias(..) => "type alias",
2580 ItemKind::Enum(..) => "enum",
2581 ItemKind::Struct(..) => "struct",
2582 ItemKind::Union(..) => "union",
2583 ItemKind::Trait(..) => "trait",
2584 ItemKind::TraitAlias(..) => "trait alias",
2585 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2590 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2591 pub struct ForeignItem {
2593 pub attrs: Vec<Attribute>,
2594 pub kind: ForeignItemKind,
2597 pub vis: Visibility,
2600 /// An item within an `extern` block.
2601 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2602 pub enum ForeignItemKind {
2603 /// A foreign function.
2604 Fn(P<FnDecl>, Generics),
2605 /// A foreign static item (`static ext: u8`).
2606 Static(P<Ty>, Mutability),
2609 /// A macro invocation.
2613 impl ForeignItemKind {
2614 pub fn descriptive_variant(&self) -> &str {
2616 ForeignItemKind::Fn(..) => "foreign function",
2617 ForeignItemKind::Static(..) => "foreign static item",
2618 ForeignItemKind::Ty => "foreign type",
2619 ForeignItemKind::Macro(..) => "macro in foreign module",