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::sync::Lrc;
37 use rustc_data_structures::thin_vec::ThinVec;
38 use rustc_index::vec::Idx;
39 use rustc_serialize::{self, Decoder, Encoder};
46 /// A "Label" is an identifier of some point in sources,
47 /// e.g. in the following code:
55 /// `'outer` is a label.
56 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
61 impl fmt::Debug for Label {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "label({:?})", self.ident)
67 /// A "Lifetime" is an annotation of the scope in which variable
68 /// can be used, e.g. `'a` in `&'a i32`.
69 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
75 impl fmt::Debug for Lifetime {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 impl fmt::Display for Lifetime {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 write!(f, "{}", self.ident.name)
92 /// A "Path" is essentially Rust's notion of a name.
94 /// It's represented as a sequence of identifiers,
95 /// along with a bunch of supporting information.
97 /// E.g., `std::cmp::PartialEq`.
98 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
101 /// The segments in the path: the things separated by `::`.
102 /// Global paths begin with `kw::PathRoot`.
103 pub segments: Vec<PathSegment>,
106 impl PartialEq<Symbol> for Path {
107 fn eq(&self, symbol: &Symbol) -> bool {
108 self.segments.len() == 1 && {
109 self.segments[0].ident.name == *symbol
115 // Convert a span and an identifier to the corresponding
117 pub fn from_ident(ident: Ident) -> Path {
119 segments: vec![PathSegment::from_ident(ident)],
124 pub fn is_global(&self) -> bool {
125 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
129 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
131 /// E.g., `std`, `String` or `Box<T>`.
132 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
133 pub struct PathSegment {
134 /// The identifier portion of this path segment.
139 /// Type/lifetime parameters attached to this path. They come in
140 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
141 /// `None` means that no parameter list is supplied (`Path`),
142 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
143 /// but it can be empty (`Path<>`).
144 /// `P` is used as a size optimization for the common case with no parameters.
145 pub args: Option<P<GenericArgs>>,
149 pub fn from_ident(ident: Ident) -> Self {
150 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
152 pub fn path_root(span: Span) -> Self {
153 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
157 /// The arguments of a path segment.
159 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
160 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
161 pub enum GenericArgs {
162 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
163 AngleBracketed(AngleBracketedArgs),
164 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
165 Parenthesized(ParenthesizedArgs),
169 pub fn is_parenthesized(&self) -> bool {
171 Parenthesized(..) => true,
176 pub fn is_angle_bracketed(&self) -> bool {
178 AngleBracketed(..) => true,
183 pub fn span(&self) -> Span {
185 AngleBracketed(ref data) => data.span,
186 Parenthesized(ref data) => data.span,
191 /// Concrete argument in the sequence of generic args.
192 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
193 pub enum GenericArg {
194 /// `'a` in `Foo<'a>`
196 /// `Bar` in `Foo<Bar>`
203 pub fn span(&self) -> Span {
205 GenericArg::Lifetime(lt) => lt.ident.span,
206 GenericArg::Type(ty) => ty.span,
207 GenericArg::Const(ct) => ct.value.span,
212 /// A path like `Foo<'a, T>`.
213 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
214 pub struct AngleBracketedArgs {
215 /// The overall span.
217 /// The arguments for this path segment.
218 pub args: Vec<GenericArg>,
219 /// Constraints on associated types, if any.
220 /// E.g., `Foo<A = Bar, B: Baz>`.
221 pub constraints: Vec<AssocTyConstraint>,
224 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
225 fn into(self) -> Option<P<GenericArgs>> {
226 Some(P(GenericArgs::AngleBracketed(self)))
230 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
231 fn into(self) -> Option<P<GenericArgs>> {
232 Some(P(GenericArgs::Parenthesized(self)))
236 /// A path like `Foo(A, B) -> C`.
237 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
238 pub struct ParenthesizedArgs {
243 pub inputs: Vec<P<Ty>>,
246 pub output: Option<P<Ty>>,
249 impl ParenthesizedArgs {
250 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
253 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
259 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
261 use rustc_index::vec::Idx;
262 rustc_index::newtype_index! {
265 DEBUG_FORMAT = "NodeId({})"
270 pub use node_id_inner::NodeId;
273 pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self {
274 NodeId::from_u32(expn_id.as_u32())
277 pub fn placeholder_to_expn_id(self) -> ExpnId {
278 ExpnId::from_u32(self.as_u32())
282 impl fmt::Display for NodeId {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 fmt::Display::fmt(&self.as_u32(), f)
288 impl rustc_serialize::UseSpecializedEncodable for NodeId {
289 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
290 s.emit_u32(self.as_u32())
294 impl rustc_serialize::UseSpecializedDecodable for NodeId {
295 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
296 d.read_u32().map(NodeId::from_u32)
300 /// `NodeId` used to represent the root of the crate.
301 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
303 /// When parsing and doing expansions, we initially give all AST nodes this AST
304 /// node value. Then later, in the renumber pass, we renumber them to have
305 /// small, positive ids.
306 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
308 /// A modifier on a bound, currently this is only used for `?Sized`, where the
309 /// modifier is `Maybe`. Negative bounds should also be handled here.
310 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
311 pub enum TraitBoundModifier {
316 /// The AST represents all type param bounds as types.
317 /// `typeck::collect::compute_bounds` matches these against
318 /// the "special" built-in traits (see `middle::lang_items`) and
319 /// detects `Copy`, `Send` and `Sync`.
320 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
321 pub enum GenericBound {
322 Trait(PolyTraitRef, TraitBoundModifier),
327 pub fn span(&self) -> Span {
329 &GenericBound::Trait(ref t, ..) => t.span,
330 &GenericBound::Outlives(ref l) => l.ident.span,
335 pub type GenericBounds = Vec<GenericBound>;
337 /// Specifies the enforced ordering for generic parameters. In the future,
338 /// if we wanted to relax this order, we could override `PartialEq` and
339 /// `PartialOrd`, to allow the kinds to be unordered.
340 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
341 pub enum ParamKindOrd {
347 impl fmt::Display for ParamKindOrd {
348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 ParamKindOrd::Lifetime => "lifetime".fmt(f),
351 ParamKindOrd::Type => "type".fmt(f),
352 ParamKindOrd::Const => "const".fmt(f),
357 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
358 pub enum GenericParamKind {
359 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
361 Type { default: Option<P<Ty>> },
365 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
366 pub struct GenericParam {
369 pub attrs: ThinVec<Attribute>,
370 pub bounds: GenericBounds,
371 pub is_placeholder: bool,
372 pub kind: GenericParamKind,
375 /// Represents lifetime, type and const parameters attached to a declaration of
376 /// a function, enum, trait, etc.
377 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
378 pub struct Generics {
379 pub params: Vec<GenericParam>,
380 pub where_clause: WhereClause,
384 impl Default for Generics {
385 /// Creates an instance of `Generics`.
386 fn default() -> Generics {
389 where_clause: WhereClause {
390 predicates: Vec::new(),
398 /// A where-clause in a definition.
399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
400 pub struct WhereClause {
401 pub predicates: Vec<WherePredicate>,
405 /// A single predicate in a where-clause.
406 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
407 pub enum WherePredicate {
408 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
409 BoundPredicate(WhereBoundPredicate),
410 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
411 RegionPredicate(WhereRegionPredicate),
412 /// An equality predicate (unsupported).
413 EqPredicate(WhereEqPredicate),
416 impl WherePredicate {
417 pub fn span(&self) -> Span {
419 &WherePredicate::BoundPredicate(ref p) => p.span,
420 &WherePredicate::RegionPredicate(ref p) => p.span,
421 &WherePredicate::EqPredicate(ref p) => p.span,
428 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
429 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
430 pub struct WhereBoundPredicate {
432 /// Any generics from a `for` binding.
433 pub bound_generic_params: Vec<GenericParam>,
434 /// The type being bounded.
435 pub bounded_ty: P<Ty>,
436 /// Trait and lifetime bounds (`Clone + Send + 'static`).
437 pub bounds: GenericBounds,
440 /// A lifetime predicate.
442 /// E.g., `'a: 'b + 'c`.
443 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
444 pub struct WhereRegionPredicate {
446 pub lifetime: Lifetime,
447 pub bounds: GenericBounds,
450 /// An equality predicate (unsupported).
453 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
454 pub struct WhereEqPredicate {
461 /// The set of `MetaItem`s that define the compilation environment of the crate,
462 /// used to drive conditional compilation.
463 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
465 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
468 pub attrs: Vec<Attribute>,
472 /// Possible values inside of compile-time attribute lists.
474 /// E.g., the '..' in `#[name(..)]`.
475 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
476 pub enum NestedMetaItem {
477 /// A full MetaItem, for recursive meta items.
481 /// E.g., `"foo"`, `64`, `true`.
485 /// A spanned compile-time attribute item.
487 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
488 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
489 pub struct MetaItem {
491 pub kind: MetaItemKind,
495 /// A compile-time attribute item.
497 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
498 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
499 pub enum MetaItemKind {
502 /// E.g., `test` as in `#[test]`.
506 /// E.g., `derive(..)` as in `#[derive(..)]`.
507 List(Vec<NestedMetaItem>),
508 /// Name value meta item.
510 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
514 /// A block (`{ .. }`).
516 /// E.g., `{ .. }` as in `fn foo() { .. }`.
517 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
519 /// The statements in the block.
520 pub stmts: Vec<Stmt>,
522 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
523 pub rules: BlockCheckMode,
527 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
535 /// Attempt reparsing the pattern as a type.
536 /// This is intended for use by diagnostics.
537 pub fn to_ty(&self) -> Option<P<Ty>> {
538 let kind = match &self.kind {
539 // In a type expression `_` is an inference variable.
540 PatKind::Wild => TyKind::Infer,
541 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
542 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
543 TyKind::Path(None, Path::from_ident(*ident))
545 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
546 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
547 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
548 PatKind::Ref(pat, mutbl) => pat
550 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
551 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
552 // when `P` can be reparsed as a type `T`.
553 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
554 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
555 // assuming `T0` to `Tn` are all syntactically valid as types.
556 PatKind::Tuple(pats) => {
557 let mut tys = Vec::with_capacity(pats.len());
558 // FIXME(#48994) - could just be collected into an Option<Vec>
560 tys.push(pat.to_ty()?);
574 /// Walk top-down and call `it` in each place where a pattern occurs
575 /// starting with the root pattern `walk` is called on. If `it` returns
576 /// false then we will descend no further but siblings will be processed.
577 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
583 // Walk into the pattern associated with `Ident` (if any).
584 PatKind::Ident(_, _, Some(p)) => p.walk(it),
586 // Walk into each field of struct.
587 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
589 // Sequence of patterns.
590 PatKind::TupleStruct(_, s)
593 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
595 // Trivial wrappers over inner patterns.
598 | PatKind::Paren(s) => s.walk(it),
600 // These patterns do not contain subpatterns, skip.
607 | PatKind::Mac(_) => {},
611 /// Is this a `..` pattern?
612 pub fn is_rest(&self) -> bool {
614 PatKind::Rest => true,
620 /// A single field in a struct pattern
622 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
623 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
624 /// except is_shorthand is true
625 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
626 pub struct FieldPat {
627 /// The identifier for the field
629 /// The pattern the field is destructured to
631 pub is_shorthand: bool,
632 pub attrs: ThinVec<Attribute>,
635 pub is_placeholder: bool,
638 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
639 pub enum BindingMode {
644 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
646 Included(RangeSyntax),
650 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
651 pub enum RangeSyntax {
658 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
660 /// Represents a wildcard pattern (`_`).
663 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
664 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
665 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
666 /// during name resolution.
667 Ident(BindingMode, Ident, Option<P<Pat>>),
669 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
670 /// The `bool` is `true` in the presence of a `..`.
671 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
673 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
674 TupleStruct(Path, Vec<P<Pat>>),
676 /// An or-pattern `A | B | C`.
677 /// Invariant: `pats.len() >= 2`.
680 /// A possibly qualified path pattern.
681 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
682 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
683 /// only legally refer to associated constants.
684 Path(Option<QSelf>, Path),
686 /// A tuple pattern (`(a, b)`).
692 /// A reference pattern (e.g., `&mut (a, b)`).
693 Ref(P<Pat>, Mutability),
698 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
699 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
701 /// A slice pattern `[a, b, c]`.
704 /// A rest pattern `..`.
706 /// Syntactically it is valid anywhere.
708 /// Semantically however, it only has meaning immediately inside:
709 /// - a slice pattern: `[a, .., b]`,
710 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
711 /// - a tuple pattern: `(a, .., b)`,
712 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
714 /// In all of these cases, an additional restriction applies,
715 /// only one rest pattern may occur in the pattern sequences.
718 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
721 /// A macro pattern; pre-expansion.
726 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
728 pub enum Mutability {
734 /// Returns `MutMutable` only if both `self` and `other` are mutable.
735 pub fn and(self, other: Self) -> Self {
737 Mutability::Mutable => other,
738 Mutability::Immutable => Mutability::Immutable,
742 pub fn invert(self) -> Self {
744 Mutability::Mutable => Mutability::Immutable,
745 Mutability::Immutable => Mutability::Mutable,
749 pub fn prefix_str(&self) -> &'static str {
751 Mutability::Mutable => "mut ",
752 Mutability::Immutable => "",
757 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
759 /// The `+` operator (addition)
761 /// The `-` operator (subtraction)
763 /// The `*` operator (multiplication)
765 /// The `/` operator (division)
767 /// The `%` operator (modulus)
769 /// The `&&` operator (logical and)
771 /// The `||` operator (logical or)
773 /// The `^` operator (bitwise xor)
775 /// The `&` operator (bitwise and)
777 /// The `|` operator (bitwise or)
779 /// The `<<` operator (shift left)
781 /// The `>>` operator (shift right)
783 /// The `==` operator (equality)
785 /// The `<` operator (less than)
787 /// The `<=` operator (less than or equal to)
789 /// The `!=` operator (not equal to)
791 /// The `>=` operator (greater than or equal to)
793 /// The `>` operator (greater than)
798 pub fn to_string(&self) -> &'static str {
821 pub fn lazy(&self) -> bool {
823 BinOpKind::And | BinOpKind::Or => true,
828 pub fn is_shift(&self) -> bool {
830 BinOpKind::Shl | BinOpKind::Shr => true,
835 pub fn is_comparison(&self) -> bool {
837 // Note for developers: please keep this as is;
838 // we want compilation to fail if another variant is added.
840 Eq | Lt | Le | Ne | Gt | Ge => true,
841 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
845 /// Returns `true` if the binary operator takes its arguments by value
846 pub fn is_by_value(&self) -> bool {
847 !self.is_comparison()
851 pub type BinOp = Spanned<BinOpKind>;
855 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
856 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
858 /// The `*` operator for dereferencing
860 /// The `!` operator for logical inversion
862 /// The `-` operator for negation
867 /// Returns `true` if the unary operator takes its argument by value
868 pub fn is_by_value(u: UnOp) -> bool {
870 UnOp::Neg | UnOp::Not => true,
875 pub fn to_string(op: UnOp) -> &'static str {
885 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
893 pub fn add_trailing_semicolon(mut self) -> Self {
894 self.kind = match self.kind {
895 StmtKind::Expr(expr) => StmtKind::Semi(expr),
896 StmtKind::Mac(mac) => {
897 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
904 pub fn is_item(&self) -> bool {
906 StmtKind::Item(_) => true,
911 pub fn is_expr(&self) -> bool {
913 StmtKind::Expr(_) => true,
919 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
921 /// A local (let) binding.
923 /// An item definition.
925 /// Expr without trailing semi-colon.
927 /// Expr with a trailing semi-colon.
930 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
933 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
934 pub enum MacStmtStyle {
935 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
936 /// `foo!(...);`, `foo![...];`).
938 /// The macro statement had braces (e.g., `foo! { ... }`).
940 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
941 /// `foo!(...)`). All of these will end up being converted into macro
946 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
947 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
951 pub ty: Option<P<Ty>>,
952 /// Initializer expression to set the value, if any.
953 pub init: Option<P<Expr>>,
955 pub attrs: ThinVec<Attribute>,
958 /// An arm of a 'match'.
960 /// E.g., `0..=10 => { println!("match!") }` as in
964 /// 0..=10 => { println!("match!") },
965 /// _ => { println!("no match!") },
968 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
970 pub attrs: Vec<Attribute>,
971 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
973 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
974 pub guard: Option<P<Expr>>,
979 pub is_placeholder: bool,
982 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
983 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
988 pub is_shorthand: bool,
989 pub attrs: ThinVec<Attribute>,
991 pub is_placeholder: bool,
994 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
995 pub enum BlockCheckMode {
997 Unsafe(UnsafeSource),
1000 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1001 pub enum UnsafeSource {
1006 /// A constant (expression) that's not an item or associated item,
1007 /// but needs its own `DefId` for type-checking, const-eval, etc.
1008 /// These are usually found nested inside types (e.g., array lengths)
1009 /// or expressions (e.g., repeat counts), and also used to define
1010 /// explicit discriminant values for enum variants.
1011 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1012 pub struct AnonConst {
1018 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1023 pub attrs: ThinVec<Attribute>,
1026 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1027 #[cfg(target_arch = "x86_64")]
1028 rustc_data_structures::static_assert_size!(Expr, 96);
1031 /// Returns `true` if this expression would be valid somewhere that expects a value;
1032 /// for example, an `if` condition.
1033 pub fn returns(&self) -> bool {
1034 if let ExprKind::Block(ref block, _) = self.kind {
1035 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1037 Some(&StmtKind::Expr(_)) => true,
1038 Some(&StmtKind::Semi(ref expr)) => {
1039 if let ExprKind::Ret(_) = expr.kind {
1040 // Last statement is explicit return.
1046 // This is a block that doesn't end in either an implicit or explicit return.
1050 // This is not a block, it is a value.
1055 pub fn to_bound(&self) -> Option<GenericBound> {
1057 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1058 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1059 TraitBoundModifier::None,
1065 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1066 pub fn to_ty(&self) -> Option<P<Ty>> {
1067 let kind = match &self.kind {
1068 // Trivial conversions.
1069 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1070 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1072 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1074 ExprKind::AddrOf(mutbl, expr) => expr
1076 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1078 ExprKind::Repeat(expr, expr_len) => {
1079 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1082 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1084 ExprKind::Tup(exprs) => {
1087 .map(|expr| expr.to_ty())
1088 .collect::<Option<Vec<_>>>()?;
1092 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1093 // then type of result is trait object.
1094 // Othewise we don't assume the result type.
1095 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1096 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1097 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1103 // This expression doesn't look like a type syntactically.
1114 pub fn precedence(&self) -> ExprPrecedence {
1116 ExprKind::Box(_) => ExprPrecedence::Box,
1117 ExprKind::Array(_) => ExprPrecedence::Array,
1118 ExprKind::Call(..) => ExprPrecedence::Call,
1119 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1120 ExprKind::Tup(_) => ExprPrecedence::Tup,
1121 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1122 ExprKind::Unary(..) => ExprPrecedence::Unary,
1123 ExprKind::Lit(_) => ExprPrecedence::Lit,
1124 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1125 ExprKind::Let(..) => ExprPrecedence::Let,
1126 ExprKind::If(..) => ExprPrecedence::If,
1127 ExprKind::While(..) => ExprPrecedence::While,
1128 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1129 ExprKind::Loop(..) => ExprPrecedence::Loop,
1130 ExprKind::Match(..) => ExprPrecedence::Match,
1131 ExprKind::Closure(..) => ExprPrecedence::Closure,
1132 ExprKind::Block(..) => ExprPrecedence::Block,
1133 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1134 ExprKind::Async(..) => ExprPrecedence::Async,
1135 ExprKind::Await(..) => ExprPrecedence::Await,
1136 ExprKind::Assign(..) => ExprPrecedence::Assign,
1137 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1138 ExprKind::Field(..) => ExprPrecedence::Field,
1139 ExprKind::Index(..) => ExprPrecedence::Index,
1140 ExprKind::Range(..) => ExprPrecedence::Range,
1141 ExprKind::Path(..) => ExprPrecedence::Path,
1142 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1143 ExprKind::Break(..) => ExprPrecedence::Break,
1144 ExprKind::Continue(..) => ExprPrecedence::Continue,
1145 ExprKind::Ret(..) => ExprPrecedence::Ret,
1146 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1147 ExprKind::Mac(..) => ExprPrecedence::Mac,
1148 ExprKind::Struct(..) => ExprPrecedence::Struct,
1149 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1150 ExprKind::Paren(..) => ExprPrecedence::Paren,
1151 ExprKind::Try(..) => ExprPrecedence::Try,
1152 ExprKind::Yield(..) => ExprPrecedence::Yield,
1153 ExprKind::Err => ExprPrecedence::Err,
1158 /// Limit types of a range (inclusive or exclusive)
1159 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1160 pub enum RangeLimits {
1161 /// Inclusive at the beginning, exclusive at the end
1163 /// Inclusive at the beginning and end
1167 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1169 /// A `box x` expression.
1171 /// An array (`[a, b, c, d]`)
1172 Array(Vec<P<Expr>>),
1175 /// The first field resolves to the function itself,
1176 /// and the second field is the list of arguments.
1177 /// This also represents calling the constructor of
1178 /// tuple-like ADTs such as tuple structs and enum variants.
1179 Call(P<Expr>, Vec<P<Expr>>),
1180 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1182 /// The `PathSegment` represents the method name and its generic arguments
1183 /// (within the angle brackets).
1184 /// The first element of the vector of an `Expr` is the expression that evaluates
1185 /// to the object on which the method is being called on (the receiver),
1186 /// and the remaining elements are the rest of the arguments.
1187 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1188 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1189 MethodCall(PathSegment, Vec<P<Expr>>),
1190 /// A tuple (e.g., `(a, b, c, d)`).
1192 /// A binary operation (e.g., `a + b`, `a * b`).
1193 Binary(BinOp, P<Expr>, P<Expr>),
1194 /// A unary operation (e.g., `!x`, `*x`).
1195 Unary(UnOp, P<Expr>),
1196 /// A literal (e.g., `1`, `"foo"`).
1198 /// A cast (e.g., `foo as f64`).
1199 Cast(P<Expr>, P<Ty>),
1200 /// A type ascription (e.g., `42: usize`).
1201 Type(P<Expr>, P<Ty>),
1202 /// A `let pat = expr` expression that is only semantically allowed in the condition
1203 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1204 Let(P<Pat>, P<Expr>),
1205 /// An `if` block, with an optional `else` block.
1207 /// `if expr { block } else { expr }`
1208 If(P<Expr>, P<Block>, Option<P<Expr>>),
1209 /// A while loop, with an optional label.
1211 /// `'label: while expr { block }`
1212 While(P<Expr>, P<Block>, Option<Label>),
1213 /// A `for` loop, with an optional label.
1215 /// `'label: for pat in expr { block }`
1217 /// This is desugared to a combination of `loop` and `match` expressions.
1218 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1219 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1221 /// `'label: loop { block }`
1222 Loop(P<Block>, Option<Label>),
1223 /// A `match` block.
1224 Match(P<Expr>, Vec<Arm>),
1225 /// A closure (e.g., `move |a, b, c| a + b + c`).
1227 /// The final span is the span of the argument block `|...|`.
1228 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1229 /// A block (`'label: { ... }`).
1230 Block(P<Block>, Option<Label>),
1231 /// An async block (`async move { ... }`).
1233 /// The `NodeId` is the `NodeId` for the closure that results from
1234 /// desugaring an async block, just like the NodeId field in the
1235 /// `IsAsync` enum. This is necessary in order to create a def for the
1236 /// closure which can be used as a parent of any child defs. Defs
1237 /// created during lowering cannot be made the parent of any other
1238 /// preexisting defs.
1239 Async(CaptureBy, NodeId, P<Block>),
1240 /// An await expression (`my_future.await`).
1243 /// A try block (`try { ... }`).
1246 /// An assignment (`a = foo()`).
1247 Assign(P<Expr>, P<Expr>),
1248 /// An assignment with an operator.
1251 AssignOp(BinOp, P<Expr>, P<Expr>),
1252 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1253 Field(P<Expr>, Ident),
1254 /// An indexing operation (e.g., `foo[2]`).
1255 Index(P<Expr>, P<Expr>),
1256 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1257 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1259 /// Variable reference, possibly containing `::` and/or type
1260 /// parameters (e.g., `foo::bar::<baz>`).
1262 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1263 Path(Option<QSelf>, Path),
1265 /// A referencing operation (`&a` or `&mut a`).
1266 AddrOf(Mutability, P<Expr>),
1267 /// A `break`, with an optional label to break, and an optional expression.
1268 Break(Option<Label>, Option<P<Expr>>),
1269 /// A `continue`, with an optional label.
1270 Continue(Option<Label>),
1271 /// A `return`, with an optional value to be returned.
1272 Ret(Option<P<Expr>>),
1274 /// Output of the `asm!()` macro.
1275 InlineAsm(P<InlineAsm>),
1277 /// A macro invocation; pre-expansion.
1280 /// A struct literal expression.
1282 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1283 /// where `base` is the `Option<Expr>`.
1284 Struct(Path, Vec<Field>, Option<P<Expr>>),
1286 /// An array literal constructed from one repeated element.
1288 /// E.g., `[1; 5]`. The expression is the element to be
1289 /// repeated; the constant is the number of times to repeat it.
1290 Repeat(P<Expr>, AnonConst),
1292 /// No-op: used solely so we can pretty-print faithfully.
1295 /// A try expression (`expr?`).
1298 /// A `yield`, with an optional value to be yielded.
1299 Yield(Option<P<Expr>>),
1301 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1305 /// The explicit `Self` type in a "qualified path". The actual
1306 /// path, including the trait and the associated item, is stored
1307 /// separately. `position` represents the index of the associated
1308 /// item qualified with this `Self` type.
1310 /// ```ignore (only-for-syntax-highlight)
1311 /// <Vec<T> as a::b::Trait>::AssociatedItem
1312 /// ^~~~~ ~~~~~~~~~~~~~~^
1315 /// <Vec<T>>::AssociatedItem
1319 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1323 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1324 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1325 /// 0`, this is an empty span.
1326 pub path_span: Span,
1327 pub position: usize,
1330 /// A capture clause used in closures and `async` blocks.
1331 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1332 pub enum CaptureBy {
1333 /// `move |x| y + x`.
1335 /// `move` keyword was not specified.
1339 /// The movability of a generator / closure literal:
1340 /// whether a generator contains self-references, causing it to be `!Unpin`.
1341 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
1342 RustcEncodable, RustcDecodable, Debug, Copy)]
1343 pub enum Movability {
1344 /// May contain self-references, `!Unpin`.
1346 /// Must not contain self-references, `Unpin`.
1350 /// Represents a macro invocation. The `Path` indicates which macro
1351 /// is being invoked, and the vector of token-trees contains the source
1352 /// of the macro invocation.
1354 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1355 /// stored in the enclosing item.
1356 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1359 pub delim: MacDelimiter,
1360 pub tts: TokenStream,
1362 pub prior_type_ascription: Option<(Span, bool)>,
1365 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1366 pub enum MacDelimiter {
1373 pub fn stream(&self) -> TokenStream {
1379 crate fn to_token(self) -> DelimToken {
1381 MacDelimiter::Parenthesis => DelimToken::Paren,
1382 MacDelimiter::Bracket => DelimToken::Bracket,
1383 MacDelimiter::Brace => DelimToken::Brace,
1388 /// Represents a macro definition.
1389 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1390 pub struct MacroDef {
1391 pub tokens: TokenStream,
1392 /// `true` if macro was defined with `macro_rules`.
1397 pub fn stream(&self) -> TokenStream {
1398 self.tokens.clone().into()
1402 // Clippy uses Hash and PartialEq
1403 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1405 /// A regular string, like `"foo"`.
1407 /// A raw string, like `r##"foo"##`.
1409 /// The value is the number of `#` symbols used.
1414 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1416 /// The original literal token as written in source code.
1417 pub token: token::Lit,
1418 /// The "semantic" representation of the literal lowered from the original tokens.
1419 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1420 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1425 /// Same as `Lit`, but restricted to string literals.
1426 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1428 /// The original literal token as written in source code.
1429 pub style: StrStyle,
1431 pub suffix: Option<Symbol>,
1433 /// The unescaped "semantic" representation of the literal lowered from the original token.
1434 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1435 pub symbol_unescaped: Symbol,
1439 crate fn as_lit(&self) -> Lit {
1440 let token_kind = match self.style {
1441 StrStyle::Cooked => token::Str,
1442 StrStyle::Raw(n) => token::StrRaw(n),
1445 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1447 kind: LitKind::Str(self.symbol_unescaped, self.style),
1452 // Clippy uses Hash and PartialEq
1453 /// Type of the integer literal based on provided suffix.
1454 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1455 pub enum LitIntType {
1464 /// Type of the float literal based on provided suffix.
1465 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1466 pub enum LitFloatType {
1467 /// A float literal with a suffix (`1f32` or `1E10f32`).
1469 /// A float literal without a suffix (`1.0 or 1.0E10`).
1475 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1476 // Clippy uses Hash and PartialEq
1477 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1479 /// A string literal (`"foo"`).
1480 Str(Symbol, StrStyle),
1481 /// A byte string (`b"foo"`).
1482 ByteStr(Lrc<Vec<u8>>),
1483 /// A byte char (`b'f'`).
1485 /// A character literal (`'a'`).
1487 /// An integer literal (`1`).
1488 Int(u128, LitIntType),
1489 /// A float literal (`1f64` or `1E10f64`).
1490 Float(Symbol, LitFloatType),
1491 /// A boolean literal.
1493 /// Placeholder for a literal that wasn't well-formed in some way.
1498 /// Returns `true` if this literal is a string.
1499 pub fn is_str(&self) -> bool {
1501 LitKind::Str(..) => true,
1506 /// Returns `true` if this literal is byte literal string.
1507 pub fn is_bytestr(&self) -> bool {
1509 LitKind::ByteStr(_) => true,
1514 /// Returns `true` if this is a numeric literal.
1515 pub fn is_numeric(&self) -> bool {
1517 LitKind::Int(..) | LitKind::Float(..) => true,
1522 /// Returns `true` if this literal has no suffix.
1523 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1524 pub fn is_unsuffixed(&self) -> bool {
1528 /// Returns `true` if this literal has a suffix.
1529 pub fn is_suffixed(&self) -> bool {
1531 // suffixed variants
1532 LitKind::Int(_, LitIntType::Signed(..))
1533 | LitKind::Int(_, LitIntType::Unsigned(..))
1534 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1535 // unsuffixed variants
1537 | LitKind::ByteStr(..)
1540 | LitKind::Int(_, LitIntType::Unsuffixed)
1541 | LitKind::Float(_, LitFloatType::Unsuffixed)
1543 | LitKind::Err(..) => false,
1548 // N.B., If you change this, you'll probably want to change the corresponding
1549 // type structure in `middle/ty.rs` as well.
1550 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1553 pub mutbl: Mutability,
1556 /// Represents a function's signature in a trait declaration,
1557 /// trait implementation, or free function.
1558 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1560 pub header: FnHeader,
1561 pub decl: P<FnDecl>,
1564 /// Represents an item declaration within a trait declaration,
1565 /// possibly including a default implementation. A trait item is
1566 /// either required (meaning it doesn't have an implementation, just a
1567 /// signature) or provided (meaning it has a default implementation).
1568 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1569 pub struct TraitItem {
1572 pub attrs: Vec<Attribute>,
1573 pub generics: Generics,
1574 pub kind: TraitItemKind,
1576 /// See `Item::tokens` for what this is.
1577 pub tokens: Option<TokenStream>,
1580 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1581 pub enum TraitItemKind {
1582 Const(P<Ty>, Option<P<Expr>>),
1583 Method(FnSig, Option<P<Block>>),
1584 Type(GenericBounds, Option<P<Ty>>),
1588 /// Represents anything within an `impl` block.
1589 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1590 pub struct ImplItem {
1593 pub vis: Visibility,
1594 pub defaultness: Defaultness,
1595 pub attrs: Vec<Attribute>,
1596 pub generics: Generics,
1597 pub kind: ImplItemKind,
1599 /// See `Item::tokens` for what this is.
1600 pub tokens: Option<TokenStream>,
1603 /// Represents various kinds of content within an `impl`.
1604 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1605 pub enum ImplItemKind {
1606 Const(P<Ty>, P<Expr>),
1607 Method(FnSig, P<Block>),
1612 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
1619 pub fn name_str(self) -> &'static str {
1621 FloatTy::F32 => "f32",
1622 FloatTy::F64 => "f64",
1626 pub fn name(self) -> Symbol {
1628 FloatTy::F32 => sym::f32,
1629 FloatTy::F64 => sym::f64,
1633 pub fn bit_width(self) -> usize {
1641 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
1652 pub fn name_str(&self) -> &'static str {
1654 IntTy::Isize => "isize",
1656 IntTy::I16 => "i16",
1657 IntTy::I32 => "i32",
1658 IntTy::I64 => "i64",
1659 IntTy::I128 => "i128",
1663 pub fn name(&self) -> Symbol {
1665 IntTy::Isize => sym::isize,
1666 IntTy::I8 => sym::i8,
1667 IntTy::I16 => sym::i16,
1668 IntTy::I32 => sym::i32,
1669 IntTy::I64 => sym::i64,
1670 IntTy::I128 => sym::i128,
1674 pub fn val_to_string(&self, val: i128) -> String {
1675 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1676 // are parsed as `u128`, so we wouldn't want to print an extra negative
1678 format!("{}{}", val as u128, self.name_str())
1681 pub fn bit_width(&self) -> Option<usize> {
1683 IntTy::Isize => return None,
1693 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy, Debug)]
1704 pub fn name_str(&self) -> &'static str {
1706 UintTy::Usize => "usize",
1708 UintTy::U16 => "u16",
1709 UintTy::U32 => "u32",
1710 UintTy::U64 => "u64",
1711 UintTy::U128 => "u128",
1715 pub fn name(&self) -> Symbol {
1717 UintTy::Usize => sym::usize,
1718 UintTy::U8 => sym::u8,
1719 UintTy::U16 => sym::u16,
1720 UintTy::U32 => sym::u32,
1721 UintTy::U64 => sym::u64,
1722 UintTy::U128 => sym::u128,
1726 pub fn val_to_string(&self, val: u128) -> String {
1727 format!("{}{}", val, self.name_str())
1730 pub fn bit_width(&self) -> Option<usize> {
1732 UintTy::Usize => return None,
1737 UintTy::U128 => 128,
1742 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1743 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1744 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1745 pub struct AssocTyConstraint {
1748 pub kind: AssocTyConstraintKind,
1752 /// The kinds of an `AssocTyConstraint`.
1753 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1754 pub enum AssocTyConstraintKind {
1755 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1759 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1761 bounds: GenericBounds,
1765 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1772 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1773 pub struct BareFnTy {
1774 pub unsafety: Unsafety,
1776 pub generic_params: Vec<GenericParam>,
1777 pub decl: P<FnDecl>,
1780 /// The various kinds of type recognized by the compiler.
1781 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1783 /// A variable-length slice (`[T]`).
1785 /// A fixed length array (`[T; n]`).
1786 Array(P<Ty>, AnonConst),
1787 /// A raw pointer (`*const T` or `*mut T`).
1789 /// A reference (`&'a T` or `&'a mut T`).
1790 Rptr(Option<Lifetime>, MutTy),
1791 /// A bare function (e.g., `fn(usize) -> bool`).
1792 BareFn(P<BareFnTy>),
1793 /// The never type (`!`).
1795 /// A tuple (`(A, B, C, D,...)`).
1797 /// A path (`module::module::...::Type`), optionally
1798 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1800 /// Type parameters are stored in the `Path` itself.
1801 Path(Option<QSelf>, Path),
1802 /// A trait object type `Bound1 + Bound2 + Bound3`
1803 /// where `Bound` is a trait or a lifetime.
1804 TraitObject(GenericBounds, TraitObjectSyntax),
1805 /// An `impl Bound1 + Bound2 + Bound3` type
1806 /// where `Bound` is a trait or a lifetime.
1808 /// The `NodeId` exists to prevent lowering from having to
1809 /// generate `NodeId`s on the fly, which would complicate
1810 /// the generation of opaque `type Foo = impl Trait` items significantly.
1811 ImplTrait(NodeId, GenericBounds),
1812 /// No-op; kept solely so that we can pretty-print faithfully.
1816 /// This means the type should be inferred instead of it having been
1817 /// specified. This can appear anywhere in a type.
1819 /// Inferred type of a `self` or `&self` argument in a method.
1821 /// A macro in the type position.
1823 /// Placeholder for a kind that has failed to be defined.
1825 /// Placeholder for a `va_list`.
1830 pub fn is_implicit_self(&self) -> bool {
1831 if let TyKind::ImplicitSelf = *self {
1838 pub fn is_unit(&self) -> bool {
1839 if let TyKind::Tup(ref tys) = *self {
1846 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1847 /// in lowering to avoid making larger changes there and beyond.
1848 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1850 Self::ImplTrait(_, bounds) => Some(bounds),
1856 /// Syntax used to declare a trait object.
1857 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1858 pub enum TraitObjectSyntax {
1863 /// Inline assembly dialect.
1865 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1866 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1867 pub enum AsmDialect {
1872 /// Inline assembly.
1874 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1875 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1876 pub struct InlineAsmOutput {
1877 pub constraint: Symbol,
1880 pub is_indirect: bool,
1883 /// Inline assembly.
1885 /// E.g., `asm!("NOP");`.
1886 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1887 pub struct InlineAsm {
1889 pub asm_str_style: StrStyle,
1890 pub outputs: Vec<InlineAsmOutput>,
1891 pub inputs: Vec<(Symbol, P<Expr>)>,
1892 pub clobbers: Vec<Symbol>,
1894 pub alignstack: bool,
1895 pub dialect: AsmDialect,
1898 /// A parameter in a function header.
1900 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1901 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1903 pub attrs: ThinVec<Attribute>,
1908 pub is_placeholder: bool,
1911 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1913 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1914 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1916 /// `self`, `mut self`
1918 /// `&'lt self`, `&'lt mut self`
1919 Region(Option<Lifetime>, Mutability),
1920 /// `self: TYPE`, `mut self: TYPE`
1921 Explicit(P<Ty>, Mutability),
1924 pub type ExplicitSelf = Spanned<SelfKind>;
1927 /// Attempts to cast parameter to `ExplicitSelf`.
1928 pub fn to_self(&self) -> Option<ExplicitSelf> {
1929 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
1930 if ident.name == kw::SelfLower {
1931 return match self.ty.kind {
1932 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1933 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
1934 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1937 self.pat.span.to(self.ty.span),
1938 SelfKind::Explicit(self.ty.clone(), mutbl),
1946 /// Returns `true` if parameter is `self`.
1947 pub fn is_self(&self) -> bool {
1948 if let PatKind::Ident(_, ident, _) = self.pat.kind {
1949 ident.name == kw::SelfLower
1955 /// Builds a `Param` object from `ExplicitSelf`.
1956 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
1957 let span = eself.span.to(eself_ident.span);
1958 let infer_ty = P(Ty {
1960 kind: TyKind::ImplicitSelf,
1963 let param = |mutbl, ty| Param {
1967 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1973 is_placeholder: false
1976 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
1977 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
1978 SelfKind::Region(lt, mutbl) => param(
1979 Mutability::Immutable,
1996 /// A signature (not the body) of a function declaration.
1998 /// E.g., `fn foo(bar: baz)`.
2000 /// Please note that it's different from `FnHeader` structure
2001 /// which contains metadata about function safety, asyncness, constness and ABI.
2002 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2004 pub inputs: Vec<Param>,
2005 pub output: FunctionRetTy,
2009 pub fn get_self(&self) -> Option<ExplicitSelf> {
2010 self.inputs.get(0).and_then(Param::to_self)
2012 pub fn has_self(&self) -> bool {
2013 self.inputs.get(0).map_or(false, Param::is_self)
2015 pub fn c_variadic(&self) -> bool {
2016 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2017 TyKind::CVarArgs => true,
2023 /// Is the trait definition an auto trait?
2024 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2030 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2031 RustcEncodable, RustcDecodable, Debug)]
2038 pub fn prefix_str(&self) -> &'static str {
2040 Unsafety::Unsafe => "unsafe ",
2041 Unsafety::Normal => "",
2046 impl fmt::Display for Unsafety {
2047 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2050 Unsafety::Normal => "normal",
2051 Unsafety::Unsafe => "unsafe",
2058 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2062 return_impl_trait_id: NodeId,
2068 pub fn is_async(self) -> bool {
2069 if let IsAsync::Async { .. } = self {
2076 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2077 pub fn opt_return_id(self) -> Option<NodeId> {
2080 return_impl_trait_id,
2082 } => Some(return_impl_trait_id),
2083 IsAsync::NotAsync => None,
2088 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2089 pub enum Constness {
2094 /// Item defaultness.
2095 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2096 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2097 pub enum Defaultness {
2102 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
2103 pub enum ImplPolarity {
2104 /// `impl Trait for Type`
2106 /// `impl !Trait for Type`
2110 impl fmt::Debug for ImplPolarity {
2111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2113 ImplPolarity::Positive => "positive".fmt(f),
2114 ImplPolarity::Negative => "negative".fmt(f),
2119 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2120 pub enum FunctionRetTy {
2121 /// Returns type is not specified.
2123 /// Functions default to `()` and closures default to inference.
2124 /// Span points to where return type would be inserted.
2126 /// Everything else.
2130 impl FunctionRetTy {
2131 pub fn span(&self) -> Span {
2133 FunctionRetTy::Default(span) => span,
2134 FunctionRetTy::Ty(ref ty) => ty.span,
2139 /// Module declaration.
2141 /// E.g., `mod foo;` or `mod foo { .. }`.
2142 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2144 /// A span from the first token past `{` to the last token until `}`.
2145 /// For `mod foo;`, the inner span ranges from the first token
2146 /// to the last token in the external file.
2148 pub items: Vec<P<Item>>,
2149 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2153 /// Foreign module declaration.
2155 /// E.g., `extern { .. }` or `extern C { .. }`.
2156 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2157 pub struct ForeignMod {
2158 pub abi: Option<StrLit>,
2159 pub items: Vec<ForeignItem>,
2162 /// Global inline assembly.
2164 /// Also known as "module-level assembly" or "file-scoped assembly".
2165 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2166 pub struct GlobalAsm {
2170 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2171 pub struct EnumDef {
2172 pub variants: Vec<Variant>,
2176 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2177 pub struct Variant {
2178 /// Name of the variant.
2180 /// Attributes of the variant.
2181 pub attrs: Vec<Attribute>,
2182 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2184 /// Fields and constructor id of the variant.
2185 pub data: VariantData,
2186 /// Explicit discriminant, e.g., `Foo = 1`.
2187 pub disr_expr: Option<AnonConst>,
2190 /// Is a macro placeholder
2191 pub is_placeholder: bool,
2194 /// Part of `use` item to the right of its prefix.
2195 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2196 pub enum UseTreeKind {
2197 /// `use prefix` or `use prefix as rename`
2199 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2201 Simple(Option<Ident>, NodeId, NodeId),
2202 /// `use prefix::{...}`
2203 Nested(Vec<(UseTree, NodeId)>),
2208 /// A tree of paths sharing common prefixes.
2209 /// Used in `use` items both at top-level and inside of braces in import groups.
2210 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2211 pub struct UseTree {
2213 pub kind: UseTreeKind,
2218 pub fn ident(&self) -> Ident {
2220 UseTreeKind::Simple(Some(rename), ..) => rename,
2221 UseTreeKind::Simple(None, ..) => {
2225 .expect("empty prefix in a simple import")
2228 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2233 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2234 /// are contained as statements within items. These two cases need to be
2235 /// distinguished for pretty-printing.
2236 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2237 pub enum AttrStyle {
2242 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2243 pub struct AttrId(pub usize);
2245 impl Idx for AttrId {
2246 fn new(idx: usize) -> Self {
2249 fn index(self) -> usize {
2254 impl rustc_serialize::Encodable for AttrId {
2255 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2260 impl rustc_serialize::Decodable for AttrId {
2261 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2262 d.read_nil().map(|_| crate::attr::mk_attr_id())
2266 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2267 pub struct AttrItem {
2269 pub tokens: TokenStream,
2272 /// Metadata associated with an item.
2273 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2274 pub struct Attribute {
2277 /// Denotes if the attribute decorates the following construct (outer)
2278 /// or the construct this attribute is contained within (inner).
2279 pub style: AttrStyle,
2283 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2285 /// A normal attribute.
2288 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2289 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2290 /// variant (which is much less compact and thus more expensive).
2292 /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2293 /// for this variant, but this may change in the future.
2298 /// `TraitRef`s appear in impls.
2300 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2301 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2302 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2303 /// same as the impl's `NodeId`).
2304 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2305 pub struct TraitRef {
2310 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2311 pub struct PolyTraitRef {
2312 /// The `'a` in `<'a> Foo<&'a T>`.
2313 pub bound_generic_params: Vec<GenericParam>,
2315 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2316 pub trait_ref: TraitRef,
2322 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2324 bound_generic_params: generic_params,
2325 trait_ref: TraitRef {
2327 ref_id: DUMMY_NODE_ID,
2334 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2335 pub enum CrateSugar {
2336 /// Source is `pub(crate)`.
2339 /// Source is (just) `crate`.
2343 pub type Visibility = Spanned<VisibilityKind>;
2345 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2346 pub enum VisibilityKind {
2349 Restricted { path: P<Path>, id: NodeId },
2353 impl VisibilityKind {
2354 pub fn is_pub(&self) -> bool {
2355 if let VisibilityKind::Public = *self {
2363 /// Field of a struct.
2365 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2366 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2367 pub struct StructField {
2369 pub ident: Option<Ident>,
2370 pub vis: Visibility,
2373 pub attrs: Vec<Attribute>,
2374 pub is_placeholder: bool,
2377 /// Fields and constructor ids of enum variants and structs.
2378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2379 pub enum VariantData {
2382 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2383 Struct(Vec<StructField>, bool),
2386 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2387 Tuple(Vec<StructField>, NodeId),
2390 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2395 /// Return the fields of this variant.
2396 pub fn fields(&self) -> &[StructField] {
2398 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2403 /// Return the `NodeId` of this variant's constructor, if it has one.
2404 pub fn ctor_id(&self) -> Option<NodeId> {
2406 VariantData::Struct(..) => None,
2407 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2414 /// The name might be a dummy name in case of anonymous items.
2415 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2418 pub attrs: Vec<Attribute>,
2421 pub vis: Visibility,
2424 /// Original tokens this item was parsed from. This isn't necessarily
2425 /// available for all items, although over time more and more items should
2426 /// have this be `Some`. Right now this is primarily used for procedural
2427 /// macros, notably custom attributes.
2429 /// Note that the tokens here do not include the outer attributes, but will
2430 /// include inner attributes.
2431 pub tokens: Option<TokenStream>,
2435 /// Return the span that encompasses the attributes.
2436 pub fn span_with_attributes(&self) -> Span {
2437 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2441 /// `extern` qualifier on a function item or function type.
2442 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2450 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2451 abi.map_or(Extern::Implicit, Extern::Explicit)
2455 /// A function header.
2457 /// All the information between the visibility and the name of the function is
2458 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2459 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2460 pub struct FnHeader {
2461 pub unsafety: Unsafety,
2462 pub asyncness: Spanned<IsAsync>,
2463 pub constness: Spanned<Constness>,
2467 impl Default for FnHeader {
2468 fn default() -> FnHeader {
2470 unsafety: Unsafety::Normal,
2471 asyncness: dummy_spanned(IsAsync::NotAsync),
2472 constness: dummy_spanned(Constness::NotConst),
2478 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2480 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2482 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2483 ExternCrate(Option<Name>),
2484 /// A use declaration item (`use`).
2486 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2488 /// A static item (`static`).
2490 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2491 Static(P<Ty>, Mutability, P<Expr>),
2492 /// A constant item (`const`).
2494 /// E.g., `const FOO: i32 = 42;`.
2495 Const(P<Ty>, P<Expr>),
2496 /// A function declaration (`fn`).
2498 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2499 Fn(FnSig, Generics, P<Block>),
2500 /// A module declaration (`mod`).
2502 /// E.g., `mod foo;` or `mod foo { .. }`.
2504 /// An external module (`extern`).
2506 /// E.g., `extern {}` or `extern "C" {}`.
2507 ForeignMod(ForeignMod),
2508 /// Module-level inline assembly (from `global_asm!()`).
2509 GlobalAsm(P<GlobalAsm>),
2510 /// A type alias (`type`).
2512 /// E.g., `type Foo = Bar<u8>;`.
2513 TyAlias(P<Ty>, Generics),
2514 /// An enum definition (`enum`).
2516 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2517 Enum(EnumDef, Generics),
2518 /// A struct definition (`struct`).
2520 /// E.g., `struct Foo<A> { x: A }`.
2521 Struct(VariantData, Generics),
2522 /// A union definition (`union`).
2524 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2525 Union(VariantData, Generics),
2526 /// A trait declaration (`trait`).
2528 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2529 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2532 /// E.g., `trait Foo = Bar + Quux;`.
2533 TraitAlias(Generics, GenericBounds),
2534 /// An implementation.
2536 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2542 Option<TraitRef>, // (optional) trait this impl implements
2546 /// A macro invocation.
2548 /// E.g., `foo!(..)`.
2551 /// A macro definition.
2556 pub fn descriptive_variant(&self) -> &str {
2558 ItemKind::ExternCrate(..) => "extern crate",
2559 ItemKind::Use(..) => "use",
2560 ItemKind::Static(..) => "static item",
2561 ItemKind::Const(..) => "constant item",
2562 ItemKind::Fn(..) => "function",
2563 ItemKind::Mod(..) => "module",
2564 ItemKind::ForeignMod(..) => "foreign module",
2565 ItemKind::GlobalAsm(..) => "global asm",
2566 ItemKind::TyAlias(..) => "type alias",
2567 ItemKind::Enum(..) => "enum",
2568 ItemKind::Struct(..) => "struct",
2569 ItemKind::Union(..) => "union",
2570 ItemKind::Trait(..) => "trait",
2571 ItemKind::TraitAlias(..) => "trait alias",
2572 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2577 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2578 pub struct ForeignItem {
2580 pub attrs: Vec<Attribute>,
2581 pub kind: ForeignItemKind,
2584 pub vis: Visibility,
2587 /// An item within an `extern` block.
2588 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2589 pub enum ForeignItemKind {
2590 /// A foreign function.
2591 Fn(P<FnDecl>, Generics),
2592 /// A foreign static item (`static ext: u8`).
2593 Static(P<Ty>, Mutability),
2596 /// A macro invocation.
2600 impl ForeignItemKind {
2601 pub fn descriptive_variant(&self) -> &str {
2603 ForeignItemKind::Fn(..) => "foreign function",
2604 ForeignItemKind::Static(..) => "foreign static item",
2605 ForeignItemKind::Ty => "foreign type",
2606 ForeignItemKind::Macro(..) => "macro in foreign module",