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::Symbol as Name;
18 pub use util::ThinVec;
20 use syntax_pos::{mk_sp, Span, DUMMY_SP, ExpnId};
21 use codemap::{respan, Spanned};
23 use ext::hygiene::SyntaxContext;
26 use symbol::{Symbol, keywords};
27 use tokenstream::{TokenTree};
29 use std::collections::HashSet;
34 use serialize::{self, Encodable, Decodable, Encoder, Decoder};
36 use rustc_i128::{u128, i128};
38 /// An identifier contains a Name (index into the interner
39 /// table) and a SyntaxContext to track renaming and
40 /// macro expansion per Flatt et al., "Macros That Work Together"
41 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
44 pub ctxt: SyntaxContext
48 pub const fn with_empty_ctxt(name: Name) -> Ident {
49 Ident { name: name, ctxt: SyntaxContext::empty() }
52 /// Maps a string to an identifier with an empty syntax context.
53 pub fn from_str(s: &str) -> Ident {
54 Ident::with_empty_ctxt(Symbol::intern(s))
57 pub fn unhygienize(&self) -> Ident {
58 Ident { name: self.name, ctxt: SyntaxContext::empty() }
62 impl fmt::Debug for Ident {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 write!(f, "{}{:?}", self.name, self.ctxt)
68 impl fmt::Display for Ident {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 fmt::Display::fmt(&self.name, f)
74 impl Encodable for Ident {
75 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
80 impl Decodable for Ident {
81 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
82 Ok(Ident::with_empty_ctxt(Name::decode(d)?))
86 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
93 impl fmt::Debug for Lifetime {
94 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
99 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
100 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
101 pub struct LifetimeDef {
102 pub attrs: ThinVec<Attribute>,
103 pub lifetime: Lifetime,
104 pub bounds: Vec<Lifetime>
107 /// A "Path" is essentially Rust's notion of a name.
109 /// It's represented as a sequence of identifiers,
110 /// along with a bunch of supporting information.
112 /// E.g. `std::cmp::PartialEq`
113 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
116 /// The segments in the path: the things separated by `::`.
117 /// Global paths begin with `keywords::CrateRoot`.
118 pub segments: Vec<PathSegment>,
121 impl fmt::Debug for Path {
122 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123 write!(f, "path({})", pprust::path_to_string(self))
127 impl fmt::Display for Path {
128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129 write!(f, "{}", pprust::path_to_string(self))
134 // convert a span and an identifier to the corresponding
136 pub fn from_ident(s: Span, identifier: Ident) -> Path {
139 segments: vec![identifier.into()],
143 pub fn default_to_global(mut self) -> Path {
144 let name = self.segments[0].identifier.name;
145 if !self.is_global() && name != "$crate" &&
146 name != keywords::SelfValue.name() && name != keywords::Super.name() {
147 self.segments.insert(0, PathSegment::crate_root());
152 pub fn is_global(&self) -> bool {
153 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
157 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
159 /// E.g. `std`, `String` or `Box<T>`
160 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
161 pub struct PathSegment {
162 /// The identifier portion of this path segment.
163 pub identifier: Ident,
165 /// Type/lifetime parameters attached to this path. They come in
166 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
167 /// this is more than just simple syntactic sugar; the use of
168 /// parens affects the region binding rules, so we preserve the
170 /// The `Option<P<..>>` wrapper is purely a size optimization;
171 /// `None` is used to represent both `Path` and `Path<>`.
172 pub parameters: Option<P<PathParameters>>,
175 impl From<Ident> for PathSegment {
176 fn from(id: Ident) -> Self {
177 PathSegment { identifier: id, parameters: None }
182 pub fn crate_root() -> Self {
184 identifier: keywords::CrateRoot.ident(),
190 /// Parameters of a path segment.
192 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
193 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
194 pub enum PathParameters {
195 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
196 AngleBracketed(AngleBracketedParameterData),
197 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
198 Parenthesized(ParenthesizedParameterData),
201 /// A path like `Foo<'a, T>`
202 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
203 pub struct AngleBracketedParameterData {
204 /// The lifetime parameters for this path segment.
205 pub lifetimes: Vec<Lifetime>,
206 /// The type parameters for this path segment, if present.
207 pub types: P<[P<Ty>]>,
208 /// Bindings (equality constraints) on associated types, if present.
210 /// E.g., `Foo<A=Bar>`.
211 pub bindings: P<[TypeBinding]>,
214 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
215 fn into(self) -> Option<P<PathParameters>> {
216 let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
217 if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
221 /// A path like `Foo(A,B) -> C`
222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
223 pub struct ParenthesizedParameterData {
228 pub inputs: Vec<P<Ty>>,
231 pub output: Option<P<Ty>>,
234 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
235 pub struct NodeId(u32);
238 pub fn new(x: usize) -> NodeId {
239 assert!(x < (u32::MAX as usize));
243 pub fn from_u32(x: u32) -> NodeId {
247 pub fn as_usize(&self) -> usize {
251 pub fn as_u32(&self) -> u32 {
256 impl fmt::Display for NodeId {
257 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
258 fmt::Display::fmt(&self.0, f)
262 impl serialize::UseSpecializedEncodable for NodeId {
263 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
268 impl serialize::UseSpecializedDecodable for NodeId {
269 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
270 d.read_u32().map(NodeId)
274 /// Node id used to represent the root of the crate.
275 pub const CRATE_NODE_ID: NodeId = NodeId(0);
277 /// When parsing and doing expansions, we initially give all AST nodes this AST
278 /// node value. Then later, in the renumber pass, we renumber them to have
279 /// small, positive ids.
280 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
282 /// The AST represents all type param bounds as types.
283 /// typeck::collect::compute_bounds matches these against
284 /// the "special" built-in traits (see middle::lang_items) and
285 /// detects Copy, Send and Sync.
286 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
287 pub enum TyParamBound {
288 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
289 RegionTyParamBound(Lifetime)
292 /// A modifier on a bound, currently this is only used for `?Sized`, where the
293 /// modifier is `Maybe`. Negative bounds should also be handled here.
294 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
295 pub enum TraitBoundModifier {
300 pub type TyParamBounds = P<[TyParamBound]>;
302 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
304 pub attrs: ThinVec<Attribute>,
307 pub bounds: TyParamBounds,
308 pub default: Option<P<Ty>>,
312 /// Represents lifetimes and type parameters attached to a declaration
313 /// of a function, enum, trait, etc.
314 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
315 pub struct Generics {
316 pub lifetimes: Vec<LifetimeDef>,
317 pub ty_params: P<[TyParam]>,
318 pub where_clause: WhereClause,
323 pub fn is_lt_parameterized(&self) -> bool {
324 !self.lifetimes.is_empty()
326 pub fn is_type_parameterized(&self) -> bool {
327 !self.ty_params.is_empty()
329 pub fn is_parameterized(&self) -> bool {
330 self.is_lt_parameterized() || self.is_type_parameterized()
332 pub fn span_for_name(&self, name: &str) -> Option<Span> {
333 for t in &self.ty_params {
334 if t.ident.name == name {
342 impl Default for Generics {
343 /// Creates an instance of `Generics`.
344 fn default() -> Generics {
346 lifetimes: Vec::new(),
348 where_clause: WhereClause {
350 predicates: Vec::new(),
357 /// A `where` clause in a definition
358 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
359 pub struct WhereClause {
361 pub predicates: Vec<WherePredicate>,
364 /// A single predicate in a `where` clause
365 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
366 pub enum WherePredicate {
367 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
368 BoundPredicate(WhereBoundPredicate),
369 /// A lifetime predicate, e.g. `'a: 'b+'c`
370 RegionPredicate(WhereRegionPredicate),
371 /// An equality predicate (unsupported)
372 EqPredicate(WhereEqPredicate),
377 /// E.g. `for<'c> Foo: Send+Clone+'c`
378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
379 pub struct WhereBoundPredicate {
381 /// Any lifetimes from a `for` binding
382 pub bound_lifetimes: Vec<LifetimeDef>,
383 /// The type being bounded
384 pub bounded_ty: P<Ty>,
385 /// Trait and lifetime bounds (`Clone+Send+'static`)
386 pub bounds: TyParamBounds,
389 /// A lifetime predicate.
392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
393 pub struct WhereRegionPredicate {
395 pub lifetime: Lifetime,
396 pub bounds: Vec<Lifetime>,
399 /// An equality predicate (unsupported).
402 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
403 pub struct WhereEqPredicate {
410 /// The set of MetaItems that define the compilation environment of the crate,
411 /// used to drive conditional compilation
412 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
414 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
417 pub attrs: Vec<Attribute>,
419 pub exported_macros: Vec<MacroDef>,
422 /// A spanned compile-time attribute list item.
423 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
425 /// Possible values inside of compile-time attribute lists.
427 /// E.g. the '..' in `#[name(..)]`.
428 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
429 pub enum NestedMetaItemKind {
430 /// A full MetaItem, for recursive meta items.
434 /// E.g. "foo", 64, true
438 /// A spanned compile-time attribute item.
440 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
441 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
442 pub struct MetaItem {
444 pub node: MetaItemKind,
448 /// A compile-time attribute item.
450 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
451 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
452 pub enum MetaItemKind {
455 /// E.g. `test` as in `#[test]`
459 /// E.g. `derive(..)` as in `#[derive(..)]`
460 List(Vec<NestedMetaItem>),
461 /// Name value meta item.
463 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
467 /// A Block (`{ .. }`).
469 /// E.g. `{ .. }` as in `fn foo() { .. }`
470 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
472 /// Statements in a block
473 pub stmts: Vec<Stmt>,
475 /// Distinguishes between `unsafe { ... }` and `{ ... }`
476 pub rules: BlockCheckMode,
480 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
487 impl fmt::Debug for Pat {
488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
494 pub fn walk<F>(&self, it: &mut F) -> bool
495 where F: FnMut(&Pat) -> bool
502 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
503 PatKind::Struct(_, ref fields, _) => {
504 fields.iter().all(|field| field.node.pat.walk(it))
506 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
507 s.iter().all(|p| p.walk(it))
509 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
512 PatKind::Slice(ref before, ref slice, ref after) => {
513 before.iter().all(|p| p.walk(it)) &&
514 slice.iter().all(|p| p.walk(it)) &&
515 after.iter().all(|p| p.walk(it))
529 /// A single field in a struct pattern
531 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
532 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
533 /// except is_shorthand is true
534 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
535 pub struct FieldPat {
536 /// The identifier for the field
538 /// The pattern the field is destructured to
540 pub is_shorthand: bool,
541 pub attrs: ThinVec<Attribute>,
544 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
545 pub enum BindingMode {
550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
552 /// Represents a wildcard pattern (`_`)
555 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
556 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
557 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
558 /// during name resolution.
559 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
561 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
562 /// The `bool` is `true` in the presence of a `..`.
563 Struct(Path, Vec<Spanned<FieldPat>>, bool),
565 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
566 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
567 /// 0 <= position <= subpats.len()
568 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
570 /// A possibly qualified path pattern.
571 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
572 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
573 /// only legally refer to associated constants.
574 Path(Option<QSelf>, Path),
576 /// A tuple pattern `(a, b)`.
577 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
578 /// 0 <= position <= subpats.len()
579 Tuple(Vec<P<Pat>>, Option<usize>),
582 /// A reference pattern, e.g. `&mut (a, b)`
583 Ref(P<Pat>, Mutability),
586 /// A range pattern, e.g. `1...2`
587 Range(P<Expr>, P<Expr>),
588 /// `[a, b, ..i, y, z]` is represented as:
589 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
590 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
591 /// A macro pattern; pre-expansion
595 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
596 pub enum Mutability {
601 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
603 /// The `+` operator (addition)
605 /// The `-` operator (subtraction)
607 /// The `*` operator (multiplication)
609 /// The `/` operator (division)
611 /// The `%` operator (modulus)
613 /// The `&&` operator (logical and)
615 /// The `||` operator (logical or)
617 /// The `^` operator (bitwise xor)
619 /// The `&` operator (bitwise and)
621 /// The `|` operator (bitwise or)
623 /// The `<<` operator (shift left)
625 /// The `>>` operator (shift right)
627 /// The `==` operator (equality)
629 /// The `<` operator (less than)
631 /// The `<=` operator (less than or equal to)
633 /// The `!=` operator (not equal to)
635 /// The `>=` operator (greater than or equal to)
637 /// The `>` operator (greater than)
642 pub fn to_string(&self) -> &'static str {
643 use self::BinOpKind::*;
665 pub fn lazy(&self) -> bool {
667 BinOpKind::And | BinOpKind::Or => true,
672 pub fn is_shift(&self) -> bool {
674 BinOpKind::Shl | BinOpKind::Shr => true,
678 pub fn is_comparison(&self) -> bool {
679 use self::BinOpKind::*;
681 Eq | Lt | Le | Ne | Gt | Ge =>
683 And | Or | Add | Sub | Mul | Div | Rem |
684 BitXor | BitAnd | BitOr | Shl | Shr =>
688 /// Returns `true` if the binary operator takes its arguments by value
689 pub fn is_by_value(&self) -> bool {
690 !self.is_comparison()
694 pub type BinOp = Spanned<BinOpKind>;
696 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
698 /// The `*` operator for dereferencing
700 /// The `!` operator for logical inversion
702 /// The `-` operator for negation
707 /// Returns `true` if the unary operator takes its argument by value
708 pub fn is_by_value(u: UnOp) -> bool {
710 UnOp::Neg | UnOp::Not => true,
715 pub fn to_string(op: UnOp) -> &'static str {
725 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
733 pub fn add_trailing_semicolon(mut self) -> Self {
734 self.node = match self.node {
735 StmtKind::Expr(expr) => StmtKind::Semi(expr),
736 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
737 (mac, MacStmtStyle::Semicolon, attrs)
745 impl fmt::Debug for Stmt {
746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
747 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
754 /// A local (let) binding.
757 /// An item definition.
760 /// Expr without trailing semi-colon.
765 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
768 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
769 pub enum MacStmtStyle {
770 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
771 /// `foo!(...);`, `foo![...];`
773 /// The macro statement had braces; e.g. foo! { ... }
775 /// The macro statement had parentheses or brackets and no semicolon; e.g.
776 /// `foo!(...)`. All of these will end up being converted into macro
781 // FIXME (pending discussion of #1697, #2178...): local should really be
782 // a refinement on pat.
783 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
787 pub ty: Option<P<Ty>>,
788 /// Initializer expression to set the value, if any
789 pub init: Option<P<Expr>>,
792 pub attrs: ThinVec<Attribute>,
795 /// An arm of a 'match'.
797 /// E.g. `0...10 => { println!("match!") }` as in
801 /// 0...10 => { println!("match!") },
805 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
807 pub attrs: Vec<Attribute>,
808 pub pats: Vec<P<Pat>>,
809 pub guard: Option<P<Expr>>,
813 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
815 pub ident: SpannedIdent,
818 pub is_shorthand: bool,
819 pub attrs: ThinVec<Attribute>,
822 pub type SpannedIdent = Spanned<Ident>;
824 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
825 pub enum BlockCheckMode {
827 Unsafe(UnsafeSource),
830 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
831 pub enum UnsafeSource {
837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
842 pub attrs: ThinVec<Attribute>
845 impl fmt::Debug for Expr {
846 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
847 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
851 /// Limit types of a range (inclusive or exclusive)
852 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
853 pub enum RangeLimits {
854 /// Inclusive at the beginning, exclusive at the end
856 /// Inclusive at the beginning and end
860 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
862 /// A `box x` expression.
864 /// First expr is the place; second expr is the value.
865 InPlace(P<Expr>, P<Expr>),
866 /// An array (`[a, b, c, d]`)
870 /// The first field resolves to the function itself,
871 /// and the second field is the list of arguments
872 Call(P<Expr>, Vec<P<Expr>>),
873 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
875 /// The `SpannedIdent` is the identifier for the method name.
876 /// The vector of `Ty`s are the ascripted type parameters for the method
877 /// (within the angle brackets).
879 /// The first element of the vector of `Expr`s is the expression that evaluates
880 /// to the object on which the method is being called on (the receiver),
881 /// and the remaining elements are the rest of the arguments.
883 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
884 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
885 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
886 /// A tuple (`(a, b, c ,d)`)
888 /// A binary operation (For example: `a + b`, `a * b`)
889 Binary(BinOp, P<Expr>, P<Expr>),
890 /// A unary operation (For example: `!x`, `*x`)
891 Unary(UnOp, P<Expr>),
892 /// A literal (For example: `1`, `"foo"`)
894 /// A cast (`foo as f64`)
895 Cast(P<Expr>, P<Ty>),
896 Type(P<Expr>, P<Ty>),
897 /// An `if` block, with an optional else block
899 /// `if expr { block } else { expr }`
900 If(P<Expr>, P<Block>, Option<P<Expr>>),
901 /// An `if let` expression with an optional else block
903 /// `if let pat = expr { block } else { expr }`
905 /// This is desugared to a `match` expression.
906 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
907 /// A while loop, with an optional label
909 /// `'label: while expr { block }`
910 While(P<Expr>, P<Block>, Option<SpannedIdent>),
911 /// A while-let loop, with an optional label
913 /// `'label: while let pat = expr { block }`
915 /// This is desugared to a combination of `loop` and `match` expressions.
916 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
917 /// A for loop, with an optional label
919 /// `'label: for pat in expr { block }`
921 /// This is desugared to a combination of `loop` and `match` expressions.
922 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
923 /// Conditionless loop (can be exited with break, continue, or return)
925 /// `'label: loop { block }`
926 Loop(P<Block>, Option<SpannedIdent>),
928 Match(P<Expr>, Vec<Arm>),
929 /// A closure (for example, `move |a, b, c| a + b + c`)
931 /// The final span is the span of the argument block `|...|`
932 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
933 /// A block (`{ ... }`)
936 /// An assignment (`a = foo()`)
937 Assign(P<Expr>, P<Expr>),
938 /// An assignment with an operator
940 /// For example, `a += 1`.
941 AssignOp(BinOp, P<Expr>, P<Expr>),
942 /// Access of a named struct field (`obj.foo`)
943 Field(P<Expr>, SpannedIdent),
944 /// Access of an unnamed field of a struct or tuple-struct
946 /// For example, `foo.0`.
947 TupField(P<Expr>, Spanned<usize>),
948 /// An indexing operation (`foo[2]`)
949 Index(P<Expr>, P<Expr>),
950 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
951 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
953 /// Variable reference, possibly containing `::` and/or type
954 /// parameters, e.g. foo::bar::<baz>.
956 /// Optionally "qualified",
957 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
958 Path(Option<QSelf>, Path),
960 /// A referencing operation (`&a` or `&mut a`)
961 AddrOf(Mutability, P<Expr>),
962 /// A `break`, with an optional label to break, and an optional expression
963 Break(Option<SpannedIdent>, Option<P<Expr>>),
964 /// A `continue`, with an optional label
965 Continue(Option<SpannedIdent>),
966 /// A `return`, with an optional value to be returned
967 Ret(Option<P<Expr>>),
969 /// Output of the `asm!()` macro
970 InlineAsm(P<InlineAsm>),
972 /// A macro invocation; pre-expansion
975 /// A struct literal expression.
977 /// For example, `Foo {x: 1, y: 2}`, or
978 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
979 Struct(Path, Vec<Field>, Option<P<Expr>>),
981 /// An array literal constructed from one repeated element.
983 /// For example, `[1; 5]`. The first expression is the element
984 /// to be repeated; the second is the number of times to repeat it.
985 Repeat(P<Expr>, P<Expr>),
987 /// No-op: used solely so we can pretty-print faithfully
994 /// The explicit Self type in a "qualified path". The actual
995 /// path, including the trait and the associated item, is stored
996 /// separately. `position` represents the index of the associated
997 /// item qualified with this Self type.
1000 /// <Vec<T> as a::b::Trait>::AssociatedItem
1001 /// ^~~~~ ~~~~~~~~~~~~~~^
1004 /// <Vec<T>>::AssociatedItem
1008 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1014 /// A capture clause
1015 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1016 pub enum CaptureBy {
1021 pub type Mac = Spanned<Mac_>;
1023 /// Represents a macro invocation. The Path indicates which macro
1024 /// is being invoked, and the vector of token-trees contains the source
1025 /// of the macro invocation.
1027 /// NB: the additional ident for a macro_rules-style macro is actually
1028 /// stored in the enclosing item. Oog.
1029 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1032 pub tts: Vec<TokenTree>,
1035 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1037 /// A regular string, like `"foo"`
1039 /// A raw string, like `r##"foo"##`
1041 /// The uint is the number of `#` symbols used
1046 pub type Lit = Spanned<LitKind>;
1048 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1049 pub enum LitIntType {
1057 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1058 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1060 /// A string literal (`"foo"`)
1061 Str(Symbol, StrStyle),
1062 /// A byte string (`b"foo"`)
1063 ByteStr(Rc<Vec<u8>>),
1064 /// A byte char (`b'f'`)
1066 /// A character literal (`'a'`)
1068 /// An integer literal (`1`)
1069 Int(u128, LitIntType),
1070 /// A float literal (`1f64` or `1E10f64`)
1071 Float(Symbol, FloatTy),
1072 /// A float literal without a suffix (`1.0 or 1.0E10`)
1073 FloatUnsuffixed(Symbol),
1074 /// A boolean literal
1079 /// Returns true if this literal is a string and false otherwise.
1080 pub fn is_str(&self) -> bool {
1082 LitKind::Str(..) => true,
1087 /// Returns true if this literal has no suffix. Note: this will return true
1088 /// for literals with prefixes such as raw strings and byte strings.
1089 pub fn is_unsuffixed(&self) -> bool {
1091 // unsuffixed variants
1092 LitKind::Str(..) => true,
1093 LitKind::ByteStr(..) => true,
1094 LitKind::Byte(..) => true,
1095 LitKind::Char(..) => true,
1096 LitKind::Int(_, LitIntType::Unsuffixed) => true,
1097 LitKind::FloatUnsuffixed(..) => true,
1098 LitKind::Bool(..) => true,
1099 // suffixed variants
1100 LitKind::Int(_, LitIntType::Signed(..)) => false,
1101 LitKind::Int(_, LitIntType::Unsigned(..)) => false,
1102 LitKind::Float(..) => false,
1106 /// Returns true if this literal has a suffix.
1107 pub fn is_suffixed(&self) -> bool {
1108 !self.is_unsuffixed()
1112 // NB: If you change this, you'll probably want to change the corresponding
1113 // type structure in middle/ty.rs as well.
1114 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1117 pub mutbl: Mutability,
1120 /// Represents a method's signature in a trait declaration,
1121 /// or in an implementation.
1122 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1123 pub struct MethodSig {
1124 pub unsafety: Unsafety,
1125 pub constness: Spanned<Constness>,
1127 pub decl: P<FnDecl>,
1128 pub generics: Generics,
1131 /// Represents an item declaration within a trait declaration,
1132 /// possibly including a default implementation. A trait item is
1133 /// either required (meaning it doesn't have an implementation, just a
1134 /// signature) or provided (meaning it has a default implementation).
1135 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1136 pub struct TraitItem {
1139 pub attrs: Vec<Attribute>,
1140 pub node: TraitItemKind,
1144 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1145 pub enum TraitItemKind {
1146 Const(P<Ty>, Option<P<Expr>>),
1147 Method(MethodSig, Option<P<Block>>),
1148 Type(TyParamBounds, Option<P<Ty>>),
1152 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1153 pub struct ImplItem {
1156 pub vis: Visibility,
1157 pub defaultness: Defaultness,
1158 pub attrs: Vec<Attribute>,
1159 pub node: ImplItemKind,
1163 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1164 pub enum ImplItemKind {
1165 Const(P<Ty>, P<Expr>),
1166 Method(MethodSig, P<Block>),
1171 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1181 impl fmt::Debug for IntTy {
1182 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1183 fmt::Display::fmt(self, f)
1187 impl fmt::Display for IntTy {
1188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1189 write!(f, "{}", self.ty_to_string())
1194 pub fn ty_to_string(&self) -> &'static str {
1196 IntTy::Is => "isize",
1198 IntTy::I16 => "i16",
1199 IntTy::I32 => "i32",
1200 IntTy::I64 => "i64",
1201 IntTy::I128 => "i128",
1205 pub fn val_to_string(&self, val: i128) -> String {
1206 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1207 // are parsed as u128, so we wouldn't want to print an extra negative
1209 format!("{}{}", val as u128, self.ty_to_string())
1212 pub fn bit_width(&self) -> Option<usize> {
1214 IntTy::Is => return None,
1224 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1235 pub fn ty_to_string(&self) -> &'static str {
1237 UintTy::Us => "usize",
1239 UintTy::U16 => "u16",
1240 UintTy::U32 => "u32",
1241 UintTy::U64 => "u64",
1242 UintTy::U128 => "u128",
1246 pub fn val_to_string(&self, val: u128) -> String {
1247 format!("{}{}", val, self.ty_to_string())
1250 pub fn bit_width(&self) -> Option<usize> {
1252 UintTy::Us => return None,
1257 UintTy::U128 => 128,
1262 impl fmt::Debug for UintTy {
1263 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1264 fmt::Display::fmt(self, f)
1268 impl fmt::Display for UintTy {
1269 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1270 write!(f, "{}", self.ty_to_string())
1274 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1280 impl fmt::Debug for FloatTy {
1281 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1282 fmt::Display::fmt(self, f)
1286 impl fmt::Display for FloatTy {
1287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1288 write!(f, "{}", self.ty_to_string())
1293 pub fn ty_to_string(&self) -> &'static str {
1295 FloatTy::F32 => "f32",
1296 FloatTy::F64 => "f64",
1300 pub fn bit_width(&self) -> usize {
1308 // Bind a type to an associated type: `A=Foo`.
1309 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1310 pub struct TypeBinding {
1317 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1324 impl fmt::Debug for Ty {
1325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1326 write!(f, "type({})", pprust::ty_to_string(self))
1330 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1331 pub struct BareFnTy {
1332 pub unsafety: Unsafety,
1334 pub lifetimes: Vec<LifetimeDef>,
1338 /// The different kinds of types recognized by the compiler
1339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1341 /// A variable-length slice (`[T]`)
1343 /// A fixed length array (`[T; n]`)
1344 Array(P<Ty>, P<Expr>),
1345 /// A raw pointer (`*const T` or `*mut T`)
1347 /// A reference (`&'a T` or `&'a mut T`)
1348 Rptr(Option<Lifetime>, MutTy),
1349 /// A bare function (e.g. `fn(usize) -> bool`)
1350 BareFn(P<BareFnTy>),
1351 /// The never type (`!`)
1353 /// A tuple (`(A, B, C, D,...)`)
1355 /// A path (`module::module::...::Type`), optionally
1356 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1358 /// Type parameters are stored in the Path itself
1359 Path(Option<QSelf>, Path),
1360 /// Something like `A+B`. Note that `B` must always be a path.
1361 ObjectSum(P<Ty>, TyParamBounds),
1362 /// A type like `for<'a> Foo<&'a Bar>`
1363 PolyTraitRef(TyParamBounds),
1364 /// An `impl TraitA+TraitB` type.
1365 ImplTrait(TyParamBounds),
1366 /// No-op; kept solely so that we can pretty-print faithfully
1370 /// TyKind::Infer means the type should be inferred instead of it having been
1371 /// specified. This can appear anywhere in a type.
1373 /// Inferred type of a `self` or `&self` argument in a method.
1375 // A macro in the type position.
1379 /// Inline assembly dialect.
1381 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1382 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1383 pub enum AsmDialect {
1388 /// Inline assembly.
1390 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1392 pub struct InlineAsmOutput {
1393 pub constraint: Symbol,
1396 pub is_indirect: bool,
1399 /// Inline assembly.
1401 /// E.g. `asm!("NOP");`
1402 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1403 pub struct InlineAsm {
1405 pub asm_str_style: StrStyle,
1406 pub outputs: Vec<InlineAsmOutput>,
1407 pub inputs: Vec<(Symbol, P<Expr>)>,
1408 pub clobbers: Vec<Symbol>,
1410 pub alignstack: bool,
1411 pub dialect: AsmDialect,
1412 pub expn_id: ExpnId,
1415 /// An argument in a function header.
1417 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1418 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1425 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1427 /// E.g. `&mut self` as in `fn foo(&mut self)`
1428 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1430 /// `self`, `mut self`
1432 /// `&'lt self`, `&'lt mut self`
1433 Region(Option<Lifetime>, Mutability),
1434 /// `self: TYPE`, `mut self: TYPE`
1435 Explicit(P<Ty>, Mutability),
1438 pub type ExplicitSelf = Spanned<SelfKind>;
1441 pub fn to_self(&self) -> Option<ExplicitSelf> {
1442 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1443 if ident.node.name == keywords::SelfValue.name() {
1444 return match self.ty.node {
1445 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1446 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1447 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1449 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1450 SelfKind::Explicit(self.ty.clone(), mutbl))),
1457 pub fn is_self(&self) -> bool {
1458 if let PatKind::Ident(_, ident, _) = self.pat.node {
1459 ident.node.name == keywords::SelfValue.name()
1465 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1466 let span = mk_sp(eself.span.lo, eself_ident.span.hi);
1467 let infer_ty = P(Ty {
1469 node: TyKind::ImplicitSelf,
1472 let arg = |mutbl, ty| Arg {
1475 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1482 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1483 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1484 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1486 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1493 /// Header (not the body) of a function declaration.
1495 /// E.g. `fn foo(bar: baz)`
1496 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1498 pub inputs: Vec<Arg>,
1499 pub output: FunctionRetTy,
1504 pub fn get_self(&self) -> Option<ExplicitSelf> {
1505 self.inputs.get(0).and_then(Arg::to_self)
1507 pub fn has_self(&self) -> bool {
1508 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1512 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1518 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1519 pub enum Constness {
1524 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1525 pub enum Defaultness {
1530 impl fmt::Display for Unsafety {
1531 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1532 fmt::Display::fmt(match *self {
1533 Unsafety::Normal => "normal",
1534 Unsafety::Unsafe => "unsafe",
1539 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1540 pub enum ImplPolarity {
1541 /// `impl Trait for Type`
1543 /// `impl !Trait for Type`
1547 impl fmt::Debug for ImplPolarity {
1548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1550 ImplPolarity::Positive => "positive".fmt(f),
1551 ImplPolarity::Negative => "negative".fmt(f),
1557 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1558 pub enum FunctionRetTy {
1559 /// Return type is not specified.
1561 /// Functions default to `()` and
1562 /// closures default to inference. Span points to where return
1563 /// type would be inserted.
1569 impl FunctionRetTy {
1570 pub fn span(&self) -> Span {
1572 FunctionRetTy::Default(span) => span,
1573 FunctionRetTy::Ty(ref ty) => ty.span,
1578 /// Module declaration.
1580 /// E.g. `mod foo;` or `mod foo { .. }`
1581 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1583 /// A span from the first token past `{` to the last token until `}`.
1584 /// For `mod foo;`, the inner span ranges from the first token
1585 /// to the last token in the external file.
1587 pub items: Vec<P<Item>>,
1590 /// Foreign module declaration.
1592 /// E.g. `extern { .. }` or `extern C { .. }`
1593 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1594 pub struct ForeignMod {
1596 pub items: Vec<ForeignItem>,
1599 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1600 pub struct EnumDef {
1601 pub variants: Vec<Variant>,
1604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1605 pub struct Variant_ {
1607 pub attrs: Vec<Attribute>,
1608 pub data: VariantData,
1609 /// Explicit discriminant, e.g. `Foo = 1`
1610 pub disr_expr: Option<P<Expr>>,
1613 pub type Variant = Spanned<Variant_>;
1615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1616 pub struct PathListItem_ {
1618 /// renamed in list, e.g. `use foo::{bar as baz};`
1619 pub rename: Option<Ident>,
1623 pub type PathListItem = Spanned<PathListItem_>;
1625 pub type ViewPath = Spanned<ViewPath_>;
1627 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1628 pub enum ViewPath_ {
1630 /// `foo::bar::baz as quux`
1634 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1635 ViewPathSimple(Ident, Path),
1640 /// `foo::bar::{a,b,c}`
1641 ViewPathList(Path, Vec<PathListItem>)
1645 pub fn path(&self) -> &Path {
1647 ViewPathSimple(_, ref path) |
1648 ViewPathGlob (ref path) |
1649 ViewPathList(ref path, _) => path
1655 /// Distinguishes between Attributes that decorate items and Attributes that
1656 /// are contained as statements within items. These two cases need to be
1657 /// distinguished for pretty-printing.
1658 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1659 pub enum AttrStyle {
1664 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1665 pub struct AttrId(pub usize);
1667 /// Meta-data associated with an item
1668 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1669 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1670 pub struct Attribute {
1672 pub style: AttrStyle,
1673 pub value: MetaItem,
1674 pub is_sugared_doc: bool,
1678 /// TraitRef's appear in impls.
1680 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1681 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1682 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1683 /// same as the impl's node id).
1684 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1685 pub struct TraitRef {
1690 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1691 pub struct PolyTraitRef {
1692 /// The `'a` in `<'a> Foo<&'a T>`
1693 pub bound_lifetimes: Vec<LifetimeDef>,
1695 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1696 pub trait_ref: TraitRef,
1701 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1702 pub enum Visibility {
1705 Restricted { path: P<Path>, id: NodeId },
1709 /// Field of a struct.
1711 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1712 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1713 pub struct StructField {
1715 pub ident: Option<Ident>,
1716 pub vis: Visibility,
1719 pub attrs: Vec<Attribute>,
1722 /// Fields and Ids of enum variants and structs
1724 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1725 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1726 /// One shared Id can be successfully used for these two purposes.
1727 /// Id of the whole enum lives in `Item`.
1729 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1730 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1731 /// the variant itself" from enum variants.
1732 /// Id of the whole struct lives in `Item`.
1733 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1734 pub enum VariantData {
1737 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1738 Struct(Vec<StructField>, NodeId),
1741 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1742 Tuple(Vec<StructField>, NodeId),
1745 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1750 pub fn fields(&self) -> &[StructField] {
1752 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1756 pub fn id(&self) -> NodeId {
1758 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1761 pub fn is_struct(&self) -> bool {
1762 if let VariantData::Struct(..) = *self { true } else { false }
1764 pub fn is_tuple(&self) -> bool {
1765 if let VariantData::Tuple(..) = *self { true } else { false }
1767 pub fn is_unit(&self) -> bool {
1768 if let VariantData::Unit(..) = *self { true } else { false }
1774 /// The name might be a dummy name in case of anonymous items
1775 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1778 pub attrs: Vec<Attribute>,
1781 pub vis: Visibility,
1785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1787 /// An`extern crate` item, with optional original crate name.
1789 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1790 ExternCrate(Option<Name>),
1791 /// A use declaration (`use` or `pub use`) item.
1793 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1795 /// A static item (`static` or `pub static`).
1797 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1798 Static(P<Ty>, Mutability, P<Expr>),
1799 /// A constant item (`const` or `pub const`).
1801 /// E.g. `const FOO: i32 = 42;`
1802 Const(P<Ty>, P<Expr>),
1803 /// A function declaration (`fn` or `pub fn`).
1805 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1806 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1807 /// A module declaration (`mod` or `pub mod`).
1809 /// E.g. `mod foo;` or `mod foo { .. }`
1811 /// An external module (`extern` or `pub extern`).
1813 /// E.g. `extern {}` or `extern "C" {}`
1814 ForeignMod(ForeignMod),
1815 /// A type alias (`type` or `pub type`).
1817 /// E.g. `type Foo = Bar<u8>;`
1818 Ty(P<Ty>, Generics),
1819 /// An enum definition (`enum` or `pub enum`).
1821 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1822 Enum(EnumDef, Generics),
1823 /// A struct definition (`struct` or `pub struct`).
1825 /// E.g. `struct Foo<A> { x: A }`
1826 Struct(VariantData, Generics),
1827 /// A union definition (`union` or `pub union`).
1829 /// E.g. `union Foo<A, B> { x: A, y: B }`
1830 Union(VariantData, Generics),
1831 /// A Trait declaration (`trait` or `pub trait`).
1833 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1834 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1835 // Default trait implementation.
1837 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1838 DefaultImpl(Unsafety, TraitRef),
1839 /// An implementation.
1841 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1845 Option<TraitRef>, // (optional) trait this impl implements
1848 /// A macro invocation (which includes macro definition).
1850 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1855 pub fn descriptive_variant(&self) -> &str {
1857 ItemKind::ExternCrate(..) => "extern crate",
1858 ItemKind::Use(..) => "use",
1859 ItemKind::Static(..) => "static item",
1860 ItemKind::Const(..) => "constant item",
1861 ItemKind::Fn(..) => "function",
1862 ItemKind::Mod(..) => "module",
1863 ItemKind::ForeignMod(..) => "foreign module",
1864 ItemKind::Ty(..) => "type alias",
1865 ItemKind::Enum(..) => "enum",
1866 ItemKind::Struct(..) => "struct",
1867 ItemKind::Union(..) => "union",
1868 ItemKind::Trait(..) => "trait",
1870 ItemKind::Impl(..) |
1871 ItemKind::DefaultImpl(..) => "item"
1876 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1877 pub struct ForeignItem {
1879 pub attrs: Vec<Attribute>,
1880 pub node: ForeignItemKind,
1883 pub vis: Visibility,
1886 /// An item within an `extern` block
1887 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1888 pub enum ForeignItemKind {
1889 /// A foreign function
1890 Fn(P<FnDecl>, Generics),
1891 /// A foreign static item (`static ext: u8`), with optional mutability
1892 /// (the boolean is true when mutable)
1893 Static(P<Ty>, bool),
1896 impl ForeignItemKind {
1897 pub fn descriptive_variant(&self) -> &str {
1899 ForeignItemKind::Fn(..) => "foreign function",
1900 ForeignItemKind::Static(..) => "foreign static item"
1905 /// A macro definition, in this crate or imported from another.
1907 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1908 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1909 pub struct MacroDef {
1911 pub attrs: Vec<Attribute>,
1914 pub body: Vec<TokenTree>,
1922 // are ASTs encodable?
1924 fn check_asts_encodable() {
1925 fn assert_encodable<T: serialize::Encodable>() {}
1926 assert_encodable::<Crate>();