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::ViewPath_::*;
16 pub use self::PathParameters::*;
17 pub use symbol::{Ident, Symbol as Name};
18 pub use util::ThinVec;
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;
36 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
43 impl fmt::Debug for Lifetime {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
49 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
50 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
51 pub struct LifetimeDef {
52 pub attrs: ThinVec<Attribute>,
53 pub lifetime: Lifetime,
54 pub bounds: Vec<Lifetime>
57 /// A "Path" is essentially Rust's notion of a name.
59 /// It's represented as a sequence of identifiers,
60 /// along with a bunch of supporting information.
62 /// E.g. `std::cmp::PartialEq`
63 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
66 /// The segments in the path: the things separated by `::`.
67 /// Global paths begin with `keywords::CrateRoot`.
68 pub segments: Vec<PathSegment>,
71 impl<'a> PartialEq<&'a str> for Path {
72 fn eq(&self, string: &&'a str) -> bool {
73 self.segments.len() == 1 && self.segments[0].identifier.name == *string
77 impl fmt::Debug for Path {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 write!(f, "path({})", pprust::path_to_string(self))
83 impl fmt::Display for Path {
84 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85 write!(f, "{}", pprust::path_to_string(self))
90 // convert a span and an identifier to the corresponding
92 pub fn from_ident(s: Span, identifier: Ident) -> Path {
95 segments: vec![PathSegment::from_ident(identifier, s)],
99 pub fn default_to_global(mut self) -> Path {
100 let name = self.segments[0].identifier.name;
101 if !self.is_global() && name != "$crate" &&
102 name != keywords::SelfValue.name() && name != keywords::Super.name() {
103 self.segments.insert(0, PathSegment::crate_root());
108 pub fn is_global(&self) -> bool {
109 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
113 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
115 /// E.g. `std`, `String` or `Box<T>`
116 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
117 pub struct PathSegment {
118 /// The identifier portion of this path segment.
119 pub identifier: Ident,
120 /// Span of the segment identifier.
123 /// Type/lifetime parameters attached to this path. They come in
124 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
125 /// this is more than just simple syntactic sugar; the use of
126 /// parens affects the region binding rules, so we preserve the
128 /// The `Option<P<..>>` wrapper is purely a size optimization;
129 /// `None` is used to represent both `Path` and `Path<>`.
130 pub parameters: Option<P<PathParameters>>,
134 pub fn from_ident(ident: Ident, span: Span) -> Self {
135 PathSegment { identifier: ident, span: span, parameters: None }
137 pub fn crate_root() -> Self {
139 identifier: keywords::CrateRoot.ident(),
146 /// Parameters of a path segment.
148 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
149 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
150 pub enum PathParameters {
151 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
152 AngleBracketed(AngleBracketedParameterData),
153 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
154 Parenthesized(ParenthesizedParameterData),
157 /// A path like `Foo<'a, T>`
158 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
159 pub struct AngleBracketedParameterData {
160 /// The lifetime parameters for this path segment.
161 pub lifetimes: Vec<Lifetime>,
162 /// The type parameters for this path segment, if present.
163 pub types: Vec<P<Ty>>,
164 /// Bindings (equality constraints) on associated types, if present.
166 /// E.g., `Foo<A=Bar>`.
167 pub bindings: Vec<TypeBinding>,
170 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
171 fn into(self) -> Option<P<PathParameters>> {
172 let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
173 if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
177 /// A path like `Foo(A,B) -> C`
178 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
179 pub struct ParenthesizedParameterData {
184 pub inputs: Vec<P<Ty>>,
187 pub output: Option<P<Ty>>,
190 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
191 pub struct NodeId(u32);
194 pub fn new(x: usize) -> NodeId {
195 assert!(x < (u32::MAX as usize));
199 pub fn from_u32(x: u32) -> NodeId {
203 pub fn as_usize(&self) -> usize {
207 pub fn as_u32(&self) -> u32 {
211 pub fn placeholder_from_mark(mark: Mark) -> Self {
212 NodeId(mark.as_u32())
215 pub fn placeholder_to_mark(self) -> Mark {
216 Mark::from_u32(self.0)
220 impl fmt::Display for NodeId {
221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
222 fmt::Display::fmt(&self.0, f)
226 impl serialize::UseSpecializedEncodable for NodeId {
227 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
232 impl serialize::UseSpecializedDecodable for NodeId {
233 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
234 d.read_u32().map(NodeId)
238 impl indexed_vec::Idx for NodeId {
239 fn new(idx: usize) -> Self {
243 fn index(self) -> usize {
248 /// Node id used to represent the root of the crate.
249 pub const CRATE_NODE_ID: NodeId = NodeId(0);
251 /// When parsing and doing expansions, we initially give all AST nodes this AST
252 /// node value. Then later, in the renumber pass, we renumber them to have
253 /// small, positive ids.
254 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
256 /// The AST represents all type param bounds as types.
257 /// typeck::collect::compute_bounds matches these against
258 /// the "special" built-in traits (see middle::lang_items) and
259 /// detects Copy, Send and Sync.
260 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
261 pub enum TyParamBound {
262 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
263 RegionTyParamBound(Lifetime)
266 /// A modifier on a bound, currently this is only used for `?Sized`, where the
267 /// modifier is `Maybe`. Negative bounds should also be handled here.
268 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
269 pub enum TraitBoundModifier {
274 pub type TyParamBounds = Vec<TyParamBound>;
276 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
278 pub attrs: ThinVec<Attribute>,
281 pub bounds: TyParamBounds,
282 pub default: Option<P<Ty>>,
286 /// Represents lifetimes and type parameters attached to a declaration
287 /// of a function, enum, trait, etc.
288 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
289 pub struct Generics {
290 pub lifetimes: Vec<LifetimeDef>,
291 pub ty_params: Vec<TyParam>,
292 pub where_clause: WhereClause,
297 pub fn is_lt_parameterized(&self) -> bool {
298 !self.lifetimes.is_empty()
300 pub fn is_type_parameterized(&self) -> bool {
301 !self.ty_params.is_empty()
303 pub fn is_parameterized(&self) -> bool {
304 self.is_lt_parameterized() || self.is_type_parameterized()
306 pub fn span_for_name(&self, name: &str) -> Option<Span> {
307 for t in &self.ty_params {
308 if t.ident.name == name {
316 impl Default for Generics {
317 /// Creates an instance of `Generics`.
318 fn default() -> Generics {
320 lifetimes: Vec::new(),
321 ty_params: Vec::new(),
322 where_clause: WhereClause {
324 predicates: Vec::new(),
331 /// A `where` clause in a definition
332 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
333 pub struct WhereClause {
335 pub predicates: Vec<WherePredicate>,
338 /// A single predicate in a `where` clause
339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
340 pub enum WherePredicate {
341 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
342 BoundPredicate(WhereBoundPredicate),
343 /// A lifetime predicate, e.g. `'a: 'b+'c`
344 RegionPredicate(WhereRegionPredicate),
345 /// An equality predicate (unsupported)
346 EqPredicate(WhereEqPredicate),
351 /// E.g. `for<'c> Foo: Send+Clone+'c`
352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
353 pub struct WhereBoundPredicate {
355 /// Any lifetimes from a `for` binding
356 pub bound_lifetimes: Vec<LifetimeDef>,
357 /// The type being bounded
358 pub bounded_ty: P<Ty>,
359 /// Trait and lifetime bounds (`Clone+Send+'static`)
360 pub bounds: TyParamBounds,
363 /// A lifetime predicate.
366 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
367 pub struct WhereRegionPredicate {
369 pub lifetime: Lifetime,
370 pub bounds: Vec<Lifetime>,
373 /// An equality predicate (unsupported).
376 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
377 pub struct WhereEqPredicate {
384 /// The set of MetaItems that define the compilation environment of the crate,
385 /// used to drive conditional compilation
386 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
388 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
391 pub attrs: Vec<Attribute>,
395 /// A spanned compile-time attribute list item.
396 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
398 /// Possible values inside of compile-time attribute lists.
400 /// E.g. the '..' in `#[name(..)]`.
401 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
402 pub enum NestedMetaItemKind {
403 /// A full MetaItem, for recursive meta items.
407 /// E.g. "foo", 64, true
411 /// A spanned compile-time attribute item.
413 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
414 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
415 pub struct MetaItem {
417 pub node: MetaItemKind,
421 /// A compile-time attribute item.
423 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
424 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
425 pub enum MetaItemKind {
428 /// E.g. `test` as in `#[test]`
432 /// E.g. `derive(..)` as in `#[derive(..)]`
433 List(Vec<NestedMetaItem>),
434 /// Name value meta item.
436 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
440 /// A Block (`{ .. }`).
442 /// E.g. `{ .. }` as in `fn foo() { .. }`
443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
445 /// Statements in a block
446 pub stmts: Vec<Stmt>,
448 /// Distinguishes between `unsafe { ... }` and `{ ... }`
449 pub rules: BlockCheckMode,
453 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
460 impl fmt::Debug for Pat {
461 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
462 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
467 pub fn walk<F>(&self, it: &mut F) -> bool
468 where F: FnMut(&Pat) -> bool
475 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
476 PatKind::Struct(_, ref fields, _) => {
477 fields.iter().all(|field| field.node.pat.walk(it))
479 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
480 s.iter().all(|p| p.walk(it))
482 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
485 PatKind::Slice(ref before, ref slice, ref after) => {
486 before.iter().all(|p| p.walk(it)) &&
487 slice.iter().all(|p| p.walk(it)) &&
488 after.iter().all(|p| p.walk(it))
502 /// A single field in a struct pattern
504 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
505 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
506 /// except is_shorthand is true
507 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
508 pub struct FieldPat {
509 /// The identifier for the field
511 /// The pattern the field is destructured to
513 pub is_shorthand: bool,
514 pub attrs: ThinVec<Attribute>,
517 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
518 pub enum BindingMode {
523 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
529 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
531 /// Represents a wildcard pattern (`_`)
534 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
535 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
536 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
537 /// during name resolution.
538 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
540 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
541 /// The `bool` is `true` in the presence of a `..`.
542 Struct(Path, Vec<Spanned<FieldPat>>, bool),
544 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
545 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
546 /// 0 <= position <= subpats.len()
547 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
549 /// A possibly qualified path pattern.
550 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
551 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
552 /// only legally refer to associated constants.
553 Path(Option<QSelf>, Path),
555 /// A tuple pattern `(a, b)`.
556 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
557 /// 0 <= position <= subpats.len()
558 Tuple(Vec<P<Pat>>, Option<usize>),
561 /// A reference pattern, e.g. `&mut (a, b)`
562 Ref(P<Pat>, Mutability),
565 /// A range pattern, e.g. `1...2` or `1..2`
566 Range(P<Expr>, P<Expr>, RangeEnd),
567 /// `[a, b, ..i, y, z]` is represented as:
568 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
569 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
570 /// A macro pattern; pre-expansion
574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
575 pub enum Mutability {
580 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
582 /// The `+` operator (addition)
584 /// The `-` operator (subtraction)
586 /// The `*` operator (multiplication)
588 /// The `/` operator (division)
590 /// The `%` operator (modulus)
592 /// The `&&` operator (logical and)
594 /// The `||` operator (logical or)
596 /// The `^` operator (bitwise xor)
598 /// The `&` operator (bitwise and)
600 /// The `|` operator (bitwise or)
602 /// The `<<` operator (shift left)
604 /// The `>>` operator (shift right)
606 /// The `==` operator (equality)
608 /// The `<` operator (less than)
610 /// The `<=` operator (less than or equal to)
612 /// The `!=` operator (not equal to)
614 /// The `>=` operator (greater than or equal to)
616 /// The `>` operator (greater than)
621 pub fn to_string(&self) -> &'static str {
622 use self::BinOpKind::*;
644 pub fn lazy(&self) -> bool {
646 BinOpKind::And | BinOpKind::Or => true,
651 pub fn is_shift(&self) -> bool {
653 BinOpKind::Shl | BinOpKind::Shr => true,
657 pub fn is_comparison(&self) -> bool {
658 use self::BinOpKind::*;
660 Eq | Lt | Le | Ne | Gt | Ge =>
662 And | Or | Add | Sub | Mul | Div | Rem |
663 BitXor | BitAnd | BitOr | Shl | Shr =>
667 /// Returns `true` if the binary operator takes its arguments by value
668 pub fn is_by_value(&self) -> bool {
669 !self.is_comparison()
673 pub type BinOp = Spanned<BinOpKind>;
675 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
677 /// The `*` operator for dereferencing
679 /// The `!` operator for logical inversion
681 /// The `-` operator for negation
686 /// Returns `true` if the unary operator takes its argument by value
687 pub fn is_by_value(u: UnOp) -> bool {
689 UnOp::Neg | UnOp::Not => true,
694 pub fn to_string(op: UnOp) -> &'static str {
704 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
712 pub fn add_trailing_semicolon(mut self) -> Self {
713 self.node = match self.node {
714 StmtKind::Expr(expr) => StmtKind::Semi(expr),
715 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
716 (mac, MacStmtStyle::Semicolon, attrs)
724 impl fmt::Debug for Stmt {
725 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
726 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
731 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
733 /// A local (let) binding.
736 /// An item definition.
739 /// Expr without trailing semi-colon.
744 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
747 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
748 pub enum MacStmtStyle {
749 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
750 /// `foo!(...);`, `foo![...];`
752 /// The macro statement had braces; e.g. foo! { ... }
754 /// The macro statement had parentheses or brackets and no semicolon; e.g.
755 /// `foo!(...)`. All of these will end up being converted into macro
760 // FIXME (pending discussion of #1697, #2178...): local should really be
761 // a refinement on pat.
762 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
763 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
766 pub ty: Option<P<Ty>>,
767 /// Initializer expression to set the value, if any
768 pub init: Option<P<Expr>>,
771 pub attrs: ThinVec<Attribute>,
774 /// An arm of a 'match'.
776 /// E.g. `0...10 => { println!("match!") }` as in
780 /// 0...10 => { println!("match!") },
784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
786 pub attrs: Vec<Attribute>,
787 pub pats: Vec<P<Pat>>,
788 pub guard: Option<P<Expr>>,
792 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
794 pub ident: SpannedIdent,
797 pub is_shorthand: bool,
798 pub attrs: ThinVec<Attribute>,
801 pub type SpannedIdent = Spanned<Ident>;
803 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
804 pub enum BlockCheckMode {
806 Unsafe(UnsafeSource),
809 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
810 pub enum UnsafeSource {
816 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
821 pub attrs: ThinVec<Attribute>
824 impl fmt::Debug for Expr {
825 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
826 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
830 /// Limit types of a range (inclusive or exclusive)
831 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
832 pub enum RangeLimits {
833 /// Inclusive at the beginning, exclusive at the end
835 /// Inclusive at the beginning and end
839 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
841 /// A `box x` expression.
843 /// First expr is the place; second expr is the value.
844 InPlace(P<Expr>, P<Expr>),
845 /// An array (`[a, b, c, d]`)
849 /// The first field resolves to the function itself,
850 /// and the second field is the list of arguments
851 Call(P<Expr>, Vec<P<Expr>>),
852 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
854 /// The `SpannedIdent` is the identifier for the method name.
855 /// The vector of `Ty`s are the ascripted type parameters for the method
856 /// (within the angle brackets).
858 /// The first element of the vector of `Expr`s is the expression that evaluates
859 /// to the object on which the method is being called on (the receiver),
860 /// and the remaining elements are the rest of the arguments.
862 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
863 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
864 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
865 /// A tuple (`(a, b, c ,d)`)
867 /// A binary operation (For example: `a + b`, `a * b`)
868 Binary(BinOp, P<Expr>, P<Expr>),
869 /// A unary operation (For example: `!x`, `*x`)
870 Unary(UnOp, P<Expr>),
871 /// A literal (For example: `1`, `"foo"`)
873 /// A cast (`foo as f64`)
874 Cast(P<Expr>, P<Ty>),
875 Type(P<Expr>, P<Ty>),
876 /// An `if` block, with an optional else block
878 /// `if expr { block } else { expr }`
879 If(P<Expr>, P<Block>, Option<P<Expr>>),
880 /// An `if let` expression with an optional else block
882 /// `if let pat = expr { block } else { expr }`
884 /// This is desugared to a `match` expression.
885 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
886 /// A while loop, with an optional label
888 /// `'label: while expr { block }`
889 While(P<Expr>, P<Block>, Option<SpannedIdent>),
890 /// A while-let loop, with an optional label
892 /// `'label: while let pat = expr { block }`
894 /// This is desugared to a combination of `loop` and `match` expressions.
895 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
896 /// A for loop, with an optional label
898 /// `'label: for pat in expr { block }`
900 /// This is desugared to a combination of `loop` and `match` expressions.
901 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
902 /// Conditionless loop (can be exited with break, continue, or return)
904 /// `'label: loop { block }`
905 Loop(P<Block>, Option<SpannedIdent>),
907 Match(P<Expr>, Vec<Arm>),
908 /// A closure (for example, `move |a, b, c| a + b + c`)
910 /// The final span is the span of the argument block `|...|`
911 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
912 /// A block (`{ ... }`)
914 /// A catch block (`catch { ... }`)
917 /// An assignment (`a = foo()`)
918 Assign(P<Expr>, P<Expr>),
919 /// An assignment with an operator
921 /// For example, `a += 1`.
922 AssignOp(BinOp, P<Expr>, P<Expr>),
923 /// Access of a named struct field (`obj.foo`)
924 Field(P<Expr>, SpannedIdent),
925 /// Access of an unnamed field of a struct or tuple-struct
927 /// For example, `foo.0`.
928 TupField(P<Expr>, Spanned<usize>),
929 /// An indexing operation (`foo[2]`)
930 Index(P<Expr>, P<Expr>),
931 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
932 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
934 /// Variable reference, possibly containing `::` and/or type
935 /// parameters, e.g. foo::bar::<baz>.
937 /// Optionally "qualified",
938 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
939 Path(Option<QSelf>, Path),
941 /// A referencing operation (`&a` or `&mut a`)
942 AddrOf(Mutability, P<Expr>),
943 /// A `break`, with an optional label to break, and an optional expression
944 Break(Option<SpannedIdent>, Option<P<Expr>>),
945 /// A `continue`, with an optional label
946 Continue(Option<SpannedIdent>),
947 /// A `return`, with an optional value to be returned
948 Ret(Option<P<Expr>>),
950 /// Output of the `asm!()` macro
951 InlineAsm(P<InlineAsm>),
953 /// A macro invocation; pre-expansion
956 /// A struct literal expression.
958 /// For example, `Foo {x: 1, y: 2}`, or
959 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
960 Struct(Path, Vec<Field>, Option<P<Expr>>),
962 /// An array literal constructed from one repeated element.
964 /// For example, `[1; 5]`. The first expression is the element
965 /// to be repeated; the second is the number of times to repeat it.
966 Repeat(P<Expr>, P<Expr>),
968 /// No-op: used solely so we can pretty-print faithfully
975 /// The explicit Self type in a "qualified path". The actual
976 /// path, including the trait and the associated item, is stored
977 /// separately. `position` represents the index of the associated
978 /// item qualified with this Self type.
981 /// <Vec<T> as a::b::Trait>::AssociatedItem
982 /// ^~~~~ ~~~~~~~~~~~~~~^
985 /// <Vec<T>>::AssociatedItem
989 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
996 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1002 pub type Mac = Spanned<Mac_>;
1004 /// Represents a macro invocation. The Path indicates which macro
1005 /// is being invoked, and the vector of token-trees contains the source
1006 /// of the macro invocation.
1008 /// NB: the additional ident for a macro_rules-style macro is actually
1009 /// stored in the enclosing item. Oog.
1010 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1013 pub tts: ThinTokenStream,
1017 pub fn stream(&self) -> TokenStream {
1018 self.tts.clone().into()
1022 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1024 /// A regular string, like `"foo"`
1026 /// A raw string, like `r##"foo"##`
1028 /// The uint is the number of `#` symbols used
1033 pub type Lit = Spanned<LitKind>;
1035 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1036 pub enum LitIntType {
1044 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1045 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1047 /// A string literal (`"foo"`)
1048 Str(Symbol, StrStyle),
1049 /// A byte string (`b"foo"`)
1050 ByteStr(Rc<Vec<u8>>),
1051 /// A byte char (`b'f'`)
1053 /// A character literal (`'a'`)
1055 /// An integer literal (`1`)
1056 Int(u128, LitIntType),
1057 /// A float literal (`1f64` or `1E10f64`)
1058 Float(Symbol, FloatTy),
1059 /// A float literal without a suffix (`1.0 or 1.0E10`)
1060 FloatUnsuffixed(Symbol),
1061 /// A boolean literal
1066 /// Returns true if this literal is a string and false otherwise.
1067 pub fn is_str(&self) -> bool {
1069 LitKind::Str(..) => true,
1074 /// Returns true if this literal has no suffix. Note: this will return true
1075 /// for literals with prefixes such as raw strings and byte strings.
1076 pub fn is_unsuffixed(&self) -> bool {
1078 // unsuffixed variants
1079 LitKind::Str(..) => true,
1080 LitKind::ByteStr(..) => true,
1081 LitKind::Byte(..) => true,
1082 LitKind::Char(..) => true,
1083 LitKind::Int(_, LitIntType::Unsuffixed) => true,
1084 LitKind::FloatUnsuffixed(..) => true,
1085 LitKind::Bool(..) => true,
1086 // suffixed variants
1087 LitKind::Int(_, LitIntType::Signed(..)) => false,
1088 LitKind::Int(_, LitIntType::Unsigned(..)) => false,
1089 LitKind::Float(..) => false,
1093 /// Returns true if this literal has a suffix.
1094 pub fn is_suffixed(&self) -> bool {
1095 !self.is_unsuffixed()
1099 // NB: If you change this, you'll probably want to change the corresponding
1100 // type structure in middle/ty.rs as well.
1101 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1104 pub mutbl: Mutability,
1107 /// Represents a method's signature in a trait declaration,
1108 /// or in an implementation.
1109 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1110 pub struct MethodSig {
1111 pub unsafety: Unsafety,
1112 pub constness: Spanned<Constness>,
1114 pub decl: P<FnDecl>,
1115 pub generics: Generics,
1118 /// Represents an item declaration within a trait declaration,
1119 /// possibly including a default implementation. A trait item is
1120 /// either required (meaning it doesn't have an implementation, just a
1121 /// signature) or provided (meaning it has a default implementation).
1122 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1123 pub struct TraitItem {
1126 pub attrs: Vec<Attribute>,
1127 pub node: TraitItemKind,
1131 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1132 pub enum TraitItemKind {
1133 Const(P<Ty>, Option<P<Expr>>),
1134 Method(MethodSig, Option<P<Block>>),
1135 Type(TyParamBounds, Option<P<Ty>>),
1139 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1140 pub struct ImplItem {
1143 pub vis: Visibility,
1144 pub defaultness: Defaultness,
1145 pub attrs: Vec<Attribute>,
1146 pub node: ImplItemKind,
1150 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1151 pub enum ImplItemKind {
1152 Const(P<Ty>, P<Expr>),
1153 Method(MethodSig, P<Block>),
1158 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1168 impl fmt::Debug for IntTy {
1169 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1170 fmt::Display::fmt(self, f)
1174 impl fmt::Display for IntTy {
1175 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1176 write!(f, "{}", self.ty_to_string())
1181 pub fn ty_to_string(&self) -> &'static str {
1183 IntTy::Is => "isize",
1185 IntTy::I16 => "i16",
1186 IntTy::I32 => "i32",
1187 IntTy::I64 => "i64",
1188 IntTy::I128 => "i128",
1192 pub fn val_to_string(&self, val: i128) -> String {
1193 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1194 // are parsed as u128, so we wouldn't want to print an extra negative
1196 format!("{}{}", val as u128, self.ty_to_string())
1199 pub fn bit_width(&self) -> Option<usize> {
1201 IntTy::Is => return None,
1211 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1222 pub fn ty_to_string(&self) -> &'static str {
1224 UintTy::Us => "usize",
1226 UintTy::U16 => "u16",
1227 UintTy::U32 => "u32",
1228 UintTy::U64 => "u64",
1229 UintTy::U128 => "u128",
1233 pub fn val_to_string(&self, val: u128) -> String {
1234 format!("{}{}", val, self.ty_to_string())
1237 pub fn bit_width(&self) -> Option<usize> {
1239 UintTy::Us => return None,
1244 UintTy::U128 => 128,
1249 impl fmt::Debug for UintTy {
1250 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1251 fmt::Display::fmt(self, f)
1255 impl fmt::Display for UintTy {
1256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1257 write!(f, "{}", self.ty_to_string())
1261 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1267 impl fmt::Debug for FloatTy {
1268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1269 fmt::Display::fmt(self, f)
1273 impl fmt::Display for FloatTy {
1274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1275 write!(f, "{}", self.ty_to_string())
1280 pub fn ty_to_string(&self) -> &'static str {
1282 FloatTy::F32 => "f32",
1283 FloatTy::F64 => "f64",
1287 pub fn bit_width(&self) -> usize {
1295 // Bind a type to an associated type: `A=Foo`.
1296 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1297 pub struct TypeBinding {
1304 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1311 impl fmt::Debug for Ty {
1312 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1313 write!(f, "type({})", pprust::ty_to_string(self))
1317 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1318 pub struct BareFnTy {
1319 pub unsafety: Unsafety,
1321 pub lifetimes: Vec<LifetimeDef>,
1325 /// The different kinds of types recognized by the compiler
1326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1328 /// A variable-length slice (`[T]`)
1330 /// A fixed length array (`[T; n]`)
1331 Array(P<Ty>, P<Expr>),
1332 /// A raw pointer (`*const T` or `*mut T`)
1334 /// A reference (`&'a T` or `&'a mut T`)
1335 Rptr(Option<Lifetime>, MutTy),
1336 /// A bare function (e.g. `fn(usize) -> bool`)
1337 BareFn(P<BareFnTy>),
1338 /// The never type (`!`)
1340 /// A tuple (`(A, B, C, D,...)`)
1342 /// A path (`module::module::...::Type`), optionally
1343 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1345 /// Type parameters are stored in the Path itself
1346 Path(Option<QSelf>, Path),
1347 /// A trait object type `Bound1 + Bound2 + Bound3`
1348 /// where `Bound` is a trait or a lifetime.
1349 TraitObject(TyParamBounds),
1350 /// An `impl Bound1 + Bound2 + Bound3` type
1351 /// where `Bound` is a trait or a lifetime.
1352 ImplTrait(TyParamBounds),
1353 /// No-op; kept solely so that we can pretty-print faithfully
1357 /// TyKind::Infer means the type should be inferred instead of it having been
1358 /// specified. This can appear anywhere in a type.
1360 /// Inferred type of a `self` or `&self` argument in a method.
1362 // A macro in the type position.
1364 /// Placeholder for a kind that has failed to be defined.
1368 /// Inline assembly dialect.
1370 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1371 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1372 pub enum AsmDialect {
1377 /// Inline assembly.
1379 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1380 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1381 pub struct InlineAsmOutput {
1382 pub constraint: Symbol,
1385 pub is_indirect: bool,
1388 /// Inline assembly.
1390 /// E.g. `asm!("NOP");`
1391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1392 pub struct InlineAsm {
1394 pub asm_str_style: StrStyle,
1395 pub outputs: Vec<InlineAsmOutput>,
1396 pub inputs: Vec<(Symbol, P<Expr>)>,
1397 pub clobbers: Vec<Symbol>,
1399 pub alignstack: bool,
1400 pub dialect: AsmDialect,
1401 pub ctxt: SyntaxContext,
1404 /// An argument in a function header.
1406 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1407 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1414 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1416 /// E.g. `&mut self` as in `fn foo(&mut self)`
1417 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1419 /// `self`, `mut self`
1421 /// `&'lt self`, `&'lt mut self`
1422 Region(Option<Lifetime>, Mutability),
1423 /// `self: TYPE`, `mut self: TYPE`
1424 Explicit(P<Ty>, Mutability),
1427 pub type ExplicitSelf = Spanned<SelfKind>;
1430 pub fn to_self(&self) -> Option<ExplicitSelf> {
1431 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1432 if ident.node.name == keywords::SelfValue.name() {
1433 return match self.ty.node {
1434 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1435 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1436 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1438 _ => Some(respan(self.pat.span.to(self.ty.span),
1439 SelfKind::Explicit(self.ty.clone(), mutbl))),
1446 pub fn is_self(&self) -> bool {
1447 if let PatKind::Ident(_, ident, _) = self.pat.node {
1448 ident.node.name == keywords::SelfValue.name()
1454 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1455 let span = eself.span.to(eself_ident.span);
1456 let infer_ty = P(Ty {
1458 node: TyKind::ImplicitSelf,
1461 let arg = |mutbl, ty| Arg {
1464 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1471 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1472 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1473 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1475 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1482 /// Header (not the body) of a function declaration.
1484 /// E.g. `fn foo(bar: baz)`
1485 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1487 pub inputs: Vec<Arg>,
1488 pub output: FunctionRetTy,
1493 pub fn get_self(&self) -> Option<ExplicitSelf> {
1494 self.inputs.get(0).and_then(Arg::to_self)
1496 pub fn has_self(&self) -> bool {
1497 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1501 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1507 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1508 pub enum Constness {
1513 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1514 pub enum Defaultness {
1519 impl fmt::Display for Unsafety {
1520 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1521 fmt::Display::fmt(match *self {
1522 Unsafety::Normal => "normal",
1523 Unsafety::Unsafe => "unsafe",
1528 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1529 pub enum ImplPolarity {
1530 /// `impl Trait for Type`
1532 /// `impl !Trait for Type`
1536 impl fmt::Debug for ImplPolarity {
1537 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1539 ImplPolarity::Positive => "positive".fmt(f),
1540 ImplPolarity::Negative => "negative".fmt(f),
1546 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1547 pub enum FunctionRetTy {
1548 /// Return type is not specified.
1550 /// Functions default to `()` and
1551 /// closures default to inference. Span points to where return
1552 /// type would be inserted.
1558 impl FunctionRetTy {
1559 pub fn span(&self) -> Span {
1561 FunctionRetTy::Default(span) => span,
1562 FunctionRetTy::Ty(ref ty) => ty.span,
1567 /// Module declaration.
1569 /// E.g. `mod foo;` or `mod foo { .. }`
1570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1572 /// A span from the first token past `{` to the last token until `}`.
1573 /// For `mod foo;`, the inner span ranges from the first token
1574 /// to the last token in the external file.
1576 pub items: Vec<P<Item>>,
1579 /// Foreign module declaration.
1581 /// E.g. `extern { .. }` or `extern C { .. }`
1582 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1583 pub struct ForeignMod {
1585 pub items: Vec<ForeignItem>,
1588 /// Global inline assembly
1590 /// aka module-level assembly or file-scoped assembly
1591 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1592 pub struct GlobalAsm {
1594 pub ctxt: SyntaxContext,
1597 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1598 pub struct EnumDef {
1599 pub variants: Vec<Variant>,
1602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1603 pub struct Variant_ {
1605 pub attrs: Vec<Attribute>,
1606 pub data: VariantData,
1607 /// Explicit discriminant, e.g. `Foo = 1`
1608 pub disr_expr: Option<P<Expr>>,
1611 pub type Variant = Spanned<Variant_>;
1613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1614 pub struct PathListItem_ {
1616 /// renamed in list, e.g. `use foo::{bar as baz};`
1617 pub rename: Option<Ident>,
1621 pub type PathListItem = Spanned<PathListItem_>;
1623 pub type ViewPath = Spanned<ViewPath_>;
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1626 pub enum ViewPath_ {
1628 /// `foo::bar::baz as quux`
1632 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1633 ViewPathSimple(Ident, Path),
1638 /// `foo::bar::{a,b,c}`
1639 ViewPathList(Path, Vec<PathListItem>)
1643 pub fn path(&self) -> &Path {
1645 ViewPathSimple(_, ref path) |
1646 ViewPathGlob (ref path) |
1647 ViewPathList(ref path, _) => path
1653 /// Distinguishes between Attributes that decorate items and Attributes that
1654 /// are contained as statements within items. These two cases need to be
1655 /// distinguished for pretty-printing.
1656 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1657 pub enum AttrStyle {
1662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1663 pub struct AttrId(pub usize);
1665 /// Meta-data associated with an item
1666 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1667 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1668 pub struct Attribute {
1670 pub style: AttrStyle,
1672 pub tokens: TokenStream,
1673 pub is_sugared_doc: bool,
1677 /// TraitRef's appear in impls.
1679 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1680 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1681 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1682 /// same as the impl's node id).
1683 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1684 pub struct TraitRef {
1689 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1690 pub struct PolyTraitRef {
1691 /// The `'a` in `<'a> Foo<&'a T>`
1692 pub bound_lifetimes: Vec<LifetimeDef>,
1694 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1695 pub trait_ref: TraitRef,
1701 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1703 bound_lifetimes: lifetimes,
1704 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1710 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1711 pub enum Visibility {
1714 Restricted { path: P<Path>, id: NodeId },
1718 /// Field of a struct.
1720 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1722 pub struct StructField {
1724 pub ident: Option<Ident>,
1725 pub vis: Visibility,
1728 pub attrs: Vec<Attribute>,
1731 /// Fields and Ids of enum variants and structs
1733 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1734 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1735 /// One shared Id can be successfully used for these two purposes.
1736 /// Id of the whole enum lives in `Item`.
1738 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1739 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1740 /// the variant itself" from enum variants.
1741 /// Id of the whole struct lives in `Item`.
1742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1743 pub enum VariantData {
1746 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1747 Struct(Vec<StructField>, NodeId),
1750 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1751 Tuple(Vec<StructField>, NodeId),
1754 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1759 pub fn fields(&self) -> &[StructField] {
1761 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1765 pub fn id(&self) -> NodeId {
1767 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1770 pub fn is_struct(&self) -> bool {
1771 if let VariantData::Struct(..) = *self { true } else { false }
1773 pub fn is_tuple(&self) -> bool {
1774 if let VariantData::Tuple(..) = *self { true } else { false }
1776 pub fn is_unit(&self) -> bool {
1777 if let VariantData::Unit(..) = *self { true } else { false }
1783 /// The name might be a dummy name in case of anonymous items
1784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1787 pub attrs: Vec<Attribute>,
1790 pub vis: Visibility,
1794 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1796 /// An`extern crate` item, with optional original crate name.
1798 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1799 ExternCrate(Option<Name>),
1800 /// A use declaration (`use` or `pub use`) item.
1802 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1804 /// A static item (`static` or `pub static`).
1806 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1807 Static(P<Ty>, Mutability, P<Expr>),
1808 /// A constant item (`const` or `pub const`).
1810 /// E.g. `const FOO: i32 = 42;`
1811 Const(P<Ty>, P<Expr>),
1812 /// A function declaration (`fn` or `pub fn`).
1814 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1815 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1816 /// A module declaration (`mod` or `pub mod`).
1818 /// E.g. `mod foo;` or `mod foo { .. }`
1820 /// An external module (`extern` or `pub extern`).
1822 /// E.g. `extern {}` or `extern "C" {}`
1823 ForeignMod(ForeignMod),
1824 /// Module-level inline assembly (from `global_asm!()`)
1825 GlobalAsm(P<GlobalAsm>),
1826 /// A type alias (`type` or `pub type`).
1828 /// E.g. `type Foo = Bar<u8>;`
1829 Ty(P<Ty>, Generics),
1830 /// An enum definition (`enum` or `pub enum`).
1832 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1833 Enum(EnumDef, Generics),
1834 /// A struct definition (`struct` or `pub struct`).
1836 /// E.g. `struct Foo<A> { x: A }`
1837 Struct(VariantData, Generics),
1838 /// A union definition (`union` or `pub union`).
1840 /// E.g. `union Foo<A, B> { x: A, y: B }`
1841 Union(VariantData, Generics),
1842 /// A Trait declaration (`trait` or `pub trait`).
1844 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1845 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1846 // Default trait implementation.
1848 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1849 DefaultImpl(Unsafety, TraitRef),
1850 /// An implementation.
1852 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1856 Option<TraitRef>, // (optional) trait this impl implements
1859 /// A macro invocation.
1861 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1864 /// A macro definition.
1865 MacroDef(ThinTokenStream),
1869 pub fn descriptive_variant(&self) -> &str {
1871 ItemKind::ExternCrate(..) => "extern crate",
1872 ItemKind::Use(..) => "use",
1873 ItemKind::Static(..) => "static item",
1874 ItemKind::Const(..) => "constant item",
1875 ItemKind::Fn(..) => "function",
1876 ItemKind::Mod(..) => "module",
1877 ItemKind::ForeignMod(..) => "foreign module",
1878 ItemKind::GlobalAsm(..) => "global asm",
1879 ItemKind::Ty(..) => "type alias",
1880 ItemKind::Enum(..) => "enum",
1881 ItemKind::Struct(..) => "struct",
1882 ItemKind::Union(..) => "union",
1883 ItemKind::Trait(..) => "trait",
1885 ItemKind::MacroDef(..) |
1886 ItemKind::Impl(..) |
1887 ItemKind::DefaultImpl(..) => "item"
1892 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1893 pub struct ForeignItem {
1895 pub attrs: Vec<Attribute>,
1896 pub node: ForeignItemKind,
1899 pub vis: Visibility,
1902 /// An item within an `extern` block
1903 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1904 pub enum ForeignItemKind {
1905 /// A foreign function
1906 Fn(P<FnDecl>, Generics),
1907 /// A foreign static item (`static ext: u8`), with optional mutability
1908 /// (the boolean is true when mutable)
1909 Static(P<Ty>, bool),
1912 impl ForeignItemKind {
1913 pub fn descriptive_variant(&self) -> &str {
1915 ForeignItemKind::Fn(..) => "foreign function",
1916 ForeignItemKind::Static(..) => "foreign static item"
1926 // are ASTs encodable?
1928 fn check_asts_encodable() {
1929 fn assert_encodable<T: serialize::Encodable>() {}
1930 assert_encodable::<Crate>();