1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items that worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`Mac`], [`MacDelimeter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`UnOpKind`], [`BinOp`], [`BinOpKind`]: Unary and binary operators.
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
25 pub use rustc_span::symbol::{Ident, Symbol as Name};
28 use crate::token::{self, DelimToken};
29 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
31 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
32 use rustc_data_structures::sync::Lrc;
33 use rustc_data_structures::thin_vec::ThinVec;
34 use rustc_index::vec::Idx;
35 use rustc_macros::HashStable_Generic;
36 use rustc_serialize::{self, Decoder, Encoder};
37 use rustc_span::source_map::{dummy_spanned, respan, Spanned};
38 use rustc_span::symbol::{kw, sym, Symbol};
39 use rustc_span::{Span, DUMMY_SP};
47 /// A "Label" is an identifier of some point in sources,
48 /// e.g. in the following code:
56 /// `'outer` is a label.
57 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable_Generic)]
62 impl fmt::Debug for Label {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "label({:?})", self.ident)
68 /// A "Lifetime" is an annotation of the scope in which variable
69 /// can be used, e.g. `'a` in `&'a i32`.
70 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
76 impl fmt::Debug for Lifetime {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "lifetime({}: {})", self.id, self)
82 impl fmt::Display for Lifetime {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 write!(f, "{}", self.ident.name)
88 /// A "Path" is essentially Rust's notion of a name.
90 /// It's represented as a sequence of identifiers,
91 /// along with a bunch of supporting information.
93 /// E.g., `std::cmp::PartialEq`.
94 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
97 /// The segments in the path: the things separated by `::`.
98 /// Global paths begin with `kw::PathRoot`.
99 pub segments: Vec<PathSegment>,
102 impl PartialEq<Symbol> for Path {
103 fn eq(&self, symbol: &Symbol) -> bool {
104 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
108 impl<CTX> HashStable<CTX> for Path {
109 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
110 self.segments.len().hash_stable(hcx, hasher);
111 for segment in &self.segments {
112 segment.ident.name.hash_stable(hcx, hasher);
118 // Convert a span and an identifier to the corresponding
120 pub fn from_ident(ident: Ident) -> Path {
121 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
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: FunctionRetTy,
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 pub use rustc_session::node_id::NodeId;
261 /// `NodeId` used to represent the root of the crate.
262 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
264 /// When parsing and doing expansions, we initially give all AST nodes this AST
265 /// node value. Then later, in the renumber pass, we renumber them to have
266 /// small, positive ids.
267 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
269 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
271 /// Negative bounds should also be handled here.
272 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
273 pub enum TraitBoundModifier {
285 // This parses but will be rejected during AST validation.
289 /// The AST represents all type param bounds as types.
290 /// `typeck::collect::compute_bounds` matches these against
291 /// the "special" built-in traits (see `middle::lang_items`) and
292 /// detects `Copy`, `Send` and `Sync`.
293 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
294 pub enum GenericBound {
295 Trait(PolyTraitRef, TraitBoundModifier),
300 pub fn span(&self) -> Span {
302 &GenericBound::Trait(ref t, ..) => t.span,
303 &GenericBound::Outlives(ref l) => l.ident.span,
308 pub type GenericBounds = Vec<GenericBound>;
310 /// Specifies the enforced ordering for generic parameters. In the future,
311 /// if we wanted to relax this order, we could override `PartialEq` and
312 /// `PartialOrd`, to allow the kinds to be unordered.
313 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
314 pub enum ParamKindOrd {
320 impl fmt::Display for ParamKindOrd {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 ParamKindOrd::Lifetime => "lifetime".fmt(f),
324 ParamKindOrd::Type => "type".fmt(f),
325 ParamKindOrd::Const => "const".fmt(f),
330 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
331 pub enum GenericParamKind {
332 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
335 default: Option<P<Ty>>,
342 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
343 pub struct GenericParam {
347 pub bounds: GenericBounds,
348 pub is_placeholder: bool,
349 pub kind: GenericParamKind,
352 /// Represents lifetime, type and const parameters attached to a declaration of
353 /// a function, enum, trait, etc.
354 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
355 pub struct Generics {
356 pub params: Vec<GenericParam>,
357 pub where_clause: WhereClause,
361 impl Default for Generics {
362 /// Creates an instance of `Generics`.
363 fn default() -> Generics {
366 where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP },
372 /// A where-clause in a definition.
373 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
374 pub struct WhereClause {
375 pub predicates: Vec<WherePredicate>,
379 /// A single predicate in a where-clause.
380 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
381 pub enum WherePredicate {
382 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
383 BoundPredicate(WhereBoundPredicate),
384 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
385 RegionPredicate(WhereRegionPredicate),
386 /// An equality predicate (unsupported).
387 EqPredicate(WhereEqPredicate),
390 impl WherePredicate {
391 pub fn span(&self) -> Span {
393 &WherePredicate::BoundPredicate(ref p) => p.span,
394 &WherePredicate::RegionPredicate(ref p) => p.span,
395 &WherePredicate::EqPredicate(ref p) => p.span,
402 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
403 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
404 pub struct WhereBoundPredicate {
406 /// Any generics from a `for` binding.
407 pub bound_generic_params: Vec<GenericParam>,
408 /// The type being bounded.
409 pub bounded_ty: P<Ty>,
410 /// Trait and lifetime bounds (`Clone + Send + 'static`).
411 pub bounds: GenericBounds,
414 /// A lifetime predicate.
416 /// E.g., `'a: 'b + 'c`.
417 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
418 pub struct WhereRegionPredicate {
420 pub lifetime: Lifetime,
421 pub bounds: GenericBounds,
424 /// An equality predicate (unsupported).
427 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
428 pub struct WhereEqPredicate {
435 pub use rustc_session::parse::CrateConfig;
437 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
440 pub attrs: Vec<Attribute>,
444 /// Possible values inside of compile-time attribute lists.
446 /// E.g., the '..' in `#[name(..)]`.
447 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
448 pub enum NestedMetaItem {
449 /// A full MetaItem, for recursive meta items.
453 /// E.g., `"foo"`, `64`, `true`.
457 /// A spanned compile-time attribute item.
459 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
460 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
461 pub struct MetaItem {
463 pub kind: MetaItemKind,
467 /// A compile-time attribute item.
469 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
470 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
471 pub enum MetaItemKind {
474 /// E.g., `test` as in `#[test]`.
478 /// E.g., `derive(..)` as in `#[derive(..)]`.
479 List(Vec<NestedMetaItem>),
480 /// Name value meta item.
482 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
486 /// A block (`{ .. }`).
488 /// E.g., `{ .. }` as in `fn foo() { .. }`.
489 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
491 /// The statements in the block.
492 pub stmts: Vec<Stmt>,
494 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
495 pub rules: BlockCheckMode,
499 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
507 /// Attempt reparsing the pattern as a type.
508 /// This is intended for use by diagnostics.
509 pub fn to_ty(&self) -> Option<P<Ty>> {
510 let kind = match &self.kind {
511 // In a type expression `_` is an inference variable.
512 PatKind::Wild => TyKind::Infer,
513 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
514 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
515 TyKind::Path(None, Path::from_ident(*ident))
517 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
518 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
519 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
520 PatKind::Ref(pat, mutbl) => {
521 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
523 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
524 // when `P` can be reparsed as a type `T`.
525 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
526 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
527 // assuming `T0` to `Tn` are all syntactically valid as types.
528 PatKind::Tuple(pats) => {
529 let mut tys = Vec::with_capacity(pats.len());
530 // FIXME(#48994) - could just be collected into an Option<Vec>
532 tys.push(pat.to_ty()?);
539 Some(P(Ty { kind, id: self.id, span: self.span }))
542 /// Walk top-down and call `it` in each place where a pattern occurs
543 /// starting with the root pattern `walk` is called on. If `it` returns
544 /// false then we will descend no further but siblings will be processed.
545 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
551 // Walk into the pattern associated with `Ident` (if any).
552 PatKind::Ident(_, _, Some(p)) => p.walk(it),
554 // Walk into each field of struct.
555 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
557 // Sequence of patterns.
558 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
559 s.iter().for_each(|p| p.walk(it))
562 // Trivial wrappers over inner patterns.
563 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
565 // These patterns do not contain subpatterns, skip.
572 | PatKind::Mac(_) => {}
576 /// Is this a `..` pattern?
577 pub fn is_rest(&self) -> bool {
579 PatKind::Rest => true,
585 /// A single field in a struct pattern
587 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
588 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
589 /// except is_shorthand is true
590 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
591 pub struct FieldPat {
592 /// The identifier for the field
594 /// The pattern the field is destructured to
596 pub is_shorthand: bool,
600 pub is_placeholder: bool,
603 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
604 pub enum BindingMode {
609 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
611 Included(RangeSyntax),
615 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
616 pub enum RangeSyntax {
623 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
625 /// Represents a wildcard pattern (`_`).
628 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
629 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
630 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
631 /// during name resolution.
632 Ident(BindingMode, Ident, Option<P<Pat>>),
634 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
635 /// The `bool` is `true` in the presence of a `..`.
636 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
638 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
639 TupleStruct(Path, Vec<P<Pat>>),
641 /// An or-pattern `A | B | C`.
642 /// Invariant: `pats.len() >= 2`.
645 /// A possibly qualified path pattern.
646 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
647 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
648 /// only legally refer to associated constants.
649 Path(Option<QSelf>, Path),
651 /// A tuple pattern (`(a, b)`).
657 /// A reference pattern (e.g., `&mut (a, b)`).
658 Ref(P<Pat>, Mutability),
663 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
664 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
666 /// A slice pattern `[a, b, c]`.
669 /// A rest pattern `..`.
671 /// Syntactically it is valid anywhere.
673 /// Semantically however, it only has meaning immediately inside:
674 /// - a slice pattern: `[a, .., b]`,
675 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
676 /// - a tuple pattern: `(a, .., b)`,
677 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
679 /// In all of these cases, an additional restriction applies,
680 /// only one rest pattern may occur in the pattern sequences.
683 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
686 /// A macro pattern; pre-expansion.
703 pub enum Mutability {
709 /// Returns `MutMutable` only if both `self` and `other` are mutable.
710 pub fn and(self, other: Self) -> Self {
712 Mutability::Mut => other,
713 Mutability::Not => Mutability::Not,
717 pub fn invert(self) -> Self {
719 Mutability::Mut => Mutability::Not,
720 Mutability::Not => Mutability::Mut,
724 pub fn prefix_str(&self) -> &'static str {
726 Mutability::Mut => "mut ",
727 Mutability::Not => "",
732 /// The kind of borrow in an `AddrOf` expression,
733 /// e.g., `&place` or `&raw const place`.
734 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
735 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
736 pub enum BorrowKind {
737 /// A normal borrow, `&$expr` or `&mut $expr`.
738 /// The resulting type is either `&'a T` or `&'a mut T`
739 /// where `T = typeof($expr)` and `'a` is some lifetime.
741 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
742 /// The resulting type is either `*const T` or `*mut T`
743 /// where `T = typeof($expr)`.
747 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
749 /// The `+` operator (addition)
751 /// The `-` operator (subtraction)
753 /// The `*` operator (multiplication)
755 /// The `/` operator (division)
757 /// The `%` operator (modulus)
759 /// The `&&` operator (logical and)
761 /// The `||` operator (logical or)
763 /// The `^` operator (bitwise xor)
765 /// The `&` operator (bitwise and)
767 /// The `|` operator (bitwise or)
769 /// The `<<` operator (shift left)
771 /// The `>>` operator (shift right)
773 /// The `==` operator (equality)
775 /// The `<` operator (less than)
777 /// The `<=` operator (less than or equal to)
779 /// The `!=` operator (not equal to)
781 /// The `>=` operator (greater than or equal to)
783 /// The `>` operator (greater than)
788 pub fn to_string(&self) -> &'static str {
811 pub fn lazy(&self) -> bool {
813 BinOpKind::And | BinOpKind::Or => true,
818 pub fn is_shift(&self) -> bool {
820 BinOpKind::Shl | BinOpKind::Shr => true,
825 pub fn is_comparison(&self) -> bool {
827 // Note for developers: please keep this as is;
828 // we want compilation to fail if another variant is added.
830 Eq | Lt | Le | Ne | Gt | Ge => true,
831 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
835 /// Returns `true` if the binary operator takes its arguments by value
836 pub fn is_by_value(&self) -> bool {
837 !self.is_comparison()
841 pub type BinOp = Spanned<BinOpKind>;
845 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
846 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
848 /// The `*` operator for dereferencing
850 /// The `!` operator for logical inversion
852 /// The `-` operator for negation
857 /// Returns `true` if the unary operator takes its argument by value
858 pub fn is_by_value(u: UnOp) -> bool {
860 UnOp::Neg | UnOp::Not => true,
865 pub fn to_string(op: UnOp) -> &'static str {
875 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
883 pub fn add_trailing_semicolon(mut self) -> Self {
884 self.kind = match self.kind {
885 StmtKind::Expr(expr) => StmtKind::Semi(expr),
886 StmtKind::Mac(mac) => {
887 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
894 pub fn is_item(&self) -> bool {
896 StmtKind::Item(_) => true,
901 pub fn is_expr(&self) -> bool {
903 StmtKind::Expr(_) => true,
909 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
911 /// A local (let) binding.
913 /// An item definition.
915 /// Expr without trailing semi-colon.
917 /// Expr with a trailing semi-colon.
920 Mac(P<(Mac, MacStmtStyle, AttrVec)>),
923 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
924 pub enum MacStmtStyle {
925 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
926 /// `foo!(...);`, `foo![...];`).
928 /// The macro statement had braces (e.g., `foo! { ... }`).
930 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
931 /// `foo!(...)`). All of these will end up being converted into macro
936 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
937 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
941 pub ty: Option<P<Ty>>,
942 /// Initializer expression to set the value, if any.
943 pub init: Option<P<Expr>>,
948 /// An arm of a 'match'.
950 /// E.g., `0..=10 => { println!("match!") }` as in
954 /// 0..=10 => { println!("match!") },
955 /// _ => { println!("no match!") },
958 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
960 pub attrs: Vec<Attribute>,
961 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
963 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
964 pub guard: Option<P<Expr>>,
969 pub is_placeholder: bool,
972 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
973 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
980 pub is_shorthand: bool,
981 pub is_placeholder: bool,
984 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
985 pub enum BlockCheckMode {
987 Unsafe(UnsafeSource),
990 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
991 pub enum UnsafeSource {
996 /// A constant (expression) that's not an item or associated item,
997 /// but needs its own `DefId` for type-checking, const-eval, etc.
998 /// These are usually found nested inside types (e.g., array lengths)
999 /// or expressions (e.g., repeat counts), and also used to define
1000 /// explicit discriminant values for enum variants.
1001 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1002 pub struct AnonConst {
1008 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1016 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1017 #[cfg(target_arch = "x86_64")]
1018 rustc_data_structures::static_assert_size!(Expr, 96);
1021 /// Returns `true` if this expression would be valid somewhere that expects a value;
1022 /// for example, an `if` condition.
1023 pub fn returns(&self) -> bool {
1024 if let ExprKind::Block(ref block, _) = self.kind {
1025 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1027 Some(&StmtKind::Expr(_)) => true,
1028 Some(&StmtKind::Semi(ref expr)) => {
1029 if let ExprKind::Ret(_) = expr.kind {
1030 // Last statement is explicit return.
1036 // This is a block that doesn't end in either an implicit or explicit return.
1040 // This is not a block, it is a value.
1045 pub fn to_bound(&self) -> Option<GenericBound> {
1047 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1048 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1049 TraitBoundModifier::None,
1055 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1056 pub fn to_ty(&self) -> Option<P<Ty>> {
1057 let kind = match &self.kind {
1058 // Trivial conversions.
1059 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1060 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1062 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1064 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1065 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1068 ExprKind::Repeat(expr, expr_len) => {
1069 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1072 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1074 ExprKind::Tup(exprs) => {
1075 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1079 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1080 // then type of result is trait object.
1081 // Othewise we don't assume the result type.
1082 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1083 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1084 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1090 // This expression doesn't look like a type syntactically.
1094 Some(P(Ty { kind, id: self.id, span: self.span }))
1097 pub fn precedence(&self) -> ExprPrecedence {
1099 ExprKind::Box(_) => ExprPrecedence::Box,
1100 ExprKind::Array(_) => ExprPrecedence::Array,
1101 ExprKind::Call(..) => ExprPrecedence::Call,
1102 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1103 ExprKind::Tup(_) => ExprPrecedence::Tup,
1104 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1105 ExprKind::Unary(..) => ExprPrecedence::Unary,
1106 ExprKind::Lit(_) => ExprPrecedence::Lit,
1107 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1108 ExprKind::Let(..) => ExprPrecedence::Let,
1109 ExprKind::If(..) => ExprPrecedence::If,
1110 ExprKind::While(..) => ExprPrecedence::While,
1111 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1112 ExprKind::Loop(..) => ExprPrecedence::Loop,
1113 ExprKind::Match(..) => ExprPrecedence::Match,
1114 ExprKind::Closure(..) => ExprPrecedence::Closure,
1115 ExprKind::Block(..) => ExprPrecedence::Block,
1116 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1117 ExprKind::Async(..) => ExprPrecedence::Async,
1118 ExprKind::Await(..) => ExprPrecedence::Await,
1119 ExprKind::Assign(..) => ExprPrecedence::Assign,
1120 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1121 ExprKind::Field(..) => ExprPrecedence::Field,
1122 ExprKind::Index(..) => ExprPrecedence::Index,
1123 ExprKind::Range(..) => ExprPrecedence::Range,
1124 ExprKind::Path(..) => ExprPrecedence::Path,
1125 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1126 ExprKind::Break(..) => ExprPrecedence::Break,
1127 ExprKind::Continue(..) => ExprPrecedence::Continue,
1128 ExprKind::Ret(..) => ExprPrecedence::Ret,
1129 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1130 ExprKind::Mac(..) => ExprPrecedence::Mac,
1131 ExprKind::Struct(..) => ExprPrecedence::Struct,
1132 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1133 ExprKind::Paren(..) => ExprPrecedence::Paren,
1134 ExprKind::Try(..) => ExprPrecedence::Try,
1135 ExprKind::Yield(..) => ExprPrecedence::Yield,
1136 ExprKind::Err => ExprPrecedence::Err,
1141 /// Limit types of a range (inclusive or exclusive)
1142 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1143 pub enum RangeLimits {
1144 /// Inclusive at the beginning, exclusive at the end
1146 /// Inclusive at the beginning and end
1150 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1152 /// A `box x` expression.
1154 /// An array (`[a, b, c, d]`)
1155 Array(Vec<P<Expr>>),
1158 /// The first field resolves to the function itself,
1159 /// and the second field is the list of arguments.
1160 /// This also represents calling the constructor of
1161 /// tuple-like ADTs such as tuple structs and enum variants.
1162 Call(P<Expr>, Vec<P<Expr>>),
1163 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1165 /// The `PathSegment` represents the method name and its generic arguments
1166 /// (within the angle brackets).
1167 /// The first element of the vector of an `Expr` is the expression that evaluates
1168 /// to the object on which the method is being called on (the receiver),
1169 /// and the remaining elements are the rest of the arguments.
1170 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1171 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1172 MethodCall(PathSegment, Vec<P<Expr>>),
1173 /// A tuple (e.g., `(a, b, c, d)`).
1175 /// A binary operation (e.g., `a + b`, `a * b`).
1176 Binary(BinOp, P<Expr>, P<Expr>),
1177 /// A unary operation (e.g., `!x`, `*x`).
1178 Unary(UnOp, P<Expr>),
1179 /// A literal (e.g., `1`, `"foo"`).
1181 /// A cast (e.g., `foo as f64`).
1182 Cast(P<Expr>, P<Ty>),
1183 /// A type ascription (e.g., `42: usize`).
1184 Type(P<Expr>, P<Ty>),
1185 /// A `let pat = expr` expression that is only semantically allowed in the condition
1186 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1187 Let(P<Pat>, P<Expr>),
1188 /// An `if` block, with an optional `else` block.
1190 /// `if expr { block } else { expr }`
1191 If(P<Expr>, P<Block>, Option<P<Expr>>),
1192 /// A while loop, with an optional label.
1194 /// `'label: while expr { block }`
1195 While(P<Expr>, P<Block>, Option<Label>),
1196 /// A `for` loop, with an optional label.
1198 /// `'label: for pat in expr { block }`
1200 /// This is desugared to a combination of `loop` and `match` expressions.
1201 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1202 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1204 /// `'label: loop { block }`
1205 Loop(P<Block>, Option<Label>),
1206 /// A `match` block.
1207 Match(P<Expr>, Vec<Arm>),
1208 /// A closure (e.g., `move |a, b, c| a + b + c`).
1210 /// The final span is the span of the argument block `|...|`.
1211 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1212 /// A block (`'label: { ... }`).
1213 Block(P<Block>, Option<Label>),
1214 /// An async block (`async move { ... }`).
1216 /// The `NodeId` is the `NodeId` for the closure that results from
1217 /// desugaring an async block, just like the NodeId field in the
1218 /// `IsAsync` enum. This is necessary in order to create a def for the
1219 /// closure which can be used as a parent of any child defs. Defs
1220 /// created during lowering cannot be made the parent of any other
1221 /// preexisting defs.
1222 Async(CaptureBy, NodeId, P<Block>),
1223 /// An await expression (`my_future.await`).
1226 /// A try block (`try { ... }`).
1229 /// An assignment (`a = foo()`).
1230 /// The `Span` argument is the span of the `=` token.
1231 Assign(P<Expr>, P<Expr>, Span),
1232 /// An assignment with an operator.
1235 AssignOp(BinOp, P<Expr>, P<Expr>),
1236 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1237 Field(P<Expr>, Ident),
1238 /// An indexing operation (e.g., `foo[2]`).
1239 Index(P<Expr>, P<Expr>),
1240 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1241 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1243 /// Variable reference, possibly containing `::` and/or type
1244 /// parameters (e.g., `foo::bar::<baz>`).
1246 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1247 Path(Option<QSelf>, Path),
1249 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1250 AddrOf(BorrowKind, Mutability, P<Expr>),
1251 /// A `break`, with an optional label to break, and an optional expression.
1252 Break(Option<Label>, Option<P<Expr>>),
1253 /// A `continue`, with an optional label.
1254 Continue(Option<Label>),
1255 /// A `return`, with an optional value to be returned.
1256 Ret(Option<P<Expr>>),
1258 /// Output of the `asm!()` macro.
1259 InlineAsm(P<InlineAsm>),
1261 /// A macro invocation; pre-expansion.
1264 /// A struct literal expression.
1266 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1267 /// where `base` is the `Option<Expr>`.
1268 Struct(Path, Vec<Field>, Option<P<Expr>>),
1270 /// An array literal constructed from one repeated element.
1272 /// E.g., `[1; 5]`. The expression is the element to be
1273 /// repeated; the constant is the number of times to repeat it.
1274 Repeat(P<Expr>, AnonConst),
1276 /// No-op: used solely so we can pretty-print faithfully.
1279 /// A try expression (`expr?`).
1282 /// A `yield`, with an optional value to be yielded.
1283 Yield(Option<P<Expr>>),
1285 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1289 /// The explicit `Self` type in a "qualified path". The actual
1290 /// path, including the trait and the associated item, is stored
1291 /// separately. `position` represents the index of the associated
1292 /// item qualified with this `Self` type.
1294 /// ```ignore (only-for-syntax-highlight)
1295 /// <Vec<T> as a::b::Trait>::AssociatedItem
1296 /// ^~~~~ ~~~~~~~~~~~~~~^
1299 /// <Vec<T>>::AssociatedItem
1303 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1307 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1308 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1309 /// 0`, this is an empty span.
1310 pub path_span: Span,
1311 pub position: usize,
1314 /// A capture clause used in closures and `async` blocks.
1315 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1316 pub enum CaptureBy {
1317 /// `move |x| y + x`.
1319 /// `move` keyword was not specified.
1323 /// The movability of a generator / closure literal:
1324 /// whether a generator contains self-references, causing it to be `!Unpin`.
1338 pub enum Movability {
1339 /// May contain self-references, `!Unpin`.
1341 /// Must not contain self-references, `Unpin`.
1345 /// Represents a macro invocation. The `path` indicates which macro
1346 /// is being invoked, and the `args` are arguments passed to it.
1347 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1350 pub args: P<MacArgs>,
1351 pub prior_type_ascription: Option<(Span, bool)>,
1355 pub fn span(&self) -> Span {
1356 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1360 /// Arguments passed to an attribute or a function-like macro.
1361 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1363 /// No arguments - `#[attr]`.
1365 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1366 Delimited(DelimSpan, MacDelimiter, TokenStream),
1367 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1369 /// Span of the `=` token.
1371 /// Token stream of the "value".
1377 pub fn delim(&self) -> DelimToken {
1379 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1380 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1384 pub fn span(&self) -> Option<Span> {
1386 MacArgs::Empty => None,
1387 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1388 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1392 /// Tokens inside the delimiters or after `=`.
1393 /// Proc macros see these tokens, for example.
1394 pub fn inner_tokens(&self) -> TokenStream {
1396 MacArgs::Empty => TokenStream::default(),
1397 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1401 /// Tokens together with the delimiters or `=`.
1402 /// Use of this method generally means that something suboptimal or hacky is happening.
1403 pub fn outer_tokens(&self) -> TokenStream {
1405 MacArgs::Empty => TokenStream::default(),
1406 MacArgs::Delimited(dspan, delim, ref tokens) => {
1407 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1409 MacArgs::Eq(eq_span, ref tokens) => {
1410 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1415 /// Whether a macro with these arguments needs a semicolon
1416 /// when used as a standalone item or statement.
1417 pub fn need_semicolon(&self) -> bool {
1418 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1422 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1423 pub enum MacDelimiter {
1430 crate fn to_token(self) -> DelimToken {
1432 MacDelimiter::Parenthesis => DelimToken::Paren,
1433 MacDelimiter::Bracket => DelimToken::Bracket,
1434 MacDelimiter::Brace => DelimToken::Brace,
1438 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1440 token::Paren => Some(MacDelimiter::Parenthesis),
1441 token::Bracket => Some(MacDelimiter::Bracket),
1442 token::Brace => Some(MacDelimiter::Brace),
1443 token::NoDelim => None,
1448 /// Represents a macro definition.
1449 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1450 pub struct MacroDef {
1451 pub body: P<MacArgs>,
1452 /// `true` if macro was defined with `macro_rules`.
1456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, Eq, PartialEq)]
1457 #[derive(HashStable_Generic)]
1459 /// A regular string, like `"foo"`.
1461 /// A raw string, like `r##"foo"##`.
1463 /// The value is the number of `#` symbols used.
1468 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1470 /// The original literal token as written in source code.
1471 pub token: token::Lit,
1472 /// The "semantic" representation of the literal lowered from the original tokens.
1473 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1474 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1479 /// Same as `Lit`, but restricted to string literals.
1480 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1482 /// The original literal token as written in source code.
1483 pub style: StrStyle,
1485 pub suffix: Option<Symbol>,
1487 /// The unescaped "semantic" representation of the literal lowered from the original token.
1488 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1489 pub symbol_unescaped: Symbol,
1493 crate fn as_lit(&self) -> Lit {
1494 let token_kind = match self.style {
1495 StrStyle::Cooked => token::Str,
1496 StrStyle::Raw(n) => token::StrRaw(n),
1499 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1501 kind: LitKind::Str(self.symbol_unescaped, self.style),
1506 /// Type of the integer literal based on provided suffix.
1507 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1508 #[derive(HashStable_Generic)]
1509 pub enum LitIntType {
1518 /// Type of the float literal based on provided suffix.
1519 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1520 #[derive(HashStable_Generic)]
1521 pub enum LitFloatType {
1522 /// A float literal with a suffix (`1f32` or `1E10f32`).
1524 /// A float literal without a suffix (`1.0 or 1.0E10`).
1530 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1531 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1533 /// A string literal (`"foo"`).
1534 Str(Symbol, StrStyle),
1535 /// A byte string (`b"foo"`).
1536 ByteStr(Lrc<Vec<u8>>),
1537 /// A byte char (`b'f'`).
1539 /// A character literal (`'a'`).
1541 /// An integer literal (`1`).
1542 Int(u128, LitIntType),
1543 /// A float literal (`1f64` or `1E10f64`).
1544 Float(Symbol, LitFloatType),
1545 /// A boolean literal.
1547 /// Placeholder for a literal that wasn't well-formed in some way.
1552 /// Returns `true` if this literal is a string.
1553 pub fn is_str(&self) -> bool {
1555 LitKind::Str(..) => true,
1560 /// Returns `true` if this literal is byte literal string.
1561 pub fn is_bytestr(&self) -> bool {
1563 LitKind::ByteStr(_) => true,
1568 /// Returns `true` if this is a numeric literal.
1569 pub fn is_numeric(&self) -> bool {
1571 LitKind::Int(..) | LitKind::Float(..) => true,
1576 /// Returns `true` if this literal has no suffix.
1577 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1578 pub fn is_unsuffixed(&self) -> bool {
1582 /// Returns `true` if this literal has a suffix.
1583 pub fn is_suffixed(&self) -> bool {
1585 // suffixed variants
1586 LitKind::Int(_, LitIntType::Signed(..))
1587 | LitKind::Int(_, LitIntType::Unsigned(..))
1588 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1589 // unsuffixed variants
1591 | LitKind::ByteStr(..)
1594 | LitKind::Int(_, LitIntType::Unsuffixed)
1595 | LitKind::Float(_, LitFloatType::Unsuffixed)
1597 | LitKind::Err(..) => false,
1602 // N.B., If you change this, you'll probably want to change the corresponding
1603 // type structure in `middle/ty.rs` as well.
1604 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1607 pub mutbl: Mutability,
1610 /// Represents a function's signature in a trait declaration,
1611 /// trait implementation, or free function.
1612 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1614 pub header: FnHeader,
1615 pub decl: P<FnDecl>,
1618 /// Represents associated items.
1619 /// These include items in `impl` and `trait` definitions.
1620 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1621 pub struct AssocItem {
1622 pub attrs: Vec<Attribute>,
1625 pub vis: Visibility,
1628 pub defaultness: Defaultness,
1629 pub generics: Generics,
1630 pub kind: AssocItemKind,
1631 /// See `Item::tokens` for what this is.
1632 pub tokens: Option<TokenStream>,
1635 /// Represents various kinds of content within an `impl`.
1637 /// The term "provided" in the variants below refers to the item having a default
1638 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
1639 /// In an implementation, all items must be provided.
1640 /// The `Option`s below denote the bodies, where `Some(_)`
1641 /// means "provided" and conversely `None` means "required".
1642 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1643 pub enum AssocItemKind {
1644 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
1645 /// If `def` is parsed, then the associated constant is provided, and otherwise required.
1646 Const(P<Ty>, Option<P<Expr>>),
1648 /// An associated function.
1649 Fn(FnSig, Option<P<Block>>),
1651 /// An associated type.
1652 TyAlias(GenericBounds, Option<P<Ty>>),
1654 /// A macro expanding to an associated item.
1677 pub fn name_str(self) -> &'static str {
1679 FloatTy::F32 => "f32",
1680 FloatTy::F64 => "f64",
1684 pub fn name(self) -> Symbol {
1686 FloatTy::F32 => sym::f32,
1687 FloatTy::F64 => sym::f64,
1691 pub fn bit_width(self) -> usize {
1722 pub fn name_str(&self) -> &'static str {
1724 IntTy::Isize => "isize",
1726 IntTy::I16 => "i16",
1727 IntTy::I32 => "i32",
1728 IntTy::I64 => "i64",
1729 IntTy::I128 => "i128",
1733 pub fn name(&self) -> Symbol {
1735 IntTy::Isize => sym::isize,
1736 IntTy::I8 => sym::i8,
1737 IntTy::I16 => sym::i16,
1738 IntTy::I32 => sym::i32,
1739 IntTy::I64 => sym::i64,
1740 IntTy::I128 => sym::i128,
1744 pub fn val_to_string(&self, val: i128) -> String {
1745 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1746 // are parsed as `u128`, so we wouldn't want to print an extra negative
1748 format!("{}{}", val as u128, self.name_str())
1751 pub fn bit_width(&self) -> Option<usize> {
1753 IntTy::Isize => return None,
1762 pub fn normalize(&self, target_width: u32) -> Self {
1764 IntTy::Isize => match target_width {
1768 _ => unreachable!(),
1798 pub fn name_str(&self) -> &'static str {
1800 UintTy::Usize => "usize",
1802 UintTy::U16 => "u16",
1803 UintTy::U32 => "u32",
1804 UintTy::U64 => "u64",
1805 UintTy::U128 => "u128",
1809 pub fn name(&self) -> Symbol {
1811 UintTy::Usize => sym::usize,
1812 UintTy::U8 => sym::u8,
1813 UintTy::U16 => sym::u16,
1814 UintTy::U32 => sym::u32,
1815 UintTy::U64 => sym::u64,
1816 UintTy::U128 => sym::u128,
1820 pub fn val_to_string(&self, val: u128) -> String {
1821 format!("{}{}", val, self.name_str())
1824 pub fn bit_width(&self) -> Option<usize> {
1826 UintTy::Usize => return None,
1831 UintTy::U128 => 128,
1835 pub fn normalize(&self, target_width: u32) -> Self {
1837 UintTy::Usize => match target_width {
1841 _ => unreachable!(),
1848 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1849 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1850 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1851 pub struct AssocTyConstraint {
1854 pub kind: AssocTyConstraintKind,
1858 /// The kinds of an `AssocTyConstraint`.
1859 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1860 pub enum AssocTyConstraintKind {
1861 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1862 Equality { ty: P<Ty> },
1863 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1864 Bound { bounds: GenericBounds },
1867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1874 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1875 pub struct BareFnTy {
1876 pub unsafety: Unsafety,
1878 pub generic_params: Vec<GenericParam>,
1879 pub decl: P<FnDecl>,
1882 /// The various kinds of type recognized by the compiler.
1883 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1885 /// A variable-length slice (`[T]`).
1887 /// A fixed length array (`[T; n]`).
1888 Array(P<Ty>, AnonConst),
1889 /// A raw pointer (`*const T` or `*mut T`).
1891 /// A reference (`&'a T` or `&'a mut T`).
1892 Rptr(Option<Lifetime>, MutTy),
1893 /// A bare function (e.g., `fn(usize) -> bool`).
1894 BareFn(P<BareFnTy>),
1895 /// The never type (`!`).
1897 /// A tuple (`(A, B, C, D,...)`).
1899 /// A path (`module::module::...::Type`), optionally
1900 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1902 /// Type parameters are stored in the `Path` itself.
1903 Path(Option<QSelf>, Path),
1904 /// A trait object type `Bound1 + Bound2 + Bound3`
1905 /// where `Bound` is a trait or a lifetime.
1906 TraitObject(GenericBounds, TraitObjectSyntax),
1907 /// An `impl Bound1 + Bound2 + Bound3` type
1908 /// where `Bound` is a trait or a lifetime.
1910 /// The `NodeId` exists to prevent lowering from having to
1911 /// generate `NodeId`s on the fly, which would complicate
1912 /// the generation of opaque `type Foo = impl Trait` items significantly.
1913 ImplTrait(NodeId, GenericBounds),
1914 /// No-op; kept solely so that we can pretty-print faithfully.
1918 /// This means the type should be inferred instead of it having been
1919 /// specified. This can appear anywhere in a type.
1921 /// Inferred type of a `self` or `&self` argument in a method.
1923 /// A macro in the type position.
1925 /// Placeholder for a kind that has failed to be defined.
1927 /// Placeholder for a `va_list`.
1932 pub fn is_implicit_self(&self) -> bool {
1933 if let TyKind::ImplicitSelf = *self { true } else { false }
1936 pub fn is_unit(&self) -> bool {
1937 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1940 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1941 /// in lowering to avoid making larger changes there and beyond.
1942 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1944 Self::ImplTrait(_, bounds) => Some(bounds),
1950 /// Syntax used to declare a trait object.
1951 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1952 pub enum TraitObjectSyntax {
1957 /// Inline assembly dialect.
1959 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1960 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1961 pub enum AsmDialect {
1966 /// Inline assembly.
1968 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1969 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1970 pub struct InlineAsmOutput {
1971 pub constraint: Symbol,
1974 pub is_indirect: bool,
1977 /// Inline assembly.
1979 /// E.g., `asm!("NOP");`.
1980 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1981 pub struct InlineAsm {
1983 pub asm_str_style: StrStyle,
1984 pub outputs: Vec<InlineAsmOutput>,
1985 pub inputs: Vec<(Symbol, P<Expr>)>,
1986 pub clobbers: Vec<Symbol>,
1988 pub alignstack: bool,
1989 pub dialect: AsmDialect,
1992 /// A parameter in a function header.
1994 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1995 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2002 pub is_placeholder: bool,
2005 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2007 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2008 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2010 /// `self`, `mut self`
2012 /// `&'lt self`, `&'lt mut self`
2013 Region(Option<Lifetime>, Mutability),
2014 /// `self: TYPE`, `mut self: TYPE`
2015 Explicit(P<Ty>, Mutability),
2018 pub type ExplicitSelf = Spanned<SelfKind>;
2021 /// Attempts to cast parameter to `ExplicitSelf`.
2022 pub fn to_self(&self) -> Option<ExplicitSelf> {
2023 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2024 if ident.name == kw::SelfLower {
2025 return match self.ty.kind {
2026 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2027 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2028 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2031 self.pat.span.to(self.ty.span),
2032 SelfKind::Explicit(self.ty.clone(), mutbl),
2040 /// Returns `true` if parameter is `self`.
2041 pub fn is_self(&self) -> bool {
2042 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2043 ident.name == kw::SelfLower
2049 /// Builds a `Param` object from `ExplicitSelf`.
2050 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2051 let span = eself.span.to(eself_ident.span);
2052 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2053 let param = |mutbl, ty| Param {
2057 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2063 is_placeholder: false,
2066 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2067 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2068 SelfKind::Region(lt, mutbl) => param(
2072 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2080 /// A signature (not the body) of a function declaration.
2082 /// E.g., `fn foo(bar: baz)`.
2084 /// Please note that it's different from `FnHeader` structure
2085 /// which contains metadata about function safety, asyncness, constness and ABI.
2086 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2088 pub inputs: Vec<Param>,
2089 pub output: FunctionRetTy,
2093 pub fn get_self(&self) -> Option<ExplicitSelf> {
2094 self.inputs.get(0).and_then(Param::to_self)
2096 pub fn has_self(&self) -> bool {
2097 self.inputs.get(0).map_or(false, Param::is_self)
2099 pub fn c_variadic(&self) -> bool {
2100 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2101 TyKind::CVarArgs => true,
2107 /// Is the trait definition an auto trait?
2108 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2133 pub fn prefix_str(&self) -> &'static str {
2135 Unsafety::Unsafe => "unsafe ",
2136 Unsafety::Normal => "",
2141 impl fmt::Display for Unsafety {
2142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2145 Unsafety::Normal => "normal",
2146 Unsafety::Unsafe => "unsafe",
2153 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2155 Async { closure_id: NodeId, return_impl_trait_id: NodeId },
2160 pub fn is_async(self) -> bool {
2161 if let IsAsync::Async { .. } = self { true } else { false }
2164 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2165 pub fn opt_return_id(self) -> Option<NodeId> {
2167 IsAsync::Async { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2168 IsAsync::NotAsync => None,
2173 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
2174 #[derive(HashStable_Generic)]
2175 pub enum Constness {
2180 /// Item defaultness.
2181 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2182 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2183 pub enum Defaultness {
2188 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2189 pub enum ImplPolarity {
2190 /// `impl Trait for Type`
2192 /// `impl !Trait for Type`
2196 impl fmt::Debug for ImplPolarity {
2197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2199 ImplPolarity::Positive => "positive".fmt(f),
2200 ImplPolarity::Negative => "negative".fmt(f),
2205 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2206 pub enum FunctionRetTy {
2207 // FIXME(Centril): Rename to `FnRetTy` and in HIR also.
2208 /// Returns type is not specified.
2210 /// Functions default to `()` and closures default to inference.
2211 /// Span points to where return type would be inserted.
2213 /// Everything else.
2217 impl FunctionRetTy {
2218 pub fn span(&self) -> Span {
2220 FunctionRetTy::Default(span) => span,
2221 FunctionRetTy::Ty(ref ty) => ty.span,
2226 /// Module declaration.
2228 /// E.g., `mod foo;` or `mod foo { .. }`.
2229 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2231 /// A span from the first token past `{` to the last token until `}`.
2232 /// For `mod foo;`, the inner span ranges from the first token
2233 /// to the last token in the external file.
2235 pub items: Vec<P<Item>>,
2236 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2240 /// Foreign module declaration.
2242 /// E.g., `extern { .. }` or `extern C { .. }`.
2243 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2244 pub struct ForeignMod {
2245 pub abi: Option<StrLit>,
2246 pub items: Vec<ForeignItem>,
2249 /// Global inline assembly.
2251 /// Also known as "module-level assembly" or "file-scoped assembly".
2252 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2253 pub struct GlobalAsm {
2257 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2258 pub struct EnumDef {
2259 pub variants: Vec<Variant>,
2262 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2263 pub struct Variant {
2264 /// Attributes of the variant.
2265 pub attrs: Vec<Attribute>,
2266 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2270 /// The visibility of the variant. Syntactically accepted but not semantically.
2271 pub vis: Visibility,
2272 /// Name of the variant.
2275 /// Fields and constructor id of the variant.
2276 pub data: VariantData,
2277 /// Explicit discriminant, e.g., `Foo = 1`.
2278 pub disr_expr: Option<AnonConst>,
2279 /// Is a macro placeholder
2280 pub is_placeholder: bool,
2283 /// Part of `use` item to the right of its prefix.
2284 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2285 pub enum UseTreeKind {
2286 /// `use prefix` or `use prefix as rename`
2288 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2290 Simple(Option<Ident>, NodeId, NodeId),
2291 /// `use prefix::{...}`
2292 Nested(Vec<(UseTree, NodeId)>),
2297 /// A tree of paths sharing common prefixes.
2298 /// Used in `use` items both at top-level and inside of braces in import groups.
2299 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2300 pub struct UseTree {
2302 pub kind: UseTreeKind,
2307 pub fn ident(&self) -> Ident {
2309 UseTreeKind::Simple(Some(rename), ..) => rename,
2310 UseTreeKind::Simple(None, ..) => {
2311 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2313 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2318 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2319 /// are contained as statements within items. These two cases need to be
2320 /// distinguished for pretty-printing.
2321 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2322 pub enum AttrStyle {
2327 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2328 pub struct AttrId(pub usize);
2330 impl Idx for AttrId {
2331 fn new(idx: usize) -> Self {
2334 fn index(self) -> usize {
2339 impl rustc_serialize::Encodable for AttrId {
2340 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2345 impl rustc_serialize::Decodable for AttrId {
2346 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2347 d.read_nil().map(|_| crate::attr::mk_attr_id())
2351 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2352 pub struct AttrItem {
2357 /// A list of attributes.
2358 pub type AttrVec = ThinVec<Attribute>;
2360 /// Metadata associated with an item.
2361 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2362 pub struct Attribute {
2365 /// Denotes if the attribute decorates the following construct (outer)
2366 /// or the construct this attribute is contained within (inner).
2367 pub style: AttrStyle,
2371 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2373 /// A normal attribute.
2376 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2377 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2378 /// variant (which is much less compact and thus more expensive).
2382 /// `TraitRef`s appear in impls.
2384 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2385 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2386 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2387 /// same as the impl's `NodeId`).
2388 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2389 pub struct TraitRef {
2394 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2395 pub struct PolyTraitRef {
2396 /// The `'a` in `<'a> Foo<&'a T>`.
2397 pub bound_generic_params: Vec<GenericParam>,
2399 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2400 pub trait_ref: TraitRef,
2406 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2408 bound_generic_params: generic_params,
2409 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2415 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2416 pub enum CrateSugar {
2417 /// Source is `pub(crate)`.
2420 /// Source is (just) `crate`.
2424 pub type Visibility = Spanned<VisibilityKind>;
2426 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2427 pub enum VisibilityKind {
2430 Restricted { path: P<Path>, id: NodeId },
2434 impl VisibilityKind {
2435 pub fn is_pub(&self) -> bool {
2436 if let VisibilityKind::Public = *self { true } else { false }
2440 /// Field of a struct.
2442 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2443 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2444 pub struct StructField {
2445 pub attrs: Vec<Attribute>,
2448 pub vis: Visibility,
2449 pub ident: Option<Ident>,
2452 pub is_placeholder: bool,
2455 /// Fields and constructor ids of enum variants and structs.
2456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2457 pub enum VariantData {
2460 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2461 Struct(Vec<StructField>, bool),
2464 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2465 Tuple(Vec<StructField>, NodeId),
2468 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2473 /// Return the fields of this variant.
2474 pub fn fields(&self) -> &[StructField] {
2476 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2481 /// Return the `NodeId` of this variant's constructor, if it has one.
2482 pub fn ctor_id(&self) -> Option<NodeId> {
2484 VariantData::Struct(..) => None,
2485 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2492 /// The name might be a dummy name in case of anonymous items.
2493 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2494 pub struct Item<K = ItemKind> {
2495 pub attrs: Vec<Attribute>,
2498 pub vis: Visibility,
2503 /// Original tokens this item was parsed from. This isn't necessarily
2504 /// available for all items, although over time more and more items should
2505 /// have this be `Some`. Right now this is primarily used for procedural
2506 /// macros, notably custom attributes.
2508 /// Note that the tokens here do not include the outer attributes, but will
2509 /// include inner attributes.
2510 pub tokens: Option<TokenStream>,
2514 /// Return the span that encompasses the attributes.
2515 pub fn span_with_attributes(&self) -> Span {
2516 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2520 /// `extern` qualifier on a function item or function type.
2521 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2529 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2530 abi.map_or(Extern::Implicit, Extern::Explicit)
2534 /// A function header.
2536 /// All the information between the visibility and the name of the function is
2537 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2538 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2539 pub struct FnHeader {
2540 pub unsafety: Unsafety,
2541 pub asyncness: Spanned<IsAsync>,
2542 pub constness: Spanned<Constness>,
2546 impl Default for FnHeader {
2547 fn default() -> FnHeader {
2549 unsafety: Unsafety::Normal,
2550 asyncness: dummy_spanned(IsAsync::NotAsync),
2551 constness: dummy_spanned(Constness::NotConst),
2557 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2559 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2561 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2562 ExternCrate(Option<Name>),
2563 /// A use declaration item (`use`).
2565 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2567 /// A static item (`static`).
2569 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2570 Static(P<Ty>, Mutability, P<Expr>),
2571 /// A constant item (`const`).
2573 /// E.g., `const FOO: i32 = 42;`.
2574 Const(P<Ty>, P<Expr>),
2575 /// A function declaration (`fn`).
2577 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2578 Fn(FnSig, Generics, P<Block>),
2579 /// A module declaration (`mod`).
2581 /// E.g., `mod foo;` or `mod foo { .. }`.
2583 /// An external module (`extern`).
2585 /// E.g., `extern {}` or `extern "C" {}`.
2586 ForeignMod(ForeignMod),
2587 /// Module-level inline assembly (from `global_asm!()`).
2588 GlobalAsm(P<GlobalAsm>),
2589 /// A type alias (`type`).
2591 /// E.g., `type Foo = Bar<u8>;`.
2592 TyAlias(P<Ty>, Generics),
2593 /// An enum definition (`enum`).
2595 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2596 Enum(EnumDef, Generics),
2597 /// A struct definition (`struct`).
2599 /// E.g., `struct Foo<A> { x: A }`.
2600 Struct(VariantData, Generics),
2601 /// A union definition (`union`).
2603 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2604 Union(VariantData, Generics),
2605 /// A trait declaration (`trait`).
2607 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2608 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<AssocItem>),
2611 /// E.g., `trait Foo = Bar + Quux;`.
2612 TraitAlias(Generics, GenericBounds),
2613 /// An implementation.
2615 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2618 polarity: ImplPolarity,
2619 defaultness: Defaultness,
2620 constness: Constness,
2623 /// The trait being implemented, if any.
2624 of_trait: Option<TraitRef>,
2627 items: Vec<AssocItem>,
2629 /// A macro invocation.
2631 /// E.g., `foo!(..)`.
2634 /// A macro definition.
2639 pub fn descriptive_variant(&self) -> &str {
2641 ItemKind::ExternCrate(..) => "extern crate",
2642 ItemKind::Use(..) => "use",
2643 ItemKind::Static(..) => "static item",
2644 ItemKind::Const(..) => "constant item",
2645 ItemKind::Fn(..) => "function",
2646 ItemKind::Mod(..) => "module",
2647 ItemKind::ForeignMod(..) => "foreign module",
2648 ItemKind::GlobalAsm(..) => "global asm",
2649 ItemKind::TyAlias(..) => "type alias",
2650 ItemKind::Enum(..) => "enum",
2651 ItemKind::Struct(..) => "struct",
2652 ItemKind::Union(..) => "union",
2653 ItemKind::Trait(..) => "trait",
2654 ItemKind::TraitAlias(..) => "trait alias",
2655 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl { .. } => "item",
2660 pub type ForeignItem = Item<ForeignItemKind>;
2662 /// An item within an `extern` block.
2663 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2664 pub enum ForeignItemKind {
2665 /// A foreign function.
2666 Fn(P<FnDecl>, Generics),
2667 /// A foreign static item (`static ext: u8`).
2668 Static(P<Ty>, Mutability),
2671 /// A macro invocation.
2675 impl ForeignItemKind {
2676 pub fn descriptive_variant(&self) -> &str {
2678 ForeignItemKind::Fn(..) => "foreign function",
2679 ForeignItemKind::Static(..) => "foreign static item",
2680 ForeignItemKind::Ty => "foreign type",
2681 ForeignItemKind::Macro(..) => "macro in foreign module",