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(),
330 /// A `where` clause in a definition
331 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
332 pub struct WhereClause {
334 pub predicates: Vec<WherePredicate>,
337 /// A single predicate in a `where` clause
338 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
339 pub enum WherePredicate {
340 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
341 BoundPredicate(WhereBoundPredicate),
342 /// A lifetime predicate, e.g. `'a: 'b+'c`
343 RegionPredicate(WhereRegionPredicate),
344 /// An equality predicate (unsupported)
345 EqPredicate(WhereEqPredicate),
350 /// E.g. `for<'c> Foo: Send+Clone+'c`
351 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
352 pub struct WhereBoundPredicate {
354 /// Any lifetimes from a `for` binding
355 pub bound_lifetimes: Vec<LifetimeDef>,
356 /// The type being bounded
357 pub bounded_ty: P<Ty>,
358 /// Trait and lifetime bounds (`Clone+Send+'static`)
359 pub bounds: TyParamBounds,
362 /// A lifetime predicate.
365 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
366 pub struct WhereRegionPredicate {
368 pub lifetime: Lifetime,
369 pub bounds: Vec<Lifetime>,
372 /// An equality predicate (unsupported).
375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
376 pub struct WhereEqPredicate {
383 /// The set of MetaItems that define the compilation environment of the crate,
384 /// used to drive conditional compilation
385 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
387 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
390 pub attrs: Vec<Attribute>,
394 /// A spanned compile-time attribute list item.
395 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
397 /// Possible values inside of compile-time attribute lists.
399 /// E.g. the '..' in `#[name(..)]`.
400 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
401 pub enum NestedMetaItemKind {
402 /// A full MetaItem, for recursive meta items.
406 /// E.g. "foo", 64, true
410 /// A spanned compile-time attribute item.
412 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
413 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
414 pub struct MetaItem {
416 pub node: MetaItemKind,
420 /// A compile-time attribute item.
422 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
423 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
424 pub enum MetaItemKind {
427 /// E.g. `test` as in `#[test]`
431 /// E.g. `derive(..)` as in `#[derive(..)]`
432 List(Vec<NestedMetaItem>),
433 /// Name value meta item.
435 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
439 /// A Block (`{ .. }`).
441 /// E.g. `{ .. }` as in `fn foo() { .. }`
442 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
444 /// Statements in a block
445 pub stmts: Vec<Stmt>,
447 /// Distinguishes between `unsafe { ... }` and `{ ... }`
448 pub rules: BlockCheckMode,
452 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
459 impl fmt::Debug for Pat {
460 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
461 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
466 pub fn walk<F>(&self, it: &mut F) -> bool
467 where F: FnMut(&Pat) -> bool
474 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
475 PatKind::Struct(_, ref fields, _) => {
476 fields.iter().all(|field| field.node.pat.walk(it))
478 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
479 s.iter().all(|p| p.walk(it))
481 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
484 PatKind::Slice(ref before, ref slice, ref after) => {
485 before.iter().all(|p| p.walk(it)) &&
486 slice.iter().all(|p| p.walk(it)) &&
487 after.iter().all(|p| p.walk(it))
501 /// A single field in a struct pattern
503 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
504 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
505 /// except is_shorthand is true
506 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
507 pub struct FieldPat {
508 /// The identifier for the field
510 /// The pattern the field is destructured to
512 pub is_shorthand: bool,
513 pub attrs: ThinVec<Attribute>,
516 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
517 pub enum BindingMode {
522 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
528 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
530 /// Represents a wildcard pattern (`_`)
533 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
534 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
535 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
536 /// during name resolution.
537 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
539 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
540 /// The `bool` is `true` in the presence of a `..`.
541 Struct(Path, Vec<Spanned<FieldPat>>, bool),
543 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
544 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
545 /// 0 <= position <= subpats.len()
546 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
548 /// A possibly qualified path pattern.
549 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
550 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
551 /// only legally refer to associated constants.
552 Path(Option<QSelf>, Path),
554 /// A tuple pattern `(a, b)`.
555 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
556 /// 0 <= position <= subpats.len()
557 Tuple(Vec<P<Pat>>, Option<usize>),
560 /// A reference pattern, e.g. `&mut (a, b)`
561 Ref(P<Pat>, Mutability),
564 /// A range pattern, e.g. `1...2` or `1..2`
565 Range(P<Expr>, P<Expr>, RangeEnd),
566 /// `[a, b, ..i, y, z]` is represented as:
567 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
568 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
569 /// A macro pattern; pre-expansion
573 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
574 pub enum Mutability {
579 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
581 /// The `+` operator (addition)
583 /// The `-` operator (subtraction)
585 /// The `*` operator (multiplication)
587 /// The `/` operator (division)
589 /// The `%` operator (modulus)
591 /// The `&&` operator (logical and)
593 /// The `||` operator (logical or)
595 /// The `^` operator (bitwise xor)
597 /// The `&` operator (bitwise and)
599 /// The `|` operator (bitwise or)
601 /// The `<<` operator (shift left)
603 /// The `>>` operator (shift right)
605 /// The `==` operator (equality)
607 /// The `<` operator (less than)
609 /// The `<=` operator (less than or equal to)
611 /// The `!=` operator (not equal to)
613 /// The `>=` operator (greater than or equal to)
615 /// The `>` operator (greater than)
620 pub fn to_string(&self) -> &'static str {
621 use self::BinOpKind::*;
643 pub fn lazy(&self) -> bool {
645 BinOpKind::And | BinOpKind::Or => true,
650 pub fn is_shift(&self) -> bool {
652 BinOpKind::Shl | BinOpKind::Shr => true,
656 pub fn is_comparison(&self) -> bool {
657 use self::BinOpKind::*;
659 Eq | Lt | Le | Ne | Gt | Ge =>
661 And | Or | Add | Sub | Mul | Div | Rem |
662 BitXor | BitAnd | BitOr | Shl | Shr =>
666 /// Returns `true` if the binary operator takes its arguments by value
667 pub fn is_by_value(&self) -> bool {
668 !self.is_comparison()
672 pub type BinOp = Spanned<BinOpKind>;
674 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
676 /// The `*` operator for dereferencing
678 /// The `!` operator for logical inversion
680 /// The `-` operator for negation
685 /// Returns `true` if the unary operator takes its argument by value
686 pub fn is_by_value(u: UnOp) -> bool {
688 UnOp::Neg | UnOp::Not => true,
693 pub fn to_string(op: UnOp) -> &'static str {
703 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
711 pub fn add_trailing_semicolon(mut self) -> Self {
712 self.node = match self.node {
713 StmtKind::Expr(expr) => StmtKind::Semi(expr),
714 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
715 (mac, MacStmtStyle::Semicolon, attrs)
722 pub fn is_item(&self) -> bool {
724 StmtKind::Local(_) => true,
730 impl fmt::Debug for Stmt {
731 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
732 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
737 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
739 /// A local (let) binding.
742 /// An item definition.
745 /// Expr without trailing semi-colon.
750 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
753 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
754 pub enum MacStmtStyle {
755 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
756 /// `foo!(...);`, `foo![...];`
758 /// The macro statement had braces; e.g. foo! { ... }
760 /// The macro statement had parentheses or brackets and no semicolon; e.g.
761 /// `foo!(...)`. All of these will end up being converted into macro
766 // FIXME (pending discussion of #1697, #2178...): local should really be
767 // a refinement on pat.
768 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
769 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
772 pub ty: Option<P<Ty>>,
773 /// Initializer expression to set the value, if any
774 pub init: Option<P<Expr>>,
777 pub attrs: ThinVec<Attribute>,
780 /// An arm of a 'match'.
782 /// E.g. `0...10 => { println!("match!") }` as in
786 /// 0...10 => { println!("match!") },
787 /// _ => { println!("no match!") },
790 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
792 pub attrs: Vec<Attribute>,
793 pub pats: Vec<P<Pat>>,
794 pub guard: Option<P<Expr>>,
798 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
800 pub ident: SpannedIdent,
803 pub is_shorthand: bool,
804 pub attrs: ThinVec<Attribute>,
807 pub type SpannedIdent = Spanned<Ident>;
809 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
810 pub enum BlockCheckMode {
812 Unsafe(UnsafeSource),
815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
816 pub enum UnsafeSource {
822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
827 pub attrs: ThinVec<Attribute>
830 impl fmt::Debug for Expr {
831 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
832 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
836 /// Limit types of a range (inclusive or exclusive)
837 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
838 pub enum RangeLimits {
839 /// Inclusive at the beginning, exclusive at the end
841 /// Inclusive at the beginning and end
845 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
847 /// A `box x` expression.
849 /// First expr is the place; second expr is the value.
850 InPlace(P<Expr>, P<Expr>),
851 /// An array (`[a, b, c, d]`)
855 /// The first field resolves to the function itself,
856 /// and the second field is the list of arguments
857 Call(P<Expr>, Vec<P<Expr>>),
858 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
860 /// The `PathSegment` represents the method name and its generic arguments
861 /// (within the angle brackets).
862 /// The first element of the vector of `Expr`s is the expression that evaluates
863 /// to the object on which the method is being called on (the receiver),
864 /// and the remaining elements are the rest of the arguments.
865 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
866 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
867 MethodCall(PathSegment, Vec<P<Expr>>),
868 /// A tuple (`(a, b, c ,d)`)
870 /// A binary operation (For example: `a + b`, `a * b`)
871 Binary(BinOp, P<Expr>, P<Expr>),
872 /// A unary operation (For example: `!x`, `*x`)
873 Unary(UnOp, P<Expr>),
874 /// A literal (For example: `1`, `"foo"`)
876 /// A cast (`foo as f64`)
877 Cast(P<Expr>, P<Ty>),
878 Type(P<Expr>, P<Ty>),
879 /// An `if` block, with an optional else block
881 /// `if expr { block } else { expr }`
882 If(P<Expr>, P<Block>, Option<P<Expr>>),
883 /// An `if let` expression with an optional else block
885 /// `if let pat = expr { block } else { expr }`
887 /// This is desugared to a `match` expression.
888 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
889 /// A while loop, with an optional label
891 /// `'label: while expr { block }`
892 While(P<Expr>, P<Block>, Option<SpannedIdent>),
893 /// A while-let loop, with an optional label
895 /// `'label: while let pat = expr { block }`
897 /// This is desugared to a combination of `loop` and `match` expressions.
898 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
899 /// A for loop, with an optional label
901 /// `'label: for pat in expr { block }`
903 /// This is desugared to a combination of `loop` and `match` expressions.
904 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
905 /// Conditionless loop (can be exited with break, continue, or return)
907 /// `'label: loop { block }`
908 Loop(P<Block>, Option<SpannedIdent>),
910 Match(P<Expr>, Vec<Arm>),
911 /// A closure (for example, `move |a, b, c| a + b + c`)
913 /// The final span is the span of the argument block `|...|`
914 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
915 /// A block (`{ ... }`)
917 /// A catch block (`catch { ... }`)
920 /// An assignment (`a = foo()`)
921 Assign(P<Expr>, P<Expr>),
922 /// An assignment with an operator
924 /// For example, `a += 1`.
925 AssignOp(BinOp, P<Expr>, P<Expr>),
926 /// Access of a named struct field (`obj.foo`)
927 Field(P<Expr>, SpannedIdent),
928 /// Access of an unnamed field of a struct or tuple-struct
930 /// For example, `foo.0`.
931 TupField(P<Expr>, Spanned<usize>),
932 /// An indexing operation (`foo[2]`)
933 Index(P<Expr>, P<Expr>),
934 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
935 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
937 /// Variable reference, possibly containing `::` and/or type
938 /// parameters, e.g. foo::bar::<baz>.
940 /// Optionally "qualified",
941 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
942 Path(Option<QSelf>, Path),
944 /// A referencing operation (`&a` or `&mut a`)
945 AddrOf(Mutability, P<Expr>),
946 /// A `break`, with an optional label to break, and an optional expression
947 Break(Option<SpannedIdent>, Option<P<Expr>>),
948 /// A `continue`, with an optional label
949 Continue(Option<SpannedIdent>),
950 /// A `return`, with an optional value to be returned
951 Ret(Option<P<Expr>>),
953 /// Output of the `asm!()` macro
954 InlineAsm(P<InlineAsm>),
956 /// A macro invocation; pre-expansion
959 /// A struct literal expression.
961 /// For example, `Foo {x: 1, y: 2}`, or
962 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
963 Struct(Path, Vec<Field>, Option<P<Expr>>),
965 /// An array literal constructed from one repeated element.
967 /// For example, `[1; 5]`. The first expression is the element
968 /// to be repeated; the second is the number of times to repeat it.
969 Repeat(P<Expr>, P<Expr>),
971 /// No-op: used solely so we can pretty-print faithfully
978 /// The explicit Self type in a "qualified path". The actual
979 /// path, including the trait and the associated item, is stored
980 /// separately. `position` represents the index of the associated
981 /// item qualified with this Self type.
983 /// ```ignore (only-for-syntax-highlight)
984 /// <Vec<T> as a::b::Trait>::AssociatedItem
985 /// ^~~~~ ~~~~~~~~~~~~~~^
988 /// <Vec<T>>::AssociatedItem
992 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
999 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1000 pub enum CaptureBy {
1005 pub type Mac = Spanned<Mac_>;
1007 /// Represents a macro invocation. The Path indicates which macro
1008 /// is being invoked, and the vector of token-trees contains the source
1009 /// of the macro invocation.
1011 /// NB: the additional ident for a macro_rules-style macro is actually
1012 /// stored in the enclosing item. Oog.
1013 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1016 pub tts: ThinTokenStream,
1020 pub fn stream(&self) -> TokenStream {
1021 self.tts.clone().into()
1025 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1026 pub struct MacroDef {
1027 pub tokens: ThinTokenStream,
1032 pub fn stream(&self) -> TokenStream {
1033 self.tokens.clone().into()
1037 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1039 /// A regular string, like `"foo"`
1041 /// A raw string, like `r##"foo"##`
1043 /// The uint is the number of `#` symbols used
1048 pub type Lit = Spanned<LitKind>;
1050 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1051 pub enum LitIntType {
1059 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1060 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1062 /// A string literal (`"foo"`)
1063 Str(Symbol, StrStyle),
1064 /// A byte string (`b"foo"`)
1065 ByteStr(Rc<Vec<u8>>),
1066 /// A byte char (`b'f'`)
1068 /// A character literal (`'a'`)
1070 /// An integer literal (`1`)
1071 Int(u128, LitIntType),
1072 /// A float literal (`1f64` or `1E10f64`)
1073 Float(Symbol, FloatTy),
1074 /// A float literal without a suffix (`1.0 or 1.0E10`)
1075 FloatUnsuffixed(Symbol),
1076 /// A boolean literal
1081 /// Returns true if this literal is a string and false otherwise.
1082 pub fn is_str(&self) -> bool {
1084 LitKind::Str(..) => true,
1089 /// Returns true if this literal has no suffix. Note: this will return true
1090 /// for literals with prefixes such as raw strings and byte strings.
1091 pub fn is_unsuffixed(&self) -> bool {
1093 // unsuffixed variants
1095 LitKind::ByteStr(..) |
1098 LitKind::Int(_, LitIntType::Unsuffixed) |
1099 LitKind::FloatUnsuffixed(..) |
1100 LitKind::Bool(..) => true,
1101 // suffixed variants
1102 LitKind::Int(_, LitIntType::Signed(..)) |
1103 LitKind::Int(_, LitIntType::Unsigned(..)) |
1104 LitKind::Float(..) => false,
1108 /// Returns true if this literal has a suffix.
1109 pub fn is_suffixed(&self) -> bool {
1110 !self.is_unsuffixed()
1114 // NB: If you change this, you'll probably want to change the corresponding
1115 // type structure in middle/ty.rs as well.
1116 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1119 pub mutbl: Mutability,
1122 /// Represents a method's signature in a trait declaration,
1123 /// or in an implementation.
1124 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1125 pub struct MethodSig {
1126 pub unsafety: Unsafety,
1127 pub constness: Spanned<Constness>,
1129 pub decl: P<FnDecl>,
1130 pub generics: Generics,
1133 /// Represents an item declaration within a trait declaration,
1134 /// possibly including a default implementation. A trait item is
1135 /// either required (meaning it doesn't have an implementation, just a
1136 /// signature) or provided (meaning it has a default implementation).
1137 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1138 pub struct TraitItem {
1141 pub attrs: Vec<Attribute>,
1142 pub node: TraitItemKind,
1146 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1147 pub enum TraitItemKind {
1148 Const(P<Ty>, Option<P<Expr>>),
1149 Method(MethodSig, Option<P<Block>>),
1150 Type(TyParamBounds, Option<P<Ty>>),
1154 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1155 pub struct ImplItem {
1158 pub vis: Visibility,
1159 pub defaultness: Defaultness,
1160 pub attrs: Vec<Attribute>,
1161 pub node: ImplItemKind,
1165 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1166 pub enum ImplItemKind {
1167 Const(P<Ty>, P<Expr>),
1168 Method(MethodSig, P<Block>),
1173 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1183 impl fmt::Debug for IntTy {
1184 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1185 fmt::Display::fmt(self, f)
1189 impl fmt::Display for IntTy {
1190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1191 write!(f, "{}", self.ty_to_string())
1196 pub fn ty_to_string(&self) -> &'static str {
1198 IntTy::Is => "isize",
1200 IntTy::I16 => "i16",
1201 IntTy::I32 => "i32",
1202 IntTy::I64 => "i64",
1203 IntTy::I128 => "i128",
1207 pub fn val_to_string(&self, val: i128) -> String {
1208 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1209 // are parsed as u128, so we wouldn't want to print an extra negative
1211 format!("{}{}", val as u128, self.ty_to_string())
1214 pub fn bit_width(&self) -> Option<usize> {
1216 IntTy::Is => return None,
1226 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1237 pub fn ty_to_string(&self) -> &'static str {
1239 UintTy::Us => "usize",
1241 UintTy::U16 => "u16",
1242 UintTy::U32 => "u32",
1243 UintTy::U64 => "u64",
1244 UintTy::U128 => "u128",
1248 pub fn val_to_string(&self, val: u128) -> String {
1249 format!("{}{}", val, self.ty_to_string())
1252 pub fn bit_width(&self) -> Option<usize> {
1254 UintTy::Us => return None,
1259 UintTy::U128 => 128,
1264 impl fmt::Debug for UintTy {
1265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1266 fmt::Display::fmt(self, f)
1270 impl fmt::Display for UintTy {
1271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1272 write!(f, "{}", self.ty_to_string())
1276 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1282 impl fmt::Debug for FloatTy {
1283 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1284 fmt::Display::fmt(self, f)
1288 impl fmt::Display for FloatTy {
1289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1290 write!(f, "{}", self.ty_to_string())
1295 pub fn ty_to_string(&self) -> &'static str {
1297 FloatTy::F32 => "f32",
1298 FloatTy::F64 => "f64",
1302 pub fn bit_width(&self) -> usize {
1310 // Bind a type to an associated type: `A=Foo`.
1311 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1312 pub struct TypeBinding {
1319 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1326 impl fmt::Debug for Ty {
1327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1328 write!(f, "type({})", pprust::ty_to_string(self))
1332 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1333 pub struct BareFnTy {
1334 pub unsafety: Unsafety,
1336 pub lifetimes: Vec<LifetimeDef>,
1340 /// The different kinds of types recognized by the compiler
1341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1343 /// A variable-length slice (`[T]`)
1345 /// A fixed length array (`[T; n]`)
1346 Array(P<Ty>, P<Expr>),
1347 /// A raw pointer (`*const T` or `*mut T`)
1349 /// A reference (`&'a T` or `&'a mut T`)
1350 Rptr(Option<Lifetime>, MutTy),
1351 /// A bare function (e.g. `fn(usize) -> bool`)
1352 BareFn(P<BareFnTy>),
1353 /// The never type (`!`)
1355 /// A tuple (`(A, B, C, D,...)`)
1357 /// A path (`module::module::...::Type`), optionally
1358 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1360 /// Type parameters are stored in the Path itself
1361 Path(Option<QSelf>, Path),
1362 /// A trait object type `Bound1 + Bound2 + Bound3`
1363 /// where `Bound` is a trait or a lifetime.
1364 TraitObject(TyParamBounds),
1365 /// An `impl Bound1 + Bound2 + Bound3` type
1366 /// where `Bound` is a trait or a lifetime.
1367 ImplTrait(TyParamBounds),
1368 /// No-op; kept solely so that we can pretty-print faithfully
1372 /// TyKind::Infer means the type should be inferred instead of it having been
1373 /// specified. This can appear anywhere in a type.
1375 /// Inferred type of a `self` or `&self` argument in a method.
1377 // A macro in the type position.
1379 /// Placeholder for a kind that has failed to be defined.
1383 /// Inline assembly dialect.
1385 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1386 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1387 pub enum AsmDialect {
1392 /// Inline assembly.
1394 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1395 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1396 pub struct InlineAsmOutput {
1397 pub constraint: Symbol,
1400 pub is_indirect: bool,
1403 /// Inline assembly.
1405 /// E.g. `asm!("NOP");`
1406 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1407 pub struct InlineAsm {
1409 pub asm_str_style: StrStyle,
1410 pub outputs: Vec<InlineAsmOutput>,
1411 pub inputs: Vec<(Symbol, P<Expr>)>,
1412 pub clobbers: Vec<Symbol>,
1414 pub alignstack: bool,
1415 pub dialect: AsmDialect,
1416 pub ctxt: SyntaxContext,
1419 /// An argument in a function header.
1421 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1422 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1429 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1431 /// E.g. `&mut self` as in `fn foo(&mut self)`
1432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1434 /// `self`, `mut self`
1436 /// `&'lt self`, `&'lt mut self`
1437 Region(Option<Lifetime>, Mutability),
1438 /// `self: TYPE`, `mut self: TYPE`
1439 Explicit(P<Ty>, Mutability),
1442 pub type ExplicitSelf = Spanned<SelfKind>;
1445 pub fn to_self(&self) -> Option<ExplicitSelf> {
1446 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1447 if ident.node.name == keywords::SelfValue.name() {
1448 return match self.ty.node {
1449 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1450 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1451 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1453 _ => Some(respan(self.pat.span.to(self.ty.span),
1454 SelfKind::Explicit(self.ty.clone(), mutbl))),
1461 pub fn is_self(&self) -> bool {
1462 if let PatKind::Ident(_, ident, _) = self.pat.node {
1463 ident.node.name == keywords::SelfValue.name()
1469 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1470 let span = eself.span.to(eself_ident.span);
1471 let infer_ty = P(Ty {
1473 node: TyKind::ImplicitSelf,
1476 let arg = |mutbl, ty| Arg {
1479 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1486 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1487 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1488 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1490 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1497 /// Header (not the body) of a function declaration.
1499 /// E.g. `fn foo(bar: baz)`
1500 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1502 pub inputs: Vec<Arg>,
1503 pub output: FunctionRetTy,
1508 pub fn get_self(&self) -> Option<ExplicitSelf> {
1509 self.inputs.get(0).and_then(Arg::to_self)
1511 pub fn has_self(&self) -> bool {
1512 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1516 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1522 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1523 pub enum Constness {
1528 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1529 pub enum Defaultness {
1534 impl fmt::Display for Unsafety {
1535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1536 fmt::Display::fmt(match *self {
1537 Unsafety::Normal => "normal",
1538 Unsafety::Unsafe => "unsafe",
1543 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1544 pub enum ImplPolarity {
1545 /// `impl Trait for Type`
1547 /// `impl !Trait for Type`
1551 impl fmt::Debug for ImplPolarity {
1552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1554 ImplPolarity::Positive => "positive".fmt(f),
1555 ImplPolarity::Negative => "negative".fmt(f),
1561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1562 pub enum FunctionRetTy {
1563 /// Return type is not specified.
1565 /// Functions default to `()` and
1566 /// closures default to inference. Span points to where return
1567 /// type would be inserted.
1573 impl FunctionRetTy {
1574 pub fn span(&self) -> Span {
1576 FunctionRetTy::Default(span) => span,
1577 FunctionRetTy::Ty(ref ty) => ty.span,
1582 /// Module declaration.
1584 /// E.g. `mod foo;` or `mod foo { .. }`
1585 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1587 /// A span from the first token past `{` to the last token until `}`.
1588 /// For `mod foo;`, the inner span ranges from the first token
1589 /// to the last token in the external file.
1591 pub items: Vec<P<Item>>,
1594 /// Foreign module declaration.
1596 /// E.g. `extern { .. }` or `extern C { .. }`
1597 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1598 pub struct ForeignMod {
1600 pub items: Vec<ForeignItem>,
1603 /// Global inline assembly
1605 /// aka module-level assembly or file-scoped assembly
1606 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1607 pub struct GlobalAsm {
1609 pub ctxt: SyntaxContext,
1612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1613 pub struct EnumDef {
1614 pub variants: Vec<Variant>,
1617 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1618 pub struct Variant_ {
1620 pub attrs: Vec<Attribute>,
1621 pub data: VariantData,
1622 /// Explicit discriminant, e.g. `Foo = 1`
1623 pub disr_expr: Option<P<Expr>>,
1626 pub type Variant = Spanned<Variant_>;
1628 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1629 pub struct PathListItem_ {
1631 /// renamed in list, e.g. `use foo::{bar as baz};`
1632 pub rename: Option<Ident>,
1636 pub type PathListItem = Spanned<PathListItem_>;
1638 pub type ViewPath = Spanned<ViewPath_>;
1640 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1641 pub enum ViewPath_ {
1643 /// `foo::bar::baz as quux`
1647 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1648 ViewPathSimple(Ident, Path),
1653 /// `foo::bar::{a,b,c}`
1654 ViewPathList(Path, Vec<PathListItem>)
1658 pub fn path(&self) -> &Path {
1660 ViewPathSimple(_, ref path) |
1661 ViewPathGlob (ref path) |
1662 ViewPathList(ref path, _) => path
1668 /// Distinguishes between Attributes that decorate items and Attributes that
1669 /// are contained as statements within items. These two cases need to be
1670 /// distinguished for pretty-printing.
1671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1672 pub enum AttrStyle {
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1678 pub struct AttrId(pub usize);
1680 /// Meta-data associated with an item
1681 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1682 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1683 pub struct Attribute {
1685 pub style: AttrStyle,
1687 pub tokens: TokenStream,
1688 pub is_sugared_doc: bool,
1692 /// TraitRef's appear in impls.
1694 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1695 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1696 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1697 /// same as the impl's node id).
1698 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1699 pub struct TraitRef {
1704 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1705 pub struct PolyTraitRef {
1706 /// The `'a` in `<'a> Foo<&'a T>`
1707 pub bound_lifetimes: Vec<LifetimeDef>,
1709 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1710 pub trait_ref: TraitRef,
1716 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1718 bound_lifetimes: lifetimes,
1719 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1725 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1726 pub enum Visibility {
1729 Restricted { path: P<Path>, id: NodeId },
1733 /// Field of a struct.
1735 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1736 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1737 pub struct StructField {
1739 pub ident: Option<Ident>,
1740 pub vis: Visibility,
1743 pub attrs: Vec<Attribute>,
1746 /// Fields and Ids of enum variants and structs
1748 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1749 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1750 /// One shared Id can be successfully used for these two purposes.
1751 /// Id of the whole enum lives in `Item`.
1753 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1754 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1755 /// the variant itself" from enum variants.
1756 /// Id of the whole struct lives in `Item`.
1757 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1758 pub enum VariantData {
1761 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1762 Struct(Vec<StructField>, NodeId),
1765 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1766 Tuple(Vec<StructField>, NodeId),
1769 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1774 pub fn fields(&self) -> &[StructField] {
1776 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1780 pub fn id(&self) -> NodeId {
1782 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1785 pub fn is_struct(&self) -> bool {
1786 if let VariantData::Struct(..) = *self { true } else { false }
1788 pub fn is_tuple(&self) -> bool {
1789 if let VariantData::Tuple(..) = *self { true } else { false }
1791 pub fn is_unit(&self) -> bool {
1792 if let VariantData::Unit(..) = *self { true } else { false }
1798 /// The name might be a dummy name in case of anonymous items
1799 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1802 pub attrs: Vec<Attribute>,
1805 pub vis: Visibility,
1809 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1811 /// An`extern crate` item, with optional original crate name.
1813 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1814 ExternCrate(Option<Name>),
1815 /// A use declaration (`use` or `pub use`) item.
1817 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1819 /// A static item (`static` or `pub static`).
1821 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1822 Static(P<Ty>, Mutability, P<Expr>),
1823 /// A constant item (`const` or `pub const`).
1825 /// E.g. `const FOO: i32 = 42;`
1826 Const(P<Ty>, P<Expr>),
1827 /// A function declaration (`fn` or `pub fn`).
1829 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1830 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1831 /// A module declaration (`mod` or `pub mod`).
1833 /// E.g. `mod foo;` or `mod foo { .. }`
1835 /// An external module (`extern` or `pub extern`).
1837 /// E.g. `extern {}` or `extern "C" {}`
1838 ForeignMod(ForeignMod),
1839 /// Module-level inline assembly (from `global_asm!()`)
1840 GlobalAsm(P<GlobalAsm>),
1841 /// A type alias (`type` or `pub type`).
1843 /// E.g. `type Foo = Bar<u8>;`
1844 Ty(P<Ty>, Generics),
1845 /// An enum definition (`enum` or `pub enum`).
1847 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1848 Enum(EnumDef, Generics),
1849 /// A struct definition (`struct` or `pub struct`).
1851 /// E.g. `struct Foo<A> { x: A }`
1852 Struct(VariantData, Generics),
1853 /// A union definition (`union` or `pub union`).
1855 /// E.g. `union Foo<A, B> { x: A, y: B }`
1856 Union(VariantData, Generics),
1857 /// A Trait declaration (`trait` or `pub trait`).
1859 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1860 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1861 // Default trait implementation.
1863 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1864 DefaultImpl(Unsafety, TraitRef),
1865 /// An implementation.
1867 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1872 Option<TraitRef>, // (optional) trait this impl implements
1875 /// A macro invocation.
1877 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1880 /// A macro definition.
1885 pub fn descriptive_variant(&self) -> &str {
1887 ItemKind::ExternCrate(..) => "extern crate",
1888 ItemKind::Use(..) => "use",
1889 ItemKind::Static(..) => "static item",
1890 ItemKind::Const(..) => "constant item",
1891 ItemKind::Fn(..) => "function",
1892 ItemKind::Mod(..) => "module",
1893 ItemKind::ForeignMod(..) => "foreign module",
1894 ItemKind::GlobalAsm(..) => "global asm",
1895 ItemKind::Ty(..) => "type alias",
1896 ItemKind::Enum(..) => "enum",
1897 ItemKind::Struct(..) => "struct",
1898 ItemKind::Union(..) => "union",
1899 ItemKind::Trait(..) => "trait",
1901 ItemKind::MacroDef(..) |
1902 ItemKind::Impl(..) |
1903 ItemKind::DefaultImpl(..) => "item"
1908 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1909 pub struct ForeignItem {
1911 pub attrs: Vec<Attribute>,
1912 pub node: ForeignItemKind,
1915 pub vis: Visibility,
1918 /// An item within an `extern` block
1919 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1920 pub enum ForeignItemKind {
1921 /// A foreign function
1922 Fn(P<FnDecl>, Generics),
1923 /// A foreign static item (`static ext: u8`), with optional mutability
1924 /// (the boolean is true when mutable)
1925 Static(P<Ty>, bool),
1928 impl ForeignItemKind {
1929 pub fn descriptive_variant(&self) -> &str {
1931 ForeignItemKind::Fn(..) => "foreign function",
1932 ForeignItemKind::Static(..) => "foreign static item"
1942 // are ASTs encodable?
1944 fn check_asts_encodable() {
1945 fn assert_encodable<T: serialize::Encodable>() {}
1946 assert_encodable::<Crate>();