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::TyParamBound::*;
14 pub use self::UnsafeSource::*;
15 pub use self::PathParameters::*;
16 pub use symbol::{Ident, Symbol as Name};
17 pub use util::ThinVec;
18 pub use util::parser::ExprPrecedence;
20 use syntax_pos::{Span, DUMMY_SP};
21 use codemap::{respan, Spanned};
23 use ext::hygiene::{Mark, SyntaxContext};
26 use rustc_data_structures::indexed_vec;
27 use symbol::{Symbol, keywords};
28 use tokenstream::{ThinTokenStream, TokenStream};
30 use serialize::{self, Encoder, Decoder};
31 use std::collections::HashSet;
33 use rustc_data_structures::sync::Lrc;
36 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, 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, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
55 impl fmt::Debug for Lifetime {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
61 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
62 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
63 pub struct LifetimeDef {
64 pub attrs: ThinVec<Attribute>,
65 pub lifetime: Lifetime,
66 pub bounds: Vec<Lifetime>
69 /// A "Path" is essentially Rust's notion of a name.
71 /// It's represented as a sequence of identifiers,
72 /// along with a bunch of supporting information.
74 /// E.g. `std::cmp::PartialEq`
75 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
78 /// The segments in the path: the things separated by `::`.
79 /// Global paths begin with `keywords::CrateRoot`.
80 pub segments: Vec<PathSegment>,
83 impl<'a> PartialEq<&'a str> for Path {
84 fn eq(&self, string: &&'a str) -> bool {
85 self.segments.len() == 1 && self.segments[0].identifier.name == *string
89 impl fmt::Debug for Path {
90 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
91 write!(f, "path({})", pprust::path_to_string(self))
95 impl fmt::Display for Path {
96 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97 write!(f, "{}", pprust::path_to_string(self))
102 // convert a span and an identifier to the corresponding
104 pub fn from_ident(s: Span, identifier: Ident) -> Path {
107 segments: vec![PathSegment::from_ident(identifier, s)],
111 // Make a "crate root" segment for this path unless it already has it
112 // or starts with something like `self`/`super`/`$crate`/etc.
113 pub fn make_root(&self) -> Option<PathSegment> {
114 if let Some(ident) = self.segments.get(0).map(|seg| seg.identifier) {
115 if ::parse::token::is_path_segment_keyword(ident) &&
116 ident.name != keywords::Crate.name() {
120 Some(PathSegment::crate_root(self.span.shrink_to_lo()))
123 pub fn is_global(&self) -> bool {
124 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
128 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
130 /// E.g. `std`, `String` or `Box<T>`
131 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
132 pub struct PathSegment {
133 /// The identifier portion of this path segment.
134 pub identifier: Ident,
135 /// Span of the segment identifier.
138 /// Type/lifetime parameters attached to this path. They come in
139 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
140 /// `None` means that no parameter list is supplied (`Path`),
141 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
142 /// but it can be empty (`Path<>`).
143 /// `P` is used as a size optimization for the common case with no parameters.
144 pub parameters: Option<P<PathParameters>>,
148 pub fn from_ident(ident: Ident, span: Span) -> Self {
149 PathSegment { identifier: ident, span: span, parameters: None }
151 pub fn crate_root(span: Span) -> Self {
153 identifier: Ident::new(keywords::CrateRoot.name(), span),
160 /// Parameters of a path segment.
162 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
163 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
164 pub enum PathParameters {
165 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
166 AngleBracketed(AngleBracketedParameterData),
167 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
168 Parenthesized(ParenthesizedParameterData),
171 impl PathParameters {
172 pub fn span(&self) -> Span {
174 AngleBracketed(ref data) => data.span,
175 Parenthesized(ref data) => data.span,
180 /// A path like `Foo<'a, T>`
181 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
182 pub struct AngleBracketedParameterData {
185 /// The lifetime parameters for this path segment.
186 pub lifetimes: Vec<Lifetime>,
187 /// The type parameters for this path segment, if present.
188 pub types: Vec<P<Ty>>,
189 /// Bindings (equality constraints) on associated types, if present.
191 /// E.g., `Foo<A=Bar>`.
192 pub bindings: Vec<TypeBinding>,
195 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
196 fn into(self) -> Option<P<PathParameters>> {
197 Some(P(PathParameters::AngleBracketed(self)))
201 impl Into<Option<P<PathParameters>>> for ParenthesizedParameterData {
202 fn into(self) -> Option<P<PathParameters>> {
203 Some(P(PathParameters::Parenthesized(self)))
207 /// A path like `Foo(A,B) -> C`
208 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
209 pub struct ParenthesizedParameterData {
214 pub inputs: Vec<P<Ty>>,
217 pub output: Option<P<Ty>>,
220 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
221 pub struct NodeId(u32);
224 pub fn new(x: usize) -> NodeId {
225 assert!(x < (u32::MAX as usize));
229 pub fn from_u32(x: u32) -> NodeId {
233 pub fn as_usize(&self) -> usize {
237 pub fn as_u32(&self) -> u32 {
241 pub fn placeholder_from_mark(mark: Mark) -> Self {
242 NodeId(mark.as_u32())
245 pub fn placeholder_to_mark(self) -> Mark {
246 Mark::from_u32(self.0)
250 impl fmt::Display for NodeId {
251 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
252 fmt::Display::fmt(&self.0, f)
256 impl serialize::UseSpecializedEncodable for NodeId {
257 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
262 impl serialize::UseSpecializedDecodable for NodeId {
263 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
264 d.read_u32().map(NodeId)
268 impl indexed_vec::Idx for NodeId {
269 fn new(idx: usize) -> Self {
273 fn index(self) -> usize {
278 /// Node id used to represent the root of the crate.
279 pub const CRATE_NODE_ID: NodeId = NodeId(0);
281 /// When parsing and doing expansions, we initially give all AST nodes this AST
282 /// node value. Then later, in the renumber pass, we renumber them to have
283 /// small, positive ids.
284 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
286 /// The AST represents all type param bounds as types.
287 /// typeck::collect::compute_bounds matches these against
288 /// the "special" built-in traits (see middle::lang_items) and
289 /// detects Copy, Send and Sync.
290 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
291 pub enum TyParamBound {
292 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
293 RegionTyParamBound(Lifetime)
297 pub fn span(&self) -> Span {
299 &TraitTyParamBound(ref t, ..) => t.span,
300 &RegionTyParamBound(ref l) => l.span,
305 /// A modifier on a bound, currently this is only used for `?Sized`, where the
306 /// modifier is `Maybe`. Negative bounds should also be handled here.
307 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
308 pub enum TraitBoundModifier {
313 pub type TyParamBounds = Vec<TyParamBound>;
315 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
317 pub attrs: ThinVec<Attribute>,
320 pub bounds: TyParamBounds,
321 pub default: Option<P<Ty>>,
325 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
326 pub enum GenericParam {
327 Lifetime(LifetimeDef),
332 pub fn is_lifetime_param(&self) -> bool {
334 GenericParam::Lifetime(_) => true,
339 pub fn is_type_param(&self) -> bool {
341 GenericParam::Type(_) => true,
347 /// Represents lifetime, type and const parameters attached to a declaration of
348 /// a function, enum, trait, etc.
349 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
350 pub struct Generics {
351 pub params: Vec<GenericParam>,
352 pub where_clause: WhereClause,
357 pub fn is_lt_parameterized(&self) -> bool {
358 self.params.iter().any(|param| param.is_lifetime_param())
361 pub fn is_type_parameterized(&self) -> bool {
362 self.params.iter().any(|param| param.is_type_param())
365 pub fn is_parameterized(&self) -> bool {
366 !self.params.is_empty()
369 pub fn span_for_name(&self, name: &str) -> Option<Span> {
370 for param in &self.params {
371 if let GenericParam::Type(ref t) = *param {
372 if t.ident.name == name {
381 impl Default for Generics {
382 /// Creates an instance of `Generics`.
383 fn default() -> Generics {
386 where_clause: WhereClause {
388 predicates: Vec::new(),
396 /// A `where` clause in a definition
397 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
398 pub struct WhereClause {
400 pub predicates: Vec<WherePredicate>,
404 /// A single predicate in a `where` clause
405 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
406 pub enum WherePredicate {
407 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
408 BoundPredicate(WhereBoundPredicate),
409 /// A lifetime predicate, e.g. `'a: 'b+'c`
410 RegionPredicate(WhereRegionPredicate),
411 /// An equality predicate (unsupported)
412 EqPredicate(WhereEqPredicate),
415 impl WherePredicate {
416 pub fn span(&self) -> Span {
418 &WherePredicate::BoundPredicate(ref p) => p.span,
419 &WherePredicate::RegionPredicate(ref p) => p.span,
420 &WherePredicate::EqPredicate(ref p) => p.span,
427 /// E.g. `for<'c> Foo: Send+Clone+'c`
428 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
429 pub struct WhereBoundPredicate {
431 /// Any generics from a `for` binding
432 pub bound_generic_params: Vec<GenericParam>,
433 /// The type being bounded
434 pub bounded_ty: P<Ty>,
435 /// Trait and lifetime bounds (`Clone+Send+'static`)
436 pub bounds: TyParamBounds,
439 /// A lifetime predicate.
442 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
443 pub struct WhereRegionPredicate {
445 pub lifetime: Lifetime,
446 pub bounds: Vec<Lifetime>,
449 /// An equality predicate (unsupported).
452 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
453 pub struct WhereEqPredicate {
460 /// The set of MetaItems that define the compilation environment of the crate,
461 /// used to drive conditional compilation
462 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
464 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
467 pub attrs: Vec<Attribute>,
471 /// A spanned compile-time attribute list item.
472 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
474 /// Possible values inside of compile-time attribute lists.
476 /// E.g. the '..' in `#[name(..)]`.
477 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
478 pub enum NestedMetaItemKind {
479 /// A full MetaItem, for recursive meta items.
483 /// E.g. "foo", 64, true
487 /// A spanned compile-time attribute item.
489 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
490 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
491 pub struct MetaItem {
493 pub node: MetaItemKind,
497 /// A compile-time attribute item.
499 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
500 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
501 pub enum MetaItemKind {
504 /// E.g. `test` as in `#[test]`
508 /// E.g. `derive(..)` as in `#[derive(..)]`
509 List(Vec<NestedMetaItem>),
510 /// Name value meta item.
512 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
516 /// A Block (`{ .. }`).
518 /// E.g. `{ .. }` as in `fn foo() { .. }`
519 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
521 /// Statements in a block
522 pub stmts: Vec<Stmt>,
524 /// Distinguishes between `unsafe { ... }` and `{ ... }`
525 pub rules: BlockCheckMode,
530 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
537 impl fmt::Debug for Pat {
538 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
539 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
544 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
545 let node = match &self.node {
546 PatKind::Wild => TyKind::Infer,
547 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) =>
548 TyKind::Path(None, Path::from_ident(ident.span, ident.node)),
549 PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
550 PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
551 PatKind::Ref(pat, mutbl) =>
552 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
553 PatKind::Slice(pats, None, _) if pats.len() == 1 =>
554 pats[0].to_ty().map(TyKind::Slice)?,
555 PatKind::Tuple(pats, None) => {
556 let mut tys = Vec::new();
558 tys.push(pat.to_ty()?);
565 Some(P(Ty { node, id: self.id, span: self.span }))
568 pub fn walk<F>(&self, it: &mut F) -> bool
569 where F: FnMut(&Pat) -> bool
576 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
577 PatKind::Struct(_, ref fields, _) => {
578 fields.iter().all(|field| field.node.pat.walk(it))
580 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
581 s.iter().all(|p| p.walk(it))
583 PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => {
586 PatKind::Slice(ref before, ref slice, ref after) => {
587 before.iter().all(|p| p.walk(it)) &&
588 slice.iter().all(|p| p.walk(it)) &&
589 after.iter().all(|p| p.walk(it))
603 /// A single field in a struct pattern
605 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
606 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
607 /// except is_shorthand is true
608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
609 pub struct FieldPat {
610 /// The identifier for the field
612 /// The pattern the field is destructured to
614 pub is_shorthand: bool,
615 pub attrs: ThinVec<Attribute>,
618 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
619 pub enum BindingMode {
624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
626 Included(RangeSyntax),
630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
631 pub enum RangeSyntax {
636 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
638 /// Represents a wildcard pattern (`_`)
641 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
642 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
643 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
644 /// during name resolution.
645 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
647 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
648 /// The `bool` is `true` in the presence of a `..`.
649 Struct(Path, Vec<Spanned<FieldPat>>, bool),
651 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
652 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
653 /// 0 <= position <= subpats.len()
654 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
656 /// A possibly qualified path pattern.
657 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
658 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
659 /// only legally refer to associated constants.
660 Path(Option<QSelf>, Path),
662 /// A tuple pattern `(a, b)`.
663 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
664 /// 0 <= position <= subpats.len()
665 Tuple(Vec<P<Pat>>, Option<usize>),
668 /// A reference pattern, e.g. `&mut (a, b)`
669 Ref(P<Pat>, Mutability),
672 /// A range pattern, e.g. `1...2`, `1..=2` or `1..2`
673 Range(P<Expr>, P<Expr>, RangeEnd),
674 /// `[a, b, ..i, y, z]` is represented as:
675 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
676 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
677 /// Parentheses in patters used for grouping, i.e. `(PAT)`.
679 /// A macro pattern; pre-expansion
683 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
684 pub enum Mutability {
689 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
691 /// The `+` operator (addition)
693 /// The `-` operator (subtraction)
695 /// The `*` operator (multiplication)
697 /// The `/` operator (division)
699 /// The `%` operator (modulus)
701 /// The `&&` operator (logical and)
703 /// The `||` operator (logical or)
705 /// The `^` operator (bitwise xor)
707 /// The `&` operator (bitwise and)
709 /// The `|` operator (bitwise or)
711 /// The `<<` operator (shift left)
713 /// The `>>` operator (shift right)
715 /// The `==` operator (equality)
717 /// The `<` operator (less than)
719 /// The `<=` operator (less than or equal to)
721 /// The `!=` operator (not equal to)
723 /// The `>=` operator (greater than or equal to)
725 /// The `>` operator (greater than)
730 pub fn to_string(&self) -> &'static str {
731 use self::BinOpKind::*;
753 pub fn lazy(&self) -> bool {
755 BinOpKind::And | BinOpKind::Or => true,
760 pub fn is_shift(&self) -> bool {
762 BinOpKind::Shl | BinOpKind::Shr => true,
767 pub fn is_comparison(&self) -> bool {
768 use self::BinOpKind::*;
770 Eq | Lt | Le | Ne | Gt | Ge =>
772 And | Or | Add | Sub | Mul | Div | Rem |
773 BitXor | BitAnd | BitOr | Shl | Shr =>
778 /// Returns `true` if the binary operator takes its arguments by value
779 pub fn is_by_value(&self) -> bool {
780 !self.is_comparison()
784 pub type BinOp = Spanned<BinOpKind>;
786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
788 /// The `*` operator for dereferencing
790 /// The `!` operator for logical inversion
792 /// The `-` operator for negation
797 /// Returns `true` if the unary operator takes its argument by value
798 pub fn is_by_value(u: UnOp) -> bool {
800 UnOp::Neg | UnOp::Not => true,
805 pub fn to_string(op: UnOp) -> &'static str {
815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
823 pub fn add_trailing_semicolon(mut self) -> Self {
824 self.node = match self.node {
825 StmtKind::Expr(expr) => StmtKind::Semi(expr),
826 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
827 (mac, MacStmtStyle::Semicolon, attrs)
834 pub fn is_item(&self) -> bool {
836 StmtKind::Local(_) => true,
841 pub fn is_expr(&self) -> bool {
843 StmtKind::Expr(_) => true,
849 impl fmt::Debug for Stmt {
850 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
851 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
856 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
858 /// A local (let) binding.
861 /// An item definition.
864 /// Expr without trailing semi-colon.
866 /// Expr with a trailing semi-colon.
869 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
872 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
873 pub enum MacStmtStyle {
874 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
875 /// `foo!(...);`, `foo![...];`
877 /// The macro statement had braces; e.g. foo! { ... }
879 /// The macro statement had parentheses or brackets and no semicolon; e.g.
880 /// `foo!(...)`. All of these will end up being converted into macro
885 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
886 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
889 pub ty: Option<P<Ty>>,
890 /// Initializer expression to set the value, if any
891 pub init: Option<P<Expr>>,
894 pub attrs: ThinVec<Attribute>,
897 /// An arm of a 'match'.
899 /// E.g. `0...10 => { println!("match!") }` as in
903 /// 0...10 => { println!("match!") },
904 /// _ => { println!("no match!") },
907 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
909 pub attrs: Vec<Attribute>,
910 pub pats: Vec<P<Pat>>,
911 pub guard: Option<P<Expr>>,
915 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
917 pub ident: SpannedIdent,
920 pub is_shorthand: bool,
921 pub attrs: ThinVec<Attribute>,
924 pub type SpannedIdent = Spanned<Ident>;
926 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
927 pub enum BlockCheckMode {
929 Unsafe(UnsafeSource),
932 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
933 pub enum UnsafeSource {
939 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
944 pub attrs: ThinVec<Attribute>
948 /// Whether this expression would be valid somewhere that expects a value, for example, an `if`
950 pub fn returns(&self) -> bool {
951 if let ExprKind::Block(ref block) = self.node {
952 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
954 Some(&StmtKind::Expr(_)) => true,
955 Some(&StmtKind::Semi(ref expr)) => {
956 if let ExprKind::Ret(_) = expr.node {
957 // last statement is explicit return
963 // This is a block that doesn't end in either an implicit or explicit return
967 // This is not a block, it is a value
972 fn to_bound(&self) -> Option<TyParamBound> {
974 ExprKind::Path(None, path) =>
975 Some(TraitTyParamBound(PolyTraitRef::new(Vec::new(), path.clone(), self.span),
976 TraitBoundModifier::None)),
981 pub(super) fn to_ty(&self) -> Option<P<Ty>> {
982 let node = match &self.node {
983 ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
984 ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
985 ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
986 ExprKind::AddrOf(mutbl, expr) =>
987 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
988 ExprKind::Repeat(expr, expr_len) =>
989 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?,
990 ExprKind::Array(exprs) if exprs.len() == 1 =>
991 exprs[0].to_ty().map(TyKind::Slice)?,
992 ExprKind::Tup(exprs) => {
993 let mut tys = Vec::new();
995 tys.push(expr.to_ty()?);
999 ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add =>
1000 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1001 TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1008 Some(P(Ty { node, id: self.id, span: self.span }))
1011 pub fn precedence(&self) -> ExprPrecedence {
1013 ExprKind::Box(_) => ExprPrecedence::Box,
1014 ExprKind::Array(_) => ExprPrecedence::Array,
1015 ExprKind::Call(..) => ExprPrecedence::Call,
1016 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1017 ExprKind::Tup(_) => ExprPrecedence::Tup,
1018 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1019 ExprKind::Unary(..) => ExprPrecedence::Unary,
1020 ExprKind::Lit(_) => ExprPrecedence::Lit,
1021 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1022 ExprKind::If(..) => ExprPrecedence::If,
1023 ExprKind::IfLet(..) => ExprPrecedence::IfLet,
1024 ExprKind::While(..) => ExprPrecedence::While,
1025 ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
1026 ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1027 ExprKind::Loop(..) => ExprPrecedence::Loop,
1028 ExprKind::Match(..) => ExprPrecedence::Match,
1029 ExprKind::Closure(..) => ExprPrecedence::Closure,
1030 ExprKind::Block(..) => ExprPrecedence::Block,
1031 ExprKind::Catch(..) => ExprPrecedence::Catch,
1032 ExprKind::Assign(..) => ExprPrecedence::Assign,
1033 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1034 ExprKind::Field(..) => ExprPrecedence::Field,
1035 ExprKind::TupField(..) => ExprPrecedence::TupField,
1036 ExprKind::Index(..) => ExprPrecedence::Index,
1037 ExprKind::Range(..) => ExprPrecedence::Range,
1038 ExprKind::Path(..) => ExprPrecedence::Path,
1039 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1040 ExprKind::Break(..) => ExprPrecedence::Break,
1041 ExprKind::Continue(..) => ExprPrecedence::Continue,
1042 ExprKind::Ret(..) => ExprPrecedence::Ret,
1043 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1044 ExprKind::Mac(..) => ExprPrecedence::Mac,
1045 ExprKind::Struct(..) => ExprPrecedence::Struct,
1046 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1047 ExprKind::Paren(..) => ExprPrecedence::Paren,
1048 ExprKind::Try(..) => ExprPrecedence::Try,
1049 ExprKind::Yield(..) => ExprPrecedence::Yield,
1054 impl fmt::Debug for Expr {
1055 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1056 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1060 /// Limit types of a range (inclusive or exclusive)
1061 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1062 pub enum RangeLimits {
1063 /// Inclusive at the beginning, exclusive at the end
1065 /// Inclusive at the beginning and end
1069 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1071 /// A `box x` expression.
1073 /// An array (`[a, b, c, d]`)
1074 Array(Vec<P<Expr>>),
1077 /// The first field resolves to the function itself,
1078 /// and the second field is the list of arguments.
1079 /// This also represents calling the constructor of
1080 /// tuple-like ADTs such as tuple structs and enum variants.
1081 Call(P<Expr>, Vec<P<Expr>>),
1082 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1084 /// The `PathSegment` represents the method name and its generic arguments
1085 /// (within the angle brackets).
1086 /// The first element of the vector of `Expr`s is the expression that evaluates
1087 /// to the object on which the method is being called on (the receiver),
1088 /// and the remaining elements are the rest of the arguments.
1089 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1090 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1091 MethodCall(PathSegment, Vec<P<Expr>>),
1092 /// A tuple (`(a, b, c ,d)`)
1094 /// A binary operation (For example: `a + b`, `a * b`)
1095 Binary(BinOp, P<Expr>, P<Expr>),
1096 /// A unary operation (For example: `!x`, `*x`)
1097 Unary(UnOp, P<Expr>),
1098 /// A literal (For example: `1`, `"foo"`)
1100 /// A cast (`foo as f64`)
1101 Cast(P<Expr>, P<Ty>),
1102 Type(P<Expr>, P<Ty>),
1103 /// An `if` block, with an optional else block
1105 /// `if expr { block } else { expr }`
1106 If(P<Expr>, P<Block>, Option<P<Expr>>),
1107 /// An `if let` expression with an optional else block
1109 /// `if let pat = expr { block } else { expr }`
1111 /// This is desugared to a `match` expression.
1112 IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
1113 /// A while loop, with an optional label
1115 /// `'label: while expr { block }`
1116 While(P<Expr>, P<Block>, Option<Label>),
1117 /// A while-let loop, with an optional label
1119 /// `'label: while let pat = expr { block }`
1121 /// This is desugared to a combination of `loop` and `match` expressions.
1122 WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
1123 /// A for loop, with an optional label
1125 /// `'label: for pat in expr { block }`
1127 /// This is desugared to a combination of `loop` and `match` expressions.
1128 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1129 /// Conditionless loop (can be exited with break, continue, or return)
1131 /// `'label: loop { block }`
1132 Loop(P<Block>, Option<Label>),
1133 /// A `match` block.
1134 Match(P<Expr>, Vec<Arm>),
1135 /// A closure (for example, `move |a, b, c| a + b + c`)
1137 /// The final span is the span of the argument block `|...|`
1138 Closure(CaptureBy, Movability, P<FnDecl>, P<Expr>, Span),
1139 /// A block (`{ ... }`)
1141 /// A catch block (`catch { ... }`)
1144 /// An assignment (`a = foo()`)
1145 Assign(P<Expr>, P<Expr>),
1146 /// An assignment with an operator
1148 /// For example, `a += 1`.
1149 AssignOp(BinOp, P<Expr>, P<Expr>),
1150 /// Access of a named struct field (`obj.foo`)
1151 Field(P<Expr>, SpannedIdent),
1152 /// Access of an unnamed field of a struct or tuple-struct
1154 /// For example, `foo.0`.
1155 TupField(P<Expr>, Spanned<usize>),
1156 /// An indexing operation (`foo[2]`)
1157 Index(P<Expr>, P<Expr>),
1158 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
1159 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1161 /// Variable reference, possibly containing `::` and/or type
1162 /// parameters, e.g. foo::bar::<baz>.
1164 /// Optionally "qualified",
1165 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1166 Path(Option<QSelf>, Path),
1168 /// A referencing operation (`&a` or `&mut a`)
1169 AddrOf(Mutability, P<Expr>),
1170 /// A `break`, with an optional label to break, and an optional expression
1171 Break(Option<Label>, Option<P<Expr>>),
1172 /// A `continue`, with an optional label
1173 Continue(Option<Label>),
1174 /// A `return`, with an optional value to be returned
1175 Ret(Option<P<Expr>>),
1177 /// Output of the `asm!()` macro
1178 InlineAsm(P<InlineAsm>),
1180 /// A macro invocation; pre-expansion
1183 /// A struct literal expression.
1185 /// For example, `Foo {x: 1, y: 2}`, or
1186 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1187 Struct(Path, Vec<Field>, Option<P<Expr>>),
1189 /// An array literal constructed from one repeated element.
1191 /// For example, `[1; 5]`. The first expression is the element
1192 /// to be repeated; the second is the number of times to repeat it.
1193 Repeat(P<Expr>, P<Expr>),
1195 /// No-op: used solely so we can pretty-print faithfully
1201 /// A `yield`, with an optional value to be yielded
1202 Yield(Option<P<Expr>>),
1205 /// The explicit Self type in a "qualified path". The actual
1206 /// path, including the trait and the associated item, is stored
1207 /// separately. `position` represents the index of the associated
1208 /// item qualified with this Self type.
1210 /// ```ignore (only-for-syntax-highlight)
1211 /// <Vec<T> as a::b::Trait>::AssociatedItem
1212 /// ^~~~~ ~~~~~~~~~~~~~~^
1215 /// <Vec<T>>::AssociatedItem
1219 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1225 /// A capture clause
1226 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1227 pub enum CaptureBy {
1232 /// The movability of a generator / closure literal
1233 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1234 pub enum Movability {
1239 pub type Mac = Spanned<Mac_>;
1241 /// Represents a macro invocation. The Path indicates which macro
1242 /// is being invoked, and the vector of token-trees contains the source
1243 /// of the macro invocation.
1245 /// NB: the additional ident for a macro_rules-style macro is actually
1246 /// stored in the enclosing item. Oog.
1247 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1250 pub tts: ThinTokenStream,
1254 pub fn stream(&self) -> TokenStream {
1255 self.tts.clone().into()
1259 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1260 pub struct MacroDef {
1261 pub tokens: ThinTokenStream,
1266 pub fn stream(&self) -> TokenStream {
1267 self.tokens.clone().into()
1271 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1273 /// A regular string, like `"foo"`
1275 /// A raw string, like `r##"foo"##`
1277 /// The uint is the number of `#` symbols used
1282 pub type Lit = Spanned<LitKind>;
1284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1285 pub enum LitIntType {
1293 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1294 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1296 /// A string literal (`"foo"`)
1297 Str(Symbol, StrStyle),
1298 /// A byte string (`b"foo"`)
1299 ByteStr(Lrc<Vec<u8>>),
1300 /// A byte char (`b'f'`)
1302 /// A character literal (`'a'`)
1304 /// An integer literal (`1`)
1305 Int(u128, LitIntType),
1306 /// A float literal (`1f64` or `1E10f64`)
1307 Float(Symbol, FloatTy),
1308 /// A float literal without a suffix (`1.0 or 1.0E10`)
1309 FloatUnsuffixed(Symbol),
1310 /// A boolean literal
1315 /// Returns true if this literal is a string and false otherwise.
1316 pub fn is_str(&self) -> bool {
1318 LitKind::Str(..) => true,
1323 /// Returns true if this literal has no suffix. Note: this will return true
1324 /// for literals with prefixes such as raw strings and byte strings.
1325 pub fn is_unsuffixed(&self) -> bool {
1327 // unsuffixed variants
1329 LitKind::ByteStr(..) |
1332 LitKind::Int(_, LitIntType::Unsuffixed) |
1333 LitKind::FloatUnsuffixed(..) |
1334 LitKind::Bool(..) => true,
1335 // suffixed variants
1336 LitKind::Int(_, LitIntType::Signed(..)) |
1337 LitKind::Int(_, LitIntType::Unsigned(..)) |
1338 LitKind::Float(..) => false,
1342 /// Returns true if this literal has a suffix.
1343 pub fn is_suffixed(&self) -> bool {
1344 !self.is_unsuffixed()
1348 // NB: If you change this, you'll probably want to change the corresponding
1349 // type structure in middle/ty.rs as well.
1350 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1353 pub mutbl: Mutability,
1356 /// Represents a method's signature in a trait declaration,
1357 /// or in an implementation.
1358 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1359 pub struct MethodSig {
1360 pub unsafety: Unsafety,
1361 pub constness: Spanned<Constness>,
1363 pub decl: P<FnDecl>,
1366 /// Represents an item declaration within a trait declaration,
1367 /// possibly including a default implementation. A trait item is
1368 /// either required (meaning it doesn't have an implementation, just a
1369 /// signature) or provided (meaning it has a default implementation).
1370 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1371 pub struct TraitItem {
1374 pub attrs: Vec<Attribute>,
1375 pub generics: Generics,
1376 pub node: TraitItemKind,
1378 /// See `Item::tokens` for what this is
1379 pub tokens: Option<TokenStream>,
1382 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1383 pub enum TraitItemKind {
1384 Const(P<Ty>, Option<P<Expr>>),
1385 Method(MethodSig, Option<P<Block>>),
1386 Type(TyParamBounds, Option<P<Ty>>),
1390 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1391 pub struct ImplItem {
1394 pub vis: Visibility,
1395 pub defaultness: Defaultness,
1396 pub attrs: Vec<Attribute>,
1397 pub generics: Generics,
1398 pub node: ImplItemKind,
1400 /// See `Item::tokens` for what this is
1401 pub tokens: Option<TokenStream>,
1404 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1405 pub enum ImplItemKind {
1406 Const(P<Ty>, P<Expr>),
1407 Method(MethodSig, P<Block>),
1412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1423 impl fmt::Debug for IntTy {
1424 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1425 fmt::Display::fmt(self, f)
1429 impl fmt::Display for IntTy {
1430 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1431 write!(f, "{}", self.ty_to_string())
1436 pub fn ty_to_string(&self) -> &'static str {
1438 IntTy::Isize => "isize",
1440 IntTy::I16 => "i16",
1441 IntTy::I32 => "i32",
1442 IntTy::I64 => "i64",
1443 IntTy::I128 => "i128",
1447 pub fn val_to_string(&self, val: i128) -> String {
1448 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1449 // are parsed as u128, so we wouldn't want to print an extra negative
1451 format!("{}{}", val as u128, self.ty_to_string())
1454 pub fn bit_width(&self) -> Option<usize> {
1456 IntTy::Isize => return None,
1466 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1478 pub fn ty_to_string(&self) -> &'static str {
1480 UintTy::Usize => "usize",
1482 UintTy::U16 => "u16",
1483 UintTy::U32 => "u32",
1484 UintTy::U64 => "u64",
1485 UintTy::U128 => "u128",
1489 pub fn val_to_string(&self, val: u128) -> String {
1490 format!("{}{}", val, self.ty_to_string())
1493 pub fn bit_width(&self) -> Option<usize> {
1495 UintTy::Usize => return None,
1500 UintTy::U128 => 128,
1505 impl fmt::Debug for UintTy {
1506 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1507 fmt::Display::fmt(self, f)
1511 impl fmt::Display for UintTy {
1512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1513 write!(f, "{}", self.ty_to_string())
1517 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1524 impl fmt::Debug for FloatTy {
1525 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1526 fmt::Display::fmt(self, f)
1530 impl fmt::Display for FloatTy {
1531 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1532 write!(f, "{}", self.ty_to_string())
1537 pub fn ty_to_string(&self) -> &'static str {
1539 FloatTy::F32 => "f32",
1540 FloatTy::F64 => "f64",
1544 pub fn bit_width(&self) -> usize {
1552 // Bind a type to an associated type: `A=Foo`.
1553 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1554 pub struct TypeBinding {
1561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1568 impl fmt::Debug for Ty {
1569 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1570 write!(f, "type({})", pprust::ty_to_string(self))
1574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1575 pub struct BareFnTy {
1576 pub unsafety: Unsafety,
1578 pub generic_params: Vec<GenericParam>,
1582 /// The different kinds of types recognized by the compiler
1583 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1585 /// A variable-length slice (`[T]`)
1587 /// A fixed length array (`[T; n]`)
1588 Array(P<Ty>, P<Expr>),
1589 /// A raw pointer (`*const T` or `*mut T`)
1591 /// A reference (`&'a T` or `&'a mut T`)
1592 Rptr(Option<Lifetime>, MutTy),
1593 /// A bare function (e.g. `fn(usize) -> bool`)
1594 BareFn(P<BareFnTy>),
1595 /// The never type (`!`)
1597 /// A tuple (`(A, B, C, D,...)`)
1599 /// A path (`module::module::...::Type`), optionally
1600 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1602 /// Type parameters are stored in the Path itself
1603 Path(Option<QSelf>, Path),
1604 /// A trait object type `Bound1 + Bound2 + Bound3`
1605 /// where `Bound` is a trait or a lifetime.
1606 TraitObject(TyParamBounds, TraitObjectSyntax),
1607 /// An `impl Bound1 + Bound2 + Bound3` type
1608 /// where `Bound` is a trait or a lifetime.
1609 ImplTrait(TyParamBounds),
1610 /// No-op; kept solely so that we can pretty-print faithfully
1614 /// TyKind::Infer means the type should be inferred instead of it having been
1615 /// specified. This can appear anywhere in a type.
1617 /// Inferred type of a `self` or `&self` argument in a method.
1619 // A macro in the type position.
1621 /// Placeholder for a kind that has failed to be defined.
1625 /// Syntax used to declare a trait object.
1626 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1627 pub enum TraitObjectSyntax {
1632 /// Inline assembly dialect.
1634 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1636 pub enum AsmDialect {
1641 /// Inline assembly.
1643 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
1644 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1645 pub struct InlineAsmOutput {
1646 pub constraint: Symbol,
1649 pub is_indirect: bool,
1652 /// Inline assembly.
1654 /// E.g. `asm!("NOP");`
1655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1656 pub struct InlineAsm {
1658 pub asm_str_style: StrStyle,
1659 pub outputs: Vec<InlineAsmOutput>,
1660 pub inputs: Vec<(Symbol, P<Expr>)>,
1661 pub clobbers: Vec<Symbol>,
1663 pub alignstack: bool,
1664 pub dialect: AsmDialect,
1665 pub ctxt: SyntaxContext,
1668 /// An argument in a function header.
1670 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1680 /// E.g. `&mut self` as in `fn foo(&mut self)`
1681 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1683 /// `self`, `mut self`
1685 /// `&'lt self`, `&'lt mut self`
1686 Region(Option<Lifetime>, Mutability),
1687 /// `self: TYPE`, `mut self: TYPE`
1688 Explicit(P<Ty>, Mutability),
1691 pub type ExplicitSelf = Spanned<SelfKind>;
1694 pub fn to_self(&self) -> Option<ExplicitSelf> {
1695 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1696 if ident.node.name == keywords::SelfValue.name() {
1697 return match self.ty.node {
1698 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1699 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1700 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1702 _ => Some(respan(self.pat.span.to(self.ty.span),
1703 SelfKind::Explicit(self.ty.clone(), mutbl))),
1710 pub fn is_self(&self) -> bool {
1711 if let PatKind::Ident(_, ident, _) = self.pat.node {
1712 ident.node.name == keywords::SelfValue.name()
1718 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1719 let span = eself.span.to(eself_ident.span);
1720 let infer_ty = P(Ty {
1722 node: TyKind::ImplicitSelf,
1725 let arg = |mutbl, ty| Arg {
1728 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1735 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1736 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1737 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1739 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1746 /// Header (not the body) of a function declaration.
1748 /// E.g. `fn foo(bar: baz)`
1749 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1751 pub inputs: Vec<Arg>,
1752 pub output: FunctionRetTy,
1757 pub fn get_self(&self) -> Option<ExplicitSelf> {
1758 self.inputs.get(0).and_then(Arg::to_self)
1760 pub fn has_self(&self) -> bool {
1761 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1765 /// Is the trait definition an auto trait?
1766 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1772 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1778 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1779 pub enum Constness {
1784 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1785 pub enum Defaultness {
1790 impl fmt::Display for Unsafety {
1791 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1792 fmt::Display::fmt(match *self {
1793 Unsafety::Normal => "normal",
1794 Unsafety::Unsafe => "unsafe",
1799 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1800 pub enum ImplPolarity {
1801 /// `impl Trait for Type`
1803 /// `impl !Trait for Type`
1807 impl fmt::Debug for ImplPolarity {
1808 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1810 ImplPolarity::Positive => "positive".fmt(f),
1811 ImplPolarity::Negative => "negative".fmt(f),
1817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1818 pub enum FunctionRetTy {
1819 /// Return type is not specified.
1821 /// Functions default to `()` and
1822 /// closures default to inference. Span points to where return
1823 /// type would be inserted.
1829 impl FunctionRetTy {
1830 pub fn span(&self) -> Span {
1832 FunctionRetTy::Default(span) => span,
1833 FunctionRetTy::Ty(ref ty) => ty.span,
1838 /// Module declaration.
1840 /// E.g. `mod foo;` or `mod foo { .. }`
1841 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1843 /// A span from the first token past `{` to the last token until `}`.
1844 /// For `mod foo;`, the inner span ranges from the first token
1845 /// to the last token in the external file.
1847 pub items: Vec<P<Item>>,
1850 /// Foreign module declaration.
1852 /// E.g. `extern { .. }` or `extern C { .. }`
1853 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1854 pub struct ForeignMod {
1856 pub items: Vec<ForeignItem>,
1859 /// Global inline assembly
1861 /// aka module-level assembly or file-scoped assembly
1862 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1863 pub struct GlobalAsm {
1865 pub ctxt: SyntaxContext,
1868 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1869 pub struct EnumDef {
1870 pub variants: Vec<Variant>,
1873 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1874 pub struct Variant_ {
1876 pub attrs: Vec<Attribute>,
1877 pub data: VariantData,
1878 /// Explicit discriminant, e.g. `Foo = 1`
1879 pub disr_expr: Option<P<Expr>>,
1882 pub type Variant = Spanned<Variant_>;
1884 /// Part of `use` item to the right of its prefix.
1885 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1886 pub enum UseTreeKind {
1887 /// `use prefix` or `use prefix as rename`
1888 Simple(Option<Ident>),
1889 /// `use prefix::{...}`
1890 Nested(Vec<(UseTree, NodeId)>),
1895 /// A tree of paths sharing common prefixes.
1896 /// Used in `use` items both at top-level and inside of braces in import groups.
1897 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1898 pub struct UseTree {
1900 pub kind: UseTreeKind,
1905 pub fn ident(&self) -> Ident {
1907 UseTreeKind::Simple(Some(rename)) => rename,
1908 UseTreeKind::Simple(None) =>
1909 self.prefix.segments.last().expect("empty prefix in a simple import").identifier,
1910 _ => panic!("`UseTree::ident` can only be used on a simple import"),
1915 /// Distinguishes between Attributes that decorate items and Attributes that
1916 /// are contained as statements within items. These two cases need to be
1917 /// distinguished for pretty-printing.
1918 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1919 pub enum AttrStyle {
1924 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1925 pub struct AttrId(pub usize);
1927 /// Meta-data associated with an item
1928 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1929 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1930 pub struct Attribute {
1932 pub style: AttrStyle,
1934 pub tokens: TokenStream,
1935 pub is_sugared_doc: bool,
1939 /// TraitRef's appear in impls.
1941 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1942 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1943 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1944 /// same as the impl's node id).
1945 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1946 pub struct TraitRef {
1951 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1952 pub struct PolyTraitRef {
1953 /// The `'a` in `<'a> Foo<&'a T>`
1954 pub bound_generic_params: Vec<GenericParam>,
1956 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1957 pub trait_ref: TraitRef,
1963 pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
1965 bound_generic_params: generic_params,
1966 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1972 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1973 pub enum CrateSugar {
1974 /// Source is `pub(crate)`
1977 /// Source is (just) `crate`
1981 pub type Visibility = Spanned<VisibilityKind>;
1983 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1984 pub enum VisibilityKind {
1987 Restricted { path: P<Path>, id: NodeId },
1991 /// Field of a struct.
1993 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1994 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, 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, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, 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, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, 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 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2078 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2080 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2081 ExternCrate(Option<Name>),
2082 /// A use declaration (`use` or `pub use`) item.
2084 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
2086 /// A static item (`static` or `pub static`).
2088 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
2089 Static(P<Ty>, Mutability, P<Expr>),
2090 /// A constant item (`const` or `pub const`).
2092 /// E.g. `const FOO: i32 = 42;`
2093 Const(P<Ty>, P<Expr>),
2094 /// A function declaration (`fn` or `pub fn`).
2096 /// E.g. `fn foo(bar: usize) -> usize { .. }`
2097 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
2098 /// A module declaration (`mod` or `pub mod`).
2100 /// E.g. `mod foo;` or `mod foo { .. }`
2102 /// An external module (`extern` or `pub extern`).
2104 /// E.g. `extern {}` or `extern "C" {}`
2105 ForeignMod(ForeignMod),
2106 /// Module-level inline assembly (from `global_asm!()`)
2107 GlobalAsm(P<GlobalAsm>),
2108 /// A type alias (`type` or `pub type`).
2110 /// E.g. `type Foo = Bar<u8>;`
2111 Ty(P<Ty>, Generics),
2112 /// An enum definition (`enum` or `pub enum`).
2114 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
2115 Enum(EnumDef, Generics),
2116 /// A struct definition (`struct` or `pub struct`).
2118 /// E.g. `struct Foo<A> { x: A }`
2119 Struct(VariantData, Generics),
2120 /// A union definition (`union` or `pub union`).
2122 /// E.g. `union Foo<A, B> { x: A, y: B }`
2123 Union(VariantData, Generics),
2124 /// A Trait declaration (`trait` or `pub trait`).
2126 /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
2127 Trait(IsAuto, Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
2130 /// E.g. `trait Foo = Bar + Quux;`
2131 TraitAlias(Generics, TyParamBounds),
2132 /// An implementation.
2134 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
2139 Option<TraitRef>, // (optional) trait this impl implements
2142 /// A macro invocation.
2144 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
2147 /// A macro definition.
2152 pub fn descriptive_variant(&self) -> &str {
2154 ItemKind::ExternCrate(..) => "extern crate",
2155 ItemKind::Use(..) => "use",
2156 ItemKind::Static(..) => "static item",
2157 ItemKind::Const(..) => "constant item",
2158 ItemKind::Fn(..) => "function",
2159 ItemKind::Mod(..) => "module",
2160 ItemKind::ForeignMod(..) => "foreign module",
2161 ItemKind::GlobalAsm(..) => "global asm",
2162 ItemKind::Ty(..) => "type alias",
2163 ItemKind::Enum(..) => "enum",
2164 ItemKind::Struct(..) => "struct",
2165 ItemKind::Union(..) => "union",
2166 ItemKind::Trait(..) => "trait",
2167 ItemKind::TraitAlias(..) => "trait alias",
2169 ItemKind::MacroDef(..) |
2170 ItemKind::Impl(..) => "item"
2175 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2176 pub struct ForeignItem {
2178 pub attrs: Vec<Attribute>,
2179 pub node: ForeignItemKind,
2182 pub vis: Visibility,
2185 /// An item within an `extern` block
2186 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2187 pub enum ForeignItemKind {
2188 /// A foreign function
2189 Fn(P<FnDecl>, Generics),
2190 /// A foreign static item (`static ext: u8`), with optional mutability
2191 /// (the boolean is true when mutable)
2192 Static(P<Ty>, bool),
2195 /// A macro invocation
2199 impl ForeignItemKind {
2200 pub fn descriptive_variant(&self) -> &str {
2202 ForeignItemKind::Fn(..) => "foreign function",
2203 ForeignItemKind::Static(..) => "foreign static item",
2204 ForeignItemKind::Ty => "foreign type",
2205 ForeignItemKind::Macro(..) => "macro in foreign module",
2215 // are ASTs encodable?
2217 fn check_asts_encodable() {
2218 fn assert_encodable<T: serialize::Encodable>() {}
2219 assert_encodable::<Crate>();