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 /// The kind of borrow in an `AddrOf` expression,
768 /// e.g., `&place` or `&raw const place`.
769 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
770 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
771 pub enum BorrowKind {
772 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
773 /// The resulting type is either `*const T` or `*mut T`
774 /// where `T = typeof($expr)`.
776 /// A normal borrow, `&$expr` or `&mut $expr`.
777 /// The resulting type is either `&'a T` or `&'a mut T`
778 /// where `T = typeof($expr)` and `'a` is some lifetime.
782 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
784 /// The `+` operator (addition)
786 /// The `-` operator (subtraction)
788 /// The `*` operator (multiplication)
790 /// The `/` operator (division)
792 /// The `%` operator (modulus)
794 /// The `&&` operator (logical and)
796 /// The `||` operator (logical or)
798 /// The `^` operator (bitwise xor)
800 /// The `&` operator (bitwise and)
802 /// The `|` operator (bitwise or)
804 /// The `<<` operator (shift left)
806 /// The `>>` operator (shift right)
808 /// The `==` operator (equality)
810 /// The `<` operator (less than)
812 /// The `<=` operator (less than or equal to)
814 /// The `!=` operator (not equal to)
816 /// The `>=` operator (greater than or equal to)
818 /// The `>` operator (greater than)
823 pub fn to_string(&self) -> &'static str {
846 pub fn lazy(&self) -> bool {
848 BinOpKind::And | BinOpKind::Or => true,
853 pub fn is_shift(&self) -> bool {
855 BinOpKind::Shl | BinOpKind::Shr => true,
860 pub fn is_comparison(&self) -> bool {
862 // Note for developers: please keep this as is;
863 // we want compilation to fail if another variant is added.
865 Eq | Lt | Le | Ne | Gt | Ge => true,
866 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
870 /// Returns `true` if the binary operator takes its arguments by value
871 pub fn is_by_value(&self) -> bool {
872 !self.is_comparison()
876 pub type BinOp = Spanned<BinOpKind>;
880 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
881 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
883 /// The `*` operator for dereferencing
885 /// The `!` operator for logical inversion
887 /// The `-` operator for negation
892 /// Returns `true` if the unary operator takes its argument by value
893 pub fn is_by_value(u: UnOp) -> bool {
895 UnOp::Neg | UnOp::Not => true,
900 pub fn to_string(op: UnOp) -> &'static str {
910 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
918 pub fn add_trailing_semicolon(mut self) -> Self {
919 self.kind = match self.kind {
920 StmtKind::Expr(expr) => StmtKind::Semi(expr),
921 StmtKind::Mac(mac) => {
922 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
929 pub fn is_item(&self) -> bool {
931 StmtKind::Item(_) => true,
936 pub fn is_expr(&self) -> bool {
938 StmtKind::Expr(_) => true,
944 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
946 /// A local (let) binding.
948 /// An item definition.
950 /// Expr without trailing semi-colon.
952 /// Expr with a trailing semi-colon.
955 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
958 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
959 pub enum MacStmtStyle {
960 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
961 /// `foo!(...);`, `foo![...];`).
963 /// The macro statement had braces (e.g., `foo! { ... }`).
965 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
966 /// `foo!(...)`). All of these will end up being converted into macro
971 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
972 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
976 pub ty: Option<P<Ty>>,
977 /// Initializer expression to set the value, if any.
978 pub init: Option<P<Expr>>,
980 pub attrs: ThinVec<Attribute>,
983 /// An arm of a 'match'.
985 /// E.g., `0..=10 => { println!("match!") }` as in
989 /// 0..=10 => { println!("match!") },
990 /// _ => { println!("no match!") },
993 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
995 pub attrs: Vec<Attribute>,
996 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
998 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
999 pub guard: Option<P<Expr>>,
1004 pub is_placeholder: bool,
1007 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1008 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1010 pub attrs: ThinVec<Attribute>,
1015 pub is_shorthand: bool,
1016 pub is_placeholder: bool,
1019 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1020 pub enum BlockCheckMode {
1022 Unsafe(UnsafeSource),
1025 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1026 pub enum UnsafeSource {
1031 /// A constant (expression) that's not an item or associated item,
1032 /// but needs its own `DefId` for type-checking, const-eval, etc.
1033 /// These are usually found nested inside types (e.g., array lengths)
1034 /// or expressions (e.g., repeat counts), and also used to define
1035 /// explicit discriminant values for enum variants.
1036 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1037 pub struct AnonConst {
1043 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1048 pub attrs: ThinVec<Attribute>,
1051 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1052 #[cfg(target_arch = "x86_64")]
1053 rustc_data_structures::static_assert_size!(Expr, 96);
1056 /// Returns `true` if this expression would be valid somewhere that expects a value;
1057 /// for example, an `if` condition.
1058 pub fn returns(&self) -> bool {
1059 if let ExprKind::Block(ref block, _) = self.kind {
1060 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1062 Some(&StmtKind::Expr(_)) => true,
1063 Some(&StmtKind::Semi(ref expr)) => {
1064 if let ExprKind::Ret(_) = expr.kind {
1065 // Last statement is explicit return.
1071 // This is a block that doesn't end in either an implicit or explicit return.
1075 // This is not a block, it is a value.
1080 pub fn to_bound(&self) -> Option<GenericBound> {
1082 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1083 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1084 TraitBoundModifier::None,
1090 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1091 pub fn to_ty(&self) -> Option<P<Ty>> {
1092 let kind = match &self.kind {
1093 // Trivial conversions.
1094 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1095 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1097 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1099 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => expr
1101 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1103 ExprKind::Repeat(expr, expr_len) => {
1104 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1107 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1109 ExprKind::Tup(exprs) => {
1112 .map(|expr| expr.to_ty())
1113 .collect::<Option<Vec<_>>>()?;
1117 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1118 // then type of result is trait object.
1119 // Othewise we don't assume the result type.
1120 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1121 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1122 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1128 // This expression doesn't look like a type syntactically.
1139 pub fn precedence(&self) -> ExprPrecedence {
1141 ExprKind::Box(_) => ExprPrecedence::Box,
1142 ExprKind::Array(_) => ExprPrecedence::Array,
1143 ExprKind::Call(..) => ExprPrecedence::Call,
1144 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1145 ExprKind::Tup(_) => ExprPrecedence::Tup,
1146 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1147 ExprKind::Unary(..) => ExprPrecedence::Unary,
1148 ExprKind::Lit(_) => ExprPrecedence::Lit,
1149 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1150 ExprKind::Let(..) => ExprPrecedence::Let,
1151 ExprKind::If(..) => ExprPrecedence::If,
1152 ExprKind::While(..) => ExprPrecedence::While,
1153 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1154 ExprKind::Loop(..) => ExprPrecedence::Loop,
1155 ExprKind::Match(..) => ExprPrecedence::Match,
1156 ExprKind::Closure(..) => ExprPrecedence::Closure,
1157 ExprKind::Block(..) => ExprPrecedence::Block,
1158 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1159 ExprKind::Async(..) => ExprPrecedence::Async,
1160 ExprKind::Await(..) => ExprPrecedence::Await,
1161 ExprKind::Assign(..) => ExprPrecedence::Assign,
1162 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1163 ExprKind::Field(..) => ExprPrecedence::Field,
1164 ExprKind::Index(..) => ExprPrecedence::Index,
1165 ExprKind::Range(..) => ExprPrecedence::Range,
1166 ExprKind::Path(..) => ExprPrecedence::Path,
1167 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1168 ExprKind::Break(..) => ExprPrecedence::Break,
1169 ExprKind::Continue(..) => ExprPrecedence::Continue,
1170 ExprKind::Ret(..) => ExprPrecedence::Ret,
1171 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1172 ExprKind::Mac(..) => ExprPrecedence::Mac,
1173 ExprKind::Struct(..) => ExprPrecedence::Struct,
1174 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1175 ExprKind::Paren(..) => ExprPrecedence::Paren,
1176 ExprKind::Try(..) => ExprPrecedence::Try,
1177 ExprKind::Yield(..) => ExprPrecedence::Yield,
1178 ExprKind::Err => ExprPrecedence::Err,
1183 /// Limit types of a range (inclusive or exclusive)
1184 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1185 pub enum RangeLimits {
1186 /// Inclusive at the beginning, exclusive at the end
1188 /// Inclusive at the beginning and end
1192 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1194 /// A `box x` expression.
1196 /// An array (`[a, b, c, d]`)
1197 Array(Vec<P<Expr>>),
1200 /// The first field resolves to the function itself,
1201 /// and the second field is the list of arguments.
1202 /// This also represents calling the constructor of
1203 /// tuple-like ADTs such as tuple structs and enum variants.
1204 Call(P<Expr>, Vec<P<Expr>>),
1205 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1207 /// The `PathSegment` represents the method name and its generic arguments
1208 /// (within the angle brackets).
1209 /// The first element of the vector of an `Expr` is the expression that evaluates
1210 /// to the object on which the method is being called on (the receiver),
1211 /// and the remaining elements are the rest of the arguments.
1212 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1213 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1214 MethodCall(PathSegment, Vec<P<Expr>>),
1215 /// A tuple (e.g., `(a, b, c, d)`).
1217 /// A binary operation (e.g., `a + b`, `a * b`).
1218 Binary(BinOp, P<Expr>, P<Expr>),
1219 /// A unary operation (e.g., `!x`, `*x`).
1220 Unary(UnOp, P<Expr>),
1221 /// A literal (e.g., `1`, `"foo"`).
1223 /// A cast (e.g., `foo as f64`).
1224 Cast(P<Expr>, P<Ty>),
1225 /// A type ascription (e.g., `42: usize`).
1226 Type(P<Expr>, P<Ty>),
1227 /// A `let pat = expr` expression that is only semantically allowed in the condition
1228 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1229 Let(P<Pat>, P<Expr>),
1230 /// An `if` block, with an optional `else` block.
1232 /// `if expr { block } else { expr }`
1233 If(P<Expr>, P<Block>, Option<P<Expr>>),
1234 /// A while loop, with an optional label.
1236 /// `'label: while expr { block }`
1237 While(P<Expr>, P<Block>, Option<Label>),
1238 /// A `for` loop, with an optional label.
1240 /// `'label: for pat in expr { block }`
1242 /// This is desugared to a combination of `loop` and `match` expressions.
1243 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1244 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1246 /// `'label: loop { block }`
1247 Loop(P<Block>, Option<Label>),
1248 /// A `match` block.
1249 Match(P<Expr>, Vec<Arm>),
1250 /// A closure (e.g., `move |a, b, c| a + b + c`).
1252 /// The final span is the span of the argument block `|...|`.
1253 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1254 /// A block (`'label: { ... }`).
1255 Block(P<Block>, Option<Label>),
1256 /// An async block (`async move { ... }`).
1258 /// The `NodeId` is the `NodeId` for the closure that results from
1259 /// desugaring an async block, just like the NodeId field in the
1260 /// `IsAsync` enum. This is necessary in order to create a def for the
1261 /// closure which can be used as a parent of any child defs. Defs
1262 /// created during lowering cannot be made the parent of any other
1263 /// preexisting defs.
1264 Async(CaptureBy, NodeId, P<Block>),
1265 /// An await expression (`my_future.await`).
1268 /// A try block (`try { ... }`).
1271 /// An assignment (`a = foo()`).
1272 Assign(P<Expr>, P<Expr>),
1273 /// An assignment with an operator.
1276 AssignOp(BinOp, P<Expr>, P<Expr>),
1277 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1278 Field(P<Expr>, Ident),
1279 /// An indexing operation (e.g., `foo[2]`).
1280 Index(P<Expr>, P<Expr>),
1281 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1282 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1284 /// Variable reference, possibly containing `::` and/or type
1285 /// parameters (e.g., `foo::bar::<baz>`).
1287 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1288 Path(Option<QSelf>, Path),
1290 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1291 AddrOf(BorrowKind, Mutability, P<Expr>),
1292 /// A `break`, with an optional label to break, and an optional expression.
1293 Break(Option<Label>, Option<P<Expr>>),
1294 /// A `continue`, with an optional label.
1295 Continue(Option<Label>),
1296 /// A `return`, with an optional value to be returned.
1297 Ret(Option<P<Expr>>),
1299 /// Output of the `asm!()` macro.
1300 InlineAsm(P<InlineAsm>),
1302 /// A macro invocation; pre-expansion.
1305 /// A struct literal expression.
1307 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1308 /// where `base` is the `Option<Expr>`.
1309 Struct(Path, Vec<Field>, Option<P<Expr>>),
1311 /// An array literal constructed from one repeated element.
1313 /// E.g., `[1; 5]`. The expression is the element to be
1314 /// repeated; the constant is the number of times to repeat it.
1315 Repeat(P<Expr>, AnonConst),
1317 /// No-op: used solely so we can pretty-print faithfully.
1320 /// A try expression (`expr?`).
1323 /// A `yield`, with an optional value to be yielded.
1324 Yield(Option<P<Expr>>),
1326 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1330 /// The explicit `Self` type in a "qualified path". The actual
1331 /// path, including the trait and the associated item, is stored
1332 /// separately. `position` represents the index of the associated
1333 /// item qualified with this `Self` type.
1335 /// ```ignore (only-for-syntax-highlight)
1336 /// <Vec<T> as a::b::Trait>::AssociatedItem
1337 /// ^~~~~ ~~~~~~~~~~~~~~^
1340 /// <Vec<T>>::AssociatedItem
1344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1348 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1349 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1350 /// 0`, this is an empty span.
1351 pub path_span: Span,
1352 pub position: usize,
1355 /// A capture clause used in closures and `async` blocks.
1356 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1357 pub enum CaptureBy {
1358 /// `move |x| y + x`.
1360 /// `move` keyword was not specified.
1364 /// The movability of a generator / closure literal:
1365 /// whether a generator contains self-references, causing it to be `!Unpin`.
1366 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
1367 RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1368 pub enum Movability {
1369 /// May contain self-references, `!Unpin`.
1371 /// Must not contain self-references, `Unpin`.
1375 /// Represents a macro invocation. The `Path` indicates which macro
1376 /// is being invoked, and the vector of token-trees contains the source
1377 /// of the macro invocation.
1379 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1380 /// stored in the enclosing item.
1381 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1384 pub delim: MacDelimiter,
1385 pub tts: TokenStream,
1387 pub prior_type_ascription: Option<(Span, bool)>,
1390 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1391 pub enum MacDelimiter {
1398 pub fn stream(&self) -> TokenStream {
1404 crate fn to_token(self) -> DelimToken {
1406 MacDelimiter::Parenthesis => DelimToken::Paren,
1407 MacDelimiter::Bracket => DelimToken::Bracket,
1408 MacDelimiter::Brace => DelimToken::Brace,
1413 /// Represents a macro definition.
1414 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1415 pub struct MacroDef {
1416 pub tokens: TokenStream,
1417 /// `true` if macro was defined with `macro_rules`.
1422 pub fn stream(&self) -> TokenStream {
1423 self.tokens.clone().into()
1427 // Clippy uses Hash and PartialEq
1428 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
1430 /// A regular string, like `"foo"`.
1432 /// A raw string, like `r##"foo"##`.
1434 /// The value is the number of `#` symbols used.
1439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1441 /// The original literal token as written in source code.
1442 pub token: token::Lit,
1443 /// The "semantic" representation of the literal lowered from the original tokens.
1444 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1445 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1450 /// Same as `Lit`, but restricted to string literals.
1451 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1453 /// The original literal token as written in source code.
1454 pub style: StrStyle,
1456 pub suffix: Option<Symbol>,
1458 /// The unescaped "semantic" representation of the literal lowered from the original token.
1459 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1460 pub symbol_unescaped: Symbol,
1464 crate fn as_lit(&self) -> Lit {
1465 let token_kind = match self.style {
1466 StrStyle::Cooked => token::Str,
1467 StrStyle::Raw(n) => token::StrRaw(n),
1470 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1472 kind: LitKind::Str(self.symbol_unescaped, self.style),
1477 // Clippy uses Hash and PartialEq
1478 /// Type of the integer literal based on provided suffix.
1479 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1480 pub enum LitIntType {
1489 /// Type of the float literal based on provided suffix.
1490 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1491 pub enum LitFloatType {
1492 /// A float literal with a suffix (`1f32` or `1E10f32`).
1494 /// A float literal without a suffix (`1.0 or 1.0E10`).
1500 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1501 // Clippy uses Hash and PartialEq
1502 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1504 /// A string literal (`"foo"`).
1505 Str(Symbol, StrStyle),
1506 /// A byte string (`b"foo"`).
1507 ByteStr(Lrc<Vec<u8>>),
1508 /// A byte char (`b'f'`).
1510 /// A character literal (`'a'`).
1512 /// An integer literal (`1`).
1513 Int(u128, LitIntType),
1514 /// A float literal (`1f64` or `1E10f64`).
1515 Float(Symbol, LitFloatType),
1516 /// A boolean literal.
1518 /// Placeholder for a literal that wasn't well-formed in some way.
1523 /// Returns `true` if this literal is a string.
1524 pub fn is_str(&self) -> bool {
1526 LitKind::Str(..) => true,
1531 /// Returns `true` if this literal is byte literal string.
1532 pub fn is_bytestr(&self) -> bool {
1534 LitKind::ByteStr(_) => true,
1539 /// Returns `true` if this is a numeric literal.
1540 pub fn is_numeric(&self) -> bool {
1542 LitKind::Int(..) | LitKind::Float(..) => true,
1547 /// Returns `true` if this literal has no suffix.
1548 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1549 pub fn is_unsuffixed(&self) -> bool {
1553 /// Returns `true` if this literal has a suffix.
1554 pub fn is_suffixed(&self) -> bool {
1556 // suffixed variants
1557 LitKind::Int(_, LitIntType::Signed(..))
1558 | LitKind::Int(_, LitIntType::Unsigned(..))
1559 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1560 // unsuffixed variants
1562 | LitKind::ByteStr(..)
1565 | LitKind::Int(_, LitIntType::Unsuffixed)
1566 | LitKind::Float(_, LitFloatType::Unsuffixed)
1568 | LitKind::Err(..) => false,
1573 // N.B., If you change this, you'll probably want to change the corresponding
1574 // type structure in `middle/ty.rs` as well.
1575 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1578 pub mutbl: Mutability,
1581 /// Represents a function's signature in a trait declaration,
1582 /// trait implementation, or free function.
1583 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1585 pub header: FnHeader,
1586 pub decl: P<FnDecl>,
1589 /// Represents an item declaration within a trait declaration,
1590 /// possibly including a default implementation. A trait item is
1591 /// either required (meaning it doesn't have an implementation, just a
1592 /// signature) or provided (meaning it has a default implementation).
1593 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1594 pub struct TraitItem {
1595 pub attrs: Vec<Attribute>,
1598 pub vis: Visibility,
1601 pub generics: Generics,
1602 pub kind: TraitItemKind,
1603 /// See `Item::tokens` for what this is.
1604 pub tokens: Option<TokenStream>,
1607 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1608 pub enum TraitItemKind {
1609 Const(P<Ty>, Option<P<Expr>>),
1610 Method(FnSig, Option<P<Block>>),
1611 Type(GenericBounds, Option<P<Ty>>),
1615 /// Represents anything within an `impl` block.
1616 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1617 pub struct ImplItem {
1618 pub attrs: Vec<Attribute>,
1621 pub vis: Visibility,
1624 pub defaultness: Defaultness,
1625 pub generics: Generics,
1626 pub kind: ImplItemKind,
1627 /// See `Item::tokens` for what this is.
1628 pub tokens: Option<TokenStream>,
1631 /// Represents various kinds of content within an `impl`.
1632 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1633 pub enum ImplItemKind {
1634 Const(P<Ty>, P<Expr>),
1635 Method(FnSig, P<Block>),
1640 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1641 RustcEncodable, RustcDecodable, Debug)]
1648 pub fn name_str(self) -> &'static str {
1650 FloatTy::F32 => "f32",
1651 FloatTy::F64 => "f64",
1655 pub fn name(self) -> Symbol {
1657 FloatTy::F32 => sym::f32,
1658 FloatTy::F64 => sym::f64,
1662 pub fn bit_width(self) -> usize {
1670 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1671 RustcEncodable, RustcDecodable, Debug)]
1682 pub fn name_str(&self) -> &'static str {
1684 IntTy::Isize => "isize",
1686 IntTy::I16 => "i16",
1687 IntTy::I32 => "i32",
1688 IntTy::I64 => "i64",
1689 IntTy::I128 => "i128",
1693 pub fn name(&self) -> Symbol {
1695 IntTy::Isize => sym::isize,
1696 IntTy::I8 => sym::i8,
1697 IntTy::I16 => sym::i16,
1698 IntTy::I32 => sym::i32,
1699 IntTy::I64 => sym::i64,
1700 IntTy::I128 => sym::i128,
1704 pub fn val_to_string(&self, val: i128) -> String {
1705 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1706 // are parsed as `u128`, so we wouldn't want to print an extra negative
1708 format!("{}{}", val as u128, self.name_str())
1711 pub fn bit_width(&self) -> Option<usize> {
1713 IntTy::Isize => return None,
1723 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1724 RustcEncodable, RustcDecodable, Copy, Debug)]
1735 pub fn name_str(&self) -> &'static str {
1737 UintTy::Usize => "usize",
1739 UintTy::U16 => "u16",
1740 UintTy::U32 => "u32",
1741 UintTy::U64 => "u64",
1742 UintTy::U128 => "u128",
1746 pub fn name(&self) -> Symbol {
1748 UintTy::Usize => sym::usize,
1749 UintTy::U8 => sym::u8,
1750 UintTy::U16 => sym::u16,
1751 UintTy::U32 => sym::u32,
1752 UintTy::U64 => sym::u64,
1753 UintTy::U128 => sym::u128,
1757 pub fn val_to_string(&self, val: u128) -> String {
1758 format!("{}{}", val, self.name_str())
1761 pub fn bit_width(&self) -> Option<usize> {
1763 UintTy::Usize => return None,
1768 UintTy::U128 => 128,
1773 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1774 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1775 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1776 pub struct AssocTyConstraint {
1779 pub kind: AssocTyConstraintKind,
1783 /// The kinds of an `AssocTyConstraint`.
1784 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1785 pub enum AssocTyConstraintKind {
1786 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1790 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1792 bounds: GenericBounds,
1796 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1803 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1804 pub struct BareFnTy {
1805 pub unsafety: Unsafety,
1807 pub generic_params: Vec<GenericParam>,
1808 pub decl: P<FnDecl>,
1811 /// The various kinds of type recognized by the compiler.
1812 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1814 /// A variable-length slice (`[T]`).
1816 /// A fixed length array (`[T; n]`).
1817 Array(P<Ty>, AnonConst),
1818 /// A raw pointer (`*const T` or `*mut T`).
1820 /// A reference (`&'a T` or `&'a mut T`).
1821 Rptr(Option<Lifetime>, MutTy),
1822 /// A bare function (e.g., `fn(usize) -> bool`).
1823 BareFn(P<BareFnTy>),
1824 /// The never type (`!`).
1826 /// A tuple (`(A, B, C, D,...)`).
1828 /// A path (`module::module::...::Type`), optionally
1829 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1831 /// Type parameters are stored in the `Path` itself.
1832 Path(Option<QSelf>, Path),
1833 /// A trait object type `Bound1 + Bound2 + Bound3`
1834 /// where `Bound` is a trait or a lifetime.
1835 TraitObject(GenericBounds, TraitObjectSyntax),
1836 /// An `impl Bound1 + Bound2 + Bound3` type
1837 /// where `Bound` is a trait or a lifetime.
1839 /// The `NodeId` exists to prevent lowering from having to
1840 /// generate `NodeId`s on the fly, which would complicate
1841 /// the generation of opaque `type Foo = impl Trait` items significantly.
1842 ImplTrait(NodeId, GenericBounds),
1843 /// No-op; kept solely so that we can pretty-print faithfully.
1847 /// This means the type should be inferred instead of it having been
1848 /// specified. This can appear anywhere in a type.
1850 /// Inferred type of a `self` or `&self` argument in a method.
1852 /// A macro in the type position.
1854 /// Placeholder for a kind that has failed to be defined.
1856 /// Placeholder for a `va_list`.
1861 pub fn is_implicit_self(&self) -> bool {
1862 if let TyKind::ImplicitSelf = *self {
1869 pub fn is_unit(&self) -> bool {
1870 if let TyKind::Tup(ref tys) = *self {
1877 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1878 /// in lowering to avoid making larger changes there and beyond.
1879 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1881 Self::ImplTrait(_, bounds) => Some(bounds),
1887 /// Syntax used to declare a trait object.
1888 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1889 pub enum TraitObjectSyntax {
1894 /// Inline assembly dialect.
1896 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1897 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1898 pub enum AsmDialect {
1903 /// Inline assembly.
1905 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1906 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1907 pub struct InlineAsmOutput {
1908 pub constraint: Symbol,
1911 pub is_indirect: bool,
1914 /// Inline assembly.
1916 /// E.g., `asm!("NOP");`.
1917 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1918 pub struct InlineAsm {
1920 pub asm_str_style: StrStyle,
1921 pub outputs: Vec<InlineAsmOutput>,
1922 pub inputs: Vec<(Symbol, P<Expr>)>,
1923 pub clobbers: Vec<Symbol>,
1925 pub alignstack: bool,
1926 pub dialect: AsmDialect,
1929 /// A parameter in a function header.
1931 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1932 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1934 pub attrs: ThinVec<Attribute>,
1939 pub is_placeholder: bool,
1942 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1944 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1945 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1947 /// `self`, `mut self`
1949 /// `&'lt self`, `&'lt mut self`
1950 Region(Option<Lifetime>, Mutability),
1951 /// `self: TYPE`, `mut self: TYPE`
1952 Explicit(P<Ty>, Mutability),
1955 pub type ExplicitSelf = Spanned<SelfKind>;
1958 /// Attempts to cast parameter to `ExplicitSelf`.
1959 pub fn to_self(&self) -> Option<ExplicitSelf> {
1960 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
1961 if ident.name == kw::SelfLower {
1962 return match self.ty.kind {
1963 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1964 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
1965 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1968 self.pat.span.to(self.ty.span),
1969 SelfKind::Explicit(self.ty.clone(), mutbl),
1977 /// Returns `true` if parameter is `self`.
1978 pub fn is_self(&self) -> bool {
1979 if let PatKind::Ident(_, ident, _) = self.pat.kind {
1980 ident.name == kw::SelfLower
1986 /// Builds a `Param` object from `ExplicitSelf`.
1987 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
1988 let span = eself.span.to(eself_ident.span);
1989 let infer_ty = P(Ty {
1991 kind: TyKind::ImplicitSelf,
1994 let param = |mutbl, ty| Param {
1998 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2004 is_placeholder: false
2007 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2008 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2009 SelfKind::Region(lt, mutbl) => param(
2010 Mutability::Immutable,
2027 /// A signature (not the body) of a function declaration.
2029 /// E.g., `fn foo(bar: baz)`.
2031 /// Please note that it's different from `FnHeader` structure
2032 /// which contains metadata about function safety, asyncness, constness and ABI.
2033 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2035 pub inputs: Vec<Param>,
2036 pub output: FunctionRetTy,
2040 pub fn get_self(&self) -> Option<ExplicitSelf> {
2041 self.inputs.get(0).and_then(Param::to_self)
2043 pub fn has_self(&self) -> bool {
2044 self.inputs.get(0).map_or(false, Param::is_self)
2046 pub fn c_variadic(&self) -> bool {
2047 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2048 TyKind::CVarArgs => true,
2054 /// Is the trait definition an auto trait?
2055 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2061 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2062 RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2069 pub fn prefix_str(&self) -> &'static str {
2071 Unsafety::Unsafe => "unsafe ",
2072 Unsafety::Normal => "",
2077 impl fmt::Display for Unsafety {
2078 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2081 Unsafety::Normal => "normal",
2082 Unsafety::Unsafe => "unsafe",
2089 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2093 return_impl_trait_id: NodeId,
2099 pub fn is_async(self) -> bool {
2100 if let IsAsync::Async { .. } = self {
2107 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2108 pub fn opt_return_id(self) -> Option<NodeId> {
2111 return_impl_trait_id,
2113 } => Some(return_impl_trait_id),
2114 IsAsync::NotAsync => None,
2119 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2120 pub enum Constness {
2125 /// Item defaultness.
2126 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2127 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2128 pub enum Defaultness {
2133 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2134 pub enum ImplPolarity {
2135 /// `impl Trait for Type`
2137 /// `impl !Trait for Type`
2141 impl fmt::Debug for ImplPolarity {
2142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2144 ImplPolarity::Positive => "positive".fmt(f),
2145 ImplPolarity::Negative => "negative".fmt(f),
2150 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2151 pub enum FunctionRetTy {
2152 /// Returns type is not specified.
2154 /// Functions default to `()` and closures default to inference.
2155 /// Span points to where return type would be inserted.
2157 /// Everything else.
2161 impl FunctionRetTy {
2162 pub fn span(&self) -> Span {
2164 FunctionRetTy::Default(span) => span,
2165 FunctionRetTy::Ty(ref ty) => ty.span,
2170 /// Module declaration.
2172 /// E.g., `mod foo;` or `mod foo { .. }`.
2173 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2175 /// A span from the first token past `{` to the last token until `}`.
2176 /// For `mod foo;`, the inner span ranges from the first token
2177 /// to the last token in the external file.
2179 pub items: Vec<P<Item>>,
2180 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2184 /// Foreign module declaration.
2186 /// E.g., `extern { .. }` or `extern C { .. }`.
2187 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2188 pub struct ForeignMod {
2189 pub abi: Option<StrLit>,
2190 pub items: Vec<ForeignItem>,
2193 /// Global inline assembly.
2195 /// Also known as "module-level assembly" or "file-scoped assembly".
2196 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2197 pub struct GlobalAsm {
2201 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2202 pub struct EnumDef {
2203 pub variants: Vec<Variant>,
2206 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2207 pub struct Variant {
2208 /// Attributes of the variant.
2209 pub attrs: Vec<Attribute>,
2210 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2214 /// The visibility of the variant. Syntactically accepted but not semantically.
2215 pub vis: Visibility,
2216 /// Name of the variant.
2219 /// Fields and constructor id of the variant.
2220 pub data: VariantData,
2221 /// Explicit discriminant, e.g., `Foo = 1`.
2222 pub disr_expr: Option<AnonConst>,
2223 /// Is a macro placeholder
2224 pub is_placeholder: bool,
2227 /// Part of `use` item to the right of its prefix.
2228 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2229 pub enum UseTreeKind {
2230 /// `use prefix` or `use prefix as rename`
2232 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2234 Simple(Option<Ident>, NodeId, NodeId),
2235 /// `use prefix::{...}`
2236 Nested(Vec<(UseTree, NodeId)>),
2241 /// A tree of paths sharing common prefixes.
2242 /// Used in `use` items both at top-level and inside of braces in import groups.
2243 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2244 pub struct UseTree {
2246 pub kind: UseTreeKind,
2251 pub fn ident(&self) -> Ident {
2253 UseTreeKind::Simple(Some(rename), ..) => rename,
2254 UseTreeKind::Simple(None, ..) => {
2258 .expect("empty prefix in a simple import")
2261 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2266 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2267 /// are contained as statements within items. These two cases need to be
2268 /// distinguished for pretty-printing.
2269 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2270 pub enum AttrStyle {
2275 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2276 pub struct AttrId(pub usize);
2278 impl Idx for AttrId {
2279 fn new(idx: usize) -> Self {
2282 fn index(self) -> usize {
2287 impl rustc_serialize::Encodable for AttrId {
2288 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2293 impl rustc_serialize::Decodable for AttrId {
2294 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2295 d.read_nil().map(|_| crate::attr::mk_attr_id())
2299 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2300 pub struct AttrItem {
2302 pub tokens: TokenStream,
2305 /// Metadata associated with an item.
2306 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2307 pub struct Attribute {
2310 /// Denotes if the attribute decorates the following construct (outer)
2311 /// or the construct this attribute is contained within (inner).
2312 pub style: AttrStyle,
2316 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2318 /// A normal attribute.
2321 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2322 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2323 /// variant (which is much less compact and thus more expensive).
2325 /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2326 /// for this variant, but this may change in the future.
2331 /// `TraitRef`s appear in impls.
2333 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2334 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2335 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2336 /// same as the impl's `NodeId`).
2337 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2338 pub struct TraitRef {
2343 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2344 pub struct PolyTraitRef {
2345 /// The `'a` in `<'a> Foo<&'a T>`.
2346 pub bound_generic_params: Vec<GenericParam>,
2348 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2349 pub trait_ref: TraitRef,
2355 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2357 bound_generic_params: generic_params,
2358 trait_ref: TraitRef {
2360 ref_id: DUMMY_NODE_ID,
2367 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2368 pub enum CrateSugar {
2369 /// Source is `pub(crate)`.
2372 /// Source is (just) `crate`.
2376 pub type Visibility = Spanned<VisibilityKind>;
2378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2379 pub enum VisibilityKind {
2382 Restricted { path: P<Path>, id: NodeId },
2386 impl VisibilityKind {
2387 pub fn is_pub(&self) -> bool {
2388 if let VisibilityKind::Public = *self {
2396 /// Field of a struct.
2398 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2400 pub struct StructField {
2401 pub attrs: Vec<Attribute>,
2404 pub vis: Visibility,
2405 pub ident: Option<Ident>,
2408 pub is_placeholder: bool,
2411 /// Fields and constructor ids of enum variants and structs.
2412 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2413 pub enum VariantData {
2416 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2417 Struct(Vec<StructField>, bool),
2420 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2421 Tuple(Vec<StructField>, NodeId),
2424 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2429 /// Return the fields of this variant.
2430 pub fn fields(&self) -> &[StructField] {
2432 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2437 /// Return the `NodeId` of this variant's constructor, if it has one.
2438 pub fn ctor_id(&self) -> Option<NodeId> {
2440 VariantData::Struct(..) => None,
2441 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2448 /// The name might be a dummy name in case of anonymous items.
2449 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2451 pub attrs: Vec<Attribute>,
2454 pub vis: Visibility,
2459 /// Original tokens this item was parsed from. This isn't necessarily
2460 /// available for all items, although over time more and more items should
2461 /// have this be `Some`. Right now this is primarily used for procedural
2462 /// macros, notably custom attributes.
2464 /// Note that the tokens here do not include the outer attributes, but will
2465 /// include inner attributes.
2466 pub tokens: Option<TokenStream>,
2470 /// Return the span that encompasses the attributes.
2471 pub fn span_with_attributes(&self) -> Span {
2472 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2476 /// `extern` qualifier on a function item or function type.
2477 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2485 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2486 abi.map_or(Extern::Implicit, Extern::Explicit)
2490 /// A function header.
2492 /// All the information between the visibility and the name of the function is
2493 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2494 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2495 pub struct FnHeader {
2496 pub unsafety: Unsafety,
2497 pub asyncness: Spanned<IsAsync>,
2498 pub constness: Spanned<Constness>,
2502 impl Default for FnHeader {
2503 fn default() -> FnHeader {
2505 unsafety: Unsafety::Normal,
2506 asyncness: dummy_spanned(IsAsync::NotAsync),
2507 constness: dummy_spanned(Constness::NotConst),
2513 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2515 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2517 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2518 ExternCrate(Option<Name>),
2519 /// A use declaration item (`use`).
2521 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2523 /// A static item (`static`).
2525 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2526 Static(P<Ty>, Mutability, P<Expr>),
2527 /// A constant item (`const`).
2529 /// E.g., `const FOO: i32 = 42;`.
2530 Const(P<Ty>, P<Expr>),
2531 /// A function declaration (`fn`).
2533 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2534 Fn(FnSig, Generics, P<Block>),
2535 /// A module declaration (`mod`).
2537 /// E.g., `mod foo;` or `mod foo { .. }`.
2539 /// An external module (`extern`).
2541 /// E.g., `extern {}` or `extern "C" {}`.
2542 ForeignMod(ForeignMod),
2543 /// Module-level inline assembly (from `global_asm!()`).
2544 GlobalAsm(P<GlobalAsm>),
2545 /// A type alias (`type`).
2547 /// E.g., `type Foo = Bar<u8>;`.
2548 TyAlias(P<Ty>, Generics),
2549 /// An enum definition (`enum`).
2551 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2552 Enum(EnumDef, Generics),
2553 /// A struct definition (`struct`).
2555 /// E.g., `struct Foo<A> { x: A }`.
2556 Struct(VariantData, Generics),
2557 /// A union definition (`union`).
2559 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2560 Union(VariantData, Generics),
2561 /// A trait declaration (`trait`).
2563 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2564 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2567 /// E.g., `trait Foo = Bar + Quux;`.
2568 TraitAlias(Generics, GenericBounds),
2569 /// An implementation.
2571 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2577 Option<TraitRef>, // (optional) trait this impl implements
2581 /// A macro invocation.
2583 /// E.g., `foo!(..)`.
2586 /// A macro definition.
2591 pub fn descriptive_variant(&self) -> &str {
2593 ItemKind::ExternCrate(..) => "extern crate",
2594 ItemKind::Use(..) => "use",
2595 ItemKind::Static(..) => "static item",
2596 ItemKind::Const(..) => "constant item",
2597 ItemKind::Fn(..) => "function",
2598 ItemKind::Mod(..) => "module",
2599 ItemKind::ForeignMod(..) => "foreign module",
2600 ItemKind::GlobalAsm(..) => "global asm",
2601 ItemKind::TyAlias(..) => "type alias",
2602 ItemKind::Enum(..) => "enum",
2603 ItemKind::Struct(..) => "struct",
2604 ItemKind::Union(..) => "union",
2605 ItemKind::Trait(..) => "trait",
2606 ItemKind::TraitAlias(..) => "trait alias",
2607 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2612 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2613 pub struct ForeignItem {
2614 pub attrs: Vec<Attribute>,
2617 pub vis: Visibility,
2620 pub kind: ForeignItemKind,
2623 /// An item within an `extern` block.
2624 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2625 pub enum ForeignItemKind {
2626 /// A foreign function.
2627 Fn(P<FnDecl>, Generics),
2628 /// A foreign static item (`static ext: u8`).
2629 Static(P<Ty>, Mutability),
2632 /// A macro invocation.
2636 impl ForeignItemKind {
2637 pub fn descriptive_variant(&self) -> &str {
2639 ForeignItemKind::Fn(..) => "foreign function",
2640 ForeignItemKind::Static(..) => "foreign static item",
2641 ForeignItemKind::Ty => "foreign type",
2642 ForeignItemKind::Macro(..) => "macro in foreign module",