1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // The Rust abstract syntax tree.
13 pub use self::GenericArgs::*;
14 pub use self::UnsafeSource::*;
15 pub use symbol::{Ident, Symbol as Name};
16 pub use util::parser::ExprPrecedence;
18 use ext::hygiene::{Mark, SyntaxContext};
21 use rustc_data_structures::indexed_vec::Idx;
22 #[cfg(target_arch = "x86_64")]
23 use rustc_data_structures::static_assert;
24 use rustc_target::spec::abi::Abi;
25 use source_map::{dummy_spanned, respan, Spanned};
26 use symbol::{keywords, Symbol};
27 use syntax_pos::{Span, DUMMY_SP};
28 use tokenstream::{ThinTokenStream, TokenStream};
31 use rustc_data_structures::fx::FxHashSet;
32 use rustc_data_structures::sync::Lrc;
33 use serialize::{self, Decoder, Encoder};
36 pub use rustc_target::abi::FloatTy;
38 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
43 impl fmt::Debug for Label {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45 write!(f, "label({:?})", self.ident)
49 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
55 impl fmt::Debug for Lifetime {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 pprust::lifetime_to_string(self)
66 /// A "Path" is essentially Rust's notion of a name.
68 /// It's represented as a sequence of identifiers,
69 /// along with a bunch of supporting information.
71 /// E.g. `std::cmp::PartialEq`
72 #[derive(Clone, RustcEncodable, RustcDecodable)]
75 /// The segments in the path: the things separated by `::`.
76 /// Global paths begin with `keywords::CrateRoot`.
77 pub segments: Vec<PathSegment>,
80 impl<'a> PartialEq<&'a str> for Path {
81 fn eq(&self, string: &&'a str) -> bool {
82 self.segments.len() == 1 && self.segments[0].ident.name == *string
86 impl fmt::Debug for Path {
87 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88 write!(f, "path({})", pprust::path_to_string(self))
92 impl fmt::Display for Path {
93 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94 write!(f, "{}", pprust::path_to_string(self))
99 // convert a span and an identifier to the corresponding
101 pub fn from_ident(ident: Ident) -> Path {
103 segments: vec![PathSegment::from_ident(ident)],
108 // Make a "crate root" segment for this path unless it already has it
109 // or starts with something like `self`/`super`/`$crate`/etc.
110 pub fn make_root(&self) -> Option<PathSegment> {
111 if let Some(ident) = self.segments.get(0).map(|seg| seg.ident) {
112 if ident.is_path_segment_keyword() {
116 Some(PathSegment::crate_root(self.span.shrink_to_lo()))
119 pub fn is_global(&self) -> bool {
120 !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name()
124 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
126 /// E.g. `std`, `String` or `Box<T>`
127 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
128 pub struct PathSegment {
129 /// The identifier portion of this path segment.
134 /// Type/lifetime parameters attached to this path. They come in
135 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
136 /// `None` means that no parameter list is supplied (`Path`),
137 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
138 /// but it can be empty (`Path<>`).
139 /// `P` is used as a size optimization for the common case with no parameters.
140 pub args: Option<P<GenericArgs>>,
144 pub fn from_ident(ident: Ident) -> Self {
145 PathSegment { ident, id: DUMMY_NODE_ID, args: None }
147 pub fn crate_root(span: Span) -> Self {
148 PathSegment::from_ident(Ident::new(keywords::CrateRoot.name(), span))
152 /// Arguments of a path segment.
154 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
155 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
156 pub enum GenericArgs {
157 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
158 AngleBracketed(AngleBracketedArgs),
159 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
160 Parenthesized(ParenthesisedArgs),
164 pub fn span(&self) -> Span {
166 AngleBracketed(ref data) => data.span,
167 Parenthesized(ref data) => data.span,
172 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
173 pub enum GenericArg {
178 /// A path like `Foo<'a, T>`
179 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
180 pub struct AngleBracketedArgs {
183 /// The arguments for this path segment.
184 pub args: Vec<GenericArg>,
185 /// Bindings (equality constraints) on associated types, if present.
187 /// E.g., `Foo<A=Bar>`.
188 pub bindings: Vec<TypeBinding>,
191 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
192 fn into(self) -> Option<P<GenericArgs>> {
193 Some(P(GenericArgs::AngleBracketed(self)))
197 impl Into<Option<P<GenericArgs>>> for ParenthesisedArgs {
198 fn into(self) -> Option<P<GenericArgs>> {
199 Some(P(GenericArgs::Parenthesized(self)))
203 /// A path like `Foo(A,B) -> C`
204 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
205 pub struct ParenthesisedArgs {
210 pub inputs: Vec<P<Ty>>,
213 pub output: Option<P<Ty>>,
216 // hack to ensure that we don't try to access the private parts of `NodeId` in this module
218 use rustc_data_structures::indexed_vec::Idx;
222 DEBUG_FORMAT = "NodeId({})"
227 pub use self::node_id_inner::NodeId;
230 pub fn placeholder_from_mark(mark: Mark) -> Self {
231 NodeId::from_u32(mark.as_u32())
234 pub fn placeholder_to_mark(self) -> Mark {
235 Mark::from_u32(self.as_u32())
239 impl fmt::Display for NodeId {
240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
241 fmt::Display::fmt(&self.as_u32(), f)
245 impl serialize::UseSpecializedEncodable for NodeId {
246 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
247 s.emit_u32(self.as_u32())
251 impl serialize::UseSpecializedDecodable for NodeId {
252 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
253 d.read_u32().map(NodeId::from_u32)
257 /// Node id used to represent the root of the crate.
258 pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
260 /// When parsing and doing expansions, we initially give all AST nodes this AST
261 /// node value. Then later, in the renumber pass, we renumber them to have
262 /// small, positive ids.
263 pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
265 /// A modifier on a bound, currently this is only used for `?Sized`, where the
266 /// modifier is `Maybe`. Negative bounds should also be handled here.
267 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
268 pub enum TraitBoundModifier {
273 /// The AST represents all type param bounds as types.
274 /// `typeck::collect::compute_bounds` matches these against
275 /// the "special" built-in traits (see `middle::lang_items`) and
276 /// detects `Copy`, `Send` and `Sync`.
277 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
278 pub enum GenericBound {
279 Trait(PolyTraitRef, TraitBoundModifier),
284 pub fn span(&self) -> Span {
286 &GenericBound::Trait(ref t, ..) => t.span,
287 &GenericBound::Outlives(ref l) => l.ident.span,
292 pub type GenericBounds = Vec<GenericBound>;
294 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
295 pub enum GenericParamKind {
296 /// A lifetime definition, e.g. `'a: 'b+'c+'d`.
299 default: Option<P<Ty>>,
303 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
304 pub struct GenericParam {
307 pub attrs: ThinVec<Attribute>,
308 pub bounds: GenericBounds,
310 pub kind: GenericParamKind,
313 /// Represents lifetime, type and const parameters attached to a declaration of
314 /// a function, enum, trait, etc.
315 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
316 pub struct Generics {
317 pub params: Vec<GenericParam>,
318 pub where_clause: WhereClause,
322 impl Default for Generics {
323 /// Creates an instance of `Generics`.
324 fn default() -> Generics {
327 where_clause: WhereClause {
329 predicates: Vec::new(),
337 /// A `where` clause in a definition
338 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
339 pub struct WhereClause {
341 pub predicates: Vec<WherePredicate>,
345 /// A single predicate in a `where` clause
346 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
347 pub enum WherePredicate {
348 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
349 BoundPredicate(WhereBoundPredicate),
350 /// A lifetime predicate, e.g. `'a: 'b+'c`
351 RegionPredicate(WhereRegionPredicate),
352 /// An equality predicate (unsupported)
353 EqPredicate(WhereEqPredicate),
356 impl WherePredicate {
357 pub fn span(&self) -> Span {
359 &WherePredicate::BoundPredicate(ref p) => p.span,
360 &WherePredicate::RegionPredicate(ref p) => p.span,
361 &WherePredicate::EqPredicate(ref p) => p.span,
368 /// E.g. `for<'c> Foo: Send+Clone+'c`
369 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
370 pub struct WhereBoundPredicate {
372 /// Any generics from a `for` binding
373 pub bound_generic_params: Vec<GenericParam>,
374 /// The type being bounded
375 pub bounded_ty: P<Ty>,
376 /// Trait and lifetime bounds (`Clone+Send+'static`)
377 pub bounds: GenericBounds,
380 /// A lifetime predicate.
383 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
384 pub struct WhereRegionPredicate {
386 pub lifetime: Lifetime,
387 pub bounds: GenericBounds,
390 /// An equality predicate (unsupported).
393 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
394 pub struct WhereEqPredicate {
401 /// The set of MetaItems that define the compilation environment of the crate,
402 /// used to drive conditional compilation
403 pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
405 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
408 pub attrs: Vec<Attribute>,
412 /// A spanned compile-time attribute list item.
413 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
415 /// Possible values inside of compile-time attribute lists.
417 /// E.g. the '..' in `#[name(..)]`.
418 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
419 pub enum NestedMetaItemKind {
420 /// A full MetaItem, for recursive meta items.
424 /// E.g. "foo", 64, true
428 /// A spanned compile-time attribute item.
430 /// E.g. `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`
431 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
432 pub struct MetaItem {
434 pub node: MetaItemKind,
438 /// A compile-time attribute item.
440 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
441 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
442 pub enum MetaItemKind {
445 /// E.g. `test` as in `#[test]`
449 /// E.g. `derive(..)` as in `#[derive(..)]`
450 List(Vec<NestedMetaItem>),
451 /// Name value meta item.
453 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
457 /// A Block (`{ .. }`).
459 /// E.g. `{ .. }` as in `fn foo() { .. }`
460 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
462 /// Statements in a block
463 pub stmts: Vec<Stmt>,
465 /// Distinguishes between `unsafe { ... }` and `{ ... }`
466 pub rules: BlockCheckMode,
471 #[derive(Clone, RustcEncodable, RustcDecodable)]
478 impl fmt::Debug for Pat {
479 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
480 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
485 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
486 let node = match &self.node {
487 PatKind::Wild => TyKind::Infer,
488 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
489 TyKind::Path(None, Path::from_ident(*ident))
491 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
492 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
493 PatKind::Ref(pat, mutbl) => pat
495 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
496 PatKind::Slice(pats, None, _) if pats.len() == 1 => {
497 pats[0].to_ty().map(TyKind::Slice)?
499 PatKind::Tuple(pats, None) => {
500 let mut tys = Vec::with_capacity(pats.len());
501 // FIXME(#48994) - could just be collected into an Option<Vec>
503 tys.push(pat.to_ty()?);
517 pub fn walk<F>(&self, it: &mut F) -> bool
519 F: FnMut(&Pat) -> bool,
526 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
527 PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
528 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
529 s.iter().all(|p| p.walk(it))
531 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
532 PatKind::Slice(ref before, ref slice, ref after) => {
533 before.iter().all(|p| p.walk(it))
534 && slice.iter().all(|p| p.walk(it))
535 && after.iter().all(|p| p.walk(it))
542 | PatKind::Mac(_) => true,
547 /// A single field in a struct pattern
549 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
550 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
551 /// except is_shorthand is true
552 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
553 pub struct FieldPat {
554 /// The identifier for the field
556 /// The pattern the field is destructured to
558 pub is_shorthand: bool,
559 pub attrs: ThinVec<Attribute>,
562 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
563 pub enum BindingMode {
568 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
570 Included(RangeSyntax),
574 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
575 pub enum RangeSyntax {
580 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
582 /// Represents a wildcard pattern (`_`)
585 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
586 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
587 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
588 /// during name resolution.
589 Ident(BindingMode, Ident, Option<P<Pat>>),
591 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
592 /// The `bool` is `true` in the presence of a `..`.
593 Struct(Path, Vec<Spanned<FieldPat>>, bool),
595 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
596 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
597 /// 0 <= position <= subpats.len()
598 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
600 /// A possibly qualified path pattern.
601 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
602 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
603 /// only legally refer to associated constants.
604 Path(Option<QSelf>, Path),
606 /// A tuple pattern `(a, b)`.
607 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
608 /// 0 <= position <= subpats.len()
609 Tuple(Vec<P<Pat>>, Option<usize>),
612 /// A reference pattern, e.g. `&mut (a, b)`
613 Ref(P<Pat>, Mutability),
616 /// A range pattern, e.g. `1...2`, `1..=2` or `1..2`
617 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
618 /// `[a, b, ..i, y, z]` is represented as:
619 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
620 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
621 /// Parentheses in patterns used for grouping, i.e. `(PAT)`.
623 /// A macro pattern; pre-expansion
628 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
630 pub enum Mutability {
635 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
637 /// The `+` operator (addition)
639 /// The `-` operator (subtraction)
641 /// The `*` operator (multiplication)
643 /// The `/` operator (division)
645 /// The `%` operator (modulus)
647 /// The `&&` operator (logical and)
649 /// The `||` operator (logical or)
651 /// The `^` operator (bitwise xor)
653 /// The `&` operator (bitwise and)
655 /// The `|` operator (bitwise or)
657 /// The `<<` operator (shift left)
659 /// The `>>` operator (shift right)
661 /// The `==` operator (equality)
663 /// The `<` operator (less than)
665 /// The `<=` operator (less than or equal to)
667 /// The `!=` operator (not equal to)
669 /// The `>=` operator (greater than or equal to)
671 /// The `>` operator (greater than)
676 pub fn to_string(&self) -> &'static str {
677 use self::BinOpKind::*;
699 pub fn lazy(&self) -> bool {
701 BinOpKind::And | BinOpKind::Or => true,
706 pub fn is_shift(&self) -> bool {
708 BinOpKind::Shl | BinOpKind::Shr => true,
713 pub fn is_comparison(&self) -> bool {
714 use self::BinOpKind::*;
716 Eq | Lt | Le | Ne | Gt | Ge => true,
717 And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
721 /// Returns `true` if the binary operator takes its arguments by value
722 pub fn is_by_value(&self) -> bool {
723 !self.is_comparison()
727 pub type BinOp = Spanned<BinOpKind>;
729 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
731 /// The `*` operator for dereferencing
733 /// The `!` operator for logical inversion
735 /// The `-` operator for negation
740 /// Returns `true` if the unary operator takes its argument by value
741 pub fn is_by_value(u: UnOp) -> bool {
743 UnOp::Neg | UnOp::Not => true,
748 pub fn to_string(op: UnOp) -> &'static str {
758 #[derive(Clone, RustcEncodable, RustcDecodable)]
766 pub fn add_trailing_semicolon(mut self) -> Self {
767 self.node = match self.node {
768 StmtKind::Expr(expr) => StmtKind::Semi(expr),
769 StmtKind::Mac(mac) => {
770 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
777 pub fn is_item(&self) -> bool {
779 StmtKind::Item(_) => true,
784 pub fn is_expr(&self) -> bool {
786 StmtKind::Expr(_) => true,
792 impl fmt::Debug for Stmt {
793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
798 pprust::stmt_to_string(self)
803 #[derive(Clone, RustcEncodable, RustcDecodable)]
805 /// A local (let) binding.
808 /// An item definition.
811 /// Expr without trailing semi-colon.
813 /// Expr with a trailing semi-colon.
816 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
819 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
820 pub enum MacStmtStyle {
821 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
822 /// `foo!(...);`, `foo![...];`
824 /// The macro statement had braces; e.g. foo! { ... }
826 /// The macro statement had parentheses or brackets and no semicolon; e.g.
827 /// `foo!(...)`. All of these will end up being converted into macro
832 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
833 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
836 pub ty: Option<P<Ty>>,
837 /// Initializer expression to set the value, if any
838 pub init: Option<P<Expr>>,
841 pub attrs: ThinVec<Attribute>,
844 /// An arm of a 'match'.
846 /// E.g. `0..=10 => { println!("match!") }` as in
850 /// 0..=10 => { println!("match!") },
851 /// _ => { println!("no match!") },
854 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
856 pub attrs: Vec<Attribute>,
857 pub pats: Vec<P<Pat>>,
858 pub guard: Option<Guard>,
862 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
872 pub is_shorthand: bool,
873 pub attrs: ThinVec<Attribute>,
876 pub type SpannedIdent = Spanned<Ident>;
878 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
879 pub enum BlockCheckMode {
881 Unsafe(UnsafeSource),
884 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
885 pub enum UnsafeSource {
890 /// A constant (expression) that's not an item or associated item,
891 /// but needs its own `DefId` for type-checking, const-eval, etc.
892 /// These are usually found nested inside types (e.g. array lengths)
893 /// or expressions (e.g. repeat counts), and also used to define
894 /// explicit discriminant values for enum variants.
895 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
896 pub struct AnonConst {
902 #[derive(Clone, RustcEncodable, RustcDecodable)]
907 pub attrs: ThinVec<Attribute>,
910 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
911 #[cfg(target_arch = "x86_64")]
912 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
915 /// Whether this expression would be valid somewhere that expects a value, for example, an `if`
917 pub fn returns(&self) -> bool {
918 if let ExprKind::Block(ref block, _) = self.node {
919 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
921 Some(&StmtKind::Expr(_)) => true,
922 Some(&StmtKind::Semi(ref expr)) => {
923 if let ExprKind::Ret(_) = expr.node {
924 // last statement is explicit return
930 // This is a block that doesn't end in either an implicit or explicit return
934 // This is not a block, it is a value
939 fn to_bound(&self) -> Option<GenericBound> {
941 ExprKind::Path(None, path) => Some(GenericBound::Trait(
942 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
943 TraitBoundModifier::None,
949 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
950 let node = match &self.node {
951 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
952 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
953 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
954 ExprKind::AddrOf(mutbl, expr) => expr
956 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
957 ExprKind::Repeat(expr, expr_len) => {
958 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
960 ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
961 ExprKind::Tup(exprs) => {
964 .map(|expr| expr.to_ty())
965 .collect::<Option<Vec<_>>>()?;
968 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
969 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
970 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
985 pub fn precedence(&self) -> ExprPrecedence {
987 ExprKind::Box(_) => ExprPrecedence::Box,
988 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
989 ExprKind::Array(_) => ExprPrecedence::Array,
990 ExprKind::Call(..) => ExprPrecedence::Call,
991 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
992 ExprKind::Tup(_) => ExprPrecedence::Tup,
993 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
994 ExprKind::Unary(..) => ExprPrecedence::Unary,
995 ExprKind::Lit(_) => ExprPrecedence::Lit,
996 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
997 ExprKind::If(..) => ExprPrecedence::If,
998 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
999 ExprKind::While(..) => ExprPrecedence::While,
1000 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1001 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1002 ExprKind::Loop(..) => ExprPrecedence::Loop,
1003 ExprKind::Match(..) => ExprPrecedence::Match,
1004 ExprKind::Closure(..) => ExprPrecedence::Closure,
1005 ExprKind::Block(..) => ExprPrecedence::Block,
1006 ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1007 ExprKind::Async(..) => ExprPrecedence::Async,
1008 ExprKind::Assign(..) => ExprPrecedence::Assign,
1009 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1010 ExprKind::Field(..) => ExprPrecedence::Field,
1011 ExprKind::Index(..) => ExprPrecedence::Index,
1012 ExprKind::Range(..) => ExprPrecedence::Range,
1013 ExprKind::Path(..) => ExprPrecedence::Path,
1014 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1015 ExprKind::Break(..) => ExprPrecedence::Break,
1016 ExprKind::Continue(..) => ExprPrecedence::Continue,
1017 ExprKind::Ret(..) => ExprPrecedence::Ret,
1018 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1019 ExprKind::Mac(..) => ExprPrecedence::Mac,
1020 ExprKind::Struct(..) => ExprPrecedence::Struct,
1021 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1022 ExprKind::Paren(..) => ExprPrecedence::Paren,
1023 ExprKind::Try(..) => ExprPrecedence::Try,
1024 ExprKind::Yield(..) => ExprPrecedence::Yield,
1029 impl fmt::Debug for Expr {
1030 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1031 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1035 /// Limit types of a range (inclusive or exclusive)
1036 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1037 pub enum RangeLimits {
1038 /// Inclusive at the beginning, exclusive at the end
1040 /// Inclusive at the beginning and end
1044 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1046 /// A `box x` expression.
1048 /// First expr is the place; second expr is the value.
1049 ObsoleteInPlace(P<Expr>, P<Expr>),
1050 /// An array (`[a, b, c, d]`)
1051 Array(Vec<P<Expr>>),
1054 /// The first field resolves to the function itself,
1055 /// and the second field is the list of arguments.
1056 /// This also represents calling the constructor of
1057 /// tuple-like ADTs such as tuple structs and enum variants.
1058 Call(P<Expr>, Vec<P<Expr>>),
1059 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1061 /// The `PathSegment` represents the method name and its generic arguments
1062 /// (within the angle brackets).
1063 /// The first element of the vector of `Expr`s is the expression that evaluates
1064 /// to the object on which the method is being called on (the receiver),
1065 /// and the remaining elements are the rest of the arguments.
1066 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1067 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1068 MethodCall(PathSegment, Vec<P<Expr>>),
1069 /// A tuple (`(a, b, c ,d)`)
1071 /// A binary operation (For example: `a + b`, `a * b`)
1072 Binary(BinOp, P<Expr>, P<Expr>),
1073 /// A unary operation (For example: `!x`, `*x`)
1074 Unary(UnOp, P<Expr>),
1075 /// A literal (For example: `1`, `"foo"`)
1077 /// A cast (`foo as f64`)
1078 Cast(P<Expr>, P<Ty>),
1079 Type(P<Expr>, P<Ty>),
1080 /// An `if` block, with an optional else block
1082 /// `if expr { block } else { expr }`
1083 If(P<Expr>, P<Block>, Option<P<Expr>>),
1084 /// An `if let` expression with an optional else block
1086 /// `if let pat = expr { block } else { expr }`
1088 /// This is desugared to a `match` expression.
1089 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1090 /// A while loop, with an optional label
1092 /// `'label: while expr { block }`
1093 While(P<Expr>, P<Block>, Option<Label>),
1094 /// A while-let loop, with an optional label
1096 /// `'label: while let pat = expr { block }`
1098 /// This is desugared to a combination of `loop` and `match` expressions.
1099 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1100 /// A for loop, with an optional label
1102 /// `'label: for pat in expr { block }`
1104 /// This is desugared to a combination of `loop` and `match` expressions.
1105 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1106 /// Conditionless loop (can be exited with break, continue, or return)
1108 /// `'label: loop { block }`
1109 Loop(P<Block>, Option<Label>),
1110 /// A `match` block.
1111 Match(P<Expr>, Vec<Arm>),
1112 /// A closure (for example, `move |a, b, c| a + b + c`)
1114 /// The final span is the span of the argument block `|...|`
1115 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1116 /// A block (`'label: { ... }`)
1117 Block(P<Block>, Option<Label>),
1118 /// An async block (`async move { ... }`)
1120 /// The `NodeId` is the `NodeId` for the closure that results from
1121 /// desugaring an async block, just like the NodeId field in the
1122 /// `IsAsync` enum. This is necessary in order to create a def for the
1123 /// closure which can be used as a parent of any child defs. Defs
1124 /// created during lowering cannot be made the parent of any other
1125 /// preexisting defs.
1126 Async(CaptureBy, NodeId, P<Block>),
1127 /// A try block (`try { ... }`)
1130 /// An assignment (`a = foo()`)
1131 Assign(P<Expr>, P<Expr>),
1132 /// An assignment with an operator
1134 /// For example, `a += 1`.
1135 AssignOp(BinOp, P<Expr>, P<Expr>),
1136 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct field
1137 Field(P<Expr>, Ident),
1138 /// An indexing operation (`foo[2]`)
1139 Index(P<Expr>, P<Expr>),
1140 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
1141 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1143 /// Variable reference, possibly containing `::` and/or type
1144 /// parameters, e.g. foo::bar::<baz>.
1146 /// Optionally "qualified",
1147 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1148 Path(Option<QSelf>, Path),
1150 /// A referencing operation (`&a` or `&mut a`)
1151 AddrOf(Mutability, P<Expr>),
1152 /// A `break`, with an optional label to break, and an optional expression
1153 Break(Option<Label>, Option<P<Expr>>),
1154 /// A `continue`, with an optional label
1155 Continue(Option<Label>),
1156 /// A `return`, with an optional value to be returned
1157 Ret(Option<P<Expr>>),
1159 /// Output of the `asm!()` macro
1160 InlineAsm(P<InlineAsm>),
1162 /// A macro invocation; pre-expansion
1165 /// A struct literal expression.
1167 /// For example, `Foo {x: 1, y: 2}`, or
1168 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1169 Struct(Path, Vec<Field>, Option<P<Expr>>),
1171 /// An array literal constructed from one repeated element.
1173 /// For example, `[1; 5]`. The expression is the element to be
1174 /// repeated; the constant is the number of times to repeat it.
1175 Repeat(P<Expr>, AnonConst),
1177 /// No-op: used solely so we can pretty-print faithfully
1183 /// A `yield`, with an optional value to be yielded
1184 Yield(Option<P<Expr>>),
1187 /// The explicit Self type in a "qualified path". The actual
1188 /// path, including the trait and the associated item, is stored
1189 /// separately. `position` represents the index of the associated
1190 /// item qualified with this Self type.
1192 /// ```ignore (only-for-syntax-highlight)
1193 /// <Vec<T> as a::b::Trait>::AssociatedItem
1194 /// ^~~~~ ~~~~~~~~~~~~~~^
1197 /// <Vec<T>>::AssociatedItem
1201 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1205 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1206 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1207 /// 0`, this is an empty span.
1208 pub path_span: Span,
1209 pub position: usize,
1212 /// A capture clause
1213 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1214 pub enum CaptureBy {
1219 /// The movability of a generator / closure literal
1220 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1221 pub enum Movability {
1226 pub type Mac = Spanned<Mac_>;
1228 /// Represents a macro invocation. The Path indicates which macro
1229 /// is being invoked, and the vector of token-trees contains the source
1230 /// of the macro invocation.
1232 /// NB: the additional ident for a macro_rules-style macro is actually
1233 /// stored in the enclosing item. Oog.
1234 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1237 pub delim: MacDelimiter,
1238 pub tts: ThinTokenStream,
1241 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1242 pub enum MacDelimiter {
1249 pub fn stream(&self) -> TokenStream {
1250 self.tts.clone().into()
1254 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1255 pub struct MacroDef {
1256 pub tokens: ThinTokenStream,
1261 pub fn stream(&self) -> TokenStream {
1262 self.tokens.clone().into()
1266 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1268 /// A regular string, like `"foo"`
1270 /// A raw string, like `r##"foo"##`
1272 /// The value is the number of `#` symbols used.
1277 pub type Lit = Spanned<LitKind>;
1279 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1280 pub enum LitIntType {
1288 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1289 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1291 /// A string literal (`"foo"`)
1292 Str(Symbol, StrStyle),
1293 /// A byte string (`b"foo"`)
1294 ByteStr(Lrc<Vec<u8>>),
1295 /// A byte char (`b'f'`)
1297 /// A character literal (`'a'`)
1299 /// An integer literal (`1`)
1300 Int(u128, LitIntType),
1301 /// A float literal (`1f64` or `1E10f64`)
1302 Float(Symbol, FloatTy),
1303 /// A float literal without a suffix (`1.0 or 1.0E10`)
1304 FloatUnsuffixed(Symbol),
1305 /// A boolean literal
1310 /// Returns true if this literal is a string and false otherwise.
1311 pub fn is_str(&self) -> bool {
1313 LitKind::Str(..) => true,
1318 /// Returns true if this literal is byte literal string false otherwise.
1319 pub fn is_bytestr(&self) -> bool {
1321 LitKind::ByteStr(_) => true,
1326 /// Returns true if this is a numeric literal.
1327 pub fn is_numeric(&self) -> bool {
1329 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1334 /// Returns true if this literal has no suffix. Note: this will return true
1335 /// for literals with prefixes such as raw strings and byte strings.
1336 pub fn is_unsuffixed(&self) -> bool {
1338 // unsuffixed variants
1340 | LitKind::ByteStr(..)
1343 | LitKind::Int(_, LitIntType::Unsuffixed)
1344 | LitKind::FloatUnsuffixed(..)
1345 | LitKind::Bool(..) => true,
1346 // suffixed variants
1347 LitKind::Int(_, LitIntType::Signed(..))
1348 | LitKind::Int(_, LitIntType::Unsigned(..))
1349 | LitKind::Float(..) => false,
1353 /// Returns true if this literal has a suffix.
1354 pub fn is_suffixed(&self) -> bool {
1355 !self.is_unsuffixed()
1359 // NB: If you change this, you'll probably want to change the corresponding
1360 // type structure in middle/ty.rs as well.
1361 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1364 pub mutbl: Mutability,
1367 /// Represents a method's signature in a trait declaration,
1368 /// or in an implementation.
1369 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1370 pub struct MethodSig {
1371 pub header: FnHeader,
1372 pub decl: P<FnDecl>,
1375 /// Represents an item declaration within a trait declaration,
1376 /// possibly including a default implementation. A trait item is
1377 /// either required (meaning it doesn't have an implementation, just a
1378 /// signature) or provided (meaning it has a default implementation).
1379 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1380 pub struct TraitItem {
1383 pub attrs: Vec<Attribute>,
1384 pub generics: Generics,
1385 pub node: TraitItemKind,
1387 /// See `Item::tokens` for what this is
1388 pub tokens: Option<TokenStream>,
1391 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1392 pub enum TraitItemKind {
1393 Const(P<Ty>, Option<P<Expr>>),
1394 Method(MethodSig, Option<P<Block>>),
1395 Type(GenericBounds, Option<P<Ty>>),
1399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1400 pub struct ImplItem {
1403 pub vis: Visibility,
1404 pub defaultness: Defaultness,
1405 pub attrs: Vec<Attribute>,
1406 pub generics: Generics,
1407 pub node: ImplItemKind,
1409 /// See `Item::tokens` for what this is
1410 pub tokens: Option<TokenStream>,
1413 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1414 pub enum ImplItemKind {
1415 Const(P<Ty>, P<Expr>),
1416 Method(MethodSig, P<Block>),
1418 Existential(GenericBounds),
1422 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1432 impl fmt::Debug for IntTy {
1433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1434 fmt::Display::fmt(self, f)
1438 impl fmt::Display for IntTy {
1439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1440 write!(f, "{}", self.ty_to_string())
1445 pub fn ty_to_string(&self) -> &'static str {
1447 IntTy::Isize => "isize",
1449 IntTy::I16 => "i16",
1450 IntTy::I32 => "i32",
1451 IntTy::I64 => "i64",
1452 IntTy::I128 => "i128",
1456 pub fn val_to_string(&self, val: i128) -> String {
1457 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1458 // are parsed as u128, so we wouldn't want to print an extra negative
1460 format!("{}{}", val as u128, self.ty_to_string())
1463 pub fn bit_width(&self) -> Option<usize> {
1465 IntTy::Isize => return None,
1475 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1486 pub fn ty_to_string(&self) -> &'static str {
1488 UintTy::Usize => "usize",
1490 UintTy::U16 => "u16",
1491 UintTy::U32 => "u32",
1492 UintTy::U64 => "u64",
1493 UintTy::U128 => "u128",
1497 pub fn val_to_string(&self, val: u128) -> String {
1498 format!("{}{}", val, self.ty_to_string())
1501 pub fn bit_width(&self) -> Option<usize> {
1503 UintTy::Usize => return None,
1508 UintTy::U128 => 128,
1513 impl fmt::Debug for UintTy {
1514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1515 fmt::Display::fmt(self, f)
1519 impl fmt::Display for UintTy {
1520 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1521 write!(f, "{}", self.ty_to_string())
1525 // Bind a type to an associated type: `A=Foo`.
1526 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1527 pub struct TypeBinding {
1534 #[derive(Clone, RustcEncodable, RustcDecodable)]
1541 impl fmt::Debug for Ty {
1542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543 write!(f, "type({})", pprust::ty_to_string(self))
1547 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1548 pub struct BareFnTy {
1549 pub unsafety: Unsafety,
1551 pub generic_params: Vec<GenericParam>,
1552 pub decl: P<FnDecl>,
1555 /// The different kinds of types recognized by the compiler
1556 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1558 /// A variable-length slice (`[T]`)
1560 /// A fixed length array (`[T; n]`)
1561 Array(P<Ty>, AnonConst),
1562 /// A raw pointer (`*const T` or `*mut T`)
1564 /// A reference (`&'a T` or `&'a mut T`)
1565 Rptr(Option<Lifetime>, MutTy),
1566 /// A bare function (e.g. `fn(usize) -> bool`)
1567 BareFn(P<BareFnTy>),
1568 /// The never type (`!`)
1570 /// A tuple (`(A, B, C, D,...)`)
1572 /// A path (`module::module::...::Type`), optionally
1573 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1575 /// Type parameters are stored in the Path itself
1576 Path(Option<QSelf>, Path),
1577 /// A trait object type `Bound1 + Bound2 + Bound3`
1578 /// where `Bound` is a trait or a lifetime.
1579 TraitObject(GenericBounds, TraitObjectSyntax),
1580 /// An `impl Bound1 + Bound2 + Bound3` type
1581 /// where `Bound` is a trait or a lifetime.
1583 /// The `NodeId` exists to prevent lowering from having to
1584 /// generate `NodeId`s on the fly, which would complicate
1585 /// the generation of `existential type` items significantly
1586 ImplTrait(NodeId, GenericBounds),
1587 /// No-op; kept solely so that we can pretty-print faithfully
1591 /// TyKind::Infer means the type should be inferred instead of it having been
1592 /// specified. This can appear anywhere in a type.
1594 /// Inferred type of a `self` or `&self` argument in a method.
1596 // A macro in the type position.
1598 /// Placeholder for a kind that has failed to be defined.
1603 pub fn is_implicit_self(&self) -> bool {
1604 if let TyKind::ImplicitSelf = *self {
1611 pub fn is_unit(&self) -> bool {
1612 if let TyKind::Tup(ref tys) = *self {
1620 /// Syntax used to declare a trait object.
1621 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1622 pub enum TraitObjectSyntax {
1627 /// Inline assembly dialect.
1629 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1630 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1631 pub enum AsmDialect {
1636 /// Inline assembly.
1638 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1639 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1640 pub struct InlineAsmOutput {
1641 pub constraint: Symbol,
1644 pub is_indirect: bool,
1647 /// Inline assembly.
1649 /// E.g. `asm!("NOP");`
1650 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1651 pub struct InlineAsm {
1653 pub asm_str_style: StrStyle,
1654 pub outputs: Vec<InlineAsmOutput>,
1655 pub inputs: Vec<(Symbol, P<Expr>)>,
1656 pub clobbers: Vec<Symbol>,
1658 pub alignstack: bool,
1659 pub dialect: AsmDialect,
1660 pub ctxt: SyntaxContext,
1663 /// An argument in a function header.
1665 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1666 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1673 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1675 /// E.g. `&mut self` as in `fn foo(&mut self)`
1676 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1678 /// `self`, `mut self`
1680 /// `&'lt self`, `&'lt mut self`
1681 Region(Option<Lifetime>, Mutability),
1682 /// `self: TYPE`, `mut self: TYPE`
1683 Explicit(P<Ty>, Mutability),
1686 pub type ExplicitSelf = Spanned<SelfKind>;
1689 pub fn to_self(&self) -> Option<ExplicitSelf> {
1690 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1691 if ident.name == keywords::SelfValue.name() {
1692 return match self.ty.node {
1693 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1694 TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1695 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1698 self.pat.span.to(self.ty.span),
1699 SelfKind::Explicit(self.ty.clone(), mutbl),
1707 pub fn is_self(&self) -> bool {
1708 if let PatKind::Ident(_, ident, _) = self.pat.node {
1709 ident.name == keywords::SelfValue.name()
1715 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1716 let span = eself.span.to(eself_ident.span);
1717 let infer_ty = P(Ty {
1719 node: TyKind::ImplicitSelf,
1722 let arg = |mutbl, ty| Arg {
1725 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1732 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1733 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1734 SelfKind::Region(lt, mutbl) => arg(
1735 Mutability::Immutable,
1752 /// Header (not the body) of a function declaration.
1754 /// E.g. `fn foo(bar: baz)`
1755 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1757 pub inputs: Vec<Arg>,
1758 pub output: FunctionRetTy,
1763 pub fn get_self(&self) -> Option<ExplicitSelf> {
1764 self.inputs.get(0).and_then(Arg::to_self)
1766 pub fn has_self(&self) -> bool {
1767 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1771 /// Is the trait definition an auto trait?
1772 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1778 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1784 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1788 return_impl_trait_id: NodeId,
1794 pub fn is_async(self) -> bool {
1795 if let IsAsync::Async { .. } = self {
1801 /// In case this is an `Async` return the `NodeId` for the generated impl Trait item
1802 pub fn opt_return_id(self) -> Option<NodeId> {
1805 return_impl_trait_id,
1807 } => Some(return_impl_trait_id),
1808 IsAsync::NotAsync => None,
1813 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1814 pub enum Constness {
1819 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1820 pub enum Defaultness {
1825 impl fmt::Display for Unsafety {
1826 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1829 Unsafety::Normal => "normal",
1830 Unsafety::Unsafe => "unsafe",
1837 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1838 pub enum ImplPolarity {
1839 /// `impl Trait for Type`
1841 /// `impl !Trait for Type`
1845 impl fmt::Debug for ImplPolarity {
1846 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1848 ImplPolarity::Positive => "positive".fmt(f),
1849 ImplPolarity::Negative => "negative".fmt(f),
1854 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1855 pub enum FunctionRetTy {
1856 /// Return type is not specified.
1858 /// Functions default to `()` and
1859 /// closures default to inference. Span points to where return
1860 /// type would be inserted.
1866 impl FunctionRetTy {
1867 pub fn span(&self) -> Span {
1869 FunctionRetTy::Default(span) => span,
1870 FunctionRetTy::Ty(ref ty) => ty.span,
1875 /// Module declaration.
1877 /// E.g. `mod foo;` or `mod foo { .. }`
1878 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1880 /// A span from the first token past `{` to the last token until `}`.
1881 /// For `mod foo;`, the inner span ranges from the first token
1882 /// to the last token in the external file.
1884 pub items: Vec<P<Item>>,
1885 /// For `mod foo;` inline is false, for `mod foo { .. }` it is true.
1889 /// Foreign module declaration.
1891 /// E.g. `extern { .. }` or `extern C { .. }`
1892 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1893 pub struct ForeignMod {
1895 pub items: Vec<ForeignItem>,
1898 /// Global inline assembly
1900 /// aka module-level assembly or file-scoped assembly
1901 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1902 pub struct GlobalAsm {
1904 pub ctxt: SyntaxContext,
1907 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1908 pub struct EnumDef {
1909 pub variants: Vec<Variant>,
1912 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1913 pub struct Variant_ {
1915 pub attrs: Vec<Attribute>,
1916 pub data: VariantData,
1917 /// Explicit discriminant, e.g. `Foo = 1`
1918 pub disr_expr: Option<AnonConst>,
1921 pub type Variant = Spanned<Variant_>;
1923 /// Part of `use` item to the right of its prefix.
1924 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1925 pub enum UseTreeKind {
1926 /// `use prefix` or `use prefix as rename`
1928 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1930 Simple(Option<Ident>, NodeId, NodeId),
1931 /// `use prefix::{...}`
1932 Nested(Vec<(UseTree, NodeId)>),
1937 /// A tree of paths sharing common prefixes.
1938 /// Used in `use` items both at top-level and inside of braces in import groups.
1939 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1940 pub struct UseTree {
1942 pub kind: UseTreeKind,
1947 pub fn ident(&self) -> Ident {
1949 UseTreeKind::Simple(Some(rename), ..) => rename,
1950 UseTreeKind::Simple(None, ..) => {
1954 .expect("empty prefix in a simple import")
1957 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1962 /// Distinguishes between Attributes that decorate items and Attributes that
1963 /// are contained as statements within items. These two cases need to be
1964 /// distinguished for pretty-printing.
1965 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1966 pub enum AttrStyle {
1972 Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
1974 pub struct AttrId(pub usize);
1976 impl Idx for AttrId {
1977 fn new(idx: usize) -> Self {
1980 fn index(self) -> usize {
1985 /// Meta-data associated with an item
1986 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1987 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1988 pub struct Attribute {
1990 pub style: AttrStyle,
1992 pub tokens: TokenStream,
1993 pub is_sugared_doc: bool,
1997 /// TraitRef's appear in impls.
1999 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2000 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
2001 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
2002 /// same as the impl's node id).
2003 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2004 pub struct TraitRef {
2009 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2010 pub struct PolyTraitRef {
2011 /// The `'a` in `<'a> Foo<&'a T>`
2012 pub bound_generic_params: Vec<GenericParam>,
2014 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2015 pub trait_ref: TraitRef,
2021 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2023 bound_generic_params: generic_params,
2024 trait_ref: TraitRef {
2026 ref_id: DUMMY_NODE_ID,
2033 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2034 pub enum CrateSugar {
2035 /// Source is `pub(crate)`
2038 /// Source is (just) `crate`
2042 pub type Visibility = Spanned<VisibilityKind>;
2044 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2045 pub enum VisibilityKind {
2048 Restricted { path: P<Path>, id: NodeId },
2052 impl VisibilityKind {
2053 pub fn is_pub(&self) -> bool {
2054 if let VisibilityKind::Public = *self {
2062 /// Field of a struct.
2064 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
2065 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2066 pub struct StructField {
2068 pub ident: Option<Ident>,
2069 pub vis: Visibility,
2072 pub attrs: Vec<Attribute>,
2075 /// Fields and Ids of enum variants and structs
2077 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2078 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2079 /// One shared Id can be successfully used for these two purposes.
2080 /// Id of the whole enum lives in `Item`.
2082 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2083 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2084 /// the variant itself" from enum variants.
2085 /// Id of the whole struct lives in `Item`.
2086 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2087 pub enum VariantData {
2090 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
2091 Struct(Vec<StructField>, NodeId),
2094 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
2095 Tuple(Vec<StructField>, NodeId),
2098 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
2103 pub fn fields(&self) -> &[StructField] {
2105 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2109 pub fn id(&self) -> NodeId {
2111 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2114 pub fn is_struct(&self) -> bool {
2115 if let VariantData::Struct(..) = *self {
2121 pub fn is_tuple(&self) -> bool {
2122 if let VariantData::Tuple(..) = *self {
2128 pub fn is_unit(&self) -> bool {
2129 if let VariantData::Unit(..) = *self {
2139 /// The name might be a dummy name in case of anonymous items
2140 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2143 pub attrs: Vec<Attribute>,
2146 pub vis: Visibility,
2149 /// Original tokens this item was parsed from. This isn't necessarily
2150 /// available for all items, although over time more and more items should
2151 /// have this be `Some`. Right now this is primarily used for procedural
2152 /// macros, notably custom attributes.
2154 /// Note that the tokens here do not include the outer attributes, but will
2155 /// include inner attributes.
2156 pub tokens: Option<TokenStream>,
2159 /// A function header
2161 /// All the information between the visibility & the name of the function is
2162 /// included in this struct (e.g. `async unsafe fn` or `const extern "C" fn`)
2163 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2164 pub struct FnHeader {
2165 pub unsafety: Unsafety,
2166 pub asyncness: IsAsync,
2167 pub constness: Spanned<Constness>,
2171 impl Default for FnHeader {
2172 fn default() -> FnHeader {
2174 unsafety: Unsafety::Normal,
2175 asyncness: IsAsync::NotAsync,
2176 constness: dummy_spanned(Constness::NotConst),
2182 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2184 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2186 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2187 ExternCrate(Option<Name>),
2188 /// A use declaration (`use` or `pub use`) item.
2190 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
2192 /// A static item (`static` or `pub static`).
2194 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
2195 Static(P<Ty>, Mutability, P<Expr>),
2196 /// A constant item (`const` or `pub const`).
2198 /// E.g. `const FOO: i32 = 42;`
2199 Const(P<Ty>, P<Expr>),
2200 /// A function declaration (`fn` or `pub fn`).
2202 /// E.g. `fn foo(bar: usize) -> usize { .. }`
2203 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2204 /// A module declaration (`mod` or `pub mod`).
2206 /// E.g. `mod foo;` or `mod foo { .. }`
2208 /// An external module (`extern` or `pub extern`).
2210 /// E.g. `extern {}` or `extern "C" {}`
2211 ForeignMod(ForeignMod),
2212 /// Module-level inline assembly (from `global_asm!()`)
2213 GlobalAsm(P<GlobalAsm>),
2214 /// A type alias (`type` or `pub type`).
2216 /// E.g. `type Foo = Bar<u8>;`
2217 Ty(P<Ty>, Generics),
2218 /// An existential type declaration (`existential type`).
2220 /// E.g. `existential type Foo: Bar + Boo;`
2221 Existential(GenericBounds, Generics),
2222 /// An enum definition (`enum` or `pub enum`).
2224 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
2225 Enum(EnumDef, Generics),
2226 /// A struct definition (`struct` or `pub struct`).
2228 /// E.g. `struct Foo<A> { x: A }`
2229 Struct(VariantData, Generics),
2230 /// A union definition (`union` or `pub union`).
2232 /// E.g. `union Foo<A, B> { x: A, y: B }`
2233 Union(VariantData, Generics),
2234 /// A Trait declaration (`trait` or `pub trait`).
2236 /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
2237 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2240 /// E.g. `trait Foo = Bar + Quux;`
2241 TraitAlias(Generics, GenericBounds),
2242 /// An implementation.
2244 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
2250 Option<TraitRef>, // (optional) trait this impl implements
2254 /// A macro invocation.
2256 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
2259 /// A macro definition.
2264 pub fn descriptive_variant(&self) -> &str {
2266 ItemKind::ExternCrate(..) => "extern crate",
2267 ItemKind::Use(..) => "use",
2268 ItemKind::Static(..) => "static item",
2269 ItemKind::Const(..) => "constant item",
2270 ItemKind::Fn(..) => "function",
2271 ItemKind::Mod(..) => "module",
2272 ItemKind::ForeignMod(..) => "foreign module",
2273 ItemKind::GlobalAsm(..) => "global asm",
2274 ItemKind::Ty(..) => "type alias",
2275 ItemKind::Existential(..) => "existential type",
2276 ItemKind::Enum(..) => "enum",
2277 ItemKind::Struct(..) => "struct",
2278 ItemKind::Union(..) => "union",
2279 ItemKind::Trait(..) => "trait",
2280 ItemKind::TraitAlias(..) => "trait alias",
2281 ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2286 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2287 pub struct ForeignItem {
2289 pub attrs: Vec<Attribute>,
2290 pub node: ForeignItemKind,
2293 pub vis: Visibility,
2296 /// An item within an `extern` block
2297 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2298 pub enum ForeignItemKind {
2299 /// A foreign function
2300 Fn(P<FnDecl>, Generics),
2301 /// A foreign static item (`static ext: u8`), with optional mutability
2302 /// (the boolean is true when mutable)
2303 Static(P<Ty>, bool),
2306 /// A macro invocation
2310 impl ForeignItemKind {
2311 pub fn descriptive_variant(&self) -> &str {
2313 ForeignItemKind::Fn(..) => "foreign function",
2314 ForeignItemKind::Static(..) => "foreign static item",
2315 ForeignItemKind::Ty => "foreign type",
2316 ForeignItemKind::Macro(..) => "macro in foreign module",
2326 // are ASTs encodable?
2328 fn check_asts_encodable() {
2329 fn assert_encodable<T: serialize::Encodable>() {}
2330 assert_encodable::<Crate>();