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};
41 use std::convert::TryFrom;
48 /// A "Label" is an identifier of some point in sources,
49 /// e.g. in the following code:
57 /// `'outer` is a label.
58 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable_Generic)]
63 impl fmt::Debug for Label {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 write!(f, "label({:?})", self.ident)
69 /// A "Lifetime" is an annotation of the scope in which variable
70 /// can be used, e.g. `'a` in `&'a i32`.
71 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
77 impl fmt::Debug for Lifetime {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 write!(f, "lifetime({}: {})", self.id, self)
83 impl fmt::Display for Lifetime {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 write!(f, "{}", self.ident.name)
89 /// A "Path" is essentially Rust's notion of a name.
91 /// It's represented as a sequence of identifiers,
92 /// along with a bunch of supporting information.
94 /// E.g., `std::cmp::PartialEq`.
95 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
98 /// The segments in the path: the things separated by `::`.
99 /// Global paths begin with `kw::PathRoot`.
100 pub segments: Vec<PathSegment>,
103 impl PartialEq<Symbol> for Path {
104 fn eq(&self, symbol: &Symbol) -> bool {
105 self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
109 impl<CTX> HashStable<CTX> for Path {
110 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
111 self.segments.len().hash_stable(hcx, hasher);
112 for segment in &self.segments {
113 segment.ident.name.hash_stable(hcx, hasher);
119 // Convert a span and an identifier to the corresponding
121 pub fn from_ident(ident: Ident) -> Path {
122 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
125 pub fn is_global(&self) -> bool {
126 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
130 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
132 /// E.g., `std`, `String` or `Box<T>`.
133 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
134 pub struct PathSegment {
135 /// The identifier portion of this path segment.
140 /// Type/lifetime parameters attached to this path. They come in
141 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
142 /// `None` means that no parameter list is supplied (`Path`),
143 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
144 /// but it can be empty (`Path<>`).
145 /// `P` is used as a size optimization for the common case with no parameters.
146 pub args: Option<P<GenericArgs>>,
150 pub fn from_ident(ident: Ident) -> Self {
151 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
153 pub fn path_root(span: Span) -> Self {
154 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
158 /// The arguments of a path segment.
160 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
161 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
162 pub enum GenericArgs {
163 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
164 AngleBracketed(AngleBracketedArgs),
165 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
166 Parenthesized(ParenthesizedArgs),
170 pub fn is_parenthesized(&self) -> bool {
172 Parenthesized(..) => true,
177 pub fn is_angle_bracketed(&self) -> bool {
179 AngleBracketed(..) => true,
184 pub fn span(&self) -> Span {
186 AngleBracketed(ref data) => data.span,
187 Parenthesized(ref data) => data.span,
192 /// Concrete argument in the sequence of generic args.
193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
194 pub enum GenericArg {
195 /// `'a` in `Foo<'a>`
197 /// `Bar` in `Foo<Bar>`
204 pub fn span(&self) -> Span {
206 GenericArg::Lifetime(lt) => lt.ident.span,
207 GenericArg::Type(ty) => ty.span,
208 GenericArg::Const(ct) => ct.value.span,
213 /// A path like `Foo<'a, T>`.
214 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
215 pub struct AngleBracketedArgs {
216 /// The overall span.
218 /// The arguments for this path segment.
219 pub args: Vec<GenericArg>,
220 /// Constraints on associated types, if any.
221 /// E.g., `Foo<A = Bar, B: Baz>`.
222 pub constraints: Vec<AssocTyConstraint>,
225 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
226 fn into(self) -> Option<P<GenericArgs>> {
227 Some(P(GenericArgs::AngleBracketed(self)))
231 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
232 fn into(self) -> Option<P<GenericArgs>> {
233 Some(P(GenericArgs::Parenthesized(self)))
237 /// A path like `Foo(A, B) -> C`.
238 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
239 pub struct ParenthesizedArgs {
244 pub inputs: Vec<P<Ty>>,
250 impl ParenthesizedArgs {
251 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
254 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
260 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
262 /// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
264 /// Negative bounds should also be handled here.
265 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
266 pub enum TraitBoundModifier {
278 // This parses but will be rejected during AST validation.
282 /// The AST represents all type param bounds as types.
283 /// `typeck::collect::compute_bounds` matches these against
284 /// the "special" built-in traits (see `middle::lang_items`) and
285 /// detects `Copy`, `Send` and `Sync`.
286 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
287 pub enum GenericBound {
288 Trait(PolyTraitRef, TraitBoundModifier),
293 pub fn span(&self) -> Span {
295 &GenericBound::Trait(ref t, ..) => t.span,
296 &GenericBound::Outlives(ref l) => l.ident.span,
301 pub type GenericBounds = Vec<GenericBound>;
303 /// Specifies the enforced ordering for generic parameters. In the future,
304 /// if we wanted to relax this order, we could override `PartialEq` and
305 /// `PartialOrd`, to allow the kinds to be unordered.
306 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
307 pub enum ParamKindOrd {
313 impl fmt::Display for ParamKindOrd {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 ParamKindOrd::Lifetime => "lifetime".fmt(f),
317 ParamKindOrd::Type => "type".fmt(f),
318 ParamKindOrd::Const => "const".fmt(f),
323 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
324 pub enum GenericParamKind {
325 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
328 default: Option<P<Ty>>,
335 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
336 pub struct GenericParam {
340 pub bounds: GenericBounds,
341 pub is_placeholder: bool,
342 pub kind: GenericParamKind,
345 /// Represents lifetime, type and const parameters attached to a declaration of
346 /// a function, enum, trait, etc.
347 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
348 pub struct Generics {
349 pub params: Vec<GenericParam>,
350 pub where_clause: WhereClause,
354 impl Default for Generics {
355 /// Creates an instance of `Generics`.
356 fn default() -> Generics {
359 where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP },
365 /// A where-clause in a definition.
366 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
367 pub struct WhereClause {
368 pub predicates: Vec<WherePredicate>,
372 /// A single predicate in a where-clause.
373 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
374 pub enum WherePredicate {
375 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
376 BoundPredicate(WhereBoundPredicate),
377 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
378 RegionPredicate(WhereRegionPredicate),
379 /// An equality predicate (unsupported).
380 EqPredicate(WhereEqPredicate),
383 impl WherePredicate {
384 pub fn span(&self) -> Span {
386 &WherePredicate::BoundPredicate(ref p) => p.span,
387 &WherePredicate::RegionPredicate(ref p) => p.span,
388 &WherePredicate::EqPredicate(ref p) => p.span,
395 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
396 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
397 pub struct WhereBoundPredicate {
399 /// Any generics from a `for` binding.
400 pub bound_generic_params: Vec<GenericParam>,
401 /// The type being bounded.
402 pub bounded_ty: P<Ty>,
403 /// Trait and lifetime bounds (`Clone + Send + 'static`).
404 pub bounds: GenericBounds,
407 /// A lifetime predicate.
409 /// E.g., `'a: 'b + 'c`.
410 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
411 pub struct WhereRegionPredicate {
413 pub lifetime: Lifetime,
414 pub bounds: GenericBounds,
417 /// An equality predicate (unsupported).
420 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
421 pub struct WhereEqPredicate {
428 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
431 pub attrs: Vec<Attribute>,
433 /// The order of items in the HIR is unrelated to the order of
434 /// items in the AST. However, we generate proc macro harnesses
435 /// based on the AST order, and later refer to these harnesses
436 /// from the HIR. This field keeps track of the order in which
437 /// we generated proc macros harnesses, so that we can map
438 /// HIR proc macros items back to their harness items.
439 pub proc_macros: Vec<NodeId>,
442 /// Possible values inside of compile-time attribute lists.
444 /// E.g., the '..' in `#[name(..)]`.
445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
446 pub enum NestedMetaItem {
447 /// A full MetaItem, for recursive meta items.
451 /// E.g., `"foo"`, `64`, `true`.
455 /// A spanned compile-time attribute item.
457 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
458 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
459 pub struct MetaItem {
461 pub kind: MetaItemKind,
465 /// A compile-time attribute item.
467 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
468 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
469 pub enum MetaItemKind {
472 /// E.g., `test` as in `#[test]`.
476 /// E.g., `derive(..)` as in `#[derive(..)]`.
477 List(Vec<NestedMetaItem>),
478 /// Name value meta item.
480 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
484 /// A block (`{ .. }`).
486 /// E.g., `{ .. }` as in `fn foo() { .. }`.
487 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
489 /// The statements in the block.
490 pub stmts: Vec<Stmt>,
492 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
493 pub rules: BlockCheckMode,
497 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
505 /// Attempt reparsing the pattern as a type.
506 /// This is intended for use by diagnostics.
507 pub fn to_ty(&self) -> Option<P<Ty>> {
508 let kind = match &self.kind {
509 // In a type expression `_` is an inference variable.
510 PatKind::Wild => TyKind::Infer,
511 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
512 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
513 TyKind::Path(None, Path::from_ident(*ident))
515 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
516 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
517 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
518 PatKind::Ref(pat, mutbl) => {
519 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
521 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
522 // when `P` can be reparsed as a type `T`.
523 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
524 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
525 // assuming `T0` to `Tn` are all syntactically valid as types.
526 PatKind::Tuple(pats) => {
527 let mut tys = Vec::with_capacity(pats.len());
528 // FIXME(#48994) - could just be collected into an Option<Vec>
530 tys.push(pat.to_ty()?);
537 Some(P(Ty { kind, id: self.id, span: self.span }))
540 /// Walk top-down and call `it` in each place where a pattern occurs
541 /// starting with the root pattern `walk` is called on. If `it` returns
542 /// false then we will descend no further but siblings will be processed.
543 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
549 // Walk into the pattern associated with `Ident` (if any).
550 PatKind::Ident(_, _, Some(p)) => p.walk(it),
552 // Walk into each field of struct.
553 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
555 // Sequence of patterns.
556 PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => {
557 s.iter().for_each(|p| p.walk(it))
560 // Trivial wrappers over inner patterns.
561 PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
563 // These patterns do not contain subpatterns, skip.
570 | PatKind::Mac(_) => {}
574 /// Is this a `..` pattern?
575 pub fn is_rest(&self) -> bool {
577 PatKind::Rest => true,
583 /// A single field in a struct pattern
585 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
586 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
587 /// except is_shorthand is true
588 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
589 pub struct FieldPat {
590 /// The identifier for the field
592 /// The pattern the field is destructured to
594 pub is_shorthand: bool,
598 pub is_placeholder: bool,
601 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
602 pub enum BindingMode {
607 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
609 Included(RangeSyntax),
613 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
614 pub enum RangeSyntax {
621 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
623 /// Represents a wildcard pattern (`_`).
626 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
627 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
628 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
629 /// during name resolution.
630 Ident(BindingMode, Ident, Option<P<Pat>>),
632 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
633 /// The `bool` is `true` in the presence of a `..`.
634 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
636 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
637 TupleStruct(Path, Vec<P<Pat>>),
639 /// An or-pattern `A | B | C`.
640 /// Invariant: `pats.len() >= 2`.
643 /// A possibly qualified path pattern.
644 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
645 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
646 /// only legally refer to associated constants.
647 Path(Option<QSelf>, Path),
649 /// A tuple pattern (`(a, b)`).
655 /// A reference pattern (e.g., `&mut (a, b)`).
656 Ref(P<Pat>, Mutability),
661 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
662 Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
664 /// A slice pattern `[a, b, c]`.
667 /// A rest pattern `..`.
669 /// Syntactically it is valid anywhere.
671 /// Semantically however, it only has meaning immediately inside:
672 /// - a slice pattern: `[a, .., b]`,
673 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
674 /// - a tuple pattern: `(a, .., b)`,
675 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
677 /// In all of these cases, an additional restriction applies,
678 /// only one rest pattern may occur in the pattern sequences.
681 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
684 /// A macro pattern; pre-expansion.
701 pub enum Mutability {
707 /// Returns `MutMutable` only if both `self` and `other` are mutable.
708 pub fn and(self, other: Self) -> Self {
710 Mutability::Mut => other,
711 Mutability::Not => Mutability::Not,
715 pub fn invert(self) -> Self {
717 Mutability::Mut => Mutability::Not,
718 Mutability::Not => Mutability::Mut,
722 pub fn prefix_str(&self) -> &'static str {
724 Mutability::Mut => "mut ",
725 Mutability::Not => "",
730 /// The kind of borrow in an `AddrOf` expression,
731 /// e.g., `&place` or `&raw const place`.
732 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
733 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
734 pub enum BorrowKind {
735 /// A normal borrow, `&$expr` or `&mut $expr`.
736 /// The resulting type is either `&'a T` or `&'a mut T`
737 /// where `T = typeof($expr)` and `'a` is some lifetime.
739 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
740 /// The resulting type is either `*const T` or `*mut T`
741 /// where `T = typeof($expr)`.
745 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
747 /// The `+` operator (addition)
749 /// The `-` operator (subtraction)
751 /// The `*` operator (multiplication)
753 /// The `/` operator (division)
755 /// The `%` operator (modulus)
757 /// The `&&` operator (logical and)
759 /// The `||` operator (logical or)
761 /// The `^` operator (bitwise xor)
763 /// The `&` operator (bitwise and)
765 /// The `|` operator (bitwise or)
767 /// The `<<` operator (shift left)
769 /// The `>>` operator (shift right)
771 /// The `==` operator (equality)
773 /// The `<` operator (less than)
775 /// The `<=` operator (less than or equal to)
777 /// The `!=` operator (not equal to)
779 /// The `>=` operator (greater than or equal to)
781 /// The `>` operator (greater than)
786 pub fn to_string(&self) -> &'static str {
809 pub fn lazy(&self) -> bool {
811 BinOpKind::And | BinOpKind::Or => true,
816 pub fn is_shift(&self) -> bool {
818 BinOpKind::Shl | BinOpKind::Shr => true,
823 pub fn is_comparison(&self) -> bool {
825 // Note for developers: please keep this as is;
826 // we want compilation to fail if another variant is added.
828 Eq | Lt | Le | Ne | Gt | Ge => true,
829 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
833 /// Returns `true` if the binary operator takes its arguments by value
834 pub fn is_by_value(&self) -> bool {
835 !self.is_comparison()
839 pub type BinOp = Spanned<BinOpKind>;
843 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
844 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
846 /// The `*` operator for dereferencing
848 /// The `!` operator for logical inversion
850 /// The `-` operator for negation
855 /// Returns `true` if the unary operator takes its argument by value
856 pub fn is_by_value(u: UnOp) -> bool {
858 UnOp::Neg | UnOp::Not => true,
863 pub fn to_string(op: UnOp) -> &'static str {
873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
881 pub fn add_trailing_semicolon(mut self) -> Self {
882 self.kind = match self.kind {
883 StmtKind::Expr(expr) => StmtKind::Semi(expr),
884 StmtKind::Mac(mac) => {
885 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
892 pub fn is_item(&self) -> bool {
894 StmtKind::Item(_) => true,
899 pub fn is_expr(&self) -> bool {
901 StmtKind::Expr(_) => true,
907 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
909 /// A local (let) binding.
911 /// An item definition.
913 /// Expr without trailing semi-colon.
915 /// Expr with a trailing semi-colon.
917 /// Just 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 // Otherwise 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, Async, 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 /// `Async::Yes` variant. 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 pub 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 pub 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>,
1637 pub fn name_str(self) -> &'static str {
1639 FloatTy::F32 => "f32",
1640 FloatTy::F64 => "f64",
1644 pub fn name(self) -> Symbol {
1646 FloatTy::F32 => sym::f32,
1647 FloatTy::F64 => sym::f64,
1651 pub fn bit_width(self) -> usize {
1682 pub fn name_str(&self) -> &'static str {
1684 IntTy::Isize => "isize",
1686 IntTy::I16 => "i16",
1687 IntTy::I32 => "i32",
1688 IntTy::I64 => "i64",
1689 IntTy::I128 => "i128",
1693 pub fn name(&self) -> Symbol {
1695 IntTy::Isize => sym::isize,
1696 IntTy::I8 => sym::i8,
1697 IntTy::I16 => sym::i16,
1698 IntTy::I32 => sym::i32,
1699 IntTy::I64 => sym::i64,
1700 IntTy::I128 => sym::i128,
1704 pub fn val_to_string(&self, val: i128) -> String {
1705 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1706 // are parsed as `u128`, so we wouldn't want to print an extra negative
1708 format!("{}{}", val as u128, self.name_str())
1711 pub fn bit_width(&self) -> Option<usize> {
1713 IntTy::Isize => return None,
1722 pub fn normalize(&self, target_width: u32) -> Self {
1724 IntTy::Isize => match target_width {
1728 _ => unreachable!(),
1758 pub fn name_str(&self) -> &'static str {
1760 UintTy::Usize => "usize",
1762 UintTy::U16 => "u16",
1763 UintTy::U32 => "u32",
1764 UintTy::U64 => "u64",
1765 UintTy::U128 => "u128",
1769 pub fn name(&self) -> Symbol {
1771 UintTy::Usize => sym::usize,
1772 UintTy::U8 => sym::u8,
1773 UintTy::U16 => sym::u16,
1774 UintTy::U32 => sym::u32,
1775 UintTy::U64 => sym::u64,
1776 UintTy::U128 => sym::u128,
1780 pub fn val_to_string(&self, val: u128) -> String {
1781 format!("{}{}", val, self.name_str())
1784 pub fn bit_width(&self) -> Option<usize> {
1786 UintTy::Usize => return None,
1791 UintTy::U128 => 128,
1795 pub fn normalize(&self, target_width: u32) -> Self {
1797 UintTy::Usize => match target_width {
1801 _ => unreachable!(),
1808 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1809 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1810 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1811 pub struct AssocTyConstraint {
1814 pub kind: AssocTyConstraintKind,
1818 /// The kinds of an `AssocTyConstraint`.
1819 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1820 pub enum AssocTyConstraintKind {
1821 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1822 Equality { ty: P<Ty> },
1823 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1824 Bound { bounds: GenericBounds },
1827 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1834 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1835 pub struct BareFnTy {
1836 pub unsafety: Unsafe,
1838 pub generic_params: Vec<GenericParam>,
1839 pub decl: P<FnDecl>,
1842 /// The various kinds of type recognized by the compiler.
1843 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1845 /// A variable-length slice (`[T]`).
1847 /// A fixed length array (`[T; n]`).
1848 Array(P<Ty>, AnonConst),
1849 /// A raw pointer (`*const T` or `*mut T`).
1851 /// A reference (`&'a T` or `&'a mut T`).
1852 Rptr(Option<Lifetime>, MutTy),
1853 /// A bare function (e.g., `fn(usize) -> bool`).
1854 BareFn(P<BareFnTy>),
1855 /// The never type (`!`).
1857 /// A tuple (`(A, B, C, D,...)`).
1859 /// A path (`module::module::...::Type`), optionally
1860 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1862 /// Type parameters are stored in the `Path` itself.
1863 Path(Option<QSelf>, Path),
1864 /// A trait object type `Bound1 + Bound2 + Bound3`
1865 /// where `Bound` is a trait or a lifetime.
1866 TraitObject(GenericBounds, TraitObjectSyntax),
1867 /// An `impl Bound1 + Bound2 + Bound3` type
1868 /// where `Bound` is a trait or a lifetime.
1870 /// The `NodeId` exists to prevent lowering from having to
1871 /// generate `NodeId`s on the fly, which would complicate
1872 /// the generation of opaque `type Foo = impl Trait` items significantly.
1873 ImplTrait(NodeId, GenericBounds),
1874 /// No-op; kept solely so that we can pretty-print faithfully.
1878 /// This means the type should be inferred instead of it having been
1879 /// specified. This can appear anywhere in a type.
1881 /// Inferred type of a `self` or `&self` argument in a method.
1883 /// A macro in the type position.
1885 /// Placeholder for a kind that has failed to be defined.
1887 /// Placeholder for a `va_list`.
1892 pub fn is_implicit_self(&self) -> bool {
1893 if let TyKind::ImplicitSelf = *self { true } else { false }
1896 pub fn is_unit(&self) -> bool {
1897 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1900 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1901 /// in lowering to avoid making larger changes there and beyond.
1902 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1904 Self::ImplTrait(_, bounds) => Some(bounds),
1910 /// Syntax used to declare a trait object.
1911 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1912 pub enum TraitObjectSyntax {
1917 /// Inline assembly dialect.
1919 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1920 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1921 pub enum AsmDialect {
1926 /// Inline assembly.
1928 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1929 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1930 pub struct InlineAsmOutput {
1931 pub constraint: Symbol,
1934 pub is_indirect: bool,
1937 /// Inline assembly.
1939 /// E.g., `asm!("NOP");`.
1940 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1941 pub struct InlineAsm {
1943 pub asm_str_style: StrStyle,
1944 pub outputs: Vec<InlineAsmOutput>,
1945 pub inputs: Vec<(Symbol, P<Expr>)>,
1946 pub clobbers: Vec<Symbol>,
1948 pub alignstack: bool,
1949 pub dialect: AsmDialect,
1952 /// A parameter in a function header.
1954 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1955 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1962 pub is_placeholder: bool,
1965 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1967 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1968 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1970 /// `self`, `mut self`
1972 /// `&'lt self`, `&'lt mut self`
1973 Region(Option<Lifetime>, Mutability),
1974 /// `self: TYPE`, `mut self: TYPE`
1975 Explicit(P<Ty>, Mutability),
1978 pub type ExplicitSelf = Spanned<SelfKind>;
1981 /// Attempts to cast parameter to `ExplicitSelf`.
1982 pub fn to_self(&self) -> Option<ExplicitSelf> {
1983 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
1984 if ident.name == kw::SelfLower {
1985 return match self.ty.kind {
1986 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1987 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
1988 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1991 self.pat.span.to(self.ty.span),
1992 SelfKind::Explicit(self.ty.clone(), mutbl),
2000 /// Returns `true` if parameter is `self`.
2001 pub fn is_self(&self) -> bool {
2002 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2003 ident.name == kw::SelfLower
2009 /// Builds a `Param` object from `ExplicitSelf`.
2010 pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2011 let span = eself.span.to(eself_ident.span);
2012 let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2013 let param = |mutbl, ty| Param {
2017 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2023 is_placeholder: false,
2026 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2027 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2028 SelfKind::Region(lt, mutbl) => param(
2032 kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2040 /// A signature (not the body) of a function declaration.
2042 /// E.g., `fn foo(bar: baz)`.
2044 /// Please note that it's different from `FnHeader` structure
2045 /// which contains metadata about function safety, asyncness, constness and ABI.
2046 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2048 pub inputs: Vec<Param>,
2049 pub output: FnRetTy,
2053 pub fn get_self(&self) -> Option<ExplicitSelf> {
2054 self.inputs.get(0).and_then(Param::to_self)
2056 pub fn has_self(&self) -> bool {
2057 self.inputs.get(0).map_or(false, Param::is_self)
2059 pub fn c_variadic(&self) -> bool {
2060 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2061 TyKind::CVarArgs => true,
2067 /// Is the trait definition an auto trait?
2068 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2074 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
2075 #[derive(HashStable_Generic)]
2081 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2083 Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2088 pub fn is_async(self) -> bool {
2089 if let Async::Yes { .. } = self { true } else { false }
2092 /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2093 pub fn opt_return_id(self) -> Option<NodeId> {
2095 Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2101 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
2102 #[derive(HashStable_Generic)]
2108 /// Item defaultness.
2109 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2110 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2111 pub enum Defaultness {
2116 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2117 pub enum ImplPolarity {
2118 /// `impl Trait for Type`
2120 /// `impl !Trait for Type`
2124 impl fmt::Debug for ImplPolarity {
2125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2127 ImplPolarity::Positive => "positive".fmt(f),
2128 ImplPolarity::Negative => "negative".fmt(f),
2133 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2135 /// Returns type is not specified.
2137 /// Functions default to `()` and closures default to inference.
2138 /// Span points to where return type would be inserted.
2140 /// Everything else.
2145 pub fn span(&self) -> Span {
2147 FnRetTy::Default(span) => span,
2148 FnRetTy::Ty(ref ty) => ty.span,
2153 /// Module declaration.
2155 /// E.g., `mod foo;` or `mod foo { .. }`.
2156 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2158 /// A span from the first token past `{` to the last token until `}`.
2159 /// For `mod foo;`, the inner span ranges from the first token
2160 /// to the last token in the external file.
2162 pub items: Vec<P<Item>>,
2163 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2167 /// Foreign module declaration.
2169 /// E.g., `extern { .. }` or `extern C { .. }`.
2170 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2171 pub struct ForeignMod {
2172 pub abi: Option<StrLit>,
2173 pub items: Vec<P<ForeignItem>>,
2176 /// Global inline assembly.
2178 /// Also known as "module-level assembly" or "file-scoped assembly".
2179 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2180 pub struct GlobalAsm {
2184 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2185 pub struct EnumDef {
2186 pub variants: Vec<Variant>,
2189 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2190 pub struct Variant {
2191 /// Attributes of the variant.
2192 pub attrs: Vec<Attribute>,
2193 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2197 /// The visibility of the variant. Syntactically accepted but not semantically.
2198 pub vis: Visibility,
2199 /// Name of the variant.
2202 /// Fields and constructor id of the variant.
2203 pub data: VariantData,
2204 /// Explicit discriminant, e.g., `Foo = 1`.
2205 pub disr_expr: Option<AnonConst>,
2206 /// Is a macro placeholder
2207 pub is_placeholder: bool,
2210 /// Part of `use` item to the right of its prefix.
2211 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2212 pub enum UseTreeKind {
2213 /// `use prefix` or `use prefix as rename`
2215 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2217 Simple(Option<Ident>, NodeId, NodeId),
2218 /// `use prefix::{...}`
2219 Nested(Vec<(UseTree, NodeId)>),
2224 /// A tree of paths sharing common prefixes.
2225 /// Used in `use` items both at top-level and inside of braces in import groups.
2226 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2227 pub struct UseTree {
2229 pub kind: UseTreeKind,
2234 pub fn ident(&self) -> Ident {
2236 UseTreeKind::Simple(Some(rename), ..) => rename,
2237 UseTreeKind::Simple(None, ..) => {
2238 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2240 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2245 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2246 /// are contained as statements within items. These two cases need to be
2247 /// distinguished for pretty-printing.
2248 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2249 pub enum AttrStyle {
2254 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2255 pub struct AttrId(pub usize);
2257 impl Idx for AttrId {
2258 fn new(idx: usize) -> Self {
2261 fn index(self) -> usize {
2266 impl rustc_serialize::Encodable for AttrId {
2267 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2272 impl rustc_serialize::Decodable for AttrId {
2273 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2274 d.read_nil().map(|_| crate::attr::mk_attr_id())
2278 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2279 pub struct AttrItem {
2284 /// A list of attributes.
2285 pub type AttrVec = ThinVec<Attribute>;
2287 /// Metadata associated with an item.
2288 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2289 pub struct Attribute {
2292 /// Denotes if the attribute decorates the following construct (outer)
2293 /// or the construct this attribute is contained within (inner).
2294 pub style: AttrStyle,
2298 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2300 /// A normal attribute.
2303 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2304 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2305 /// variant (which is much less compact and thus more expensive).
2309 /// `TraitRef`s appear in impls.
2311 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2312 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2313 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2314 /// same as the impl's `NodeId`).
2315 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2316 pub struct TraitRef {
2321 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2322 pub struct PolyTraitRef {
2323 /// The `'a` in `<'a> Foo<&'a T>`.
2324 pub bound_generic_params: Vec<GenericParam>,
2326 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2327 pub trait_ref: TraitRef,
2333 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2335 bound_generic_params: generic_params,
2336 trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2342 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2343 pub enum CrateSugar {
2344 /// Source is `pub(crate)`.
2347 /// Source is (just) `crate`.
2351 pub type Visibility = Spanned<VisibilityKind>;
2353 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2354 pub enum VisibilityKind {
2357 Restricted { path: P<Path>, id: NodeId },
2361 impl VisibilityKind {
2362 pub fn is_pub(&self) -> bool {
2363 if let VisibilityKind::Public = *self { true } else { false }
2367 /// Field of a struct.
2369 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2370 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2371 pub struct StructField {
2372 pub attrs: Vec<Attribute>,
2375 pub vis: Visibility,
2376 pub ident: Option<Ident>,
2379 pub is_placeholder: bool,
2382 /// Fields and constructor ids of enum variants and structs.
2383 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2384 pub enum VariantData {
2387 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2388 Struct(Vec<StructField>, bool),
2391 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2392 Tuple(Vec<StructField>, NodeId),
2395 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2400 /// Return the fields of this variant.
2401 pub fn fields(&self) -> &[StructField] {
2403 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2408 /// Return the `NodeId` of this variant's constructor, if it has one.
2409 pub fn ctor_id(&self) -> Option<NodeId> {
2411 VariantData::Struct(..) => None,
2412 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2417 /// An item definition.
2418 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2419 pub struct Item<K = ItemKind> {
2420 pub attrs: Vec<Attribute>,
2423 pub vis: Visibility,
2424 /// The name of the item.
2425 /// It might be a dummy name in case of anonymous items.
2430 /// Original tokens this item was parsed from. This isn't necessarily
2431 /// available for all items, although over time more and more items should
2432 /// have this be `Some`. Right now this is primarily used for procedural
2433 /// macros, notably custom attributes.
2435 /// Note that the tokens here do not include the outer attributes, but will
2436 /// include inner attributes.
2437 pub tokens: Option<TokenStream>,
2441 /// Return the span that encompasses the attributes.
2442 pub fn span_with_attributes(&self) -> Span {
2443 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2447 impl<K: Into<ItemKind>> Item<K> {
2448 pub fn into_item(self) -> Item {
2449 let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2450 Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2454 /// `extern` qualifier on a function item or function type.
2455 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2463 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2464 abi.map_or(Extern::Implicit, Extern::Explicit)
2468 /// A function header.
2470 /// All the information between the visibility and the name of the function is
2471 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2472 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2473 pub struct FnHeader {
2474 pub unsafety: Unsafe,
2475 pub asyncness: Async,
2476 pub constness: Const,
2481 /// Does this function header have any qualifiers or is it empty?
2482 pub fn has_qualifiers(&self) -> bool {
2483 let Self { unsafety, asyncness, constness, ext } = self;
2484 matches!(unsafety, Unsafe::Yes(_))
2485 || asyncness.is_async()
2486 || matches!(constness, Const::Yes(_))
2487 || !matches!(ext, Extern::None)
2491 impl Default for FnHeader {
2492 fn default() -> FnHeader {
2494 unsafety: Unsafe::No,
2495 asyncness: Async::No,
2496 constness: Const::No,
2502 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2504 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2506 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2507 ExternCrate(Option<Name>),
2508 /// A use declaration item (`use`).
2510 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2512 /// A static item (`static`).
2514 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2515 Static(P<Ty>, Mutability, Option<P<Expr>>),
2516 /// A constant item (`const`).
2518 /// E.g., `const FOO: i32 = 42;`.
2519 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2520 /// A function declaration (`fn`).
2522 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2523 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2524 /// A module declaration (`mod`).
2526 /// E.g., `mod foo;` or `mod foo { .. }`.
2528 /// An external module (`extern`).
2530 /// E.g., `extern {}` or `extern "C" {}`.
2531 ForeignMod(ForeignMod),
2532 /// Module-level inline assembly (from `global_asm!()`).
2533 GlobalAsm(P<GlobalAsm>),
2534 /// A type alias (`type`).
2536 /// E.g., `type Foo = Bar<u8>;`.
2537 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2538 /// An enum definition (`enum`).
2540 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2541 Enum(EnumDef, Generics),
2542 /// A struct definition (`struct`).
2544 /// E.g., `struct Foo<A> { x: A }`.
2545 Struct(VariantData, Generics),
2546 /// A union definition (`union`).
2548 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2549 Union(VariantData, Generics),
2550 /// A trait declaration (`trait`).
2552 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2553 Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>),
2556 /// E.g., `trait Foo = Bar + Quux;`.
2557 TraitAlias(Generics, GenericBounds),
2558 /// An implementation.
2560 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2563 polarity: ImplPolarity,
2564 defaultness: Defaultness,
2568 /// The trait being implemented, if any.
2569 of_trait: Option<TraitRef>,
2572 items: Vec<P<AssocItem>>,
2574 /// A macro invocation.
2576 /// E.g., `foo!(..)`.
2579 /// A macro definition.
2584 pub fn article(&self) -> &str {
2587 Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2588 | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2589 ExternCrate(..) | ForeignMod(..) | Mac(..) | Enum(..) | Impl { .. } => "an",
2593 pub fn descr(&self) -> &str {
2595 ItemKind::ExternCrate(..) => "extern crate",
2596 ItemKind::Use(..) => "`use` import",
2597 ItemKind::Static(..) => "static item",
2598 ItemKind::Const(..) => "constant item",
2599 ItemKind::Fn(..) => "function",
2600 ItemKind::Mod(..) => "module",
2601 ItemKind::ForeignMod(..) => "extern block",
2602 ItemKind::GlobalAsm(..) => "global asm item",
2603 ItemKind::TyAlias(..) => "type alias",
2604 ItemKind::Enum(..) => "enum",
2605 ItemKind::Struct(..) => "struct",
2606 ItemKind::Union(..) => "union",
2607 ItemKind::Trait(..) => "trait",
2608 ItemKind::TraitAlias(..) => "trait alias",
2609 ItemKind::Mac(..) => "item macro invocation",
2610 ItemKind::MacroDef(..) => "macro definition",
2611 ItemKind::Impl { .. } => "implementation",
2615 pub fn generics(&self) -> Option<&Generics> {
2617 Self::Fn(_, _, generics, _)
2618 | Self::TyAlias(_, generics, ..)
2619 | Self::Enum(_, generics)
2620 | Self::Struct(_, generics)
2621 | Self::Union(_, generics)
2622 | Self::Trait(_, _, generics, ..)
2623 | Self::TraitAlias(generics, _)
2624 | Self::Impl { generics, .. } => Some(generics),
2630 /// Represents associated items.
2631 /// These include items in `impl` and `trait` definitions.
2632 pub type AssocItem = Item<AssocItemKind>;
2634 /// Represents associated item kinds.
2636 /// The term "provided" in the variants below refers to the item having a default
2637 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2638 /// In an implementation, all items must be provided.
2639 /// The `Option`s below denote the bodies, where `Some(_)`
2640 /// means "provided" and conversely `None` means "required".
2641 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2642 pub enum AssocItemKind {
2643 /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2644 /// If `def` is parsed, then the constant is provided, and otherwise required.
2645 Const(Defaultness, P<Ty>, Option<P<Expr>>),
2646 /// An associated function.
2647 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2648 /// An associated type.
2649 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2650 /// A macro expanding to associated items.
2654 impl AssocItemKind {
2655 pub fn defaultness(&self) -> Defaultness {
2657 Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def,
2658 Self::Macro(..) => Defaultness::Final,
2663 impl From<AssocItemKind> for ItemKind {
2664 fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2665 match assoc_item_kind {
2666 AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2667 AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2668 AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2669 AssocItemKind::Macro(a) => ItemKind::Mac(a),
2674 impl TryFrom<ItemKind> for AssocItemKind {
2675 type Error = ItemKind;
2677 fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2678 Ok(match item_kind {
2679 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2680 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
2681 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
2682 ItemKind::Mac(a) => AssocItemKind::Macro(a),
2683 _ => return Err(item_kind),
2688 /// An item in `extern` block.
2689 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2690 pub enum ForeignItemKind {
2691 /// A foreign static item (`static FOO: u8`).
2692 Static(P<Ty>, Mutability, Option<P<Expr>>),
2693 /// A foreign function.
2694 Fn(Defaultness, FnSig, Generics, Option<P<Block>>),
2696 TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>),
2697 /// A macro expanding to foreign items.
2701 impl From<ForeignItemKind> for ItemKind {
2702 fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
2703 match foreign_item_kind {
2704 ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
2705 ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d),
2706 ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d),
2707 ForeignItemKind::Macro(a) => ItemKind::Mac(a),
2712 impl TryFrom<ItemKind> for ForeignItemKind {
2713 type Error = ItemKind;
2715 fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
2716 Ok(match item_kind {
2717 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
2718 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
2719 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
2720 ItemKind::Mac(a) => ForeignItemKind::Macro(a),
2721 _ => return Err(item_kind),
2726 pub type ForeignItem = Item<ForeignItemKind>;