1 //! The Rust abstract syntax tree module.
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
8 //! Other module items that worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`Mac`], [`MacDelimeter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`UnOpKind`], [`BinOp`], [`BinOpKind`]: Unary and binary operators.
21 pub use GenericArgs::*;
22 pub use UnsafeSource::*;
23 pub use crate::util::parser::ExprPrecedence;
25 pub use syntax_pos::symbol::{Ident, Symbol as Name};
28 use crate::source_map::{dummy_spanned, respan, Spanned};
29 use crate::token::{self, DelimToken};
30 use crate::tokenstream::{TokenStream, TokenTree, DelimSpan};
32 use syntax_pos::symbol::{kw, sym, Symbol};
33 use syntax_pos::{Span, DUMMY_SP, ExpnId};
35 use rustc_data_structures::fx::FxHashSet;
36 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
37 use rustc_data_structures::sync::Lrc;
38 use rustc_data_structures::thin_vec::ThinVec;
39 use rustc_index::vec::Idx;
40 use rustc_serialize::{self, Decoder, Encoder};
41 use rustc_macros::HashStable_Generic;
49 /// A "Label" is an identifier of some point in sources,
50 /// e.g. in the following code:
58 /// `'outer` is a label.
59 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable_Generic)]
64 impl fmt::Debug for Label {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 write!(f, "label({:?})", self.ident)
70 /// A "Lifetime" is an annotation of the scope in which variable
71 /// can be used, e.g. `'a` in `&'a i32`.
72 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
78 impl fmt::Debug for Lifetime {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 impl fmt::Display for Lifetime {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 write!(f, "{}", self.ident.name)
95 /// A "Path" is essentially Rust's notion of a name.
97 /// It's represented as a sequence of identifiers,
98 /// along with a bunch of supporting information.
100 /// E.g., `std::cmp::PartialEq`.
101 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
104 /// The segments in the path: the things separated by `::`.
105 /// Global paths begin with `kw::PathRoot`.
106 pub segments: Vec<PathSegment>,
109 impl PartialEq<Symbol> for Path {
110 fn eq(&self, symbol: &Symbol) -> bool {
111 self.segments.len() == 1 && {
112 self.segments[0].ident.name == *symbol
117 impl<CTX> HashStable<CTX> for Path {
118 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
119 self.segments.len().hash_stable(hcx, hasher);
120 for segment in &self.segments {
121 segment.ident.name.hash_stable(hcx, hasher);
127 // Convert a span and an identifier to the corresponding
129 pub fn from_ident(ident: Ident) -> Path {
131 segments: vec![PathSegment::from_ident(ident)],
136 pub fn is_global(&self) -> bool {
137 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
141 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
143 /// E.g., `std`, `String` or `Box<T>`.
144 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
145 pub struct PathSegment {
146 /// The identifier portion of this path segment.
151 /// Type/lifetime parameters attached to this path. They come in
152 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
153 /// `None` means that no parameter list is supplied (`Path`),
154 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
155 /// but it can be empty (`Path<>`).
156 /// `P` is used as a size optimization for the common case with no parameters.
157 pub args: Option<P<GenericArgs>>,
161 pub fn from_ident(ident: Ident) -> Self {
162 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
164 pub fn path_root(span: Span) -> Self {
165 PathSegment::from_ident(Ident::new(kw::PathRoot, span))
169 /// The arguments of a path segment.
171 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
172 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
173 pub enum GenericArgs {
174 /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
175 AngleBracketed(AngleBracketedArgs),
176 /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
177 Parenthesized(ParenthesizedArgs),
181 pub fn is_parenthesized(&self) -> bool {
183 Parenthesized(..) => true,
188 pub fn is_angle_bracketed(&self) -> bool {
190 AngleBracketed(..) => true,
195 pub fn span(&self) -> Span {
197 AngleBracketed(ref data) => data.span,
198 Parenthesized(ref data) => data.span,
203 /// Concrete argument in the sequence of generic args.
204 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
205 pub enum GenericArg {
206 /// `'a` in `Foo<'a>`
208 /// `Bar` in `Foo<Bar>`
215 pub fn span(&self) -> Span {
217 GenericArg::Lifetime(lt) => lt.ident.span,
218 GenericArg::Type(ty) => ty.span,
219 GenericArg::Const(ct) => ct.value.span,
224 /// A path like `Foo<'a, T>`.
225 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
226 pub struct AngleBracketedArgs {
227 /// The overall span.
229 /// The arguments for this path segment.
230 pub args: Vec<GenericArg>,
231 /// Constraints on associated types, if any.
232 /// E.g., `Foo<A = Bar, B: Baz>`.
233 pub constraints: Vec<AssocTyConstraint>,
236 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
237 fn into(self) -> Option<P<GenericArgs>> {
238 Some(P(GenericArgs::AngleBracketed(self)))
242 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
243 fn into(self) -> Option<P<GenericArgs>> {
244 Some(P(GenericArgs::Parenthesized(self)))
248 /// A path like `Foo(A, B) -> C`.
249 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
250 pub struct ParenthesizedArgs {
255 pub inputs: Vec<P<Ty>>,
258 pub output: Option<P<Ty>>,
261 impl ParenthesizedArgs {
262 pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
265 args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
271 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
273 use rustc_index::vec::Idx;
274 rustc_index::newtype_index! {
277 DEBUG_FORMAT = "NodeId({})"
282 pub use node_id_inner::NodeId;
285 pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self {
286 NodeId::from_u32(expn_id.as_u32())
289 pub fn placeholder_to_expn_id(self) -> ExpnId {
290 ExpnId::from_u32(self.as_u32())
294 impl fmt::Display for NodeId {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 fmt::Display::fmt(&self.as_u32(), f)
300 impl rustc_serialize::UseSpecializedEncodable for NodeId {
301 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
302 s.emit_u32(self.as_u32())
306 impl rustc_serialize::UseSpecializedDecodable for NodeId {
307 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
308 d.read_u32().map(NodeId::from_u32)
312 /// `NodeId` used to represent the root of the crate.
313 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
315 /// When parsing and doing expansions, we initially give all AST nodes this AST
316 /// node value. Then later, in the renumber pass, we renumber them to have
317 /// small, positive ids.
318 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
320 /// A modifier on a bound, currently this is only used for `?Sized`, where the
321 /// modifier is `Maybe`. Negative bounds should also be handled here.
322 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
323 pub enum TraitBoundModifier {
328 /// The AST represents all type param bounds as types.
329 /// `typeck::collect::compute_bounds` matches these against
330 /// the "special" built-in traits (see `middle::lang_items`) and
331 /// detects `Copy`, `Send` and `Sync`.
332 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
333 pub enum GenericBound {
334 Trait(PolyTraitRef, TraitBoundModifier),
339 pub fn span(&self) -> Span {
341 &GenericBound::Trait(ref t, ..) => t.span,
342 &GenericBound::Outlives(ref l) => l.ident.span,
347 pub type GenericBounds = Vec<GenericBound>;
349 /// Specifies the enforced ordering for generic parameters. In the future,
350 /// if we wanted to relax this order, we could override `PartialEq` and
351 /// `PartialOrd`, to allow the kinds to be unordered.
352 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
353 pub enum ParamKindOrd {
359 impl fmt::Display for ParamKindOrd {
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 ParamKindOrd::Lifetime => "lifetime".fmt(f),
363 ParamKindOrd::Type => "type".fmt(f),
364 ParamKindOrd::Const => "const".fmt(f),
369 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
370 pub enum GenericParamKind {
371 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
373 Type { default: Option<P<Ty>> },
377 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
378 pub struct GenericParam {
381 pub attrs: ThinVec<Attribute>,
382 pub bounds: GenericBounds,
383 pub is_placeholder: bool,
384 pub kind: GenericParamKind,
387 /// Represents lifetime, type and const parameters attached to a declaration of
388 /// a function, enum, trait, etc.
389 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
390 pub struct Generics {
391 pub params: Vec<GenericParam>,
392 pub where_clause: WhereClause,
396 impl Default for Generics {
397 /// Creates an instance of `Generics`.
398 fn default() -> Generics {
401 where_clause: WhereClause {
402 predicates: Vec::new(),
410 /// A where-clause in a definition.
411 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
412 pub struct WhereClause {
413 pub predicates: Vec<WherePredicate>,
417 /// A single predicate in a where-clause.
418 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
419 pub enum WherePredicate {
420 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
421 BoundPredicate(WhereBoundPredicate),
422 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
423 RegionPredicate(WhereRegionPredicate),
424 /// An equality predicate (unsupported).
425 EqPredicate(WhereEqPredicate),
428 impl WherePredicate {
429 pub fn span(&self) -> Span {
431 &WherePredicate::BoundPredicate(ref p) => p.span,
432 &WherePredicate::RegionPredicate(ref p) => p.span,
433 &WherePredicate::EqPredicate(ref p) => p.span,
440 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
441 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
442 pub struct WhereBoundPredicate {
444 /// Any generics from a `for` binding.
445 pub bound_generic_params: Vec<GenericParam>,
446 /// The type being bounded.
447 pub bounded_ty: P<Ty>,
448 /// Trait and lifetime bounds (`Clone + Send + 'static`).
449 pub bounds: GenericBounds,
452 /// A lifetime predicate.
454 /// E.g., `'a: 'b + 'c`.
455 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
456 pub struct WhereRegionPredicate {
458 pub lifetime: Lifetime,
459 pub bounds: GenericBounds,
462 /// An equality predicate (unsupported).
465 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
466 pub struct WhereEqPredicate {
473 /// The set of `MetaItem`s that define the compilation environment of the crate,
474 /// used to drive conditional compilation.
475 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
477 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
480 pub attrs: Vec<Attribute>,
484 /// Possible values inside of compile-time attribute lists.
486 /// E.g., the '..' in `#[name(..)]`.
487 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
488 pub enum NestedMetaItem {
489 /// A full MetaItem, for recursive meta items.
493 /// E.g., `"foo"`, `64`, `true`.
497 /// A spanned compile-time attribute item.
499 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
500 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
501 pub struct MetaItem {
503 pub kind: MetaItemKind,
507 /// A compile-time attribute item.
509 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
510 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
511 pub enum MetaItemKind {
514 /// E.g., `test` as in `#[test]`.
518 /// E.g., `derive(..)` as in `#[derive(..)]`.
519 List(Vec<NestedMetaItem>),
520 /// Name value meta item.
522 /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
526 /// A block (`{ .. }`).
528 /// E.g., `{ .. }` as in `fn foo() { .. }`.
529 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
531 /// The statements in the block.
532 pub stmts: Vec<Stmt>,
534 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
535 pub rules: BlockCheckMode,
539 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
547 /// Attempt reparsing the pattern as a type.
548 /// This is intended for use by diagnostics.
549 pub fn to_ty(&self) -> Option<P<Ty>> {
550 let kind = match &self.kind {
551 // In a type expression `_` is an inference variable.
552 PatKind::Wild => TyKind::Infer,
553 // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
554 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
555 TyKind::Path(None, Path::from_ident(*ident))
557 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
558 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
559 // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
560 PatKind::Ref(pat, mutbl) => pat
562 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
563 // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
564 // when `P` can be reparsed as a type `T`.
565 PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
566 // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
567 // assuming `T0` to `Tn` are all syntactically valid as types.
568 PatKind::Tuple(pats) => {
569 let mut tys = Vec::with_capacity(pats.len());
570 // FIXME(#48994) - could just be collected into an Option<Vec>
572 tys.push(pat.to_ty()?);
586 /// Walk top-down and call `it` in each place where a pattern occurs
587 /// starting with the root pattern `walk` is called on. If `it` returns
588 /// false then we will descend no further but siblings will be processed.
589 pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
595 // Walk into the pattern associated with `Ident` (if any).
596 PatKind::Ident(_, _, Some(p)) => p.walk(it),
598 // Walk into each field of struct.
599 PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
601 // Sequence of patterns.
602 PatKind::TupleStruct(_, s)
605 | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
607 // Trivial wrappers over inner patterns.
610 | PatKind::Paren(s) => s.walk(it),
612 // These patterns do not contain subpatterns, skip.
619 | PatKind::Mac(_) => {},
623 /// Is this a `..` pattern?
624 pub fn is_rest(&self) -> bool {
626 PatKind::Rest => true,
632 /// A single field in a struct pattern
634 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
635 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
636 /// except is_shorthand is true
637 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
638 pub struct FieldPat {
639 /// The identifier for the field
641 /// The pattern the field is destructured to
643 pub is_shorthand: bool,
644 pub attrs: ThinVec<Attribute>,
647 pub is_placeholder: bool,
650 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
651 pub enum BindingMode {
656 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
658 Included(RangeSyntax),
662 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
663 pub enum RangeSyntax {
670 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
672 /// Represents a wildcard pattern (`_`).
675 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
676 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
677 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
678 /// during name resolution.
679 Ident(BindingMode, Ident, Option<P<Pat>>),
681 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
682 /// The `bool` is `true` in the presence of a `..`.
683 Struct(Path, Vec<FieldPat>, /* recovered */ bool),
685 /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
686 TupleStruct(Path, Vec<P<Pat>>),
688 /// An or-pattern `A | B | C`.
689 /// Invariant: `pats.len() >= 2`.
692 /// A possibly qualified path pattern.
693 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
694 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
695 /// only legally refer to associated constants.
696 Path(Option<QSelf>, Path),
698 /// A tuple pattern (`(a, b)`).
704 /// A reference pattern (e.g., `&mut (a, b)`).
705 Ref(P<Pat>, Mutability),
710 /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
711 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
713 /// A slice pattern `[a, b, c]`.
716 /// A rest pattern `..`.
718 /// Syntactically it is valid anywhere.
720 /// Semantically however, it only has meaning immediately inside:
721 /// - a slice pattern: `[a, .., b]`,
722 /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
723 /// - a tuple pattern: `(a, .., b)`,
724 /// - a tuple struct/variant pattern: `$path(a, .., b)`.
726 /// In all of these cases, an additional restriction applies,
727 /// only one rest pattern may occur in the pattern sequences.
730 /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
733 /// A macro pattern; pre-expansion.
737 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
738 RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
739 pub enum Mutability {
745 /// Returns `MutMutable` only if both `self` and `other` are mutable.
746 pub fn and(self, other: Self) -> Self {
748 Mutability::Mutable => other,
749 Mutability::Immutable => Mutability::Immutable,
753 pub fn invert(self) -> Self {
755 Mutability::Mutable => Mutability::Immutable,
756 Mutability::Immutable => Mutability::Mutable,
760 pub fn prefix_str(&self) -> &'static str {
762 Mutability::Mutable => "mut ",
763 Mutability::Immutable => "",
768 /// The kind of borrow in an `AddrOf` expression,
769 /// e.g., `&place` or `&raw const place`.
770 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
771 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
772 pub enum BorrowKind {
773 /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
774 /// The resulting type is either `*const T` or `*mut T`
775 /// where `T = typeof($expr)`.
777 /// A normal borrow, `&$expr` or `&mut $expr`.
778 /// The resulting type is either `&'a T` or `&'a mut T`
779 /// where `T = typeof($expr)` and `'a` is some lifetime.
783 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
785 /// The `+` operator (addition)
787 /// The `-` operator (subtraction)
789 /// The `*` operator (multiplication)
791 /// The `/` operator (division)
793 /// The `%` operator (modulus)
795 /// The `&&` operator (logical and)
797 /// The `||` operator (logical or)
799 /// The `^` operator (bitwise xor)
801 /// The `&` operator (bitwise and)
803 /// The `|` operator (bitwise or)
805 /// The `<<` operator (shift left)
807 /// The `>>` operator (shift right)
809 /// The `==` operator (equality)
811 /// The `<` operator (less than)
813 /// The `<=` operator (less than or equal to)
815 /// The `!=` operator (not equal to)
817 /// The `>=` operator (greater than or equal to)
819 /// The `>` operator (greater than)
824 pub fn to_string(&self) -> &'static str {
847 pub fn lazy(&self) -> bool {
849 BinOpKind::And | BinOpKind::Or => true,
854 pub fn is_shift(&self) -> bool {
856 BinOpKind::Shl | BinOpKind::Shr => true,
861 pub fn is_comparison(&self) -> bool {
863 // Note for developers: please keep this as is;
864 // we want compilation to fail if another variant is added.
866 Eq | Lt | Le | Ne | Gt | Ge => true,
867 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
871 /// Returns `true` if the binary operator takes its arguments by value
872 pub fn is_by_value(&self) -> bool {
873 !self.is_comparison()
877 pub type BinOp = Spanned<BinOpKind>;
881 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
882 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
884 /// The `*` operator for dereferencing
886 /// The `!` operator for logical inversion
888 /// The `-` operator for negation
893 /// Returns `true` if the unary operator takes its argument by value
894 pub fn is_by_value(u: UnOp) -> bool {
896 UnOp::Neg | UnOp::Not => true,
901 pub fn to_string(op: UnOp) -> &'static str {
911 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
919 pub fn add_trailing_semicolon(mut self) -> Self {
920 self.kind = match self.kind {
921 StmtKind::Expr(expr) => StmtKind::Semi(expr),
922 StmtKind::Mac(mac) => {
923 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
930 pub fn is_item(&self) -> bool {
932 StmtKind::Item(_) => true,
937 pub fn is_expr(&self) -> bool {
939 StmtKind::Expr(_) => true,
945 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
947 /// A local (let) binding.
949 /// An item definition.
951 /// Expr without trailing semi-colon.
953 /// Expr with a trailing semi-colon.
956 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
959 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
960 pub enum MacStmtStyle {
961 /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
962 /// `foo!(...);`, `foo![...];`).
964 /// The macro statement had braces (e.g., `foo! { ... }`).
966 /// The macro statement had parentheses or brackets and no semicolon (e.g.,
967 /// `foo!(...)`). All of these will end up being converted into macro
972 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
973 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
977 pub ty: Option<P<Ty>>,
978 /// Initializer expression to set the value, if any.
979 pub init: Option<P<Expr>>,
981 pub attrs: ThinVec<Attribute>,
984 /// An arm of a 'match'.
986 /// E.g., `0..=10 => { println!("match!") }` as in
990 /// 0..=10 => { println!("match!") },
991 /// _ => { println!("no match!") },
994 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
996 pub attrs: Vec<Attribute>,
997 /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
999 /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1000 pub guard: Option<P<Expr>>,
1005 pub is_placeholder: bool,
1008 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1009 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1011 pub attrs: ThinVec<Attribute>,
1016 pub is_shorthand: bool,
1017 pub is_placeholder: bool,
1020 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1021 pub enum BlockCheckMode {
1023 Unsafe(UnsafeSource),
1026 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1027 pub enum UnsafeSource {
1032 /// A constant (expression) that's not an item or associated item,
1033 /// but needs its own `DefId` for type-checking, const-eval, etc.
1034 /// These are usually found nested inside types (e.g., array lengths)
1035 /// or expressions (e.g., repeat counts), and also used to define
1036 /// explicit discriminant values for enum variants.
1037 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1038 pub struct AnonConst {
1044 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1049 pub attrs: ThinVec<Attribute>,
1052 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1053 #[cfg(target_arch = "x86_64")]
1054 rustc_data_structures::static_assert_size!(Expr, 96);
1057 /// Returns `true` if this expression would be valid somewhere that expects a value;
1058 /// for example, an `if` condition.
1059 pub fn returns(&self) -> bool {
1060 if let ExprKind::Block(ref block, _) = self.kind {
1061 match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1063 Some(&StmtKind::Expr(_)) => true,
1064 Some(&StmtKind::Semi(ref expr)) => {
1065 if let ExprKind::Ret(_) = expr.kind {
1066 // Last statement is explicit return.
1072 // This is a block that doesn't end in either an implicit or explicit return.
1076 // This is not a block, it is a value.
1081 pub fn to_bound(&self) -> Option<GenericBound> {
1083 ExprKind::Path(None, path) => Some(GenericBound::Trait(
1084 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1085 TraitBoundModifier::None,
1091 /// Attempts to reparse as `Ty` (for diagnostic purposes).
1092 pub fn to_ty(&self) -> Option<P<Ty>> {
1093 let kind = match &self.kind {
1094 // Trivial conversions.
1095 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1096 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1098 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1100 ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => expr
1102 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1104 ExprKind::Repeat(expr, expr_len) => {
1105 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1108 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1110 ExprKind::Tup(exprs) => {
1113 .map(|expr| expr.to_ty())
1114 .collect::<Option<Vec<_>>>()?;
1118 // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1119 // then type of result is trait object.
1120 // Othewise we don't assume the result type.
1121 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1122 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1123 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1129 // This expression doesn't look like a type syntactically.
1140 pub fn precedence(&self) -> ExprPrecedence {
1142 ExprKind::Box(_) => ExprPrecedence::Box,
1143 ExprKind::Array(_) => ExprPrecedence::Array,
1144 ExprKind::Call(..) => ExprPrecedence::Call,
1145 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1146 ExprKind::Tup(_) => ExprPrecedence::Tup,
1147 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1148 ExprKind::Unary(..) => ExprPrecedence::Unary,
1149 ExprKind::Lit(_) => ExprPrecedence::Lit,
1150 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1151 ExprKind::Let(..) => ExprPrecedence::Let,
1152 ExprKind::If(..) => ExprPrecedence::If,
1153 ExprKind::While(..) => ExprPrecedence::While,
1154 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1155 ExprKind::Loop(..) => ExprPrecedence::Loop,
1156 ExprKind::Match(..) => ExprPrecedence::Match,
1157 ExprKind::Closure(..) => ExprPrecedence::Closure,
1158 ExprKind::Block(..) => ExprPrecedence::Block,
1159 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1160 ExprKind::Async(..) => ExprPrecedence::Async,
1161 ExprKind::Await(..) => ExprPrecedence::Await,
1162 ExprKind::Assign(..) => ExprPrecedence::Assign,
1163 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1164 ExprKind::Field(..) => ExprPrecedence::Field,
1165 ExprKind::Index(..) => ExprPrecedence::Index,
1166 ExprKind::Range(..) => ExprPrecedence::Range,
1167 ExprKind::Path(..) => ExprPrecedence::Path,
1168 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1169 ExprKind::Break(..) => ExprPrecedence::Break,
1170 ExprKind::Continue(..) => ExprPrecedence::Continue,
1171 ExprKind::Ret(..) => ExprPrecedence::Ret,
1172 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1173 ExprKind::Mac(..) => ExprPrecedence::Mac,
1174 ExprKind::Struct(..) => ExprPrecedence::Struct,
1175 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1176 ExprKind::Paren(..) => ExprPrecedence::Paren,
1177 ExprKind::Try(..) => ExprPrecedence::Try,
1178 ExprKind::Yield(..) => ExprPrecedence::Yield,
1179 ExprKind::Err => ExprPrecedence::Err,
1184 /// Limit types of a range (inclusive or exclusive)
1185 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1186 pub enum RangeLimits {
1187 /// Inclusive at the beginning, exclusive at the end
1189 /// Inclusive at the beginning and end
1193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1195 /// A `box x` expression.
1197 /// An array (`[a, b, c, d]`)
1198 Array(Vec<P<Expr>>),
1201 /// The first field resolves to the function itself,
1202 /// and the second field is the list of arguments.
1203 /// This also represents calling the constructor of
1204 /// tuple-like ADTs such as tuple structs and enum variants.
1205 Call(P<Expr>, Vec<P<Expr>>),
1206 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1208 /// The `PathSegment` represents the method name and its generic arguments
1209 /// (within the angle brackets).
1210 /// The first element of the vector of an `Expr` is the expression that evaluates
1211 /// to the object on which the method is being called on (the receiver),
1212 /// and the remaining elements are the rest of the arguments.
1213 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1214 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1215 MethodCall(PathSegment, Vec<P<Expr>>),
1216 /// A tuple (e.g., `(a, b, c, d)`).
1218 /// A binary operation (e.g., `a + b`, `a * b`).
1219 Binary(BinOp, P<Expr>, P<Expr>),
1220 /// A unary operation (e.g., `!x`, `*x`).
1221 Unary(UnOp, P<Expr>),
1222 /// A literal (e.g., `1`, `"foo"`).
1224 /// A cast (e.g., `foo as f64`).
1225 Cast(P<Expr>, P<Ty>),
1226 /// A type ascription (e.g., `42: usize`).
1227 Type(P<Expr>, P<Ty>),
1228 /// A `let pat = expr` expression that is only semantically allowed in the condition
1229 /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1230 Let(P<Pat>, P<Expr>),
1231 /// An `if` block, with an optional `else` block.
1233 /// `if expr { block } else { expr }`
1234 If(P<Expr>, P<Block>, Option<P<Expr>>),
1235 /// A while loop, with an optional label.
1237 /// `'label: while expr { block }`
1238 While(P<Expr>, P<Block>, Option<Label>),
1239 /// A `for` loop, with an optional label.
1241 /// `'label: for pat in expr { block }`
1243 /// This is desugared to a combination of `loop` and `match` expressions.
1244 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1245 /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1247 /// `'label: loop { block }`
1248 Loop(P<Block>, Option<Label>),
1249 /// A `match` block.
1250 Match(P<Expr>, Vec<Arm>),
1251 /// A closure (e.g., `move |a, b, c| a + b + c`).
1253 /// The final span is the span of the argument block `|...|`.
1254 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1255 /// A block (`'label: { ... }`).
1256 Block(P<Block>, Option<Label>),
1257 /// An async block (`async move { ... }`).
1259 /// The `NodeId` is the `NodeId` for the closure that results from
1260 /// desugaring an async block, just like the NodeId field in the
1261 /// `IsAsync` enum. This is necessary in order to create a def for the
1262 /// closure which can be used as a parent of any child defs. Defs
1263 /// created during lowering cannot be made the parent of any other
1264 /// preexisting defs.
1265 Async(CaptureBy, NodeId, P<Block>),
1266 /// An await expression (`my_future.await`).
1269 /// A try block (`try { ... }`).
1272 /// An assignment (`a = foo()`).
1273 Assign(P<Expr>, P<Expr>),
1274 /// An assignment with an operator.
1277 AssignOp(BinOp, P<Expr>, P<Expr>),
1278 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1279 Field(P<Expr>, Ident),
1280 /// An indexing operation (e.g., `foo[2]`).
1281 Index(P<Expr>, P<Expr>),
1282 /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1283 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1285 /// Variable reference, possibly containing `::` and/or type
1286 /// parameters (e.g., `foo::bar::<baz>`).
1288 /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1289 Path(Option<QSelf>, Path),
1291 /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1292 AddrOf(BorrowKind, Mutability, P<Expr>),
1293 /// A `break`, with an optional label to break, and an optional expression.
1294 Break(Option<Label>, Option<P<Expr>>),
1295 /// A `continue`, with an optional label.
1296 Continue(Option<Label>),
1297 /// A `return`, with an optional value to be returned.
1298 Ret(Option<P<Expr>>),
1300 /// Output of the `asm!()` macro.
1301 InlineAsm(P<InlineAsm>),
1303 /// A macro invocation; pre-expansion.
1306 /// A struct literal expression.
1308 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1309 /// where `base` is the `Option<Expr>`.
1310 Struct(Path, Vec<Field>, Option<P<Expr>>),
1312 /// An array literal constructed from one repeated element.
1314 /// E.g., `[1; 5]`. The expression is the element to be
1315 /// repeated; the constant is the number of times to repeat it.
1316 Repeat(P<Expr>, AnonConst),
1318 /// No-op: used solely so we can pretty-print faithfully.
1321 /// A try expression (`expr?`).
1324 /// A `yield`, with an optional value to be yielded.
1325 Yield(Option<P<Expr>>),
1327 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1331 /// The explicit `Self` type in a "qualified path". The actual
1332 /// path, including the trait and the associated item, is stored
1333 /// separately. `position` represents the index of the associated
1334 /// item qualified with this `Self` type.
1336 /// ```ignore (only-for-syntax-highlight)
1337 /// <Vec<T> as a::b::Trait>::AssociatedItem
1338 /// ^~~~~ ~~~~~~~~~~~~~~^
1341 /// <Vec<T>>::AssociatedItem
1345 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1349 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1350 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1351 /// 0`, this is an empty span.
1352 pub path_span: Span,
1353 pub position: usize,
1356 /// A capture clause used in closures and `async` blocks.
1357 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1358 pub enum CaptureBy {
1359 /// `move |x| y + x`.
1361 /// `move` keyword was not specified.
1365 /// The movability of a generator / closure literal:
1366 /// whether a generator contains self-references, causing it to be `!Unpin`.
1367 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
1368 RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1369 pub enum Movability {
1370 /// May contain self-references, `!Unpin`.
1372 /// Must not contain self-references, `Unpin`.
1376 /// Represents a macro invocation. The `path` indicates which macro
1377 /// is being invoked, and the `args` are arguments passed to it.
1378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1381 pub args: P<MacArgs>,
1382 pub prior_type_ascription: Option<(Span, bool)>,
1386 pub fn span(&self) -> Span {
1387 self.path.span.to(self.args.span().unwrap_or(self.path.span))
1391 /// Arguments passed to an attribute or a function-like macro.
1392 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1394 /// No arguments - `#[attr]`.
1396 /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1397 Delimited(DelimSpan, MacDelimiter, TokenStream),
1398 /// Arguments of a key-value attribute - `#[attr = "value"]`.
1399 /// Span belongs to the `=` token, token stream is the "value".
1400 Eq(Span, TokenStream),
1404 pub fn delim(&self) -> DelimToken {
1406 MacArgs::Delimited(_, delim, _) => delim.to_token(),
1407 MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1411 pub fn span(&self) -> Option<Span> {
1413 MacArgs::Empty => None,
1414 MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1415 MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1419 /// Tokens inside the delimiters or after `=`.
1420 /// Proc macros see these tokens, for example.
1421 pub fn inner_tokens(&self) -> TokenStream {
1423 MacArgs::Empty => TokenStream::default(),
1424 MacArgs::Delimited(.., tokens) => tokens.clone(),
1425 MacArgs::Eq(.., tokens) => tokens.clone(),
1429 /// Tokens together with the delimiters or `=`.
1430 /// Use of this functions generally means that something suboptimal or hacky is happening.
1431 pub fn outer_tokens(&self) -> TokenStream {
1433 MacArgs::Empty => TokenStream::default(),
1434 MacArgs::Delimited(dspan, delim, ref tokens) =>
1435 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into(),
1436 MacArgs::Eq(eq_span, ref tokens) => iter::once(TokenTree::token(token::Eq, eq_span))
1437 .chain(tokens.trees()).collect(),
1441 /// Whether a macro with these arguments needs a semicolon
1442 /// when used as a standalone item or statement.
1443 pub fn need_semicolon(&self) -> bool {
1444 !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace ,_))
1448 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1449 pub enum MacDelimiter {
1456 crate fn to_token(self) -> DelimToken {
1458 MacDelimiter::Parenthesis => DelimToken::Paren,
1459 MacDelimiter::Bracket => DelimToken::Bracket,
1460 MacDelimiter::Brace => DelimToken::Brace,
1464 pub fn from_token(delim: DelimToken) -> MacDelimiter {
1466 token::Paren => MacDelimiter::Parenthesis,
1467 token::Bracket => MacDelimiter::Bracket,
1468 token::Brace => MacDelimiter::Brace,
1469 token::NoDelim => panic!("expected a delimiter"),
1474 /// Represents a macro definition.
1475 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1476 pub struct MacroDef {
1477 pub body: P<MacArgs>,
1478 /// `true` if macro was defined with `macro_rules`.
1482 // Clippy uses Hash and PartialEq
1483 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
1485 /// A regular string, like `"foo"`.
1487 /// A raw string, like `r##"foo"##`.
1489 /// The value is the number of `#` symbols used.
1494 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1496 /// The original literal token as written in source code.
1497 pub token: token::Lit,
1498 /// The "semantic" representation of the literal lowered from the original tokens.
1499 /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1500 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1505 /// Same as `Lit`, but restricted to string literals.
1506 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1508 /// The original literal token as written in source code.
1509 pub style: StrStyle,
1511 pub suffix: Option<Symbol>,
1513 /// The unescaped "semantic" representation of the literal lowered from the original token.
1514 /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1515 pub symbol_unescaped: Symbol,
1519 crate fn as_lit(&self) -> Lit {
1520 let token_kind = match self.style {
1521 StrStyle::Cooked => token::Str,
1522 StrStyle::Raw(n) => token::StrRaw(n),
1525 token: token::Lit::new(token_kind, self.symbol, self.suffix),
1527 kind: LitKind::Str(self.symbol_unescaped, self.style),
1532 // Clippy uses Hash and PartialEq
1533 /// Type of the integer literal based on provided suffix.
1534 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1535 pub enum LitIntType {
1544 /// Type of the float literal based on provided suffix.
1545 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1546 pub enum LitFloatType {
1547 /// A float literal with a suffix (`1f32` or `1E10f32`).
1549 /// A float literal without a suffix (`1.0 or 1.0E10`).
1555 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1556 // Clippy uses Hash and PartialEq
1557 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1559 /// A string literal (`"foo"`).
1560 Str(Symbol, StrStyle),
1561 /// A byte string (`b"foo"`).
1562 ByteStr(Lrc<Vec<u8>>),
1563 /// A byte char (`b'f'`).
1565 /// A character literal (`'a'`).
1567 /// An integer literal (`1`).
1568 Int(u128, LitIntType),
1569 /// A float literal (`1f64` or `1E10f64`).
1570 Float(Symbol, LitFloatType),
1571 /// A boolean literal.
1573 /// Placeholder for a literal that wasn't well-formed in some way.
1578 /// Returns `true` if this literal is a string.
1579 pub fn is_str(&self) -> bool {
1581 LitKind::Str(..) => true,
1586 /// Returns `true` if this literal is byte literal string.
1587 pub fn is_bytestr(&self) -> bool {
1589 LitKind::ByteStr(_) => true,
1594 /// Returns `true` if this is a numeric literal.
1595 pub fn is_numeric(&self) -> bool {
1597 LitKind::Int(..) | LitKind::Float(..) => true,
1602 /// Returns `true` if this literal has no suffix.
1603 /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1604 pub fn is_unsuffixed(&self) -> bool {
1608 /// Returns `true` if this literal has a suffix.
1609 pub fn is_suffixed(&self) -> bool {
1611 // suffixed variants
1612 LitKind::Int(_, LitIntType::Signed(..))
1613 | LitKind::Int(_, LitIntType::Unsigned(..))
1614 | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1615 // unsuffixed variants
1617 | LitKind::ByteStr(..)
1620 | LitKind::Int(_, LitIntType::Unsuffixed)
1621 | LitKind::Float(_, LitFloatType::Unsuffixed)
1623 | LitKind::Err(..) => false,
1628 // N.B., If you change this, you'll probably want to change the corresponding
1629 // type structure in `middle/ty.rs` as well.
1630 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1633 pub mutbl: Mutability,
1636 /// Represents a function's signature in a trait declaration,
1637 /// trait implementation, or free function.
1638 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1640 pub header: FnHeader,
1641 pub decl: P<FnDecl>,
1644 /// Represents an item declaration within a trait declaration,
1645 /// possibly including a default implementation. A trait item is
1646 /// either required (meaning it doesn't have an implementation, just a
1647 /// signature) or provided (meaning it has a default implementation).
1648 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1649 pub struct TraitItem {
1650 pub attrs: Vec<Attribute>,
1653 pub vis: Visibility,
1656 pub generics: Generics,
1657 pub kind: TraitItemKind,
1658 /// See `Item::tokens` for what this is.
1659 pub tokens: Option<TokenStream>,
1662 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1663 pub enum TraitItemKind {
1664 Const(P<Ty>, Option<P<Expr>>),
1665 Method(FnSig, Option<P<Block>>),
1666 Type(GenericBounds, Option<P<Ty>>),
1670 /// Represents anything within an `impl` block.
1671 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1672 pub struct ImplItem {
1673 pub attrs: Vec<Attribute>,
1676 pub vis: Visibility,
1679 pub defaultness: Defaultness,
1680 pub generics: Generics,
1681 pub kind: ImplItemKind,
1682 /// See `Item::tokens` for what this is.
1683 pub tokens: Option<TokenStream>,
1686 /// Represents various kinds of content within an `impl`.
1687 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1688 pub enum ImplItemKind {
1689 Const(P<Ty>, P<Expr>),
1690 Method(FnSig, P<Block>),
1695 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1696 RustcEncodable, RustcDecodable, Debug)]
1703 pub fn name_str(self) -> &'static str {
1705 FloatTy::F32 => "f32",
1706 FloatTy::F64 => "f64",
1710 pub fn name(self) -> Symbol {
1712 FloatTy::F32 => sym::f32,
1713 FloatTy::F64 => sym::f64,
1717 pub fn bit_width(self) -> usize {
1725 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1726 RustcEncodable, RustcDecodable, Debug)]
1737 pub fn name_str(&self) -> &'static str {
1739 IntTy::Isize => "isize",
1741 IntTy::I16 => "i16",
1742 IntTy::I32 => "i32",
1743 IntTy::I64 => "i64",
1744 IntTy::I128 => "i128",
1748 pub fn name(&self) -> Symbol {
1750 IntTy::Isize => sym::isize,
1751 IntTy::I8 => sym::i8,
1752 IntTy::I16 => sym::i16,
1753 IntTy::I32 => sym::i32,
1754 IntTy::I64 => sym::i64,
1755 IntTy::I128 => sym::i128,
1759 pub fn val_to_string(&self, val: i128) -> String {
1760 // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1761 // are parsed as `u128`, so we wouldn't want to print an extra negative
1763 format!("{}{}", val as u128, self.name_str())
1766 pub fn bit_width(&self) -> Option<usize> {
1768 IntTy::Isize => return None,
1777 pub fn normalize(&self, target_width: u32) -> Self {
1779 IntTy::Isize => match target_width {
1783 _ => unreachable!(),
1790 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1791 RustcEncodable, RustcDecodable, Copy, Debug)]
1802 pub fn name_str(&self) -> &'static str {
1804 UintTy::Usize => "usize",
1806 UintTy::U16 => "u16",
1807 UintTy::U32 => "u32",
1808 UintTy::U64 => "u64",
1809 UintTy::U128 => "u128",
1813 pub fn name(&self) -> Symbol {
1815 UintTy::Usize => sym::usize,
1816 UintTy::U8 => sym::u8,
1817 UintTy::U16 => sym::u16,
1818 UintTy::U32 => sym::u32,
1819 UintTy::U64 => sym::u64,
1820 UintTy::U128 => sym::u128,
1824 pub fn val_to_string(&self, val: u128) -> String {
1825 format!("{}{}", val, self.name_str())
1828 pub fn bit_width(&self) -> Option<usize> {
1830 UintTy::Usize => return None,
1835 UintTy::U128 => 128,
1839 pub fn normalize(&self, target_width: u32) -> Self {
1841 UintTy::Usize => match target_width {
1845 _ => unreachable!(),
1852 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1853 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1854 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1855 pub struct AssocTyConstraint {
1858 pub kind: AssocTyConstraintKind,
1862 /// The kinds of an `AssocTyConstraint`.
1863 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1864 pub enum AssocTyConstraintKind {
1865 /// E.g., `A = Bar` in `Foo<A = Bar>`.
1869 /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1871 bounds: GenericBounds,
1875 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1882 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1883 pub struct BareFnTy {
1884 pub unsafety: Unsafety,
1886 pub generic_params: Vec<GenericParam>,
1887 pub decl: P<FnDecl>,
1890 /// The various kinds of type recognized by the compiler.
1891 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1893 /// A variable-length slice (`[T]`).
1895 /// A fixed length array (`[T; n]`).
1896 Array(P<Ty>, AnonConst),
1897 /// A raw pointer (`*const T` or `*mut T`).
1899 /// A reference (`&'a T` or `&'a mut T`).
1900 Rptr(Option<Lifetime>, MutTy),
1901 /// A bare function (e.g., `fn(usize) -> bool`).
1902 BareFn(P<BareFnTy>),
1903 /// The never type (`!`).
1905 /// A tuple (`(A, B, C, D,...)`).
1907 /// A path (`module::module::...::Type`), optionally
1908 /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1910 /// Type parameters are stored in the `Path` itself.
1911 Path(Option<QSelf>, Path),
1912 /// A trait object type `Bound1 + Bound2 + Bound3`
1913 /// where `Bound` is a trait or a lifetime.
1914 TraitObject(GenericBounds, TraitObjectSyntax),
1915 /// An `impl Bound1 + Bound2 + Bound3` type
1916 /// where `Bound` is a trait or a lifetime.
1918 /// The `NodeId` exists to prevent lowering from having to
1919 /// generate `NodeId`s on the fly, which would complicate
1920 /// the generation of opaque `type Foo = impl Trait` items significantly.
1921 ImplTrait(NodeId, GenericBounds),
1922 /// No-op; kept solely so that we can pretty-print faithfully.
1926 /// This means the type should be inferred instead of it having been
1927 /// specified. This can appear anywhere in a type.
1929 /// Inferred type of a `self` or `&self` argument in a method.
1931 /// A macro in the type position.
1933 /// Placeholder for a kind that has failed to be defined.
1935 /// Placeholder for a `va_list`.
1940 pub fn is_implicit_self(&self) -> bool {
1941 if let TyKind::ImplicitSelf = *self {
1948 pub fn is_unit(&self) -> bool {
1949 if let TyKind::Tup(ref tys) = *self {
1956 /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1957 /// in lowering to avoid making larger changes there and beyond.
1958 pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1960 Self::ImplTrait(_, bounds) => Some(bounds),
1966 /// Syntax used to declare a trait object.
1967 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1968 pub enum TraitObjectSyntax {
1973 /// Inline assembly dialect.
1975 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1976 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1977 pub enum AsmDialect {
1982 /// Inline assembly.
1984 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1985 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1986 pub struct InlineAsmOutput {
1987 pub constraint: Symbol,
1990 pub is_indirect: bool,
1993 /// Inline assembly.
1995 /// E.g., `asm!("NOP");`.
1996 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1997 pub struct InlineAsm {
1999 pub asm_str_style: StrStyle,
2000 pub outputs: Vec<InlineAsmOutput>,
2001 pub inputs: Vec<(Symbol, P<Expr>)>,
2002 pub clobbers: Vec<Symbol>,
2004 pub alignstack: bool,
2005 pub dialect: AsmDialect,
2008 /// A parameter in a function header.
2010 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2011 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2013 pub attrs: ThinVec<Attribute>,
2018 pub is_placeholder: bool,
2021 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2023 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2024 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2026 /// `self`, `mut self`
2028 /// `&'lt self`, `&'lt mut self`
2029 Region(Option<Lifetime>, Mutability),
2030 /// `self: TYPE`, `mut self: TYPE`
2031 Explicit(P<Ty>, Mutability),
2034 pub type ExplicitSelf = Spanned<SelfKind>;
2037 /// Attempts to cast parameter to `ExplicitSelf`.
2038 pub fn to_self(&self) -> Option<ExplicitSelf> {
2039 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2040 if ident.name == kw::SelfLower {
2041 return match self.ty.kind {
2042 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2043 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2044 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2047 self.pat.span.to(self.ty.span),
2048 SelfKind::Explicit(self.ty.clone(), mutbl),
2056 /// Returns `true` if parameter is `self`.
2057 pub fn is_self(&self) -> bool {
2058 if let PatKind::Ident(_, ident, _) = self.pat.kind {
2059 ident.name == kw::SelfLower
2065 /// Builds a `Param` object from `ExplicitSelf`.
2066 pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2067 let span = eself.span.to(eself_ident.span);
2068 let infer_ty = P(Ty {
2070 kind: TyKind::ImplicitSelf,
2073 let param = |mutbl, ty| Param {
2077 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2083 is_placeholder: false
2086 SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2087 SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2088 SelfKind::Region(lt, mutbl) => param(
2089 Mutability::Immutable,
2106 /// A signature (not the body) of a function declaration.
2108 /// E.g., `fn foo(bar: baz)`.
2110 /// Please note that it's different from `FnHeader` structure
2111 /// which contains metadata about function safety, asyncness, constness and ABI.
2112 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2114 pub inputs: Vec<Param>,
2115 pub output: FunctionRetTy,
2119 pub fn get_self(&self) -> Option<ExplicitSelf> {
2120 self.inputs.get(0).and_then(Param::to_self)
2122 pub fn has_self(&self) -> bool {
2123 self.inputs.get(0).map_or(false, Param::is_self)
2125 pub fn c_variadic(&self) -> bool {
2126 self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2127 TyKind::CVarArgs => true,
2133 /// Is the trait definition an auto trait?
2134 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2140 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2141 RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2148 pub fn prefix_str(&self) -> &'static str {
2150 Unsafety::Unsafe => "unsafe ",
2151 Unsafety::Normal => "",
2156 impl fmt::Display for Unsafety {
2157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2160 Unsafety::Normal => "normal",
2161 Unsafety::Unsafe => "unsafe",
2168 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2172 return_impl_trait_id: NodeId,
2178 pub fn is_async(self) -> bool {
2179 if let IsAsync::Async { .. } = self {
2186 /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2187 pub fn opt_return_id(self) -> Option<NodeId> {
2190 return_impl_trait_id,
2192 } => Some(return_impl_trait_id),
2193 IsAsync::NotAsync => None,
2198 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2199 pub enum Constness {
2204 /// Item defaultness.
2205 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2206 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2207 pub enum Defaultness {
2212 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2213 pub enum ImplPolarity {
2214 /// `impl Trait for Type`
2216 /// `impl !Trait for Type`
2220 impl fmt::Debug for ImplPolarity {
2221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2223 ImplPolarity::Positive => "positive".fmt(f),
2224 ImplPolarity::Negative => "negative".fmt(f),
2229 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2230 pub enum FunctionRetTy {
2231 /// Returns type is not specified.
2233 /// Functions default to `()` and closures default to inference.
2234 /// Span points to where return type would be inserted.
2236 /// Everything else.
2240 impl FunctionRetTy {
2241 pub fn span(&self) -> Span {
2243 FunctionRetTy::Default(span) => span,
2244 FunctionRetTy::Ty(ref ty) => ty.span,
2249 /// Module declaration.
2251 /// E.g., `mod foo;` or `mod foo { .. }`.
2252 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2254 /// A span from the first token past `{` to the last token until `}`.
2255 /// For `mod foo;`, the inner span ranges from the first token
2256 /// to the last token in the external file.
2258 pub items: Vec<P<Item>>,
2259 /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2263 /// Foreign module declaration.
2265 /// E.g., `extern { .. }` or `extern C { .. }`.
2266 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2267 pub struct ForeignMod {
2268 pub abi: Option<StrLit>,
2269 pub items: Vec<ForeignItem>,
2272 /// Global inline assembly.
2274 /// Also known as "module-level assembly" or "file-scoped assembly".
2275 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2276 pub struct GlobalAsm {
2280 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2281 pub struct EnumDef {
2282 pub variants: Vec<Variant>,
2285 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2286 pub struct Variant {
2287 /// Attributes of the variant.
2288 pub attrs: Vec<Attribute>,
2289 /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2293 /// The visibility of the variant. Syntactically accepted but not semantically.
2294 pub vis: Visibility,
2295 /// Name of the variant.
2298 /// Fields and constructor id of the variant.
2299 pub data: VariantData,
2300 /// Explicit discriminant, e.g., `Foo = 1`.
2301 pub disr_expr: Option<AnonConst>,
2302 /// Is a macro placeholder
2303 pub is_placeholder: bool,
2306 /// Part of `use` item to the right of its prefix.
2307 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2308 pub enum UseTreeKind {
2309 /// `use prefix` or `use prefix as rename`
2311 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2313 Simple(Option<Ident>, NodeId, NodeId),
2314 /// `use prefix::{...}`
2315 Nested(Vec<(UseTree, NodeId)>),
2320 /// A tree of paths sharing common prefixes.
2321 /// Used in `use` items both at top-level and inside of braces in import groups.
2322 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2323 pub struct UseTree {
2325 pub kind: UseTreeKind,
2330 pub fn ident(&self) -> Ident {
2332 UseTreeKind::Simple(Some(rename), ..) => rename,
2333 UseTreeKind::Simple(None, ..) => {
2337 .expect("empty prefix in a simple import")
2340 _ => panic!("`UseTree::ident` can only be used on a simple import"),
2345 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2346 /// are contained as statements within items. These two cases need to be
2347 /// distinguished for pretty-printing.
2348 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2349 pub enum AttrStyle {
2354 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2355 pub struct AttrId(pub usize);
2357 impl Idx for AttrId {
2358 fn new(idx: usize) -> Self {
2361 fn index(self) -> usize {
2366 impl rustc_serialize::Encodable for AttrId {
2367 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2372 impl rustc_serialize::Decodable for AttrId {
2373 fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2374 d.read_nil().map(|_| crate::attr::mk_attr_id())
2378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2379 pub struct AttrItem {
2384 /// Metadata associated with an item.
2385 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2386 pub struct Attribute {
2389 /// Denotes if the attribute decorates the following construct (outer)
2390 /// or the construct this attribute is contained within (inner).
2391 pub style: AttrStyle,
2395 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2397 /// A normal attribute.
2400 /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2401 /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2402 /// variant (which is much less compact and thus more expensive).
2404 /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2405 /// for this variant, but this may change in the future.
2410 /// `TraitRef`s appear in impls.
2412 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2413 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2414 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2415 /// same as the impl's `NodeId`).
2416 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2417 pub struct TraitRef {
2422 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2423 pub struct PolyTraitRef {
2424 /// The `'a` in `<'a> Foo<&'a T>`.
2425 pub bound_generic_params: Vec<GenericParam>,
2427 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2428 pub trait_ref: TraitRef,
2434 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2436 bound_generic_params: generic_params,
2437 trait_ref: TraitRef {
2439 ref_id: DUMMY_NODE_ID,
2446 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2447 pub enum CrateSugar {
2448 /// Source is `pub(crate)`.
2451 /// Source is (just) `crate`.
2455 pub type Visibility = Spanned<VisibilityKind>;
2457 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2458 pub enum VisibilityKind {
2461 Restricted { path: P<Path>, id: NodeId },
2465 impl VisibilityKind {
2466 pub fn is_pub(&self) -> bool {
2467 if let VisibilityKind::Public = *self {
2475 /// Field of a struct.
2477 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2478 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2479 pub struct StructField {
2480 pub attrs: Vec<Attribute>,
2483 pub vis: Visibility,
2484 pub ident: Option<Ident>,
2487 pub is_placeholder: bool,
2490 /// Fields and constructor ids of enum variants and structs.
2491 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2492 pub enum VariantData {
2495 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2496 Struct(Vec<StructField>, bool),
2499 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2500 Tuple(Vec<StructField>, NodeId),
2503 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2508 /// Return the fields of this variant.
2509 pub fn fields(&self) -> &[StructField] {
2511 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2516 /// Return the `NodeId` of this variant's constructor, if it has one.
2517 pub fn ctor_id(&self) -> Option<NodeId> {
2519 VariantData::Struct(..) => None,
2520 VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2527 /// The name might be a dummy name in case of anonymous items.
2528 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2530 pub attrs: Vec<Attribute>,
2533 pub vis: Visibility,
2538 /// Original tokens this item was parsed from. This isn't necessarily
2539 /// available for all items, although over time more and more items should
2540 /// have this be `Some`. Right now this is primarily used for procedural
2541 /// macros, notably custom attributes.
2543 /// Note that the tokens here do not include the outer attributes, but will
2544 /// include inner attributes.
2545 pub tokens: Option<TokenStream>,
2549 /// Return the span that encompasses the attributes.
2550 pub fn span_with_attributes(&self) -> Span {
2551 self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2555 /// `extern` qualifier on a function item or function type.
2556 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2564 pub fn from_abi(abi: Option<StrLit>) -> Extern {
2565 abi.map_or(Extern::Implicit, Extern::Explicit)
2569 /// A function header.
2571 /// All the information between the visibility and the name of the function is
2572 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2573 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2574 pub struct FnHeader {
2575 pub unsafety: Unsafety,
2576 pub asyncness: Spanned<IsAsync>,
2577 pub constness: Spanned<Constness>,
2581 impl Default for FnHeader {
2582 fn default() -> FnHeader {
2584 unsafety: Unsafety::Normal,
2585 asyncness: dummy_spanned(IsAsync::NotAsync),
2586 constness: dummy_spanned(Constness::NotConst),
2592 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2594 /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2596 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2597 ExternCrate(Option<Name>),
2598 /// A use declaration item (`use`).
2600 /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2602 /// A static item (`static`).
2604 /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2605 Static(P<Ty>, Mutability, P<Expr>),
2606 /// A constant item (`const`).
2608 /// E.g., `const FOO: i32 = 42;`.
2609 Const(P<Ty>, P<Expr>),
2610 /// A function declaration (`fn`).
2612 /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2613 Fn(FnSig, Generics, P<Block>),
2614 /// A module declaration (`mod`).
2616 /// E.g., `mod foo;` or `mod foo { .. }`.
2618 /// An external module (`extern`).
2620 /// E.g., `extern {}` or `extern "C" {}`.
2621 ForeignMod(ForeignMod),
2622 /// Module-level inline assembly (from `global_asm!()`).
2623 GlobalAsm(P<GlobalAsm>),
2624 /// A type alias (`type`).
2626 /// E.g., `type Foo = Bar<u8>;`.
2627 TyAlias(P<Ty>, Generics),
2628 /// An enum definition (`enum`).
2630 /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2631 Enum(EnumDef, Generics),
2632 /// A struct definition (`struct`).
2634 /// E.g., `struct Foo<A> { x: A }`.
2635 Struct(VariantData, Generics),
2636 /// A union definition (`union`).
2638 /// E.g., `union Foo<A, B> { x: A, y: B }`.
2639 Union(VariantData, Generics),
2640 /// A trait declaration (`trait`).
2642 /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2643 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2646 /// E.g., `trait Foo = Bar + Quux;`.
2647 TraitAlias(Generics, GenericBounds),
2648 /// An implementation.
2650 /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2656 Option<TraitRef>, // (optional) trait this impl implements
2660 /// A macro invocation.
2662 /// E.g., `foo!(..)`.
2665 /// A macro definition.
2670 pub fn descriptive_variant(&self) -> &str {
2672 ItemKind::ExternCrate(..) => "extern crate",
2673 ItemKind::Use(..) => "use",
2674 ItemKind::Static(..) => "static item",
2675 ItemKind::Const(..) => "constant item",
2676 ItemKind::Fn(..) => "function",
2677 ItemKind::Mod(..) => "module",
2678 ItemKind::ForeignMod(..) => "foreign module",
2679 ItemKind::GlobalAsm(..) => "global asm",
2680 ItemKind::TyAlias(..) => "type alias",
2681 ItemKind::Enum(..) => "enum",
2682 ItemKind::Struct(..) => "struct",
2683 ItemKind::Union(..) => "union",
2684 ItemKind::Trait(..) => "trait",
2685 ItemKind::TraitAlias(..) => "trait alias",
2686 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2691 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2692 pub struct ForeignItem {
2693 pub attrs: Vec<Attribute>,
2696 pub vis: Visibility,
2699 pub kind: ForeignItemKind,
2702 /// An item within an `extern` block.
2703 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2704 pub enum ForeignItemKind {
2705 /// A foreign function.
2706 Fn(P<FnDecl>, Generics),
2707 /// A foreign static item (`static ext: u8`).
2708 Static(P<Ty>, Mutability),
2711 /// A macro invocation.
2715 impl ForeignItemKind {
2716 pub fn descriptive_variant(&self) -> &str {
2718 ForeignItemKind::Fn(..) => "foreign function",
2719 ForeignItemKind::Static(..) => "foreign static item",
2720 ForeignItemKind::Ty => "foreign type",
2721 ForeignItemKind::Macro(..) => "macro in foreign module",