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 if !self.is_global() &&
101 !::parse::token::Ident(self.segments[0].identifier).is_path_segment_keyword() {
102 self.segments.insert(0, PathSegment::crate_root(self.span));
107 pub fn is_global(&self) -> bool {
108 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
112 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
114 /// E.g. `std`, `String` or `Box<T>`
115 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
116 pub struct PathSegment {
117 /// The identifier portion of this path segment.
118 pub identifier: Ident,
119 /// Span of the segment identifier.
122 /// Type/lifetime parameters attached to this path. They come in
123 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
124 /// this is more than just simple syntactic sugar; the use of
125 /// parens affects the region binding rules, so we preserve the
127 /// The `Option<P<..>>` wrapper is purely a size optimization;
128 /// `None` is used to represent both `Path` and `Path<>`.
129 pub parameters: Option<P<PathParameters>>,
133 pub fn from_ident(ident: Ident, span: Span) -> Self {
134 PathSegment { identifier: ident, span: span, parameters: None }
136 pub fn crate_root(span: Span) -> Self {
138 identifier: Ident { ctxt: span.ctxt, ..keywords::CrateRoot.ident() },
145 /// Parameters of a path segment.
147 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
148 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
149 pub enum PathParameters {
150 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
151 AngleBracketed(AngleBracketedParameterData),
152 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
153 Parenthesized(ParenthesizedParameterData),
156 /// A path like `Foo<'a, T>`
157 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
158 pub struct AngleBracketedParameterData {
159 /// The lifetime parameters for this path segment.
160 pub lifetimes: Vec<Lifetime>,
161 /// The type parameters for this path segment, if present.
162 pub types: Vec<P<Ty>>,
163 /// Bindings (equality constraints) on associated types, if present.
165 /// E.g., `Foo<A=Bar>`.
166 pub bindings: Vec<TypeBinding>,
169 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
170 fn into(self) -> Option<P<PathParameters>> {
171 let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
172 if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
176 /// A path like `Foo(A,B) -> C`
177 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
178 pub struct ParenthesizedParameterData {
183 pub inputs: Vec<P<Ty>>,
186 pub output: Option<P<Ty>>,
189 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
190 pub struct NodeId(u32);
193 pub fn new(x: usize) -> NodeId {
194 assert!(x < (u32::MAX as usize));
198 pub fn from_u32(x: u32) -> NodeId {
202 pub fn as_usize(&self) -> usize {
206 pub fn as_u32(&self) -> u32 {
210 pub fn placeholder_from_mark(mark: Mark) -> Self {
211 NodeId(mark.as_u32())
214 pub fn placeholder_to_mark(self) -> Mark {
215 Mark::from_u32(self.0)
219 impl fmt::Display for NodeId {
220 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
221 fmt::Display::fmt(&self.0, f)
225 impl serialize::UseSpecializedEncodable for NodeId {
226 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
231 impl serialize::UseSpecializedDecodable for NodeId {
232 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
233 d.read_u32().map(NodeId)
237 impl indexed_vec::Idx for NodeId {
238 fn new(idx: usize) -> Self {
242 fn index(self) -> usize {
247 /// Node id used to represent the root of the crate.
248 pub const CRATE_NODE_ID: NodeId = NodeId(0);
250 /// When parsing and doing expansions, we initially give all AST nodes this AST
251 /// node value. Then later, in the renumber pass, we renumber them to have
252 /// small, positive ids.
253 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
255 /// The AST represents all type param bounds as types.
256 /// typeck::collect::compute_bounds matches these against
257 /// the "special" built-in traits (see middle::lang_items) and
258 /// detects Copy, Send and Sync.
259 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
260 pub enum TyParamBound {
261 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
262 RegionTyParamBound(Lifetime)
265 /// A modifier on a bound, currently this is only used for `?Sized`, where the
266 /// modifier is `Maybe`. Negative bounds should also be handled here.
267 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
268 pub enum TraitBoundModifier {
273 pub type TyParamBounds = Vec<TyParamBound>;
275 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
277 pub attrs: ThinVec<Attribute>,
280 pub bounds: TyParamBounds,
281 pub default: Option<P<Ty>>,
285 /// Represents lifetimes and type parameters attached to a declaration
286 /// of a function, enum, trait, etc.
287 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
288 pub struct Generics {
289 pub lifetimes: Vec<LifetimeDef>,
290 pub ty_params: Vec<TyParam>,
291 pub where_clause: WhereClause,
296 pub fn is_lt_parameterized(&self) -> bool {
297 !self.lifetimes.is_empty()
299 pub fn is_type_parameterized(&self) -> bool {
300 !self.ty_params.is_empty()
302 pub fn is_parameterized(&self) -> bool {
303 self.is_lt_parameterized() || self.is_type_parameterized()
305 pub fn span_for_name(&self, name: &str) -> Option<Span> {
306 for t in &self.ty_params {
307 if t.ident.name == name {
315 impl Default for Generics {
316 /// Creates an instance of `Generics`.
317 fn default() -> Generics {
319 lifetimes: Vec::new(),
320 ty_params: Vec::new(),
321 where_clause: WhereClause {
323 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>,
339 /// A single predicate in a `where` clause
340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
341 pub enum WherePredicate {
342 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
343 BoundPredicate(WhereBoundPredicate),
344 /// A lifetime predicate, e.g. `'a: 'b+'c`
345 RegionPredicate(WhereRegionPredicate),
346 /// An equality predicate (unsupported)
347 EqPredicate(WhereEqPredicate),
352 /// E.g. `for<'c> Foo: Send+Clone+'c`
353 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
354 pub struct WhereBoundPredicate {
356 /// Any lifetimes from a `for` binding
357 pub bound_lifetimes: Vec<LifetimeDef>,
358 /// The type being bounded
359 pub bounded_ty: P<Ty>,
360 /// Trait and lifetime bounds (`Clone+Send+'static`)
361 pub bounds: TyParamBounds,
364 /// A lifetime predicate.
367 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
368 pub struct WhereRegionPredicate {
370 pub lifetime: Lifetime,
371 pub bounds: Vec<Lifetime>,
374 /// An equality predicate (unsupported).
377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
378 pub struct WhereEqPredicate {
385 /// The set of MetaItems that define the compilation environment of the crate,
386 /// used to drive conditional compilation
387 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
389 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
392 pub attrs: Vec<Attribute>,
396 /// A spanned compile-time attribute list item.
397 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
399 /// Possible values inside of compile-time attribute lists.
401 /// E.g. the '..' in `#[name(..)]`.
402 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
403 pub enum NestedMetaItemKind {
404 /// A full MetaItem, for recursive meta items.
408 /// E.g. "foo", 64, true
412 /// A spanned compile-time attribute item.
414 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
415 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
416 pub struct MetaItem {
418 pub node: MetaItemKind,
422 /// A compile-time attribute item.
424 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
425 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
426 pub enum MetaItemKind {
429 /// E.g. `test` as in `#[test]`
433 /// E.g. `derive(..)` as in `#[derive(..)]`
434 List(Vec<NestedMetaItem>),
435 /// Name value meta item.
437 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
441 /// A Block (`{ .. }`).
443 /// E.g. `{ .. }` as in `fn foo() { .. }`
444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
446 /// Statements in a block
447 pub stmts: Vec<Stmt>,
449 /// Distinguishes between `unsafe { ... }` and `{ ... }`
450 pub rules: BlockCheckMode,
454 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
461 impl fmt::Debug for Pat {
462 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
463 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
468 pub fn walk<F>(&self, it: &mut F) -> bool
469 where F: FnMut(&Pat) -> bool
476 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
477 PatKind::Struct(_, ref fields, _) => {
478 fields.iter().all(|field| field.node.pat.walk(it))
480 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
481 s.iter().all(|p| p.walk(it))
483 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
486 PatKind::Slice(ref before, ref slice, ref after) => {
487 before.iter().all(|p| p.walk(it)) &&
488 slice.iter().all(|p| p.walk(it)) &&
489 after.iter().all(|p| p.walk(it))
503 /// A single field in a struct pattern
505 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
506 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
507 /// except is_shorthand is true
508 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
509 pub struct FieldPat {
510 /// The identifier for the field
512 /// The pattern the field is destructured to
514 pub is_shorthand: bool,
515 pub attrs: ThinVec<Attribute>,
518 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
519 pub enum BindingMode {
524 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
530 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
532 /// Represents a wildcard pattern (`_`)
535 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
536 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
537 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
538 /// during name resolution.
539 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
541 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
542 /// The `bool` is `true` in the presence of a `..`.
543 Struct(Path, Vec<Spanned<FieldPat>>, bool),
545 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
546 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
547 /// 0 <= position <= subpats.len()
548 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
550 /// A possibly qualified path pattern.
551 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
552 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
553 /// only legally refer to associated constants.
554 Path(Option<QSelf>, Path),
556 /// A tuple pattern `(a, b)`.
557 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
558 /// 0 <= position <= subpats.len()
559 Tuple(Vec<P<Pat>>, Option<usize>),
562 /// A reference pattern, e.g. `&mut (a, b)`
563 Ref(P<Pat>, Mutability),
566 /// A range pattern, e.g. `1...2` or `1..2`
567 Range(P<Expr>, P<Expr>, RangeEnd),
568 /// `[a, b, ..i, y, z]` is represented as:
569 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
570 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
571 /// A macro pattern; pre-expansion
575 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
576 pub enum Mutability {
581 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
583 /// The `+` operator (addition)
585 /// The `-` operator (subtraction)
587 /// The `*` operator (multiplication)
589 /// The `/` operator (division)
591 /// The `%` operator (modulus)
593 /// The `&&` operator (logical and)
595 /// The `||` operator (logical or)
597 /// The `^` operator (bitwise xor)
599 /// The `&` operator (bitwise and)
601 /// The `|` operator (bitwise or)
603 /// The `<<` operator (shift left)
605 /// The `>>` operator (shift right)
607 /// The `==` operator (equality)
609 /// The `<` operator (less than)
611 /// The `<=` operator (less than or equal to)
613 /// The `!=` operator (not equal to)
615 /// The `>=` operator (greater than or equal to)
617 /// The `>` operator (greater than)
622 pub fn to_string(&self) -> &'static str {
623 use self::BinOpKind::*;
645 pub fn lazy(&self) -> bool {
647 BinOpKind::And | BinOpKind::Or => true,
652 pub fn is_shift(&self) -> bool {
654 BinOpKind::Shl | BinOpKind::Shr => true,
658 pub fn is_comparison(&self) -> bool {
659 use self::BinOpKind::*;
661 Eq | Lt | Le | Ne | Gt | Ge =>
663 And | Or | Add | Sub | Mul | Div | Rem |
664 BitXor | BitAnd | BitOr | Shl | Shr =>
668 /// Returns `true` if the binary operator takes its arguments by value
669 pub fn is_by_value(&self) -> bool {
670 !self.is_comparison()
674 pub type BinOp = Spanned<BinOpKind>;
676 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
678 /// The `*` operator for dereferencing
680 /// The `!` operator for logical inversion
682 /// The `-` operator for negation
687 /// Returns `true` if the unary operator takes its argument by value
688 pub fn is_by_value(u: UnOp) -> bool {
690 UnOp::Neg | UnOp::Not => true,
695 pub fn to_string(op: UnOp) -> &'static str {
705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
713 pub fn add_trailing_semicolon(mut self) -> Self {
714 self.node = match self.node {
715 StmtKind::Expr(expr) => StmtKind::Semi(expr),
716 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
717 (mac, MacStmtStyle::Semicolon, attrs)
725 impl fmt::Debug for Stmt {
726 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
727 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
732 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
734 /// A local (let) binding.
737 /// An item definition.
740 /// Expr without trailing semi-colon.
745 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
748 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
749 pub enum MacStmtStyle {
750 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
751 /// `foo!(...);`, `foo![...];`
753 /// The macro statement had braces; e.g. foo! { ... }
755 /// The macro statement had parentheses or brackets and no semicolon; e.g.
756 /// `foo!(...)`. All of these will end up being converted into macro
761 // FIXME (pending discussion of #1697, #2178...): local should really be
762 // a refinement on pat.
763 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
764 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
767 pub ty: Option<P<Ty>>,
768 /// Initializer expression to set the value, if any
769 pub init: Option<P<Expr>>,
772 pub attrs: ThinVec<Attribute>,
775 /// An arm of a 'match'.
777 /// E.g. `0...10 => { println!("match!") }` as in
781 /// 0...10 => { println!("match!") },
782 /// _ => { println!("no match!") },
785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
787 pub attrs: Vec<Attribute>,
788 pub pats: Vec<P<Pat>>,
789 pub guard: Option<P<Expr>>,
793 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
795 pub ident: SpannedIdent,
798 pub is_shorthand: bool,
799 pub attrs: ThinVec<Attribute>,
802 pub type SpannedIdent = Spanned<Ident>;
804 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
805 pub enum BlockCheckMode {
807 Unsafe(UnsafeSource),
810 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
811 pub enum UnsafeSource {
817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
822 pub attrs: ThinVec<Attribute>
825 impl fmt::Debug for Expr {
826 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
827 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
831 /// Limit types of a range (inclusive or exclusive)
832 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
833 pub enum RangeLimits {
834 /// Inclusive at the beginning, exclusive at the end
836 /// Inclusive at the beginning and end
840 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
842 /// A `box x` expression.
844 /// First expr is the place; second expr is the value.
845 InPlace(P<Expr>, P<Expr>),
846 /// An array (`[a, b, c, d]`)
850 /// The first field resolves to the function itself,
851 /// and the second field is the list of arguments
852 Call(P<Expr>, Vec<P<Expr>>),
853 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
855 /// The `PathSegment` represents the method name and its generic arguments
856 /// (within the angle brackets).
857 /// The first element of the vector of `Expr`s is the expression that evaluates
858 /// to the object on which the method is being called on (the receiver),
859 /// and the remaining elements are the rest of the arguments.
860 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
861 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
862 MethodCall(PathSegment, Vec<P<Expr>>),
863 /// A tuple (`(a, b, c ,d)`)
865 /// A binary operation (For example: `a + b`, `a * b`)
866 Binary(BinOp, P<Expr>, P<Expr>),
867 /// A unary operation (For example: `!x`, `*x`)
868 Unary(UnOp, P<Expr>),
869 /// A literal (For example: `1`, `"foo"`)
871 /// A cast (`foo as f64`)
872 Cast(P<Expr>, P<Ty>),
873 Type(P<Expr>, P<Ty>),
874 /// An `if` block, with an optional else block
876 /// `if expr { block } else { expr }`
877 If(P<Expr>, P<Block>, Option<P<Expr>>),
878 /// An `if let` expression with an optional else block
880 /// `if let pat = expr { block } else { expr }`
882 /// This is desugared to a `match` expression.
883 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
884 /// A while loop, with an optional label
886 /// `'label: while expr { block }`
887 While(P<Expr>, P<Block>, Option<SpannedIdent>),
888 /// A while-let loop, with an optional label
890 /// `'label: while let pat = expr { block }`
892 /// This is desugared to a combination of `loop` and `match` expressions.
893 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
894 /// A for loop, with an optional label
896 /// `'label: for pat in expr { block }`
898 /// This is desugared to a combination of `loop` and `match` expressions.
899 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
900 /// Conditionless loop (can be exited with break, continue, or return)
902 /// `'label: loop { block }`
903 Loop(P<Block>, Option<SpannedIdent>),
905 Match(P<Expr>, Vec<Arm>),
906 /// A closure (for example, `move |a, b, c| a + b + c`)
908 /// The final span is the span of the argument block `|...|`
909 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
910 /// A block (`{ ... }`)
912 /// A catch block (`catch { ... }`)
915 /// An assignment (`a = foo()`)
916 Assign(P<Expr>, P<Expr>),
917 /// An assignment with an operator
919 /// For example, `a += 1`.
920 AssignOp(BinOp, P<Expr>, P<Expr>),
921 /// Access of a named struct field (`obj.foo`)
922 Field(P<Expr>, SpannedIdent),
923 /// Access of an unnamed field of a struct or tuple-struct
925 /// For example, `foo.0`.
926 TupField(P<Expr>, Spanned<usize>),
927 /// An indexing operation (`foo[2]`)
928 Index(P<Expr>, P<Expr>),
929 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
930 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
932 /// Variable reference, possibly containing `::` and/or type
933 /// parameters, e.g. foo::bar::<baz>.
935 /// Optionally "qualified",
936 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
937 Path(Option<QSelf>, Path),
939 /// A referencing operation (`&a` or `&mut a`)
940 AddrOf(Mutability, P<Expr>),
941 /// A `break`, with an optional label to break, and an optional expression
942 Break(Option<SpannedIdent>, Option<P<Expr>>),
943 /// A `continue`, with an optional label
944 Continue(Option<SpannedIdent>),
945 /// A `return`, with an optional value to be returned
946 Ret(Option<P<Expr>>),
948 /// Output of the `asm!()` macro
949 InlineAsm(P<InlineAsm>),
951 /// A macro invocation; pre-expansion
954 /// A struct literal expression.
956 /// For example, `Foo {x: 1, y: 2}`, or
957 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
958 Struct(Path, Vec<Field>, Option<P<Expr>>),
960 /// An array literal constructed from one repeated element.
962 /// For example, `[1; 5]`. The first expression is the element
963 /// to be repeated; the second is the number of times to repeat it.
964 Repeat(P<Expr>, P<Expr>),
966 /// No-op: used solely so we can pretty-print faithfully
973 /// The explicit Self type in a "qualified path". The actual
974 /// path, including the trait and the associated item, is stored
975 /// separately. `position` represents the index of the associated
976 /// item qualified with this Self type.
978 /// ```ignore (only-for-syntax-highlight)
979 /// <Vec<T> as a::b::Trait>::AssociatedItem
980 /// ^~~~~ ~~~~~~~~~~~~~~^
983 /// <Vec<T>>::AssociatedItem
987 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
994 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1000 pub type Mac = Spanned<Mac_>;
1002 /// Represents a macro invocation. The Path indicates which macro
1003 /// is being invoked, and the vector of token-trees contains the source
1004 /// of the macro invocation.
1006 /// NB: the additional ident for a macro_rules-style macro is actually
1007 /// stored in the enclosing item. Oog.
1008 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1011 pub tts: ThinTokenStream,
1015 pub fn stream(&self) -> TokenStream {
1016 self.tts.clone().into()
1020 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1021 pub struct MacroDef {
1022 pub tokens: ThinTokenStream,
1027 pub fn stream(&self) -> TokenStream {
1028 self.tokens.clone().into()
1032 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1034 /// A regular string, like `"foo"`
1036 /// A raw string, like `r##"foo"##`
1038 /// The uint is the number of `#` symbols used
1043 pub type Lit = Spanned<LitKind>;
1045 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1046 pub enum LitIntType {
1054 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1055 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1057 /// A string literal (`"foo"`)
1058 Str(Symbol, StrStyle),
1059 /// A byte string (`b"foo"`)
1060 ByteStr(Rc<Vec<u8>>),
1061 /// A byte char (`b'f'`)
1063 /// A character literal (`'a'`)
1065 /// An integer literal (`1`)
1066 Int(u128, LitIntType),
1067 /// A float literal (`1f64` or `1E10f64`)
1068 Float(Symbol, FloatTy),
1069 /// A float literal without a suffix (`1.0 or 1.0E10`)
1070 FloatUnsuffixed(Symbol),
1071 /// A boolean literal
1076 /// Returns true if this literal is a string and false otherwise.
1077 pub fn is_str(&self) -> bool {
1079 LitKind::Str(..) => true,
1084 /// Returns true if this literal has no suffix. Note: this will return true
1085 /// for literals with prefixes such as raw strings and byte strings.
1086 pub fn is_unsuffixed(&self) -> bool {
1088 // unsuffixed variants
1090 LitKind::ByteStr(..) |
1093 LitKind::Int(_, LitIntType::Unsuffixed) |
1094 LitKind::FloatUnsuffixed(..) |
1095 LitKind::Bool(..) => true,
1096 // suffixed variants
1097 LitKind::Int(_, LitIntType::Signed(..)) |
1098 LitKind::Int(_, LitIntType::Unsigned(..)) |
1099 LitKind::Float(..) => false,
1103 /// Returns true if this literal has a suffix.
1104 pub fn is_suffixed(&self) -> bool {
1105 !self.is_unsuffixed()
1109 // NB: If you change this, you'll probably want to change the corresponding
1110 // type structure in middle/ty.rs as well.
1111 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1114 pub mutbl: Mutability,
1117 /// Represents a method's signature in a trait declaration,
1118 /// or in an implementation.
1119 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1120 pub struct MethodSig {
1121 pub unsafety: Unsafety,
1122 pub constness: Spanned<Constness>,
1124 pub decl: P<FnDecl>,
1125 pub generics: Generics,
1128 /// Represents an item declaration within a trait declaration,
1129 /// possibly including a default implementation. A trait item is
1130 /// either required (meaning it doesn't have an implementation, just a
1131 /// signature) or provided (meaning it has a default implementation).
1132 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1133 pub struct TraitItem {
1136 pub attrs: Vec<Attribute>,
1137 pub node: TraitItemKind,
1141 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1142 pub enum TraitItemKind {
1143 Const(P<Ty>, Option<P<Expr>>),
1144 Method(MethodSig, Option<P<Block>>),
1145 Type(TyParamBounds, Option<P<Ty>>),
1149 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1150 pub struct ImplItem {
1153 pub vis: Visibility,
1154 pub defaultness: Defaultness,
1155 pub attrs: Vec<Attribute>,
1156 pub node: ImplItemKind,
1160 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1161 pub enum ImplItemKind {
1162 Const(P<Ty>, P<Expr>),
1163 Method(MethodSig, P<Block>),
1168 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1178 impl fmt::Debug for IntTy {
1179 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1180 fmt::Display::fmt(self, f)
1184 impl fmt::Display for IntTy {
1185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1186 write!(f, "{}", self.ty_to_string())
1191 pub fn ty_to_string(&self) -> &'static str {
1193 IntTy::Is => "isize",
1195 IntTy::I16 => "i16",
1196 IntTy::I32 => "i32",
1197 IntTy::I64 => "i64",
1198 IntTy::I128 => "i128",
1202 pub fn val_to_string(&self, val: i128) -> String {
1203 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1204 // are parsed as u128, so we wouldn't want to print an extra negative
1206 format!("{}{}", val as u128, self.ty_to_string())
1209 pub fn bit_width(&self) -> Option<usize> {
1211 IntTy::Is => return None,
1221 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1232 pub fn ty_to_string(&self) -> &'static str {
1234 UintTy::Us => "usize",
1236 UintTy::U16 => "u16",
1237 UintTy::U32 => "u32",
1238 UintTy::U64 => "u64",
1239 UintTy::U128 => "u128",
1243 pub fn val_to_string(&self, val: u128) -> String {
1244 format!("{}{}", val, self.ty_to_string())
1247 pub fn bit_width(&self) -> Option<usize> {
1249 UintTy::Us => return None,
1254 UintTy::U128 => 128,
1259 impl fmt::Debug for UintTy {
1260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1261 fmt::Display::fmt(self, f)
1265 impl fmt::Display for UintTy {
1266 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1267 write!(f, "{}", self.ty_to_string())
1271 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1277 impl fmt::Debug for FloatTy {
1278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1279 fmt::Display::fmt(self, f)
1283 impl fmt::Display for FloatTy {
1284 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1285 write!(f, "{}", self.ty_to_string())
1290 pub fn ty_to_string(&self) -> &'static str {
1292 FloatTy::F32 => "f32",
1293 FloatTy::F64 => "f64",
1297 pub fn bit_width(&self) -> usize {
1305 // Bind a type to an associated type: `A=Foo`.
1306 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1307 pub struct TypeBinding {
1314 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1321 impl fmt::Debug for Ty {
1322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1323 write!(f, "type({})", pprust::ty_to_string(self))
1327 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1328 pub struct BareFnTy {
1329 pub unsafety: Unsafety,
1331 pub lifetimes: Vec<LifetimeDef>,
1335 /// The different kinds of types recognized by the compiler
1336 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1338 /// A variable-length slice (`[T]`)
1340 /// A fixed length array (`[T; n]`)
1341 Array(P<Ty>, P<Expr>),
1342 /// A raw pointer (`*const T` or `*mut T`)
1344 /// A reference (`&'a T` or `&'a mut T`)
1345 Rptr(Option<Lifetime>, MutTy),
1346 /// A bare function (e.g. `fn(usize) -> bool`)
1347 BareFn(P<BareFnTy>),
1348 /// The never type (`!`)
1350 /// A tuple (`(A, B, C, D,...)`)
1352 /// A path (`module::module::...::Type`), optionally
1353 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1355 /// Type parameters are stored in the Path itself
1356 Path(Option<QSelf>, Path),
1357 /// A trait object type `Bound1 + Bound2 + Bound3`
1358 /// where `Bound` is a trait or a lifetime.
1359 TraitObject(TyParamBounds),
1360 /// An `impl Bound1 + Bound2 + Bound3` type
1361 /// where `Bound` is a trait or a lifetime.
1362 ImplTrait(TyParamBounds),
1363 /// No-op; kept solely so that we can pretty-print faithfully
1367 /// TyKind::Infer means the type should be inferred instead of it having been
1368 /// specified. This can appear anywhere in a type.
1370 /// Inferred type of a `self` or `&self` argument in a method.
1372 // A macro in the type position.
1374 /// Placeholder for a kind that has failed to be defined.
1378 /// Inline assembly dialect.
1380 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1381 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1382 pub enum AsmDialect {
1387 /// Inline assembly.
1389 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1390 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1391 pub struct InlineAsmOutput {
1392 pub constraint: Symbol,
1395 pub is_indirect: bool,
1398 /// Inline assembly.
1400 /// E.g. `asm!("NOP");`
1401 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1402 pub struct InlineAsm {
1404 pub asm_str_style: StrStyle,
1405 pub outputs: Vec<InlineAsmOutput>,
1406 pub inputs: Vec<(Symbol, P<Expr>)>,
1407 pub clobbers: Vec<Symbol>,
1409 pub alignstack: bool,
1410 pub dialect: AsmDialect,
1411 pub ctxt: SyntaxContext,
1414 /// An argument in a function header.
1416 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1417 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1424 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1426 /// E.g. `&mut self` as in `fn foo(&mut self)`
1427 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1429 /// `self`, `mut self`
1431 /// `&'lt self`, `&'lt mut self`
1432 Region(Option<Lifetime>, Mutability),
1433 /// `self: TYPE`, `mut self: TYPE`
1434 Explicit(P<Ty>, Mutability),
1437 pub type ExplicitSelf = Spanned<SelfKind>;
1440 pub fn to_self(&self) -> Option<ExplicitSelf> {
1441 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1442 if ident.node.name == keywords::SelfValue.name() {
1443 return match self.ty.node {
1444 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1445 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1446 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1448 _ => Some(respan(self.pat.span.to(self.ty.span),
1449 SelfKind::Explicit(self.ty.clone(), mutbl))),
1456 pub fn is_self(&self) -> bool {
1457 if let PatKind::Ident(_, ident, _) = self.pat.node {
1458 ident.node.name == keywords::SelfValue.name()
1464 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1465 let span = eself.span.to(eself_ident.span);
1466 let infer_ty = P(Ty {
1468 node: TyKind::ImplicitSelf,
1471 let arg = |mutbl, ty| Arg {
1474 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1481 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1482 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1483 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1485 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1492 /// Header (not the body) of a function declaration.
1494 /// E.g. `fn foo(bar: baz)`
1495 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1497 pub inputs: Vec<Arg>,
1498 pub output: FunctionRetTy,
1503 pub fn get_self(&self) -> Option<ExplicitSelf> {
1504 self.inputs.get(0).and_then(Arg::to_self)
1506 pub fn has_self(&self) -> bool {
1507 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1511 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1517 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1518 pub enum Constness {
1523 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1524 pub enum Defaultness {
1529 impl fmt::Display for Unsafety {
1530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1531 fmt::Display::fmt(match *self {
1532 Unsafety::Normal => "normal",
1533 Unsafety::Unsafe => "unsafe",
1538 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1539 pub enum ImplPolarity {
1540 /// `impl Trait for Type`
1542 /// `impl !Trait for Type`
1546 impl fmt::Debug for ImplPolarity {
1547 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1549 ImplPolarity::Positive => "positive".fmt(f),
1550 ImplPolarity::Negative => "negative".fmt(f),
1556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1557 pub enum FunctionRetTy {
1558 /// Return type is not specified.
1560 /// Functions default to `()` and
1561 /// closures default to inference. Span points to where return
1562 /// type would be inserted.
1568 impl FunctionRetTy {
1569 pub fn span(&self) -> Span {
1571 FunctionRetTy::Default(span) => span,
1572 FunctionRetTy::Ty(ref ty) => ty.span,
1577 /// Module declaration.
1579 /// E.g. `mod foo;` or `mod foo { .. }`
1580 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1582 /// A span from the first token past `{` to the last token until `}`.
1583 /// For `mod foo;`, the inner span ranges from the first token
1584 /// to the last token in the external file.
1586 pub items: Vec<P<Item>>,
1589 /// Foreign module declaration.
1591 /// E.g. `extern { .. }` or `extern C { .. }`
1592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1593 pub struct ForeignMod {
1595 pub items: Vec<ForeignItem>,
1598 /// Global inline assembly
1600 /// aka module-level assembly or file-scoped assembly
1601 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1602 pub struct GlobalAsm {
1604 pub ctxt: SyntaxContext,
1607 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1608 pub struct EnumDef {
1609 pub variants: Vec<Variant>,
1612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1613 pub struct Variant_ {
1615 pub attrs: Vec<Attribute>,
1616 pub data: VariantData,
1617 /// Explicit discriminant, e.g. `Foo = 1`
1618 pub disr_expr: Option<P<Expr>>,
1621 pub type Variant = Spanned<Variant_>;
1623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1624 pub struct PathListItem_ {
1626 /// renamed in list, e.g. `use foo::{bar as baz};`
1627 pub rename: Option<Ident>,
1631 pub type PathListItem = Spanned<PathListItem_>;
1633 pub type ViewPath = Spanned<ViewPath_>;
1635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1636 pub enum ViewPath_ {
1638 /// `foo::bar::baz as quux`
1642 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1643 ViewPathSimple(Ident, Path),
1648 /// `foo::bar::{a,b,c}`
1649 ViewPathList(Path, Vec<PathListItem>)
1653 pub fn path(&self) -> &Path {
1655 ViewPathSimple(_, ref path) |
1656 ViewPathGlob (ref path) |
1657 ViewPathList(ref path, _) => path
1663 /// Distinguishes between Attributes that decorate items and Attributes that
1664 /// are contained as statements within items. These two cases need to be
1665 /// distinguished for pretty-printing.
1666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1667 pub enum AttrStyle {
1672 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1673 pub struct AttrId(pub usize);
1675 /// Meta-data associated with an item
1676 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 pub struct Attribute {
1680 pub style: AttrStyle,
1682 pub tokens: TokenStream,
1683 pub is_sugared_doc: bool,
1687 /// TraitRef's appear in impls.
1689 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1690 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1691 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1692 /// same as the impl's node id).
1693 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1694 pub struct TraitRef {
1699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1700 pub struct PolyTraitRef {
1701 /// The `'a` in `<'a> Foo<&'a T>`
1702 pub bound_lifetimes: Vec<LifetimeDef>,
1704 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1705 pub trait_ref: TraitRef,
1711 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1713 bound_lifetimes: lifetimes,
1714 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1720 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1721 pub enum Visibility {
1724 Restricted { path: P<Path>, id: NodeId },
1728 /// Field of a struct.
1730 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1731 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1732 pub struct StructField {
1734 pub ident: Option<Ident>,
1735 pub vis: Visibility,
1738 pub attrs: Vec<Attribute>,
1741 /// Fields and Ids of enum variants and structs
1743 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1744 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1745 /// One shared Id can be successfully used for these two purposes.
1746 /// Id of the whole enum lives in `Item`.
1748 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1749 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1750 /// the variant itself" from enum variants.
1751 /// Id of the whole struct lives in `Item`.
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1753 pub enum VariantData {
1756 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1757 Struct(Vec<StructField>, NodeId),
1760 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1761 Tuple(Vec<StructField>, NodeId),
1764 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1769 pub fn fields(&self) -> &[StructField] {
1771 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1775 pub fn id(&self) -> NodeId {
1777 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1780 pub fn is_struct(&self) -> bool {
1781 if let VariantData::Struct(..) = *self { true } else { false }
1783 pub fn is_tuple(&self) -> bool {
1784 if let VariantData::Tuple(..) = *self { true } else { false }
1786 pub fn is_unit(&self) -> bool {
1787 if let VariantData::Unit(..) = *self { true } else { false }
1793 /// The name might be a dummy name in case of anonymous items
1794 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1797 pub attrs: Vec<Attribute>,
1800 pub vis: Visibility,
1804 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1806 /// An`extern crate` item, with optional original crate name.
1808 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1809 ExternCrate(Option<Name>),
1810 /// A use declaration (`use` or `pub use`) item.
1812 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1814 /// A static item (`static` or `pub static`).
1816 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1817 Static(P<Ty>, Mutability, P<Expr>),
1818 /// A constant item (`const` or `pub const`).
1820 /// E.g. `const FOO: i32 = 42;`
1821 Const(P<Ty>, P<Expr>),
1822 /// A function declaration (`fn` or `pub fn`).
1824 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1825 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1826 /// A module declaration (`mod` or `pub mod`).
1828 /// E.g. `mod foo;` or `mod foo { .. }`
1830 /// An external module (`extern` or `pub extern`).
1832 /// E.g. `extern {}` or `extern "C" {}`
1833 ForeignMod(ForeignMod),
1834 /// Module-level inline assembly (from `global_asm!()`)
1835 GlobalAsm(P<GlobalAsm>),
1836 /// A type alias (`type` or `pub type`).
1838 /// E.g. `type Foo = Bar<u8>;`
1839 Ty(P<Ty>, Generics),
1840 /// An enum definition (`enum` or `pub enum`).
1842 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1843 Enum(EnumDef, Generics),
1844 /// A struct definition (`struct` or `pub struct`).
1846 /// E.g. `struct Foo<A> { x: A }`
1847 Struct(VariantData, Generics),
1848 /// A union definition (`union` or `pub union`).
1850 /// E.g. `union Foo<A, B> { x: A, y: B }`
1851 Union(VariantData, Generics),
1852 /// A Trait declaration (`trait` or `pub trait`).
1854 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1855 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1856 // Default trait implementation.
1858 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1859 DefaultImpl(Unsafety, TraitRef),
1860 /// An implementation.
1862 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1867 Option<TraitRef>, // (optional) trait this impl implements
1870 /// A macro invocation.
1872 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1875 /// A macro definition.
1880 pub fn descriptive_variant(&self) -> &str {
1882 ItemKind::ExternCrate(..) => "extern crate",
1883 ItemKind::Use(..) => "use",
1884 ItemKind::Static(..) => "static item",
1885 ItemKind::Const(..) => "constant item",
1886 ItemKind::Fn(..) => "function",
1887 ItemKind::Mod(..) => "module",
1888 ItemKind::ForeignMod(..) => "foreign module",
1889 ItemKind::GlobalAsm(..) => "global asm",
1890 ItemKind::Ty(..) => "type alias",
1891 ItemKind::Enum(..) => "enum",
1892 ItemKind::Struct(..) => "struct",
1893 ItemKind::Union(..) => "union",
1894 ItemKind::Trait(..) => "trait",
1896 ItemKind::MacroDef(..) |
1897 ItemKind::Impl(..) |
1898 ItemKind::DefaultImpl(..) => "item"
1903 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1904 pub struct ForeignItem {
1906 pub attrs: Vec<Attribute>,
1907 pub node: ForeignItemKind,
1910 pub vis: Visibility,
1913 /// An item within an `extern` block
1914 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1915 pub enum ForeignItemKind {
1916 /// A foreign function
1917 Fn(P<FnDecl>, Generics),
1918 /// A foreign static item (`static ext: u8`), with optional mutability
1919 /// (the boolean is true when mutable)
1920 Static(P<Ty>, bool),
1923 impl ForeignItemKind {
1924 pub fn descriptive_variant(&self) -> &str {
1926 ForeignItemKind::Fn(..) => "foreign function",
1927 ForeignItemKind::Static(..) => "foreign static item"
1937 // are ASTs encodable?
1939 fn check_asts_encodable() {
1940 fn assert_encodable<T: serialize::Encodable>() {}
1941 assert_encodable::<Crate>();