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::UnsafeSource::*;
14 pub use self::GenericArgs::*;
15 pub use symbol::{Ident, Symbol as Name};
16 pub use util::ThinVec;
17 pub use util::parser::ExprPrecedence;
19 use syntax_pos::{Span, DUMMY_SP};
20 use codemap::{dummy_spanned, respan, Spanned};
21 use rustc_target::spec::abi::Abi;
22 use ext::hygiene::{Mark, SyntaxContext};
25 use rustc_data_structures::indexed_vec;
26 use symbol::{Symbol, keywords};
27 use tokenstream::{ThinTokenStream, TokenStream};
29 use serialize::{self, Encoder, Decoder};
30 use std::collections::HashSet;
32 use rustc_data_structures::sync::Lrc;
35 pub use rustc_target::abi::FloatTy;
37 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
42 impl fmt::Debug for Label {
43 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44 write!(f, "label({:?})", self.ident)
48 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
54 impl fmt::Debug for Lifetime {
55 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
60 /// A "Path" is essentially Rust's notion of a name.
62 /// It's represented as a sequence of identifiers,
63 /// along with a bunch of supporting information.
65 /// E.g. `std::cmp::PartialEq`
66 #[derive(Clone, RustcEncodable, RustcDecodable)]
69 /// The segments in the path: the things separated by `::`.
70 /// Global paths begin with `keywords::CrateRoot`.
71 pub segments: Vec<PathSegment>,
74 impl<'a> PartialEq<&'a str> for Path {
75 fn eq(&self, string: &&'a str) -> bool {
76 self.segments.len() == 1 && self.segments[0].ident.name == *string
80 impl fmt::Debug for Path {
81 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82 write!(f, "path({})", pprust::path_to_string(self))
86 impl fmt::Display for Path {
87 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88 write!(f, "{}", pprust::path_to_string(self))
93 // convert a span and an identifier to the corresponding
95 pub fn from_ident(ident: Ident) -> Path {
96 Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
99 // Make a "crate root" segment for this path unless it already has it
100 // or starts with something like `self`/`super`/`$crate`/etc.
101 pub fn make_root(&self) -> Option<PathSegment> {
102 if let Some(ident) = self.segments.get(0).map(|seg| seg.ident) {
103 if ident.is_path_segment_keyword() && ident.name != keywords::Crate.name() {
107 Some(PathSegment::crate_root(self.span.shrink_to_lo()))
110 pub fn is_global(&self) -> bool {
111 !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name()
115 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
117 /// E.g. `std`, `String` or `Box<T>`
118 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
119 pub struct PathSegment {
120 /// The identifier portion of this path segment.
123 /// Type/lifetime parameters attached to this path. They come in
124 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
125 /// `None` means that no parameter list is supplied (`Path`),
126 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
127 /// but it can be empty (`Path<>`).
128 /// `P` is used as a size optimization for the common case with no parameters.
129 pub args: Option<P<GenericArgs>>,
133 pub fn from_ident(ident: Ident) -> Self {
134 PathSegment { ident, args: None }
136 pub fn crate_root(span: Span) -> Self {
137 PathSegment::from_ident(Ident::new(keywords::CrateRoot.name(), span))
141 /// Arguments of a path segment.
143 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
144 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
145 pub enum GenericArgs {
146 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
147 AngleBracketed(AngleBracketedArgs),
148 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
149 Parenthesized(ParenthesisedArgs),
153 pub fn span(&self) -> Span {
155 AngleBracketed(ref data) => data.span,
156 Parenthesized(ref data) => data.span,
161 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
162 pub enum GenericArg {
167 /// A path like `Foo<'a, T>`
168 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
169 pub struct AngleBracketedArgs {
172 /// The arguments for this path segment.
173 pub args: Vec<GenericArg>,
174 /// Bindings (equality constraints) on associated types, if present.
176 /// E.g., `Foo<A=Bar>`.
177 pub bindings: Vec<TypeBinding>,
180 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
181 fn into(self) -> Option<P<GenericArgs>> {
182 Some(P(GenericArgs::AngleBracketed(self)))
186 impl Into<Option<P<GenericArgs>>> for ParenthesisedArgs {
187 fn into(self) -> Option<P<GenericArgs>> {
188 Some(P(GenericArgs::Parenthesized(self)))
192 /// A path like `Foo(A,B) -> C`
193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
194 pub struct ParenthesisedArgs {
199 pub inputs: Vec<P<Ty>>,
202 pub output: Option<P<Ty>>,
205 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
206 pub struct NodeId(u32);
209 pub fn new(x: usize) -> NodeId {
210 assert!(x < (u32::MAX as usize));
214 pub fn from_u32(x: u32) -> NodeId {
218 pub fn as_usize(&self) -> usize {
222 pub fn as_u32(&self) -> u32 {
226 pub fn placeholder_from_mark(mark: Mark) -> Self {
227 NodeId(mark.as_u32())
230 pub fn placeholder_to_mark(self) -> Mark {
231 Mark::from_u32(self.0)
235 impl fmt::Display for NodeId {
236 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
237 fmt::Display::fmt(&self.0, f)
241 impl serialize::UseSpecializedEncodable for NodeId {
242 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
247 impl serialize::UseSpecializedDecodable for NodeId {
248 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
249 d.read_u32().map(NodeId)
253 impl indexed_vec::Idx for NodeId {
254 fn new(idx: usize) -> Self {
258 fn index(self) -> usize {
263 /// Node id used to represent the root of the crate.
264 pub const CRATE_NODE_ID: NodeId = NodeId(0);
266 /// When parsing and doing expansions, we initially give all AST nodes this AST
267 /// node value. Then later, in the renumber pass, we renumber them to have
268 /// small, positive ids.
269 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
271 /// A modifier on a bound, currently this is only used for `?Sized`, where the
272 /// modifier is `Maybe`. Negative bounds should also be handled here.
273 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
274 pub enum TraitBoundModifier {
279 /// The AST represents all type param bounds as types.
280 /// typeck::collect::compute_bounds matches these against
281 /// the "special" built-in traits (see middle::lang_items) and
282 /// detects Copy, Send and Sync.
283 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
284 pub enum GenericBound {
285 Trait(PolyTraitRef, TraitBoundModifier),
290 pub fn span(&self) -> Span {
292 &GenericBound::Trait(ref t, ..) => t.span,
293 &GenericBound::Outlives(ref l) => l.ident.span,
298 pub type GenericBounds = Vec<GenericBound>;
300 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
301 pub enum GenericParamKind {
302 /// A lifetime definition, e.g. `'a: 'b+'c+'d`.
305 default: Option<P<Ty>>,
309 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
310 pub struct GenericParam {
313 pub attrs: ThinVec<Attribute>,
314 pub bounds: GenericBounds,
316 pub kind: GenericParamKind,
319 /// Represents lifetime, type and const parameters attached to a declaration of
320 /// a function, enum, trait, etc.
321 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
322 pub struct Generics {
323 pub params: Vec<GenericParam>,
324 pub where_clause: WhereClause,
328 impl Default for Generics {
329 /// Creates an instance of `Generics`.
330 fn default() -> Generics {
333 where_clause: WhereClause {
335 predicates: Vec::new(),
343 /// A `where` clause in a definition
344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
345 pub struct WhereClause {
347 pub predicates: Vec<WherePredicate>,
351 /// A single predicate in a `where` clause
352 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
353 pub enum WherePredicate {
354 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
355 BoundPredicate(WhereBoundPredicate),
356 /// A lifetime predicate, e.g. `'a: 'b+'c`
357 RegionPredicate(WhereRegionPredicate),
358 /// An equality predicate (unsupported)
359 EqPredicate(WhereEqPredicate),
362 impl WherePredicate {
363 pub fn span(&self) -> Span {
365 &WherePredicate::BoundPredicate(ref p) => p.span,
366 &WherePredicate::RegionPredicate(ref p) => p.span,
367 &WherePredicate::EqPredicate(ref p) => p.span,
374 /// E.g. `for<'c> Foo: Send+Clone+'c`
375 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
376 pub struct WhereBoundPredicate {
378 /// Any generics from a `for` binding
379 pub bound_generic_params: Vec<GenericParam>,
380 /// The type being bounded
381 pub bounded_ty: P<Ty>,
382 /// Trait and lifetime bounds (`Clone+Send+'static`)
383 pub bounds: GenericBounds,
386 /// A lifetime predicate.
389 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
390 pub struct WhereRegionPredicate {
392 pub lifetime: Lifetime,
393 pub bounds: GenericBounds,
396 /// An equality predicate (unsupported).
399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
400 pub struct WhereEqPredicate {
407 /// The set of MetaItems that define the compilation environment of the crate,
408 /// used to drive conditional compilation
409 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
411 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
414 pub attrs: Vec<Attribute>,
418 /// A spanned compile-time attribute list item.
419 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
421 /// Possible values inside of compile-time attribute lists.
423 /// E.g. the '..' in `#[name(..)]`.
424 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
425 pub enum NestedMetaItemKind {
426 /// A full MetaItem, for recursive meta items.
430 /// E.g. "foo", 64, true
434 /// A spanned compile-time attribute item.
436 /// E.g. `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`
437 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
438 pub struct MetaItem {
440 pub node: MetaItemKind,
444 /// A compile-time attribute item.
446 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
447 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
448 pub enum MetaItemKind {
451 /// E.g. `test` as in `#[test]`
455 /// E.g. `derive(..)` as in `#[derive(..)]`
456 List(Vec<NestedMetaItem>),
457 /// Name value meta item.
459 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
463 /// A Block (`{ .. }`).
465 /// E.g. `{ .. }` as in `fn foo() { .. }`
466 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
468 /// Statements in a block
469 pub stmts: Vec<Stmt>,
471 /// Distinguishes between `unsafe { ... }` and `{ ... }`
472 pub rules: BlockCheckMode,
477 #[derive(Clone, RustcEncodable, RustcDecodable)]
484 impl fmt::Debug for Pat {
485 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
486 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
491 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
492 let node = match &self.node {
493 PatKind::Wild => TyKind::Infer,
494 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) =>
495 TyKind::Path(None, Path::from_ident(*ident)),
496 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
497 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
498 PatKind::Ref(pat, mutbl) =>
499 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
500 PatKind::Slice(pats, None, _) if pats.len() == 1 =>
501 pats[0].to_ty().map(TyKind::Slice)?,
502 PatKind::Tuple(pats, None) => {
503 let mut tys = Vec::new();
505 tys.push(pat.to_ty()?);
512 Some(P(Ty { node, id: self.id, span: self.span }))
515 pub fn walk<F>(&self, it: &mut F) -> bool
516 where F: FnMut(&Pat) -> bool
523 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
524 PatKind::Struct(_, ref fields, _) => {
525 fields.iter().all(|field| field.node.pat.walk(it))
527 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
528 s.iter().all(|p| p.walk(it))
530 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => {
533 PatKind::Slice(ref before, ref slice, ref after) => {
534 before.iter().all(|p| p.walk(it)) &&
535 slice.iter().all(|p| p.walk(it)) &&
536 after.iter().all(|p| p.walk(it))
550 /// A single field in a struct pattern
552 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
553 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
554 /// except is_shorthand is true
555 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
556 pub struct FieldPat {
557 /// The identifier for the field
559 /// The pattern the field is destructured to
561 pub is_shorthand: bool,
562 pub attrs: ThinVec<Attribute>,
565 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
566 pub enum BindingMode {
571 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
573 Included(RangeSyntax),
577 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
578 pub enum RangeSyntax {
583 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
585 /// Represents a wildcard pattern (`_`)
588 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
589 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
590 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
591 /// during name resolution.
592 Ident(BindingMode, Ident, Option<P<Pat>>),
594 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
595 /// The `bool` is `true` in the presence of a `..`.
596 Struct(Path, Vec<Spanned<FieldPat>>, bool),
598 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
599 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
600 /// 0 <= position <= subpats.len()
601 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
603 /// A possibly qualified path pattern.
604 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
605 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
606 /// only legally refer to associated constants.
607 Path(Option<QSelf>, Path),
609 /// A tuple pattern `(a, b)`.
610 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
611 /// 0 <= position <= subpats.len()
612 Tuple(Vec<P<Pat>>, Option<usize>),
615 /// A reference pattern, e.g. `&mut (a, b)`
616 Ref(P<Pat>, Mutability),
619 /// A range pattern, e.g. `1...2`, `1..=2` or `1..2`
620 Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
621 /// `[a, b, ..i, y, z]` is represented as:
622 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
623 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
624 /// Parentheses in patters used for grouping, i.e. `(PAT)`.
626 /// A macro pattern; pre-expansion
630 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
631 pub enum Mutability {
636 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
638 /// The `+` operator (addition)
640 /// The `-` operator (subtraction)
642 /// The `*` operator (multiplication)
644 /// The `/` operator (division)
646 /// The `%` operator (modulus)
648 /// The `&&` operator (logical and)
650 /// The `||` operator (logical or)
652 /// The `^` operator (bitwise xor)
654 /// The `&` operator (bitwise and)
656 /// The `|` operator (bitwise or)
658 /// The `<<` operator (shift left)
660 /// The `>>` operator (shift right)
662 /// The `==` operator (equality)
664 /// The `<` operator (less than)
666 /// The `<=` operator (less than or equal to)
668 /// The `!=` operator (not equal to)
670 /// The `>=` operator (greater than or equal to)
672 /// The `>` operator (greater than)
677 pub fn to_string(&self) -> &'static str {
678 use self::BinOpKind::*;
700 pub fn lazy(&self) -> bool {
702 BinOpKind::And | BinOpKind::Or => true,
707 pub fn is_shift(&self) -> bool {
709 BinOpKind::Shl | BinOpKind::Shr => true,
714 pub fn is_comparison(&self) -> bool {
715 use self::BinOpKind::*;
717 Eq | Lt | Le | Ne | Gt | Ge =>
719 And | Or | Add | Sub | Mul | Div | Rem |
720 BitXor | BitAnd | BitOr | Shl | Shr =>
725 /// Returns `true` if the binary operator takes its arguments by value
726 pub fn is_by_value(&self) -> bool {
727 !self.is_comparison()
731 pub type BinOp = Spanned<BinOpKind>;
733 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
735 /// The `*` operator for dereferencing
737 /// The `!` operator for logical inversion
739 /// The `-` operator for negation
744 /// Returns `true` if the unary operator takes its argument by value
745 pub fn is_by_value(u: UnOp) -> bool {
747 UnOp::Neg | UnOp::Not => true,
752 pub fn to_string(op: UnOp) -> &'static str {
762 #[derive(Clone, RustcEncodable, RustcDecodable)]
770 pub fn add_trailing_semicolon(mut self) -> Self {
771 self.node = match self.node {
772 StmtKind::Expr(expr) => StmtKind::Semi(expr),
773 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
774 (mac, MacStmtStyle::Semicolon, attrs)
781 pub fn is_item(&self) -> bool {
783 StmtKind::Item(_) => true,
788 pub fn is_expr(&self) -> bool {
790 StmtKind::Expr(_) => true,
796 impl fmt::Debug for Stmt {
797 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
798 write!(f, "stmt({}: {})", self.id.to_string(), 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<P<Expr>>,
862 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
867 pub is_shorthand: bool,
868 pub attrs: ThinVec<Attribute>,
871 pub type SpannedIdent = Spanned<Ident>;
873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
874 pub enum BlockCheckMode {
876 Unsafe(UnsafeSource),
879 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
880 pub enum UnsafeSource {
885 /// A constant (expression) that's not an item or associated item,
886 /// but needs its own `DefId` for type-checking, const-eval, etc.
887 /// These are usually found nested inside types (e.g. array lengths)
888 /// or expressions (e.g. repeat counts), and also used to define
889 /// explicit discriminant values for enum variants.
890 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
891 pub struct AnonConst {
898 #[derive(Clone, RustcEncodable, RustcDecodable)]
903 pub attrs: ThinVec<Attribute>
907 /// Whether this expression would be valid somewhere that expects a value, for example, an `if`
909 pub fn returns(&self) -> bool {
910 if let ExprKind::Block(ref block, _) = self.node {
911 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
913 Some(&StmtKind::Expr(_)) => true,
914 Some(&StmtKind::Semi(ref expr)) => {
915 if let ExprKind::Ret(_) = expr.node {
916 // last statement is explicit return
922 // This is a block that doesn't end in either an implicit or explicit return
926 // This is not a block, it is a value
931 fn to_bound(&self) -> Option<GenericBound> {
933 ExprKind::Path(None, path) =>
934 Some(GenericBound::Trait(PolyTraitRef::new(Vec::new(), path.clone(), self.span),
935 TraitBoundModifier::None)),
940 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
941 let node = match &self.node {
942 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
943 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
944 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
945 ExprKind::AddrOf(mutbl, expr) =>
946 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
947 ExprKind::Repeat(expr, expr_len) =>
948 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?,
949 ExprKind::Array(exprs) if exprs.len() == 1 =>
950 exprs[0].to_ty().map(TyKind::Slice)?,
951 ExprKind::Tup(exprs) => {
952 let mut tys = Vec::new();
954 tys.push(expr.to_ty()?);
958 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add =>
959 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
960 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
967 Some(P(Ty { node, id: self.id, span: self.span }))
970 pub fn precedence(&self) -> ExprPrecedence {
972 ExprKind::Box(_) => ExprPrecedence::Box,
973 ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
974 ExprKind::Array(_) => ExprPrecedence::Array,
975 ExprKind::Call(..) => ExprPrecedence::Call,
976 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
977 ExprKind::Tup(_) => ExprPrecedence::Tup,
978 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
979 ExprKind::Unary(..) => ExprPrecedence::Unary,
980 ExprKind::Lit(_) => ExprPrecedence::Lit,
981 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
982 ExprKind::If(..) => ExprPrecedence::If,
983 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
984 ExprKind::While(..) => ExprPrecedence::While,
985 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
986 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
987 ExprKind::Loop(..) => ExprPrecedence::Loop,
988 ExprKind::Match(..) => ExprPrecedence::Match,
989 ExprKind::Closure(..) => ExprPrecedence::Closure,
990 ExprKind::Block(..) => ExprPrecedence::Block,
991 ExprKind::Catch(..) => ExprPrecedence::Catch,
992 ExprKind::Async(..) => ExprPrecedence::Async,
993 ExprKind::Assign(..) => ExprPrecedence::Assign,
994 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
995 ExprKind::Field(..) => ExprPrecedence::Field,
996 ExprKind::Index(..) => ExprPrecedence::Index,
997 ExprKind::Range(..) => ExprPrecedence::Range,
998 ExprKind::Path(..) => ExprPrecedence::Path,
999 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1000 ExprKind::Break(..) => ExprPrecedence::Break,
1001 ExprKind::Continue(..) => ExprPrecedence::Continue,
1002 ExprKind::Ret(..) => ExprPrecedence::Ret,
1003 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1004 ExprKind::Mac(..) => ExprPrecedence::Mac,
1005 ExprKind::Struct(..) => ExprPrecedence::Struct,
1006 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1007 ExprKind::Paren(..) => ExprPrecedence::Paren,
1008 ExprKind::Try(..) => ExprPrecedence::Try,
1009 ExprKind::Yield(..) => ExprPrecedence::Yield,
1014 impl fmt::Debug for Expr {
1015 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1016 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1020 /// Limit types of a range (inclusive or exclusive)
1021 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1022 pub enum RangeLimits {
1023 /// Inclusive at the beginning, exclusive at the end
1025 /// Inclusive at the beginning and end
1029 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1031 /// A `box x` expression.
1033 /// First expr is the place; second expr is the value.
1034 ObsoleteInPlace(P<Expr>, P<Expr>),
1035 /// An array (`[a, b, c, d]`)
1036 Array(Vec<P<Expr>>),
1039 /// The first field resolves to the function itself,
1040 /// and the second field is the list of arguments.
1041 /// This also represents calling the constructor of
1042 /// tuple-like ADTs such as tuple structs and enum variants.
1043 Call(P<Expr>, Vec<P<Expr>>),
1044 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1046 /// The `PathSegment` represents the method name and its generic arguments
1047 /// (within the angle brackets).
1048 /// The first element of the vector of `Expr`s is the expression that evaluates
1049 /// to the object on which the method is being called on (the receiver),
1050 /// and the remaining elements are the rest of the arguments.
1051 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1052 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1053 MethodCall(PathSegment, Vec<P<Expr>>),
1054 /// A tuple (`(a, b, c ,d)`)
1056 /// A binary operation (For example: `a + b`, `a * b`)
1057 Binary(BinOp, P<Expr>, P<Expr>),
1058 /// A unary operation (For example: `!x`, `*x`)
1059 Unary(UnOp, P<Expr>),
1060 /// A literal (For example: `1`, `"foo"`)
1062 /// A cast (`foo as f64`)
1063 Cast(P<Expr>, P<Ty>),
1064 Type(P<Expr>, P<Ty>),
1065 /// An `if` block, with an optional else block
1067 /// `if expr { block } else { expr }`
1068 If(P<Expr>, P<Block>, Option<P<Expr>>),
1069 /// An `if let` expression with an optional else block
1071 /// `if let pat = expr { block } else { expr }`
1073 /// This is desugared to a `match` expression.
1074 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1075 /// A while loop, with an optional label
1077 /// `'label: while expr { block }`
1078 While(P<Expr>, P<Block>, Option<Label>),
1079 /// A while-let loop, with an optional label
1081 /// `'label: while let pat = expr { block }`
1083 /// This is desugared to a combination of `loop` and `match` expressions.
1084 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1085 /// A for loop, with an optional label
1087 /// `'label: for pat in expr { block }`
1089 /// This is desugared to a combination of `loop` and `match` expressions.
1090 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1091 /// Conditionless loop (can be exited with break, continue, or return)
1093 /// `'label: loop { block }`
1094 Loop(P<Block>, Option<Label>),
1095 /// A `match` block.
1096 Match(P<Expr>, Vec<Arm>),
1097 /// A closure (for example, `move |a, b, c| a + b + c`)
1099 /// The final span is the span of the argument block `|...|`
1100 Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1101 /// A block (`'label: { ... }`)
1102 Block(P<Block>, Option<Label>),
1103 /// An async block (`async move { ... }`)
1105 /// The `NodeId` is the `NodeId` for the closure that results from
1106 /// desugaring an async block, just like the NodeId field in the
1107 /// `IsAsync` enum. This is necessary in order to create a def for the
1108 /// closure which can be used as a parent of any child defs. Defs
1109 /// created during lowering cannot be made the parent of any other
1110 /// preexisting defs.
1111 Async(CaptureBy, NodeId, P<Block>),
1112 /// A catch block (`catch { ... }`)
1115 /// An assignment (`a = foo()`)
1116 Assign(P<Expr>, P<Expr>),
1117 /// An assignment with an operator
1119 /// For example, `a += 1`.
1120 AssignOp(BinOp, P<Expr>, P<Expr>),
1121 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct field
1122 Field(P<Expr>, Ident),
1123 /// An indexing operation (`foo[2]`)
1124 Index(P<Expr>, P<Expr>),
1125 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
1126 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1128 /// Variable reference, possibly containing `::` and/or type
1129 /// parameters, e.g. foo::bar::<baz>.
1131 /// Optionally "qualified",
1132 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1133 Path(Option<QSelf>, Path),
1135 /// A referencing operation (`&a` or `&mut a`)
1136 AddrOf(Mutability, P<Expr>),
1137 /// A `break`, with an optional label to break, and an optional expression
1138 Break(Option<Label>, Option<P<Expr>>),
1139 /// A `continue`, with an optional label
1140 Continue(Option<Label>),
1141 /// A `return`, with an optional value to be returned
1142 Ret(Option<P<Expr>>),
1144 /// Output of the `asm!()` macro
1145 InlineAsm(P<InlineAsm>),
1147 /// A macro invocation; pre-expansion
1150 /// A struct literal expression.
1152 /// For example, `Foo {x: 1, y: 2}`, or
1153 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1154 Struct(Path, Vec<Field>, Option<P<Expr>>),
1156 /// An array literal constructed from one repeated element.
1158 /// For example, `[1; 5]`. The expression is the element to be
1159 /// repeated; the constant is the number of times to repeat it.
1160 Repeat(P<Expr>, AnonConst),
1162 /// No-op: used solely so we can pretty-print faithfully
1168 /// A `yield`, with an optional value to be yielded
1169 Yield(Option<P<Expr>>),
1172 /// The explicit Self type in a "qualified path". The actual
1173 /// path, including the trait and the associated item, is stored
1174 /// separately. `position` represents the index of the associated
1175 /// item qualified with this Self type.
1177 /// ```ignore (only-for-syntax-highlight)
1178 /// <Vec<T> as a::b::Trait>::AssociatedItem
1179 /// ^~~~~ ~~~~~~~~~~~~~~^
1182 /// <Vec<T>>::AssociatedItem
1186 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1190 /// The span of `a::b::Trait` in a path like `<Vec<T> as
1191 /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1192 /// 0`, this is an empty span.
1193 pub path_span: Span,
1197 /// A capture clause
1198 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1199 pub enum CaptureBy {
1204 /// The movability of a generator / closure literal
1205 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1206 pub enum Movability {
1211 pub type Mac = Spanned<Mac_>;
1213 /// Represents a macro invocation. The Path indicates which macro
1214 /// is being invoked, and the vector of token-trees contains the source
1215 /// of the macro invocation.
1217 /// NB: the additional ident for a macro_rules-style macro is actually
1218 /// stored in the enclosing item. Oog.
1219 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1222 pub delim: MacDelimiter,
1223 pub tts: ThinTokenStream,
1226 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1227 pub enum MacDelimiter {
1234 pub fn stream(&self) -> TokenStream {
1235 self.tts.clone().into()
1239 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1240 pub struct MacroDef {
1241 pub tokens: ThinTokenStream,
1246 pub fn stream(&self) -> TokenStream {
1247 self.tokens.clone().into()
1251 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1253 /// A regular string, like `"foo"`
1255 /// A raw string, like `r##"foo"##`
1257 /// The value is the number of `#` symbols used.
1262 pub type Lit = Spanned<LitKind>;
1264 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1265 pub enum LitIntType {
1273 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1274 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1276 /// A string literal (`"foo"`)
1277 Str(Symbol, StrStyle),
1278 /// A byte string (`b"foo"`)
1279 ByteStr(Lrc<Vec<u8>>),
1280 /// A byte char (`b'f'`)
1282 /// A character literal (`'a'`)
1284 /// An integer literal (`1`)
1285 Int(u128, LitIntType),
1286 /// A float literal (`1f64` or `1E10f64`)
1287 Float(Symbol, FloatTy),
1288 /// A float literal without a suffix (`1.0 or 1.0E10`)
1289 FloatUnsuffixed(Symbol),
1290 /// A boolean literal
1295 /// Returns true if this literal is a string and false otherwise.
1296 pub fn is_str(&self) -> bool {
1298 LitKind::Str(..) => true,
1303 /// Returns true if this is a numeric literal.
1304 pub fn is_numeric(&self) -> bool {
1307 LitKind::Float(..) |
1308 LitKind::FloatUnsuffixed(..) => true,
1313 /// Returns true if this literal has no suffix. Note: this will return true
1314 /// for literals with prefixes such as raw strings and byte strings.
1315 pub fn is_unsuffixed(&self) -> bool {
1317 // unsuffixed variants
1319 LitKind::ByteStr(..) |
1322 LitKind::Int(_, LitIntType::Unsuffixed) |
1323 LitKind::FloatUnsuffixed(..) |
1324 LitKind::Bool(..) => true,
1325 // suffixed variants
1326 LitKind::Int(_, LitIntType::Signed(..)) |
1327 LitKind::Int(_, LitIntType::Unsigned(..)) |
1328 LitKind::Float(..) => false,
1332 /// Returns true if this literal has a suffix.
1333 pub fn is_suffixed(&self) -> bool {
1334 !self.is_unsuffixed()
1338 // NB: If you change this, you'll probably want to change the corresponding
1339 // type structure in middle/ty.rs as well.
1340 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1343 pub mutbl: Mutability,
1346 /// Represents a method's signature in a trait declaration,
1347 /// or in an implementation.
1348 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1349 pub struct MethodSig {
1350 pub header: FnHeader,
1351 pub decl: P<FnDecl>,
1354 /// Represents an item declaration within a trait declaration,
1355 /// possibly including a default implementation. A trait item is
1356 /// either required (meaning it doesn't have an implementation, just a
1357 /// signature) or provided (meaning it has a default implementation).
1358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1359 pub struct TraitItem {
1362 pub attrs: Vec<Attribute>,
1363 pub generics: Generics,
1364 pub node: TraitItemKind,
1366 /// See `Item::tokens` for what this is
1367 pub tokens: Option<TokenStream>,
1370 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1371 pub enum TraitItemKind {
1372 Const(P<Ty>, Option<P<Expr>>),
1373 Method(MethodSig, Option<P<Block>>),
1374 Type(GenericBounds, Option<P<Ty>>),
1378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1379 pub struct ImplItem {
1382 pub vis: Visibility,
1383 pub defaultness: Defaultness,
1384 pub attrs: Vec<Attribute>,
1385 pub generics: Generics,
1386 pub node: ImplItemKind,
1388 /// See `Item::tokens` for what this is
1389 pub tokens: Option<TokenStream>,
1392 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1393 pub enum ImplItemKind {
1394 Const(P<Ty>, P<Expr>),
1395 Method(MethodSig, P<Block>),
1400 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1410 impl fmt::Debug for IntTy {
1411 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1412 fmt::Display::fmt(self, f)
1416 impl fmt::Display for IntTy {
1417 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1418 write!(f, "{}", self.ty_to_string())
1423 pub fn ty_to_string(&self) -> &'static str {
1425 IntTy::Isize => "isize",
1427 IntTy::I16 => "i16",
1428 IntTy::I32 => "i32",
1429 IntTy::I64 => "i64",
1430 IntTy::I128 => "i128",
1434 pub fn val_to_string(&self, val: i128) -> String {
1435 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1436 // are parsed as u128, so we wouldn't want to print an extra negative
1438 format!("{}{}", val as u128, self.ty_to_string())
1441 pub fn bit_width(&self) -> Option<usize> {
1443 IntTy::Isize => return None,
1453 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1464 pub fn ty_to_string(&self) -> &'static str {
1466 UintTy::Usize => "usize",
1468 UintTy::U16 => "u16",
1469 UintTy::U32 => "u32",
1470 UintTy::U64 => "u64",
1471 UintTy::U128 => "u128",
1475 pub fn val_to_string(&self, val: u128) -> String {
1476 format!("{}{}", val, self.ty_to_string())
1479 pub fn bit_width(&self) -> Option<usize> {
1481 UintTy::Usize => return None,
1486 UintTy::U128 => 128,
1491 impl fmt::Debug for UintTy {
1492 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1493 fmt::Display::fmt(self, f)
1497 impl fmt::Display for UintTy {
1498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1499 write!(f, "{}", self.ty_to_string())
1503 // Bind a type to an associated type: `A=Foo`.
1504 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1505 pub struct TypeBinding {
1512 #[derive(Clone, RustcEncodable, RustcDecodable)]
1519 impl fmt::Debug for Ty {
1520 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1521 write!(f, "type({})", pprust::ty_to_string(self))
1525 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1526 pub struct BareFnTy {
1527 pub unsafety: Unsafety,
1529 pub generic_params: Vec<GenericParam>,
1533 /// The different kinds of types recognized by the compiler
1534 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1536 /// A variable-length slice (`[T]`)
1538 /// A fixed length array (`[T; n]`)
1539 Array(P<Ty>, AnonConst),
1540 /// A raw pointer (`*const T` or `*mut T`)
1542 /// A reference (`&'a T` or `&'a mut T`)
1543 Rptr(Option<Lifetime>, MutTy),
1544 /// A bare function (e.g. `fn(usize) -> bool`)
1545 BareFn(P<BareFnTy>),
1546 /// The never type (`!`)
1548 /// A tuple (`(A, B, C, D,...)`)
1550 /// A path (`module::module::...::Type`), optionally
1551 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1553 /// Type parameters are stored in the Path itself
1554 Path(Option<QSelf>, Path),
1555 /// A trait object type `Bound1 + Bound2 + Bound3`
1556 /// where `Bound` is a trait or a lifetime.
1557 TraitObject(GenericBounds, TraitObjectSyntax),
1558 /// An `impl Bound1 + Bound2 + Bound3` type
1559 /// where `Bound` is a trait or a lifetime.
1561 /// The `NodeId` exists to prevent lowering from having to
1562 /// generate `NodeId`s on the fly, which would complicate
1563 /// the generation of `existential type` items significantly
1564 ImplTrait(NodeId, GenericBounds),
1565 /// No-op; kept solely so that we can pretty-print faithfully
1569 /// TyKind::Infer means the type should be inferred instead of it having been
1570 /// specified. This can appear anywhere in a type.
1572 /// Inferred type of a `self` or `&self` argument in a method.
1574 // A macro in the type position.
1576 /// Placeholder for a kind that has failed to be defined.
1581 pub fn is_implicit_self(&self) -> bool {
1582 if let TyKind::ImplicitSelf = *self { true } else { false }
1585 crate fn is_unit(&self) -> bool {
1586 if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
1590 /// Syntax used to declare a trait object.
1591 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1592 pub enum TraitObjectSyntax {
1597 /// Inline assembly dialect.
1599 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1600 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1601 pub enum AsmDialect {
1606 /// Inline assembly.
1608 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1609 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1610 pub struct InlineAsmOutput {
1611 pub constraint: Symbol,
1614 pub is_indirect: bool,
1617 /// Inline assembly.
1619 /// E.g. `asm!("NOP");`
1620 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1621 pub struct InlineAsm {
1623 pub asm_str_style: StrStyle,
1624 pub outputs: Vec<InlineAsmOutput>,
1625 pub inputs: Vec<(Symbol, P<Expr>)>,
1626 pub clobbers: Vec<Symbol>,
1628 pub alignstack: bool,
1629 pub dialect: AsmDialect,
1630 pub ctxt: SyntaxContext,
1633 /// An argument in a function header.
1635 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1636 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1643 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1645 /// E.g. `&mut self` as in `fn foo(&mut self)`
1646 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1648 /// `self`, `mut self`
1650 /// `&'lt self`, `&'lt mut self`
1651 Region(Option<Lifetime>, Mutability),
1652 /// `self: TYPE`, `mut self: TYPE`
1653 Explicit(P<Ty>, Mutability),
1656 pub type ExplicitSelf = Spanned<SelfKind>;
1659 pub fn to_self(&self) -> Option<ExplicitSelf> {
1660 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1661 if ident.name == keywords::SelfValue.name() {
1662 return match self.ty.node {
1663 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1664 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node.is_implicit_self() => {
1665 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1667 _ => Some(respan(self.pat.span.to(self.ty.span),
1668 SelfKind::Explicit(self.ty.clone(), mutbl))),
1675 pub fn is_self(&self) -> bool {
1676 if let PatKind::Ident(_, ident, _) = self.pat.node {
1677 ident.name == keywords::SelfValue.name()
1683 pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1684 let span = eself.span.to(eself_ident.span);
1685 let infer_ty = P(Ty {
1687 node: TyKind::ImplicitSelf,
1690 let arg = |mutbl, ty| Arg {
1693 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1700 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1701 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1702 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1704 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1711 /// Header (not the body) of a function declaration.
1713 /// E.g. `fn foo(bar: baz)`
1714 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1716 pub inputs: Vec<Arg>,
1717 pub output: FunctionRetTy,
1722 pub fn get_self(&self) -> Option<ExplicitSelf> {
1723 self.inputs.get(0).and_then(Arg::to_self)
1725 pub fn has_self(&self) -> bool {
1726 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1730 /// Is the trait definition an auto trait?
1731 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1737 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1743 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1747 return_impl_trait_id: NodeId,
1753 pub fn is_async(self) -> bool {
1754 if let IsAsync::Async { .. } = self {
1760 /// In case this is an `Async` return the `NodeId` for the generated impl Trait item
1761 pub fn opt_return_id(self) -> Option<NodeId> {
1763 IsAsync::Async { return_impl_trait_id, .. } => Some(return_impl_trait_id),
1764 IsAsync::NotAsync => None,
1769 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1770 pub enum Constness {
1775 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1776 pub enum Defaultness {
1781 impl fmt::Display for Unsafety {
1782 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1783 fmt::Display::fmt(match *self {
1784 Unsafety::Normal => "normal",
1785 Unsafety::Unsafe => "unsafe",
1790 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1791 pub enum ImplPolarity {
1792 /// `impl Trait for Type`
1794 /// `impl !Trait for Type`
1798 impl fmt::Debug for ImplPolarity {
1799 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1801 ImplPolarity::Positive => "positive".fmt(f),
1802 ImplPolarity::Negative => "negative".fmt(f),
1808 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1809 pub enum FunctionRetTy {
1810 /// Return type is not specified.
1812 /// Functions default to `()` and
1813 /// closures default to inference. Span points to where return
1814 /// type would be inserted.
1820 impl FunctionRetTy {
1821 pub fn span(&self) -> Span {
1823 FunctionRetTy::Default(span) => span,
1824 FunctionRetTy::Ty(ref ty) => ty.span,
1829 /// Module declaration.
1831 /// E.g. `mod foo;` or `mod foo { .. }`
1832 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1834 /// A span from the first token past `{` to the last token until `}`.
1835 /// For `mod foo;`, the inner span ranges from the first token
1836 /// to the last token in the external file.
1838 pub items: Vec<P<Item>>,
1841 /// Foreign module declaration.
1843 /// E.g. `extern { .. }` or `extern C { .. }`
1844 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1845 pub struct ForeignMod {
1847 pub items: Vec<ForeignItem>,
1850 /// Global inline assembly
1852 /// aka module-level assembly or file-scoped assembly
1853 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1854 pub struct GlobalAsm {
1856 pub ctxt: SyntaxContext,
1859 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1860 pub struct EnumDef {
1861 pub variants: Vec<Variant>,
1864 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1865 pub struct Variant_ {
1867 pub attrs: Vec<Attribute>,
1868 pub data: VariantData,
1869 /// Explicit discriminant, e.g. `Foo = 1`
1870 pub disr_expr: Option<AnonConst>,
1873 pub type Variant = Spanned<Variant_>;
1875 /// Part of `use` item to the right of its prefix.
1876 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1877 pub enum UseTreeKind {
1878 /// `use prefix` or `use prefix as rename`
1880 /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
1882 Simple(Option<Ident>, NodeId, NodeId),
1883 /// `use prefix::{...}`
1884 Nested(Vec<(UseTree, NodeId)>),
1889 /// A tree of paths sharing common prefixes.
1890 /// Used in `use` items both at top-level and inside of braces in import groups.
1891 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1892 pub struct UseTree {
1894 pub kind: UseTreeKind,
1899 pub fn ident(&self) -> Ident {
1901 UseTreeKind::Simple(Some(rename), ..) => rename,
1902 UseTreeKind::Simple(None, ..) =>
1903 self.prefix.segments.last().expect("empty prefix in a simple import").ident,
1904 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1909 /// Distinguishes between Attributes that decorate items and Attributes that
1910 /// are contained as statements within items. These two cases need to be
1911 /// distinguished for pretty-printing.
1912 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1913 pub enum AttrStyle {
1918 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1919 pub struct AttrId(pub usize);
1921 /// Meta-data associated with an item
1922 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1923 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1924 pub struct Attribute {
1926 pub style: AttrStyle,
1928 pub tokens: TokenStream,
1929 pub is_sugared_doc: bool,
1933 /// TraitRef's appear in impls.
1935 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1936 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1937 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1938 /// same as the impl's node id).
1939 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1940 pub struct TraitRef {
1945 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1946 pub struct PolyTraitRef {
1947 /// The `'a` in `<'a> Foo<&'a T>`
1948 pub bound_generic_params: Vec<GenericParam>,
1950 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1951 pub trait_ref: TraitRef,
1957 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
1959 bound_generic_params: generic_params,
1960 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1966 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1967 pub enum CrateSugar {
1968 /// Source is `pub(crate)`
1971 /// Source is (just) `crate`
1975 pub type Visibility = Spanned<VisibilityKind>;
1977 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1978 pub enum VisibilityKind {
1981 Restricted { path: P<Path>, id: NodeId },
1985 impl VisibilityKind {
1986 pub fn is_pub(&self) -> bool {
1987 if let VisibilityKind::Public = *self { true } else { false }
1991 /// Field of a struct.
1993 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1994 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1995 pub struct StructField {
1997 pub ident: Option<Ident>,
1998 pub vis: Visibility,
2001 pub attrs: Vec<Attribute>,
2004 /// Fields and Ids of enum variants and structs
2006 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2007 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2008 /// One shared Id can be successfully used for these two purposes.
2009 /// Id of the whole enum lives in `Item`.
2011 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2012 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2013 /// the variant itself" from enum variants.
2014 /// Id of the whole struct lives in `Item`.
2015 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2016 pub enum VariantData {
2019 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
2020 Struct(Vec<StructField>, NodeId),
2023 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
2024 Tuple(Vec<StructField>, NodeId),
2027 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
2032 pub fn fields(&self) -> &[StructField] {
2034 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2038 pub fn id(&self) -> NodeId {
2040 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
2043 pub fn is_struct(&self) -> bool {
2044 if let VariantData::Struct(..) = *self { true } else { false }
2046 pub fn is_tuple(&self) -> bool {
2047 if let VariantData::Tuple(..) = *self { true } else { false }
2049 pub fn is_unit(&self) -> bool {
2050 if let VariantData::Unit(..) = *self { true } else { false }
2056 /// The name might be a dummy name in case of anonymous items
2057 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2060 pub attrs: Vec<Attribute>,
2063 pub vis: Visibility,
2066 /// Original tokens this item was parsed from. This isn't necessarily
2067 /// available for all items, although over time more and more items should
2068 /// have this be `Some`. Right now this is primarily used for procedural
2069 /// macros, notably custom attributes.
2071 /// Note that the tokens here do not include the outer attributes, but will
2072 /// include inner attributes.
2073 pub tokens: Option<TokenStream>,
2076 /// A function header
2078 /// All the information between the visibility & the name of the function is
2079 /// included in this struct (e.g. `async unsafe fn` or `const extern "C" fn`)
2080 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2081 pub struct FnHeader {
2082 pub unsafety: Unsafety,
2083 pub asyncness: IsAsync,
2084 pub constness: Spanned<Constness>,
2088 impl Default for FnHeader {
2089 fn default() -> FnHeader {
2091 unsafety: Unsafety::Normal,
2092 asyncness: IsAsync::NotAsync,
2093 constness: dummy_spanned(Constness::NotConst),
2099 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2101 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2103 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2104 ExternCrate(Option<Name>),
2105 /// A use declaration (`use` or `pub use`) item.
2107 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
2109 /// A static item (`static` or `pub static`).
2111 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
2112 Static(P<Ty>, Mutability, P<Expr>),
2113 /// A constant item (`const` or `pub const`).
2115 /// E.g. `const FOO: i32 = 42;`
2116 Const(P<Ty>, P<Expr>),
2117 /// A function declaration (`fn` or `pub fn`).
2119 /// E.g. `fn foo(bar: usize) -> usize { .. }`
2120 Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2121 /// A module declaration (`mod` or `pub mod`).
2123 /// E.g. `mod foo;` or `mod foo { .. }`
2125 /// An external module (`extern` or `pub extern`).
2127 /// E.g. `extern {}` or `extern "C" {}`
2128 ForeignMod(ForeignMod),
2129 /// Module-level inline assembly (from `global_asm!()`)
2130 GlobalAsm(P<GlobalAsm>),
2131 /// A type alias (`type` or `pub type`).
2133 /// E.g. `type Foo = Bar<u8>;`
2134 Ty(P<Ty>, Generics),
2135 /// An enum definition (`enum` or `pub enum`).
2137 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
2138 Enum(EnumDef, Generics),
2139 /// A struct definition (`struct` or `pub struct`).
2141 /// E.g. `struct Foo<A> { x: A }`
2142 Struct(VariantData, Generics),
2143 /// A union definition (`union` or `pub union`).
2145 /// E.g. `union Foo<A, B> { x: A, y: B }`
2146 Union(VariantData, Generics),
2147 /// A Trait declaration (`trait` or `pub trait`).
2149 /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
2150 Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2153 /// E.g. `trait Foo = Bar + Quux;`
2154 TraitAlias(Generics, GenericBounds),
2155 /// An implementation.
2157 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
2162 Option<TraitRef>, // (optional) trait this impl implements
2165 /// A macro invocation.
2167 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
2170 /// A macro definition.
2175 pub fn descriptive_variant(&self) -> &str {
2177 ItemKind::ExternCrate(..) => "extern crate",
2178 ItemKind::Use(..) => "use",
2179 ItemKind::Static(..) => "static item",
2180 ItemKind::Const(..) => "constant item",
2181 ItemKind::Fn(..) => "function",
2182 ItemKind::Mod(..) => "module",
2183 ItemKind::ForeignMod(..) => "foreign module",
2184 ItemKind::GlobalAsm(..) => "global asm",
2185 ItemKind::Ty(..) => "type alias",
2186 ItemKind::Enum(..) => "enum",
2187 ItemKind::Struct(..) => "struct",
2188 ItemKind::Union(..) => "union",
2189 ItemKind::Trait(..) => "trait",
2190 ItemKind::TraitAlias(..) => "trait alias",
2192 ItemKind::MacroDef(..) |
2193 ItemKind::Impl(..) => "item"
2198 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2199 pub struct ForeignItem {
2201 pub attrs: Vec<Attribute>,
2202 pub node: ForeignItemKind,
2205 pub vis: Visibility,
2208 /// An item within an `extern` block
2209 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2210 pub enum ForeignItemKind {
2211 /// A foreign function
2212 Fn(P<FnDecl>, Generics),
2213 /// A foreign static item (`static ext: u8`), with optional mutability
2214 /// (the boolean is true when mutable)
2215 Static(P<Ty>, bool),
2218 /// A macro invocation
2222 impl ForeignItemKind {
2223 pub fn descriptive_variant(&self) -> &str {
2225 ForeignItemKind::Fn(..) => "foreign function",
2226 ForeignItemKind::Static(..) => "foreign static item",
2227 ForeignItemKind::Ty => "foreign type",
2228 ForeignItemKind::Macro(..) => "macro in foreign module",
2238 // are ASTs encodable?
2240 fn check_asts_encodable() {
2241 fn assert_encodable<T: serialize::Encodable>() {}
2242 assert_encodable::<Crate>();