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::{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 crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
261 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
263 /// Negative bounds should also be handled here.
264 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
265 pub enum TraitBoundModifier {
277 // This parses but will be rejected during AST validation.
281 /// The AST represents all type param bounds as types.
282 /// `typeck::collect::compute_bounds` matches these against
283 /// the "special" built-in traits (see `middle::lang_items`) and
284 /// detects `Copy`, `Send` and `Sync`.
285 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
286 pub enum GenericBound {
287 Trait(PolyTraitRef, TraitBoundModifier),
292 pub fn span(&self) -> Span {
294 &GenericBound::Trait(ref t, ..) => t.span,
295 &GenericBound::Outlives(ref l) => l.ident.span,
300 pub type GenericBounds = Vec<GenericBound>;
302 /// Specifies the enforced ordering for generic parameters. In the future,
303 /// if we wanted to relax this order, we could override `PartialEq` and
304 /// `PartialOrd`, to allow the kinds to be unordered.
305 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
306 pub enum ParamKindOrd {
312 impl fmt::Display for ParamKindOrd {
313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 ParamKindOrd::Lifetime => "lifetime".fmt(f),
316 ParamKindOrd::Type => "type".fmt(f),
317 ParamKindOrd::Const => "const".fmt(f),
322 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
323 pub enum GenericParamKind {
324 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
327 default: Option<P<Ty>>,
334 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
335 pub struct GenericParam {
339 pub bounds: GenericBounds,
340 pub is_placeholder: bool,
341 pub kind: GenericParamKind,
344 /// Represents lifetime, type and const parameters attached to a declaration of
345 /// a function, enum, trait, etc.
346 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
347 pub struct Generics {
348 pub params: Vec<GenericParam>,
349 pub where_clause: WhereClause,
353 impl Default for Generics {
354 /// Creates an instance of `Generics`.
355 fn default() -> Generics {
358 where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP },
364 /// A where-clause in a definition.
365 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
366 pub struct WhereClause {
367 pub predicates: Vec<WherePredicate>,
371 /// A single predicate in a where-clause.
372 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
373 pub enum WherePredicate {
374 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
375 BoundPredicate(WhereBoundPredicate),
376 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
377 RegionPredicate(WhereRegionPredicate),
378 /// An equality predicate (unsupported).
379 EqPredicate(WhereEqPredicate),
382 impl WherePredicate {
383 pub fn span(&self) -> Span {
385 &WherePredicate::BoundPredicate(ref p) => p.span,
386 &WherePredicate::RegionPredicate(ref p) => p.span,
387 &WherePredicate::EqPredicate(ref p) => p.span,
394 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
395 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
396 pub struct WhereBoundPredicate {
398 /// Any generics from a `for` binding.
399 pub bound_generic_params: Vec<GenericParam>,
400 /// The type being bounded.
401 pub bounded_ty: P<Ty>,
402 /// Trait and lifetime bounds (`Clone + Send + 'static`).
403 pub bounds: GenericBounds,
406 /// A lifetime predicate.
408 /// E.g., `'a: 'b + 'c`.
409 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
410 pub struct WhereRegionPredicate {
412 pub lifetime: Lifetime,
413 pub bounds: GenericBounds,
416 /// An equality predicate (unsupported).
419 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
420 pub struct WhereEqPredicate {
427 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
430 pub attrs: Vec<Attribute>,
432 /// The order of items in the HIR is unrelated to the order of
433 /// items in the AST. However, we generate proc macro harnesses
434 /// based on the AST order, and later refer to these harnesses
435 /// from the HIR. This field keeps track of the order in which
436 /// we generated proc macros harnesses, so that we can map
437 /// HIR proc macros items back to their harness items.
438 pub proc_macros: Vec<NodeId>,
441 /// Possible values inside of compile-time attribute lists.
443 /// E.g., the '..' in `#[name(..)]`.
444 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
445 pub enum NestedMetaItem {
446 /// A full MetaItem, for recursive meta items.
450 /// E.g., `"foo"`, `64`, `true`.
454 /// A spanned compile-time attribute item.
456 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
457 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
458 pub struct MetaItem {
460 pub kind: MetaItemKind,
464 /// A compile-time attribute item.
466 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
467 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
468 pub enum MetaItemKind {
471 /// E.g., `test` as in `#[test]`.
475 /// E.g., `derive(..)` as in `#[derive(..)]`.
476 List(Vec<NestedMetaItem>),
477 /// Name value meta item.
479 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
483 /// A block (`{ .. }`).
485 /// E.g., `{ .. }` as in `fn foo() { .. }`.
486 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
488 /// The statements in the block.
489 pub stmts: Vec<Stmt>,
491 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
492 pub rules: BlockCheckMode,
496 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
504 /// Attempt reparsing the pattern as a type.
505 /// This is intended for use by diagnostics.
506 pub fn to_ty(&self) -> Option<P<Ty>> {
507 let kind = match &self.kind {
508 // In a type expression `_` is an inference variable.
509 PatKind::Wild => TyKind::Infer,
510 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
511 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
512 TyKind::Path(None, Path::from_ident(*ident))
514 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
515 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
516 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
517 PatKind::Ref(pat, mutbl) => {
518 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
520 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
521 // when `P` can be reparsed as a type `T`.
522 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
523 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
524 // assuming `T0` to `Tn` are all syntactically valid as types.
525 PatKind::Tuple(pats) => {
526 let mut tys = Vec::with_capacity(pats.len());
527 // FIXME(#48994) - could just be collected into an Option<Vec>
529 tys.push(pat.to_ty()?);
536 Some(P(Ty { kind, id: self.id, span: self.span }))
539 /// Walk top-down and call `it` in each place where a pattern occurs
540 /// starting with the root pattern `walk` is called on. If `it` returns
541 /// false then we will descend no further but siblings will be processed.
542 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
548 // Walk into the pattern associated with `Ident` (if any).
549 PatKind::Ident(_, _, Some(p)) => p.walk(it),
551 // Walk into each field of struct.
552 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
554 // Sequence of patterns.
555 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
556 s.iter().for_each(|p| p.walk(it))
559 // Trivial wrappers over inner patterns.
560 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
562 // These patterns do not contain subpatterns, skip.
569 | PatKind::Mac(_) => {}
573 /// Is this a `..` pattern?
574 pub fn is_rest(&self) -> bool {
576 PatKind::Rest => true,
582 /// A single field in a struct pattern
584 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
585 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
586 /// except is_shorthand is true
587 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
588 pub struct FieldPat {
589 /// The identifier for the field
591 /// The pattern the field is destructured to
593 pub is_shorthand: bool,
597 pub is_placeholder: bool,
600 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
601 pub enum BindingMode {
606 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
608 Included(RangeSyntax),
612 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
613 pub enum RangeSyntax {
620 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
622 /// Represents a wildcard pattern (`_`).
625 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
626 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
627 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
628 /// during name resolution.
629 Ident(BindingMode, Ident, Option<P<Pat>>),
631 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
632 /// The `bool` is `true` in the presence of a `..`.
633 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
635 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
636 TupleStruct(Path, Vec<P<Pat>>),
638 /// An or-pattern `A | B | C`.
639 /// Invariant: `pats.len() >= 2`.
642 /// A possibly qualified path pattern.
643 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
644 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
645 /// only legally refer to associated constants.
646 Path(Option<QSelf>, Path),
648 /// A tuple pattern (`(a, b)`).
654 /// A reference pattern (e.g., `&mut (a, b)`).
655 Ref(P<Pat>, Mutability),
660 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
661 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
663 /// A slice pattern `[a, b, c]`.
666 /// A rest pattern `..`.
668 /// Syntactically it is valid anywhere.
670 /// Semantically however, it only has meaning immediately inside:
671 /// - a slice pattern: `[a, .., b]`,
672 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
673 /// - a tuple pattern: `(a, .., b)`,
674 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
676 /// In all of these cases, an additional restriction applies,
677 /// only one rest pattern may occur in the pattern sequences.
680 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
683 /// A macro pattern; pre-expansion.
700 pub enum Mutability {
706 /// Returns `MutMutable` only if both `self` and `other` are mutable.
707 pub fn and(self, other: Self) -> Self {
709 Mutability::Mut => other,
710 Mutability::Not => Mutability::Not,
714 pub fn invert(self) -> Self {
716 Mutability::Mut => Mutability::Not,
717 Mutability::Not => Mutability::Mut,
721 pub fn prefix_str(&self) -> &'static str {
723 Mutability::Mut => "mut ",
724 Mutability::Not => "",
729 /// The kind of borrow in an `AddrOf` expression,
730 /// e.g., `&place` or `&raw const place`.
731 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
732 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
733 pub enum BorrowKind {
734 /// A normal borrow, `&$expr` or `&mut $expr`.
735 /// The resulting type is either `&'a T` or `&'a mut T`
736 /// where `T = typeof($expr)` and `'a` is some lifetime.
738 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
739 /// The resulting type is either `*const T` or `*mut T`
740 /// where `T = typeof($expr)`.
744 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
746 /// The `+` operator (addition)
748 /// The `-` operator (subtraction)
750 /// The `*` operator (multiplication)
752 /// The `/` operator (division)
754 /// The `%` operator (modulus)
756 /// The `&&` operator (logical and)
758 /// The `||` operator (logical or)
760 /// The `^` operator (bitwise xor)
762 /// The `&` operator (bitwise and)
764 /// The `|` operator (bitwise or)
766 /// The `<<` operator (shift left)
768 /// The `>>` operator (shift right)
770 /// The `==` operator (equality)
772 /// The `<` operator (less than)
774 /// The `<=` operator (less than or equal to)
776 /// The `!=` operator (not equal to)
778 /// The `>=` operator (greater than or equal to)
780 /// The `>` operator (greater than)
785 pub fn to_string(&self) -> &'static str {
808 pub fn lazy(&self) -> bool {
810 BinOpKind::And | BinOpKind::Or => true,
815 pub fn is_shift(&self) -> bool {
817 BinOpKind::Shl | BinOpKind::Shr => true,
822 pub fn is_comparison(&self) -> bool {
824 // Note for developers: please keep this as is;
825 // we want compilation to fail if another variant is added.
827 Eq | Lt | Le | Ne | Gt | Ge => true,
828 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
832 /// Returns `true` if the binary operator takes its arguments by value
833 pub fn is_by_value(&self) -> bool {
834 !self.is_comparison()
838 pub type BinOp = Spanned<BinOpKind>;
842 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
843 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
845 /// The `*` operator for dereferencing
847 /// The `!` operator for logical inversion
849 /// The `-` operator for negation
854 /// Returns `true` if the unary operator takes its argument by value
855 pub fn is_by_value(u: UnOp) -> bool {
857 UnOp::Neg | UnOp::Not => true,
862 pub fn to_string(op: UnOp) -> &'static str {
872 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
880 pub fn add_trailing_semicolon(mut self) -> Self {
881 self.kind = match self.kind {
882 StmtKind::Expr(expr) => StmtKind::Semi(expr),
883 StmtKind::Mac(mac) => {
884 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
891 pub fn is_item(&self) -> bool {
893 StmtKind::Item(_) => true,
898 pub fn is_expr(&self) -> bool {
900 StmtKind::Expr(_) => true,
906 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
908 /// A local (let) binding.
910 /// An item definition.
912 /// Expr without trailing semi-colon.
914 /// Expr with a trailing semi-colon.
917 Mac(P<(Mac, MacStmtStyle, AttrVec)>),
920 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
921 pub enum MacStmtStyle {
922 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
923 /// `foo!(...);`, `foo![...];`).
925 /// The macro statement had braces (e.g., `foo! { ... }`).
927 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
928 /// `foo!(...)`). All of these will end up being converted into macro
933 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
934 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
938 pub ty: Option<P<Ty>>,
939 /// Initializer expression to set the value, if any.
940 pub init: Option<P<Expr>>,
945 /// An arm of a 'match'.
947 /// E.g., `0..=10 => { println!("match!") }` as in
951 /// 0..=10 => { println!("match!") },
952 /// _ => { println!("no match!") },
955 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
957 pub attrs: Vec<Attribute>,
958 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
960 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
961 pub guard: Option<P<Expr>>,
966 pub is_placeholder: bool,
969 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
970 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
977 pub is_shorthand: bool,
978 pub is_placeholder: bool,
981 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
982 pub enum BlockCheckMode {
984 Unsafe(UnsafeSource),
987 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
988 pub enum UnsafeSource {
993 /// A constant (expression) that's not an item or associated item,
994 /// but needs its own `DefId` for type-checking, const-eval, etc.
995 /// These are usually found nested inside types (e.g., array lengths)
996 /// or expressions (e.g., repeat counts), and also used to define
997 /// explicit discriminant values for enum variants.
998 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
999 pub struct AnonConst {
1005 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1013 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1014 #[cfg(target_arch = "x86_64")]
1015 rustc_data_structures::static_assert_size!(Expr, 96);
1018 /// Returns `true` if this expression would be valid somewhere that expects a value;
1019 /// for example, an `if` condition.
1020 pub fn returns(&self) -> bool {
1021 if let ExprKind::Block(ref block, _) = self.kind {
1022 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1024 Some(&StmtKind::Expr(_)) => true,
1025 Some(&StmtKind::Semi(ref expr)) => {
1026 if let ExprKind::Ret(_) = expr.kind {
1027 // Last statement is explicit return.
1033 // This is a block that doesn't end in either an implicit or explicit return.
1037 // This is not a block, it is a value.
1042 pub fn to_bound(&self) -> Option<GenericBound> {
1044 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1045 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1046 TraitBoundModifier::None,
1052 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1053 pub fn to_ty(&self) -> Option<P<Ty>> {
1054 let kind = match &self.kind {
1055 // Trivial conversions.
1056 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1057 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1059 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1061 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1062 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1065 ExprKind::Repeat(expr, expr_len) => {
1066 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1069 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1071 ExprKind::Tup(exprs) => {
1072 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1076 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1077 // then type of result is trait object.
1078 // Othewise we don't assume the result type.
1079 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1080 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1081 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1087 // This expression doesn't look like a type syntactically.
1091 Some(P(Ty { kind, id: self.id, span: self.span }))
1094 pub fn precedence(&self) -> ExprPrecedence {
1096 ExprKind::Box(_) => ExprPrecedence::Box,
1097 ExprKind::Array(_) => ExprPrecedence::Array,
1098 ExprKind::Call(..) => ExprPrecedence::Call,
1099 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1100 ExprKind::Tup(_) => ExprPrecedence::Tup,
1101 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1102 ExprKind::Unary(..) => ExprPrecedence::Unary,
1103 ExprKind::Lit(_) => ExprPrecedence::Lit,
1104 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1105 ExprKind::Let(..) => ExprPrecedence::Let,
1106 ExprKind::If(..) => ExprPrecedence::If,
1107 ExprKind::While(..) => ExprPrecedence::While,
1108 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1109 ExprKind::Loop(..) => ExprPrecedence::Loop,
1110 ExprKind::Match(..) => ExprPrecedence::Match,
1111 ExprKind::Closure(..) => ExprPrecedence::Closure,
1112 ExprKind::Block(..) => ExprPrecedence::Block,
1113 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1114 ExprKind::Async(..) => ExprPrecedence::Async,
1115 ExprKind::Await(..) => ExprPrecedence::Await,
1116 ExprKind::Assign(..) => ExprPrecedence::Assign,
1117 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1118 ExprKind::Field(..) => ExprPrecedence::Field,
1119 ExprKind::Index(..) => ExprPrecedence::Index,
1120 ExprKind::Range(..) => ExprPrecedence::Range,
1121 ExprKind::Path(..) => ExprPrecedence::Path,
1122 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1123 ExprKind::Break(..) => ExprPrecedence::Break,
1124 ExprKind::Continue(..) => ExprPrecedence::Continue,
1125 ExprKind::Ret(..) => ExprPrecedence::Ret,
1126 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1127 ExprKind::Mac(..) => ExprPrecedence::Mac,
1128 ExprKind::Struct(..) => ExprPrecedence::Struct,
1129 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1130 ExprKind::Paren(..) => ExprPrecedence::Paren,
1131 ExprKind::Try(..) => ExprPrecedence::Try,
1132 ExprKind::Yield(..) => ExprPrecedence::Yield,
1133 ExprKind::Err => ExprPrecedence::Err,
1138 /// Limit types of a range (inclusive or exclusive)
1139 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1140 pub enum RangeLimits {
1141 /// Inclusive at the beginning, exclusive at the end
1143 /// Inclusive at the beginning and end
1147 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1149 /// A `box x` expression.
1151 /// An array (`[a, b, c, d]`)
1152 Array(Vec<P<Expr>>),
1155 /// The first field resolves to the function itself,
1156 /// and the second field is the list of arguments.
1157 /// This also represents calling the constructor of
1158 /// tuple-like ADTs such as tuple structs and enum variants.
1159 Call(P<Expr>, Vec<P<Expr>>),
1160 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1162 /// The `PathSegment` represents the method name and its generic arguments
1163 /// (within the angle brackets).
1164 /// The first element of the vector of an `Expr` is the expression that evaluates
1165 /// to the object on which the method is being called on (the receiver),
1166 /// and the remaining elements are the rest of the arguments.
1167 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1168 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1169 MethodCall(PathSegment, Vec<P<Expr>>),
1170 /// A tuple (e.g., `(a, b, c, d)`).
1172 /// A binary operation (e.g., `a + b`, `a * b`).
1173 Binary(BinOp, P<Expr>, P<Expr>),
1174 /// A unary operation (e.g., `!x`, `*x`).
1175 Unary(UnOp, P<Expr>),
1176 /// A literal (e.g., `1`, `"foo"`).
1178 /// A cast (e.g., `foo as f64`).
1179 Cast(P<Expr>, P<Ty>),
1180 /// A type ascription (e.g., `42: usize`).
1181 Type(P<Expr>, P<Ty>),
1182 /// A `let pat = expr` expression that is only semantically allowed in the condition
1183 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1184 Let(P<Pat>, P<Expr>),
1185 /// An `if` block, with an optional `else` block.
1187 /// `if expr { block } else { expr }`
1188 If(P<Expr>, P<Block>, Option<P<Expr>>),
1189 /// A while loop, with an optional label.
1191 /// `'label: while expr { block }`
1192 While(P<Expr>, P<Block>, Option<Label>),
1193 /// A `for` loop, with an optional label.
1195 /// `'label: for pat in expr { block }`
1197 /// This is desugared to a combination of `loop` and `match` expressions.
1198 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1199 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1201 /// `'label: loop { block }`
1202 Loop(P<Block>, Option<Label>),
1203 /// A `match` block.
1204 Match(P<Expr>, Vec<Arm>),
1205 /// A closure (e.g., `move |a, b, c| a + b + c`).
1207 /// The final span is the span of the argument block `|...|`.
1208 Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span),
1209 /// A block (`'label: { ... }`).
1210 Block(P<Block>, Option<Label>),
1211 /// An async block (`async move { ... }`).
1213 /// The `NodeId` is the `NodeId` for the closure that results from
1214 /// desugaring an async block, just like the NodeId field in the
1215 /// `Async::Yes` variant. This is necessary in order to create a def for the
1216 /// closure which can be used as a parent of any child defs. Defs
1217 /// created during lowering cannot be made the parent of any other
1218 /// preexisting defs.
1219 Async(CaptureBy, NodeId, P<Block>),
1220 /// An await expression (`my_future.await`).
1223 /// A try block (`try { ... }`).
1226 /// An assignment (`a = foo()`).
1227 /// The `Span` argument is the span of the `=` token.
1228 Assign(P<Expr>, P<Expr>, Span),
1229 /// An assignment with an operator.
1232 AssignOp(BinOp, P<Expr>, P<Expr>),
1233 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1234 Field(P<Expr>, Ident),
1235 /// An indexing operation (e.g., `foo[2]`).
1236 Index(P<Expr>, P<Expr>),
1237 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1238 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1240 /// Variable reference, possibly containing `::` and/or type
1241 /// parameters (e.g., `foo::bar::<baz>`).
1243 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1244 Path(Option<QSelf>, Path),
1246 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1247 AddrOf(BorrowKind, Mutability, P<Expr>),
1248 /// A `break`, with an optional label to break, and an optional expression.
1249 Break(Option<Label>, Option<P<Expr>>),
1250 /// A `continue`, with an optional label.
1251 Continue(Option<Label>),
1252 /// A `return`, with an optional value to be returned.
1253 Ret(Option<P<Expr>>),
1255 /// Output of the `asm!()` macro.
1256 InlineAsm(P<InlineAsm>),
1258 /// A macro invocation; pre-expansion.
1261 /// A struct literal expression.
1263 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1264 /// where `base` is the `Option<Expr>`.
1265 Struct(Path, Vec<Field>, Option<P<Expr>>),
1267 /// An array literal constructed from one repeated element.
1269 /// E.g., `[1; 5]`. The expression is the element to be
1270 /// repeated; the constant is the number of times to repeat it.
1271 Repeat(P<Expr>, AnonConst),
1273 /// No-op: used solely so we can pretty-print faithfully.
1276 /// A try expression (`expr?`).
1279 /// A `yield`, with an optional value to be yielded.
1280 Yield(Option<P<Expr>>),
1282 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1286 /// The explicit `Self` type in a "qualified path". The actual
1287 /// path, including the trait and the associated item, is stored
1288 /// separately. `position` represents the index of the associated
1289 /// item qualified with this `Self` type.
1291 /// ```ignore (only-for-syntax-highlight)
1292 /// <Vec<T> as a::b::Trait>::AssociatedItem
1293 /// ^~~~~ ~~~~~~~~~~~~~~^
1296 /// <Vec<T>>::AssociatedItem
1300 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1304 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1305 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1306 /// 0`, this is an empty span.
1307 pub path_span: Span,
1308 pub position: usize,
1311 /// A capture clause used in closures and `async` blocks.
1312 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1313 pub enum CaptureBy {
1314 /// `move |x| y + x`.
1316 /// `move` keyword was not specified.
1320 /// The movability of a generator / closure literal:
1321 /// whether a generator contains self-references, causing it to be `!Unpin`.
1335 pub enum Movability {
1336 /// May contain self-references, `!Unpin`.
1338 /// Must not contain self-references, `Unpin`.
1342 /// Represents a macro invocation. The `path` indicates which macro
1343 /// is being invoked, and the `args` are arguments passed to it.
1344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1347 pub args: P<MacArgs>,
1348 pub prior_type_ascription: Option<(Span, bool)>,
1352 pub fn span(&self) -> Span {
1353 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1357 /// Arguments passed to an attribute or a function-like macro.
1358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1360 /// No arguments - `#[attr]`.
1362 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1363 Delimited(DelimSpan, MacDelimiter, TokenStream),
1364 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1366 /// Span of the `=` token.
1368 /// Token stream of the "value".
1374 pub fn delim(&self) -> DelimToken {
1376 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1377 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1381 pub fn span(&self) -> Option<Span> {
1383 MacArgs::Empty => None,
1384 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1385 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1389 /// Tokens inside the delimiters or after `=`.
1390 /// Proc macros see these tokens, for example.
1391 pub fn inner_tokens(&self) -> TokenStream {
1393 MacArgs::Empty => TokenStream::default(),
1394 MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(),
1398 /// Tokens together with the delimiters or `=`.
1399 /// Use of this method generally means that something suboptimal or hacky is happening.
1400 pub fn outer_tokens(&self) -> TokenStream {
1402 MacArgs::Empty => TokenStream::default(),
1403 MacArgs::Delimited(dspan, delim, ref tokens) => {
1404 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into()
1406 MacArgs::Eq(eq_span, ref tokens) => {
1407 iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect()
1412 /// Whether a macro with these arguments needs a semicolon
1413 /// when used as a standalone item or statement.
1414 pub fn need_semicolon(&self) -> bool {
1415 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1419 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1420 pub enum MacDelimiter {
1427 pub fn to_token(self) -> DelimToken {
1429 MacDelimiter::Parenthesis => DelimToken::Paren,
1430 MacDelimiter::Bracket => DelimToken::Bracket,
1431 MacDelimiter::Brace => DelimToken::Brace,
1435 pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1437 token::Paren => Some(MacDelimiter::Parenthesis),
1438 token::Bracket => Some(MacDelimiter::Bracket),
1439 token::Brace => Some(MacDelimiter::Brace),
1440 token::NoDelim => None,
1445 /// Represents a macro definition.
1446 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1447 pub struct MacroDef {
1448 pub body: P<MacArgs>,
1449 /// `true` if macro was defined with `macro_rules`.
1453 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, Eq, PartialEq)]
1454 #[derive(HashStable_Generic)]
1456 /// A regular string, like `"foo"`.
1458 /// A raw string, like `r##"foo"##`.
1460 /// The value is the number of `#` symbols used.
1465 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1467 /// The original literal token as written in source code.
1468 pub token: token::Lit,
1469 /// The "semantic" representation of the literal lowered from the original tokens.
1470 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1471 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1476 /// Same as `Lit`, but restricted to string literals.
1477 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1479 /// The original literal token as written in source code.
1480 pub style: StrStyle,
1482 pub suffix: Option<Symbol>,
1484 /// The unescaped "semantic" representation of the literal lowered from the original token.
1485 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1486 pub symbol_unescaped: Symbol,
1490 pub fn as_lit(&self) -> Lit {
1491 let token_kind = match self.style {
1492 StrStyle::Cooked => token::Str,
1493 StrStyle::Raw(n) => token::StrRaw(n),
1496 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1498 kind: LitKind::Str(self.symbol_unescaped, self.style),
1503 /// Type of the integer literal based on provided suffix.
1504 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1505 #[derive(HashStable_Generic)]
1506 pub enum LitIntType {
1515 /// Type of the float literal based on provided suffix.
1516 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq)]
1517 #[derive(HashStable_Generic)]
1518 pub enum LitFloatType {
1519 /// A float literal with a suffix (`1f32` or `1E10f32`).
1521 /// A float literal without a suffix (`1.0 or 1.0E10`).
1527 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1528 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1530 /// A string literal (`"foo"`).
1531 Str(Symbol, StrStyle),
1532 /// A byte string (`b"foo"`).
1533 ByteStr(Lrc<Vec<u8>>),
1534 /// A byte char (`b'f'`).
1536 /// A character literal (`'a'`).
1538 /// An integer literal (`1`).
1539 Int(u128, LitIntType),
1540 /// A float literal (`1f64` or `1E10f64`).
1541 Float(Symbol, LitFloatType),
1542 /// A boolean literal.
1544 /// Placeholder for a literal that wasn't well-formed in some way.
1549 /// Returns `true` if this literal is a string.
1550 pub fn is_str(&self) -> bool {
1552 LitKind::Str(..) => true,
1557 /// Returns `true` if this literal is byte literal string.
1558 pub fn is_bytestr(&self) -> bool {
1560 LitKind::ByteStr(_) => true,
1565 /// Returns `true` if this is a numeric literal.
1566 pub fn is_numeric(&self) -> bool {
1568 LitKind::Int(..) | LitKind::Float(..) => true,
1573 /// Returns `true` if this literal has no suffix.
1574 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1575 pub fn is_unsuffixed(&self) -> bool {
1579 /// Returns `true` if this literal has a suffix.
1580 pub fn is_suffixed(&self) -> bool {
1582 // suffixed variants
1583 LitKind::Int(_, LitIntType::Signed(..))
1584 | LitKind::Int(_, LitIntType::Unsigned(..))
1585 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1586 // unsuffixed variants
1588 | LitKind::ByteStr(..)
1591 | LitKind::Int(_, LitIntType::Unsuffixed)
1592 | LitKind::Float(_, LitFloatType::Unsuffixed)
1594 | LitKind::Err(..) => false,
1599 // N.B., If you change this, you'll probably want to change the corresponding
1600 // type structure in `middle/ty.rs` as well.
1601 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1604 pub mutbl: Mutability,
1607 /// Represents a function's signature in a trait declaration,
1608 /// trait implementation, or free function.
1609 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1611 pub header: FnHeader,
1612 pub decl: P<FnDecl>,
1615 /// Represents associated items.
1616 /// These include items in `impl` and `trait` definitions.
1617 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1618 pub struct AssocItem {
1619 pub attrs: Vec<Attribute>,
1622 pub vis: Visibility,
1625 pub defaultness: Defaultness,
1626 pub generics: Generics,
1627 pub kind: AssocItemKind,
1628 /// See `Item::tokens` for what this is.
1629 pub tokens: Option<TokenStream>,
1632 /// Represents various kinds of content within an `impl`.
1634 /// The term "provided" in the variants below refers to the item having a default
1635 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
1636 /// In an implementation, all items must be provided.
1637 /// The `Option`s below denote the bodies, where `Some(_)`
1638 /// means "provided" and conversely `None` means "required".
1639 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1640 pub enum AssocItemKind {
1641 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
1642 /// If `def` is parsed, then the associated constant is provided, and otherwise required.
1643 Const(P<Ty>, Option<P<Expr>>),
1645 /// An associated function.
1646 Fn(FnSig, Option<P<Block>>),
1648 /// An associated type.
1649 TyAlias(GenericBounds, Option<P<Ty>>),
1651 /// A macro expanding to an associated item.
1674 pub fn name_str(self) -> &'static str {
1676 FloatTy::F32 => "f32",
1677 FloatTy::F64 => "f64",
1681 pub fn name(self) -> Symbol {
1683 FloatTy::F32 => sym::f32,
1684 FloatTy::F64 => sym::f64,
1688 pub fn bit_width(self) -> usize {
1719 pub fn name_str(&self) -> &'static str {
1721 IntTy::Isize => "isize",
1723 IntTy::I16 => "i16",
1724 IntTy::I32 => "i32",
1725 IntTy::I64 => "i64",
1726 IntTy::I128 => "i128",
1730 pub fn name(&self) -> Symbol {
1732 IntTy::Isize => sym::isize,
1733 IntTy::I8 => sym::i8,
1734 IntTy::I16 => sym::i16,
1735 IntTy::I32 => sym::i32,
1736 IntTy::I64 => sym::i64,
1737 IntTy::I128 => sym::i128,
1741 pub fn val_to_string(&self, val: i128) -> String {
1742 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1743 // are parsed as `u128`, so we wouldn't want to print an extra negative
1745 format!("{}{}", val as u128, self.name_str())
1748 pub fn bit_width(&self) -> Option<usize> {
1750 IntTy::Isize => return None,
1759 pub fn normalize(&self, target_width: u32) -> Self {
1761 IntTy::Isize => match target_width {
1765 _ => unreachable!(),
1795 pub fn name_str(&self) -> &'static str {
1797 UintTy::Usize => "usize",
1799 UintTy::U16 => "u16",
1800 UintTy::U32 => "u32",
1801 UintTy::U64 => "u64",
1802 UintTy::U128 => "u128",
1806 pub fn name(&self) -> Symbol {
1808 UintTy::Usize => sym::usize,
1809 UintTy::U8 => sym::u8,
1810 UintTy::U16 => sym::u16,
1811 UintTy::U32 => sym::u32,
1812 UintTy::U64 => sym::u64,
1813 UintTy::U128 => sym::u128,
1817 pub fn val_to_string(&self, val: u128) -> String {
1818 format!("{}{}", val, self.name_str())
1821 pub fn bit_width(&self) -> Option<usize> {
1823 UintTy::Usize => return None,
1828 UintTy::U128 => 128,
1832 pub fn normalize(&self, target_width: u32) -> Self {
1834 UintTy::Usize => match target_width {
1838 _ => unreachable!(),
1845 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1846 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1847 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1848 pub struct AssocTyConstraint {
1851 pub kind: AssocTyConstraintKind,
1855 /// The kinds of an `AssocTyConstraint`.
1856 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1857 pub enum AssocTyConstraintKind {
1858 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1859 Equality { ty: P<Ty> },
1860 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1861 Bound { bounds: GenericBounds },
1864 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1871 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1872 pub struct BareFnTy {
1873 pub unsafety: Unsafe,
1875 pub generic_params: Vec<GenericParam>,
1876 pub decl: P<FnDecl>,
1879 /// The various kinds of type recognized by the compiler.
1880 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1882 /// A variable-length slice (`[T]`).
1884 /// A fixed length array (`[T; n]`).
1885 Array(P<Ty>, AnonConst),
1886 /// A raw pointer (`*const T` or `*mut T`).
1888 /// A reference (`&'a T` or `&'a mut T`).
1889 Rptr(Option<Lifetime>, MutTy),
1890 /// A bare function (e.g., `fn(usize) -> bool`).
1891 BareFn(P<BareFnTy>),
1892 /// The never type (`!`).
1894 /// A tuple (`(A, B, C, D,...)`).
1896 /// A path (`module::module::...::Type`), optionally
1897 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1899 /// Type parameters are stored in the `Path` itself.
1900 Path(Option<QSelf>, Path),
1901 /// A trait object type `Bound1 + Bound2 + Bound3`
1902 /// where `Bound` is a trait or a lifetime.
1903 TraitObject(GenericBounds, TraitObjectSyntax),
1904 /// An `impl Bound1 + Bound2 + Bound3` type
1905 /// where `Bound` is a trait or a lifetime.
1907 /// The `NodeId` exists to prevent lowering from having to
1908 /// generate `NodeId`s on the fly, which would complicate
1909 /// the generation of opaque `type Foo = impl Trait` items significantly.
1910 ImplTrait(NodeId, GenericBounds),
1911 /// No-op; kept solely so that we can pretty-print faithfully.
1915 /// This means the type should be inferred instead of it having been
1916 /// specified. This can appear anywhere in a type.
1918 /// Inferred type of a `self` or `&self` argument in a method.
1920 /// A macro in the type position.
1922 /// Placeholder for a kind that has failed to be defined.
1924 /// Placeholder for a `va_list`.
1929 pub fn is_implicit_self(&self) -> bool {
1930 if let TyKind::ImplicitSelf = *self { true } else { false }
1933 pub fn is_unit(&self) -> bool {
1934 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1937 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1938 /// in lowering to avoid making larger changes there and beyond.
1939 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1941 Self::ImplTrait(_, bounds) => Some(bounds),
1947 /// Syntax used to declare a trait object.
1948 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1949 pub enum TraitObjectSyntax {
1954 /// Inline assembly dialect.
1956 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1957 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1958 pub enum AsmDialect {
1963 /// Inline assembly.
1965 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1966 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1967 pub struct InlineAsmOutput {
1968 pub constraint: Symbol,
1971 pub is_indirect: bool,
1974 /// Inline assembly.
1976 /// E.g., `asm!("NOP");`.
1977 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1978 pub struct InlineAsm {
1980 pub asm_str_style: StrStyle,
1981 pub outputs: Vec<InlineAsmOutput>,
1982 pub inputs: Vec<(Symbol, P<Expr>)>,
1983 pub clobbers: Vec<Symbol>,
1985 pub alignstack: bool,
1986 pub dialect: AsmDialect,
1989 /// A parameter in a function header.
1991 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1992 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1999 pub is_placeholder: bool,
2002 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2004 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2005 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2007 /// `self`, `mut self`
2009 /// `&'lt self`, `&'lt mut self`
2010 Region(Option<Lifetime>, Mutability),
2011 /// `self: TYPE`, `mut self: TYPE`
2012 Explicit(P<Ty>, Mutability),
2015 pub type ExplicitSelf = Spanned<SelfKind>;
2018 /// Attempts to cast parameter to `ExplicitSelf`.
2019 pub fn to_self(&self) -> Option<ExplicitSelf> {
2020 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2021 if ident.name == kw::SelfLower {
2022 return match self.ty.kind {
2023 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2024 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2025 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2028 self.pat.span.to(self.ty.span),
2029 SelfKind::Explicit(self.ty.clone(), mutbl),
2037 /// Returns `true` if parameter is `self`.
2038 pub fn is_self(&self) -> bool {
2039 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2040 ident.name == kw::SelfLower
2046 /// Builds a `Param` object from `ExplicitSelf`.
2047 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2048 let span = eself.span.to(eself_ident.span);
2049 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2050 let param = |mutbl, ty| Param {
2054 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2060 is_placeholder: false,
2063 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2064 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2065 SelfKind::Region(lt, mutbl) => param(
2069 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2077 /// A signature (not the body) of a function declaration.
2079 /// E.g., `fn foo(bar: baz)`.
2081 /// Please note that it's different from `FnHeader` structure
2082 /// which contains metadata about function safety, asyncness, constness and ABI.
2083 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2085 pub inputs: Vec<Param>,
2086 pub output: FunctionRetTy,
2090 pub fn get_self(&self) -> Option<ExplicitSelf> {
2091 self.inputs.get(0).and_then(Param::to_self)
2093 pub fn has_self(&self) -> bool {
2094 self.inputs.get(0).map_or(false, Param::is_self)
2096 pub fn c_variadic(&self) -> bool {
2097 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2098 TyKind::CVarArgs => true,
2104 /// Is the trait definition an auto trait?
2105 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2111 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
2112 #[derive(HashStable_Generic)]
2118 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2120 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2125 pub fn is_async(self) -> bool {
2126 if let Async::Yes { .. } = self { true } else { false }
2129 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2130 pub fn opt_return_id(self) -> Option<NodeId> {
2132 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2138 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
2139 #[derive(HashStable_Generic)]
2145 /// Item defaultness.
2146 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2147 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2148 pub enum Defaultness {
2153 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2154 pub enum ImplPolarity {
2155 /// `impl Trait for Type`
2157 /// `impl !Trait for Type`
2161 impl fmt::Debug for ImplPolarity {
2162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2164 ImplPolarity::Positive => "positive".fmt(f),
2165 ImplPolarity::Negative => "negative".fmt(f),
2170 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2171 pub enum FunctionRetTy {
2172 // FIXME(Centril): Rename to `FnRetTy` and in HIR also.
2173 /// Returns type is not specified.
2175 /// Functions default to `()` and closures default to inference.
2176 /// Span points to where return type would be inserted.
2178 /// Everything else.
2182 impl FunctionRetTy {
2183 pub fn span(&self) -> Span {
2185 FunctionRetTy::Default(span) => span,
2186 FunctionRetTy::Ty(ref ty) => ty.span,
2191 /// Module declaration.
2193 /// E.g., `mod foo;` or `mod foo { .. }`.
2194 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2196 /// A span from the first token past `{` to the last token until `}`.
2197 /// For `mod foo;`, the inner span ranges from the first token
2198 /// to the last token in the external file.
2200 pub items: Vec<P<Item>>,
2201 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2205 /// Foreign module declaration.
2207 /// E.g., `extern { .. }` or `extern C { .. }`.
2208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2209 pub struct ForeignMod {
2210 pub abi: Option<StrLit>,
2211 pub items: Vec<P<ForeignItem>>,
2214 /// Global inline assembly.
2216 /// Also known as "module-level assembly" or "file-scoped assembly".
2217 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2218 pub struct GlobalAsm {
2222 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2223 pub struct EnumDef {
2224 pub variants: Vec<Variant>,
2227 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2228 pub struct Variant {
2229 /// Attributes of the variant.
2230 pub attrs: Vec<Attribute>,
2231 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2235 /// The visibility of the variant. Syntactically accepted but not semantically.
2236 pub vis: Visibility,
2237 /// Name of the variant.
2240 /// Fields and constructor id of the variant.
2241 pub data: VariantData,
2242 /// Explicit discriminant, e.g., `Foo = 1`.
2243 pub disr_expr: Option<AnonConst>,
2244 /// Is a macro placeholder
2245 pub is_placeholder: bool,
2248 /// Part of `use` item to the right of its prefix.
2249 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2250 pub enum UseTreeKind {
2251 /// `use prefix` or `use prefix as rename`
2253 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2255 Simple(Option<Ident>, NodeId, NodeId),
2256 /// `use prefix::{...}`
2257 Nested(Vec<(UseTree, NodeId)>),
2262 /// A tree of paths sharing common prefixes.
2263 /// Used in `use` items both at top-level and inside of braces in import groups.
2264 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2265 pub struct UseTree {
2267 pub kind: UseTreeKind,
2272 pub fn ident(&self) -> Ident {
2274 UseTreeKind::Simple(Some(rename), ..) => rename,
2275 UseTreeKind::Simple(None, ..) => {
2276 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2278 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2283 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2284 /// are contained as statements within items. These two cases need to be
2285 /// distinguished for pretty-printing.
2286 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2287 pub enum AttrStyle {
2292 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2293 pub struct AttrId(pub usize);
2295 impl Idx for AttrId {
2296 fn new(idx: usize) -> Self {
2299 fn index(self) -> usize {
2304 impl rustc_serialize::Encodable for AttrId {
2305 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2310 impl rustc_serialize::Decodable for AttrId {
2311 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2312 d.read_nil().map(|_| crate::attr::mk_attr_id())
2316 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2317 pub struct AttrItem {
2322 /// A list of attributes.
2323 pub type AttrVec = ThinVec<Attribute>;
2325 /// Metadata associated with an item.
2326 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2327 pub struct Attribute {
2330 /// Denotes if the attribute decorates the following construct (outer)
2331 /// or the construct this attribute is contained within (inner).
2332 pub style: AttrStyle,
2336 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2338 /// A normal attribute.
2341 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2342 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2343 /// variant (which is much less compact and thus more expensive).
2347 /// `TraitRef`s appear in impls.
2349 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2350 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2351 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2352 /// same as the impl's `NodeId`).
2353 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2354 pub struct TraitRef {
2359 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2360 pub struct PolyTraitRef {
2361 /// The `'a` in `<'a> Foo<&'a T>`.
2362 pub bound_generic_params: Vec<GenericParam>,
2364 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2365 pub trait_ref: TraitRef,
2371 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2373 bound_generic_params: generic_params,
2374 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2380 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2381 pub enum CrateSugar {
2382 /// Source is `pub(crate)`.
2385 /// Source is (just) `crate`.
2389 pub type Visibility = Spanned<VisibilityKind>;
2391 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2392 pub enum VisibilityKind {
2395 Restricted { path: P<Path>, id: NodeId },
2399 impl VisibilityKind {
2400 pub fn is_pub(&self) -> bool {
2401 if let VisibilityKind::Public = *self { true } else { false }
2405 /// Field of a struct.
2407 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2408 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2409 pub struct StructField {
2410 pub attrs: Vec<Attribute>,
2413 pub vis: Visibility,
2414 pub ident: Option<Ident>,
2417 pub is_placeholder: bool,
2420 /// Fields and constructor ids of enum variants and structs.
2421 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2422 pub enum VariantData {
2425 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2426 Struct(Vec<StructField>, bool),
2429 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2430 Tuple(Vec<StructField>, NodeId),
2433 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2438 /// Return the fields of this variant.
2439 pub fn fields(&self) -> &[StructField] {
2441 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2446 /// Return the `NodeId` of this variant's constructor, if it has one.
2447 pub fn ctor_id(&self) -> Option<NodeId> {
2449 VariantData::Struct(..) => None,
2450 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2457 /// The name might be a dummy name in case of anonymous items.
2458 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2459 pub struct Item<K = ItemKind> {
2460 pub attrs: Vec<Attribute>,
2463 pub vis: Visibility,
2468 /// Original tokens this item was parsed from. This isn't necessarily
2469 /// available for all items, although over time more and more items should
2470 /// have this be `Some`. Right now this is primarily used for procedural
2471 /// macros, notably custom attributes.
2473 /// Note that the tokens here do not include the outer attributes, but will
2474 /// include inner attributes.
2475 pub tokens: Option<TokenStream>,
2479 /// Return the span that encompasses the attributes.
2480 pub fn span_with_attributes(&self) -> Span {
2481 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2485 /// `extern` qualifier on a function item or function type.
2486 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2494 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2495 abi.map_or(Extern::Implicit, Extern::Explicit)
2499 /// A function header.
2501 /// All the information between the visibility and the name of the function is
2502 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2503 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2504 pub struct FnHeader {
2505 pub unsafety: Unsafe,
2506 pub asyncness: Async,
2507 pub constness: Const,
2512 /// Does this function header have any qualifiers or is it empty?
2513 pub fn has_qualifiers(&self) -> bool {
2514 let Self { unsafety, asyncness, constness, ext } = self;
2515 matches!(unsafety, Unsafe::Yes(_))
2516 || asyncness.is_async()
2517 || matches!(constness, Const::Yes(_))
2518 || !matches!(ext, Extern::None)
2522 impl Default for FnHeader {
2523 fn default() -> FnHeader {
2525 unsafety: Unsafe::No,
2526 asyncness: Async::No,
2527 constness: Const::No,
2533 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2535 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2537 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2538 ExternCrate(Option<Name>),
2539 /// A use declaration item (`use`).
2541 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2543 /// A static item (`static`).
2545 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2546 Static(P<Ty>, Mutability, P<Expr>),
2547 /// A constant item (`const`).
2549 /// E.g., `const FOO: i32 = 42;`.
2550 Const(P<Ty>, P<Expr>),
2551 /// A function declaration (`fn`).
2553 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2554 Fn(FnSig, Generics, Option<P<Block>>),
2555 /// A module declaration (`mod`).
2557 /// E.g., `mod foo;` or `mod foo { .. }`.
2559 /// An external module (`extern`).
2561 /// E.g., `extern {}` or `extern "C" {}`.
2562 ForeignMod(ForeignMod),
2563 /// Module-level inline assembly (from `global_asm!()`).
2564 GlobalAsm(P<GlobalAsm>),
2565 /// A type alias (`type`).
2567 /// E.g., `type Foo = Bar<u8>;`.
2568 TyAlias(P<Ty>, Generics),
2569 /// An enum definition (`enum`).
2571 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2572 Enum(EnumDef, Generics),
2573 /// A struct definition (`struct`).
2575 /// E.g., `struct Foo<A> { x: A }`.
2576 Struct(VariantData, Generics),
2577 /// A union definition (`union`).
2579 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2580 Union(VariantData, Generics),
2581 /// A trait declaration (`trait`).
2583 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2584 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2587 /// E.g., `trait Foo = Bar + Quux;`.
2588 TraitAlias(Generics, GenericBounds),
2589 /// An implementation.
2591 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2594 polarity: ImplPolarity,
2595 defaultness: Defaultness,
2599 /// The trait being implemented, if any.
2600 of_trait: Option<TraitRef>,
2603 items: Vec<P<AssocItem>>,
2605 /// A macro invocation.
2607 /// E.g., `foo!(..)`.
2610 /// A macro definition.
2615 pub fn descriptive_variant(&self) -> &str {
2617 ItemKind::ExternCrate(..) => "extern crate",
2618 ItemKind::Use(..) => "use",
2619 ItemKind::Static(..) => "static item",
2620 ItemKind::Const(..) => "constant item",
2621 ItemKind::Fn(..) => "function",
2622 ItemKind::Mod(..) => "module",
2623 ItemKind::ForeignMod(..) => "foreign module",
2624 ItemKind::GlobalAsm(..) => "global asm",
2625 ItemKind::TyAlias(..) => "type alias",
2626 ItemKind::Enum(..) => "enum",
2627 ItemKind::Struct(..) => "struct",
2628 ItemKind::Union(..) => "union",
2629 ItemKind::Trait(..) => "trait",
2630 ItemKind::TraitAlias(..) => "trait alias",
2631 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl { .. } => "item",
2635 pub fn generics(&self) -> Option<&Generics> {
2637 Self::Fn(_, generics, _)
2638 | Self::TyAlias(_, generics)
2639 | Self::Enum(_, generics)
2640 | Self::Struct(_, generics)
2641 | Self::Union(_, generics)
2642 | Self::Trait(_, _, generics, ..)
2643 | Self::TraitAlias(generics, _)
2644 | Self::Impl { generics, .. } => Some(generics),
2650 pub type ForeignItem = Item<ForeignItemKind>;
2652 /// An item within an `extern` block.
2653 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2654 pub enum ForeignItemKind {
2655 /// A foreign function.
2656 Fn(FnSig, Generics, Option<P<Block>>),
2657 /// A foreign static item (`static ext: u8`).
2658 Static(P<Ty>, Mutability),
2661 /// A macro invocation.
2665 impl ForeignItemKind {
2666 pub fn descriptive_variant(&self) -> &str {
2668 ForeignItemKind::Fn(..) => "foreign function",
2669 ForeignItemKind::Static(..) => "foreign static item",
2670 ForeignItemKind::Ty => "foreign type",
2671 ForeignItemKind::Macro(..) => "macro in foreign module",