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::{ThinTokenStream, TokenStream};
29 use std::collections::HashSet;
34 use serialize::{self, Encodable, Decodable, Encoder, Decoder};
36 /// An identifier contains a Name (index into the interner
37 /// table) and a SyntaxContext to track renaming and
38 /// macro expansion per Flatt et al., "Macros That Work Together"
39 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
42 pub ctxt: SyntaxContext
46 pub const fn with_empty_ctxt(name: Name) -> Ident {
47 Ident { name: name, ctxt: SyntaxContext::empty() }
50 /// Maps a string to an identifier with an empty syntax context.
51 pub fn from_str(s: &str) -> Ident {
52 Ident::with_empty_ctxt(Symbol::intern(s))
55 pub fn unhygienize(&self) -> Ident {
56 Ident { name: self.name, ctxt: SyntaxContext::empty() }
60 impl fmt::Debug for Ident {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 write!(f, "{}{:?}", self.name, self.ctxt)
66 impl fmt::Display for Ident {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 fmt::Display::fmt(&self.name, f)
72 impl Encodable for Ident {
73 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
78 impl Decodable for Ident {
79 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
80 Ok(Ident::with_empty_ctxt(Name::decode(d)?))
84 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
91 impl fmt::Debug for Lifetime {
92 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
97 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
98 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
99 pub struct LifetimeDef {
100 pub attrs: ThinVec<Attribute>,
101 pub lifetime: Lifetime,
102 pub bounds: Vec<Lifetime>
105 /// A "Path" is essentially Rust's notion of a name.
107 /// It's represented as a sequence of identifiers,
108 /// along with a bunch of supporting information.
110 /// E.g. `std::cmp::PartialEq`
111 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
114 /// The segments in the path: the things separated by `::`.
115 /// Global paths begin with `keywords::CrateRoot`.
116 pub segments: Vec<PathSegment>,
119 impl fmt::Debug for Path {
120 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121 write!(f, "path({})", pprust::path_to_string(self))
125 impl fmt::Display for Path {
126 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127 write!(f, "{}", pprust::path_to_string(self))
132 // convert a span and an identifier to the corresponding
134 pub fn from_ident(s: Span, identifier: Ident) -> Path {
137 segments: vec![PathSegment::from_ident(identifier, s)],
141 pub fn default_to_global(mut self) -> Path {
142 let name = self.segments[0].identifier.name;
143 if !self.is_global() && name != "$crate" &&
144 name != keywords::SelfValue.name() && name != keywords::Super.name() {
145 self.segments.insert(0, PathSegment::crate_root());
150 pub fn is_global(&self) -> bool {
151 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
155 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
157 /// E.g. `std`, `String` or `Box<T>`
158 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
159 pub struct PathSegment {
160 /// The identifier portion of this path segment.
161 pub identifier: Ident,
162 /// Span of the segment identifier.
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>>,
176 pub fn from_ident(ident: Ident, span: Span) -> Self {
177 PathSegment { identifier: ident, span: span, parameters: None }
179 pub fn crate_root() -> Self {
181 identifier: keywords::CrateRoot.ident(),
188 /// Parameters of a path segment.
190 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
192 pub enum PathParameters {
193 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
194 AngleBracketed(AngleBracketedParameterData),
195 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
196 Parenthesized(ParenthesizedParameterData),
199 /// A path like `Foo<'a, T>`
200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
201 pub struct AngleBracketedParameterData {
202 /// The lifetime parameters for this path segment.
203 pub lifetimes: Vec<Lifetime>,
204 /// The type parameters for this path segment, if present.
205 pub types: Vec<P<Ty>>,
206 /// Bindings (equality constraints) on associated types, if present.
208 /// E.g., `Foo<A=Bar>`.
209 pub bindings: Vec<TypeBinding>,
212 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
213 fn into(self) -> Option<P<PathParameters>> {
214 let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
215 if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
219 /// A path like `Foo(A,B) -> C`
220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
221 pub struct ParenthesizedParameterData {
226 pub inputs: Vec<P<Ty>>,
229 pub output: Option<P<Ty>>,
232 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
233 pub struct NodeId(u32);
236 pub fn new(x: usize) -> NodeId {
237 assert!(x < (u32::MAX as usize));
241 pub fn from_u32(x: u32) -> NodeId {
245 pub fn as_usize(&self) -> usize {
249 pub fn as_u32(&self) -> u32 {
254 impl fmt::Display for NodeId {
255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
256 fmt::Display::fmt(&self.0, f)
260 impl serialize::UseSpecializedEncodable for NodeId {
261 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
266 impl serialize::UseSpecializedDecodable for NodeId {
267 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
268 d.read_u32().map(NodeId)
272 /// Node id used to represent the root of the crate.
273 pub const CRATE_NODE_ID: NodeId = NodeId(0);
275 /// When parsing and doing expansions, we initially give all AST nodes this AST
276 /// node value. Then later, in the renumber pass, we renumber them to have
277 /// small, positive ids.
278 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
280 /// The AST represents all type param bounds as types.
281 /// typeck::collect::compute_bounds matches these against
282 /// the "special" built-in traits (see middle::lang_items) and
283 /// detects Copy, Send and Sync.
284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
285 pub enum TyParamBound {
286 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
287 RegionTyParamBound(Lifetime)
290 /// A modifier on a bound, currently this is only used for `?Sized`, where the
291 /// modifier is `Maybe`. Negative bounds should also be handled here.
292 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
293 pub enum TraitBoundModifier {
298 pub type TyParamBounds = Vec<TyParamBound>;
300 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
302 pub attrs: ThinVec<Attribute>,
305 pub bounds: TyParamBounds,
306 pub default: Option<P<Ty>>,
310 /// Represents lifetimes and type parameters attached to a declaration
311 /// of a function, enum, trait, etc.
312 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
313 pub struct Generics {
314 pub lifetimes: Vec<LifetimeDef>,
315 pub ty_params: Vec<TyParam>,
316 pub where_clause: WhereClause,
321 pub fn is_lt_parameterized(&self) -> bool {
322 !self.lifetimes.is_empty()
324 pub fn is_type_parameterized(&self) -> bool {
325 !self.ty_params.is_empty()
327 pub fn is_parameterized(&self) -> bool {
328 self.is_lt_parameterized() || self.is_type_parameterized()
330 pub fn span_for_name(&self, name: &str) -> Option<Span> {
331 for t in &self.ty_params {
332 if t.ident.name == name {
340 impl Default for Generics {
341 /// Creates an instance of `Generics`.
342 fn default() -> Generics {
344 lifetimes: Vec::new(),
345 ty_params: Vec::new(),
346 where_clause: WhereClause {
348 predicates: Vec::new(),
355 /// A `where` clause in a definition
356 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
357 pub struct WhereClause {
359 pub predicates: Vec<WherePredicate>,
362 /// A single predicate in a `where` clause
363 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
364 pub enum WherePredicate {
365 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
366 BoundPredicate(WhereBoundPredicate),
367 /// A lifetime predicate, e.g. `'a: 'b+'c`
368 RegionPredicate(WhereRegionPredicate),
369 /// An equality predicate (unsupported)
370 EqPredicate(WhereEqPredicate),
375 /// E.g. `for<'c> Foo: Send+Clone+'c`
376 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
377 pub struct WhereBoundPredicate {
379 /// Any lifetimes from a `for` binding
380 pub bound_lifetimes: Vec<LifetimeDef>,
381 /// The type being bounded
382 pub bounded_ty: P<Ty>,
383 /// Trait and lifetime bounds (`Clone+Send+'static`)
384 pub bounds: TyParamBounds,
387 /// A lifetime predicate.
390 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
391 pub struct WhereRegionPredicate {
393 pub lifetime: Lifetime,
394 pub bounds: Vec<Lifetime>,
397 /// An equality predicate (unsupported).
400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
401 pub struct WhereEqPredicate {
408 /// The set of MetaItems that define the compilation environment of the crate,
409 /// used to drive conditional compilation
410 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
415 pub attrs: Vec<Attribute>,
419 /// A spanned compile-time attribute list item.
420 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
422 /// Possible values inside of compile-time attribute lists.
424 /// E.g. the '..' in `#[name(..)]`.
425 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
426 pub enum NestedMetaItemKind {
427 /// A full MetaItem, for recursive meta items.
431 /// E.g. "foo", 64, true
435 /// A spanned compile-time attribute item.
437 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub struct MetaItem {
441 pub node: MetaItemKind,
445 /// A compile-time attribute item.
447 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
448 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
449 pub enum MetaItemKind {
452 /// E.g. `test` as in `#[test]`
456 /// E.g. `derive(..)` as in `#[derive(..)]`
457 List(Vec<NestedMetaItem>),
458 /// Name value meta item.
460 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
464 /// A Block (`{ .. }`).
466 /// E.g. `{ .. }` as in `fn foo() { .. }`
467 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
469 /// Statements in a block
470 pub stmts: Vec<Stmt>,
472 /// Distinguishes between `unsafe { ... }` and `{ ... }`
473 pub rules: BlockCheckMode,
477 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
484 impl fmt::Debug for Pat {
485 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
486 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
491 pub fn walk<F>(&self, it: &mut F) -> bool
492 where F: FnMut(&Pat) -> bool
499 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
500 PatKind::Struct(_, ref fields, _) => {
501 fields.iter().all(|field| field.node.pat.walk(it))
503 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
504 s.iter().all(|p| p.walk(it))
506 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
509 PatKind::Slice(ref before, ref slice, ref after) => {
510 before.iter().all(|p| p.walk(it)) &&
511 slice.iter().all(|p| p.walk(it)) &&
512 after.iter().all(|p| p.walk(it))
526 /// A single field in a struct pattern
528 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
529 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
530 /// except is_shorthand is true
531 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
532 pub struct FieldPat {
533 /// The identifier for the field
535 /// The pattern the field is destructured to
537 pub is_shorthand: bool,
538 pub attrs: ThinVec<Attribute>,
541 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
542 pub enum BindingMode {
547 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
553 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
555 /// Represents a wildcard pattern (`_`)
558 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
559 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
560 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
561 /// during name resolution.
562 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
564 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
565 /// The `bool` is `true` in the presence of a `..`.
566 Struct(Path, Vec<Spanned<FieldPat>>, bool),
568 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
569 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
570 /// 0 <= position <= subpats.len()
571 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
573 /// A possibly qualified path pattern.
574 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
575 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
576 /// only legally refer to associated constants.
577 Path(Option<QSelf>, Path),
579 /// A tuple pattern `(a, b)`.
580 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
581 /// 0 <= position <= subpats.len()
582 Tuple(Vec<P<Pat>>, Option<usize>),
585 /// A reference pattern, e.g. `&mut (a, b)`
586 Ref(P<Pat>, Mutability),
589 /// A range pattern, e.g. `1...2` or `1..2`
590 Range(P<Expr>, P<Expr>, RangeEnd),
591 /// `[a, b, ..i, y, z]` is represented as:
592 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
593 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
594 /// A macro pattern; pre-expansion
598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
599 pub enum Mutability {
604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
606 /// The `+` operator (addition)
608 /// The `-` operator (subtraction)
610 /// The `*` operator (multiplication)
612 /// The `/` operator (division)
614 /// The `%` operator (modulus)
616 /// The `&&` operator (logical and)
618 /// The `||` operator (logical or)
620 /// The `^` operator (bitwise xor)
622 /// The `&` operator (bitwise and)
624 /// The `|` operator (bitwise or)
626 /// The `<<` operator (shift left)
628 /// The `>>` operator (shift right)
630 /// The `==` operator (equality)
632 /// The `<` operator (less than)
634 /// The `<=` operator (less than or equal to)
636 /// The `!=` operator (not equal to)
638 /// The `>=` operator (greater than or equal to)
640 /// The `>` operator (greater than)
645 pub fn to_string(&self) -> &'static str {
646 use self::BinOpKind::*;
668 pub fn lazy(&self) -> bool {
670 BinOpKind::And | BinOpKind::Or => true,
675 pub fn is_shift(&self) -> bool {
677 BinOpKind::Shl | BinOpKind::Shr => true,
681 pub fn is_comparison(&self) -> bool {
682 use self::BinOpKind::*;
684 Eq | Lt | Le | Ne | Gt | Ge =>
686 And | Or | Add | Sub | Mul | Div | Rem |
687 BitXor | BitAnd | BitOr | Shl | Shr =>
691 /// Returns `true` if the binary operator takes its arguments by value
692 pub fn is_by_value(&self) -> bool {
693 !self.is_comparison()
697 pub type BinOp = Spanned<BinOpKind>;
699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
701 /// The `*` operator for dereferencing
703 /// The `!` operator for logical inversion
705 /// The `-` operator for negation
710 /// Returns `true` if the unary operator takes its argument by value
711 pub fn is_by_value(u: UnOp) -> bool {
713 UnOp::Neg | UnOp::Not => true,
718 pub fn to_string(op: UnOp) -> &'static str {
728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
736 pub fn add_trailing_semicolon(mut self) -> Self {
737 self.node = match self.node {
738 StmtKind::Expr(expr) => StmtKind::Semi(expr),
739 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
740 (mac, MacStmtStyle::Semicolon, attrs)
748 impl fmt::Debug for Stmt {
749 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
750 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
755 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
757 /// A local (let) binding.
760 /// An item definition.
763 /// Expr without trailing semi-colon.
768 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
771 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
772 pub enum MacStmtStyle {
773 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
774 /// `foo!(...);`, `foo![...];`
776 /// The macro statement had braces; e.g. foo! { ... }
778 /// The macro statement had parentheses or brackets and no semicolon; e.g.
779 /// `foo!(...)`. All of these will end up being converted into macro
784 // FIXME (pending discussion of #1697, #2178...): local should really be
785 // a refinement on pat.
786 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
787 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
790 pub ty: Option<P<Ty>>,
791 /// Initializer expression to set the value, if any
792 pub init: Option<P<Expr>>,
795 pub attrs: ThinVec<Attribute>,
798 /// An arm of a 'match'.
800 /// E.g. `0...10 => { println!("match!") }` as in
804 /// 0...10 => { println!("match!") },
808 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
810 pub attrs: Vec<Attribute>,
811 pub pats: Vec<P<Pat>>,
812 pub guard: Option<P<Expr>>,
816 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
818 pub ident: SpannedIdent,
821 pub is_shorthand: bool,
822 pub attrs: ThinVec<Attribute>,
825 pub type SpannedIdent = Spanned<Ident>;
827 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
828 pub enum BlockCheckMode {
830 Unsafe(UnsafeSource),
833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
834 pub enum UnsafeSource {
840 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
845 pub attrs: ThinVec<Attribute>
848 impl fmt::Debug for Expr {
849 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
850 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
854 /// Limit types of a range (inclusive or exclusive)
855 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
856 pub enum RangeLimits {
857 /// Inclusive at the beginning, exclusive at the end
859 /// Inclusive at the beginning and end
863 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
865 /// A `box x` expression.
867 /// First expr is the place; second expr is the value.
868 InPlace(P<Expr>, P<Expr>),
869 /// An array (`[a, b, c, d]`)
873 /// The first field resolves to the function itself,
874 /// and the second field is the list of arguments
875 Call(P<Expr>, Vec<P<Expr>>),
876 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
878 /// The `SpannedIdent` is the identifier for the method name.
879 /// The vector of `Ty`s are the ascripted type parameters for the method
880 /// (within the angle brackets).
882 /// The first element of the vector of `Expr`s is the expression that evaluates
883 /// to the object on which the method is being called on (the receiver),
884 /// and the remaining elements are the rest of the arguments.
886 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
887 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
888 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
889 /// A tuple (`(a, b, c ,d)`)
891 /// A binary operation (For example: `a + b`, `a * b`)
892 Binary(BinOp, P<Expr>, P<Expr>),
893 /// A unary operation (For example: `!x`, `*x`)
894 Unary(UnOp, P<Expr>),
895 /// A literal (For example: `1`, `"foo"`)
897 /// A cast (`foo as f64`)
898 Cast(P<Expr>, P<Ty>),
899 Type(P<Expr>, P<Ty>),
900 /// An `if` block, with an optional else block
902 /// `if expr { block } else { expr }`
903 If(P<Expr>, P<Block>, Option<P<Expr>>),
904 /// An `if let` expression with an optional else block
906 /// `if let pat = expr { block } else { expr }`
908 /// This is desugared to a `match` expression.
909 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
910 /// A while loop, with an optional label
912 /// `'label: while expr { block }`
913 While(P<Expr>, P<Block>, Option<SpannedIdent>),
914 /// A while-let loop, with an optional label
916 /// `'label: while let pat = expr { block }`
918 /// This is desugared to a combination of `loop` and `match` expressions.
919 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
920 /// A for loop, with an optional label
922 /// `'label: for pat in expr { block }`
924 /// This is desugared to a combination of `loop` and `match` expressions.
925 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
926 /// Conditionless loop (can be exited with break, continue, or return)
928 /// `'label: loop { block }`
929 Loop(P<Block>, Option<SpannedIdent>),
931 Match(P<Expr>, Vec<Arm>),
932 /// A closure (for example, `move |a, b, c| a + b + c`)
934 /// The final span is the span of the argument block `|...|`
935 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
936 /// A block (`{ ... }`)
938 /// A catch block (`catch { ... }`)
941 /// An assignment (`a = foo()`)
942 Assign(P<Expr>, P<Expr>),
943 /// An assignment with an operator
945 /// For example, `a += 1`.
946 AssignOp(BinOp, P<Expr>, P<Expr>),
947 /// Access of a named struct field (`obj.foo`)
948 Field(P<Expr>, SpannedIdent),
949 /// Access of an unnamed field of a struct or tuple-struct
951 /// For example, `foo.0`.
952 TupField(P<Expr>, Spanned<usize>),
953 /// An indexing operation (`foo[2]`)
954 Index(P<Expr>, P<Expr>),
955 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
956 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
958 /// Variable reference, possibly containing `::` and/or type
959 /// parameters, e.g. foo::bar::<baz>.
961 /// Optionally "qualified",
962 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
963 Path(Option<QSelf>, Path),
965 /// A referencing operation (`&a` or `&mut a`)
966 AddrOf(Mutability, P<Expr>),
967 /// A `break`, with an optional label to break, and an optional expression
968 Break(Option<SpannedIdent>, Option<P<Expr>>),
969 /// A `continue`, with an optional label
970 Continue(Option<SpannedIdent>),
971 /// A `return`, with an optional value to be returned
972 Ret(Option<P<Expr>>),
974 /// Output of the `asm!()` macro
975 InlineAsm(P<InlineAsm>),
977 /// A macro invocation; pre-expansion
980 /// A struct literal expression.
982 /// For example, `Foo {x: 1, y: 2}`, or
983 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
984 Struct(Path, Vec<Field>, Option<P<Expr>>),
986 /// An array literal constructed from one repeated element.
988 /// For example, `[1; 5]`. The first expression is the element
989 /// to be repeated; the second is the number of times to repeat it.
990 Repeat(P<Expr>, P<Expr>),
992 /// No-op: used solely so we can pretty-print faithfully
999 /// The explicit Self type in a "qualified path". The actual
1000 /// path, including the trait and the associated item, is stored
1001 /// separately. `position` represents the index of the associated
1002 /// item qualified with this Self type.
1005 /// <Vec<T> as a::b::Trait>::AssociatedItem
1006 /// ^~~~~ ~~~~~~~~~~~~~~^
1009 /// <Vec<T>>::AssociatedItem
1013 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1019 /// A capture clause
1020 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1021 pub enum CaptureBy {
1026 pub type Mac = Spanned<Mac_>;
1028 /// Represents a macro invocation. The Path indicates which macro
1029 /// is being invoked, and the vector of token-trees contains the source
1030 /// of the macro invocation.
1032 /// NB: the additional ident for a macro_rules-style macro is actually
1033 /// stored in the enclosing item. Oog.
1034 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1037 pub tts: ThinTokenStream,
1041 pub fn stream(&self) -> TokenStream {
1042 self.tts.clone().into()
1046 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1048 /// A regular string, like `"foo"`
1050 /// A raw string, like `r##"foo"##`
1052 /// The uint is the number of `#` symbols used
1057 pub type Lit = Spanned<LitKind>;
1059 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1060 pub enum LitIntType {
1068 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1069 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1071 /// A string literal (`"foo"`)
1072 Str(Symbol, StrStyle),
1073 /// A byte string (`b"foo"`)
1074 ByteStr(Rc<Vec<u8>>),
1075 /// A byte char (`b'f'`)
1077 /// A character literal (`'a'`)
1079 /// An integer literal (`1`)
1080 Int(u128, LitIntType),
1081 /// A float literal (`1f64` or `1E10f64`)
1082 Float(Symbol, FloatTy),
1083 /// A float literal without a suffix (`1.0 or 1.0E10`)
1084 FloatUnsuffixed(Symbol),
1085 /// A boolean literal
1090 /// Returns true if this literal is a string and false otherwise.
1091 pub fn is_str(&self) -> bool {
1093 LitKind::Str(..) => true,
1098 /// Returns true if this literal has no suffix. Note: this will return true
1099 /// for literals with prefixes such as raw strings and byte strings.
1100 pub fn is_unsuffixed(&self) -> bool {
1102 // unsuffixed variants
1103 LitKind::Str(..) => true,
1104 LitKind::ByteStr(..) => true,
1105 LitKind::Byte(..) => true,
1106 LitKind::Char(..) => true,
1107 LitKind::Int(_, LitIntType::Unsuffixed) => true,
1108 LitKind::FloatUnsuffixed(..) => true,
1109 LitKind::Bool(..) => true,
1110 // suffixed variants
1111 LitKind::Int(_, LitIntType::Signed(..)) => false,
1112 LitKind::Int(_, LitIntType::Unsigned(..)) => false,
1113 LitKind::Float(..) => false,
1117 /// Returns true if this literal has a suffix.
1118 pub fn is_suffixed(&self) -> bool {
1119 !self.is_unsuffixed()
1123 // NB: If you change this, you'll probably want to change the corresponding
1124 // type structure in middle/ty.rs as well.
1125 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1128 pub mutbl: Mutability,
1131 /// Represents a method's signature in a trait declaration,
1132 /// or in an implementation.
1133 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1134 pub struct MethodSig {
1135 pub unsafety: Unsafety,
1136 pub constness: Spanned<Constness>,
1138 pub decl: P<FnDecl>,
1139 pub generics: Generics,
1142 /// Represents an item declaration within a trait declaration,
1143 /// possibly including a default implementation. A trait item is
1144 /// either required (meaning it doesn't have an implementation, just a
1145 /// signature) or provided (meaning it has a default implementation).
1146 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1147 pub struct TraitItem {
1150 pub attrs: Vec<Attribute>,
1151 pub node: TraitItemKind,
1155 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1156 pub enum TraitItemKind {
1157 Const(P<Ty>, Option<P<Expr>>),
1158 Method(MethodSig, Option<P<Block>>),
1159 Type(TyParamBounds, Option<P<Ty>>),
1163 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1164 pub struct ImplItem {
1167 pub vis: Visibility,
1168 pub defaultness: Defaultness,
1169 pub attrs: Vec<Attribute>,
1170 pub node: ImplItemKind,
1174 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1175 pub enum ImplItemKind {
1176 Const(P<Ty>, P<Expr>),
1177 Method(MethodSig, P<Block>),
1182 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1192 impl fmt::Debug for IntTy {
1193 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1194 fmt::Display::fmt(self, f)
1198 impl fmt::Display for IntTy {
1199 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1200 write!(f, "{}", self.ty_to_string())
1205 pub fn ty_to_string(&self) -> &'static str {
1207 IntTy::Is => "isize",
1209 IntTy::I16 => "i16",
1210 IntTy::I32 => "i32",
1211 IntTy::I64 => "i64",
1212 IntTy::I128 => "i128",
1216 pub fn val_to_string(&self, val: i128) -> String {
1217 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1218 // are parsed as u128, so we wouldn't want to print an extra negative
1220 format!("{}{}", val as u128, self.ty_to_string())
1223 pub fn bit_width(&self) -> Option<usize> {
1225 IntTy::Is => return None,
1235 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1246 pub fn ty_to_string(&self) -> &'static str {
1248 UintTy::Us => "usize",
1250 UintTy::U16 => "u16",
1251 UintTy::U32 => "u32",
1252 UintTy::U64 => "u64",
1253 UintTy::U128 => "u128",
1257 pub fn val_to_string(&self, val: u128) -> String {
1258 format!("{}{}", val, self.ty_to_string())
1261 pub fn bit_width(&self) -> Option<usize> {
1263 UintTy::Us => return None,
1268 UintTy::U128 => 128,
1273 impl fmt::Debug for UintTy {
1274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1275 fmt::Display::fmt(self, f)
1279 impl fmt::Display for UintTy {
1280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1281 write!(f, "{}", self.ty_to_string())
1285 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1291 impl fmt::Debug for FloatTy {
1292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1293 fmt::Display::fmt(self, f)
1297 impl fmt::Display for FloatTy {
1298 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1299 write!(f, "{}", self.ty_to_string())
1304 pub fn ty_to_string(&self) -> &'static str {
1306 FloatTy::F32 => "f32",
1307 FloatTy::F64 => "f64",
1311 pub fn bit_width(&self) -> usize {
1319 // Bind a type to an associated type: `A=Foo`.
1320 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1321 pub struct TypeBinding {
1328 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1335 impl fmt::Debug for Ty {
1336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1337 write!(f, "type({})", pprust::ty_to_string(self))
1341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1342 pub struct BareFnTy {
1343 pub unsafety: Unsafety,
1345 pub lifetimes: Vec<LifetimeDef>,
1349 /// The different kinds of types recognized by the compiler
1350 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1352 /// A variable-length slice (`[T]`)
1354 /// A fixed length array (`[T; n]`)
1355 Array(P<Ty>, P<Expr>),
1356 /// A raw pointer (`*const T` or `*mut T`)
1358 /// A reference (`&'a T` or `&'a mut T`)
1359 Rptr(Option<Lifetime>, MutTy),
1360 /// A bare function (e.g. `fn(usize) -> bool`)
1361 BareFn(P<BareFnTy>),
1362 /// The never type (`!`)
1364 /// A tuple (`(A, B, C, D,...)`)
1366 /// A path (`module::module::...::Type`), optionally
1367 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1369 /// Type parameters are stored in the Path itself
1370 Path(Option<QSelf>, Path),
1371 /// A trait object type `Bound1 + Bound2 + Bound3`
1372 /// where `Bound` is a trait or a lifetime.
1373 TraitObject(TyParamBounds),
1374 /// An `impl Bound1 + Bound2 + Bound3` type
1375 /// where `Bound` is a trait or a lifetime.
1376 ImplTrait(TyParamBounds),
1377 /// No-op; kept solely so that we can pretty-print faithfully
1381 /// TyKind::Infer means the type should be inferred instead of it having been
1382 /// specified. This can appear anywhere in a type.
1384 /// Inferred type of a `self` or `&self` argument in a method.
1386 // A macro in the type position.
1390 /// Inline assembly dialect.
1392 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1393 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1394 pub enum AsmDialect {
1399 /// Inline assembly.
1401 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1402 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1403 pub struct InlineAsmOutput {
1404 pub constraint: Symbol,
1407 pub is_indirect: bool,
1410 /// Inline assembly.
1412 /// E.g. `asm!("NOP");`
1413 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1414 pub struct InlineAsm {
1416 pub asm_str_style: StrStyle,
1417 pub outputs: Vec<InlineAsmOutput>,
1418 pub inputs: Vec<(Symbol, P<Expr>)>,
1419 pub clobbers: Vec<Symbol>,
1421 pub alignstack: bool,
1422 pub dialect: AsmDialect,
1423 pub expn_id: ExpnId,
1426 /// An argument in a function header.
1428 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1429 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1436 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1438 /// E.g. `&mut self` as in `fn foo(&mut self)`
1439 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1441 /// `self`, `mut self`
1443 /// `&'lt self`, `&'lt mut self`
1444 Region(Option<Lifetime>, Mutability),
1445 /// `self: TYPE`, `mut self: TYPE`
1446 Explicit(P<Ty>, Mutability),
1449 pub type ExplicitSelf = Spanned<SelfKind>;
1452 pub fn to_self(&self) -> Option<ExplicitSelf> {
1453 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1454 if ident.node.name == keywords::SelfValue.name() {
1455 return match self.ty.node {
1456 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1457 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1458 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1460 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1461 SelfKind::Explicit(self.ty.clone(), mutbl))),
1468 pub fn is_self(&self) -> bool {
1469 if let PatKind::Ident(_, ident, _) = self.pat.node {
1470 ident.node.name == keywords::SelfValue.name()
1476 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1477 let span = mk_sp(eself.span.lo, eself_ident.span.hi);
1478 let infer_ty = P(Ty {
1480 node: TyKind::ImplicitSelf,
1483 let arg = |mutbl, ty| Arg {
1486 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1493 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1494 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1495 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1497 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1504 /// Header (not the body) of a function declaration.
1506 /// E.g. `fn foo(bar: baz)`
1507 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1509 pub inputs: Vec<Arg>,
1510 pub output: FunctionRetTy,
1515 pub fn get_self(&self) -> Option<ExplicitSelf> {
1516 self.inputs.get(0).and_then(Arg::to_self)
1518 pub fn has_self(&self) -> bool {
1519 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1523 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1529 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1530 pub enum Constness {
1535 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub enum Defaultness {
1541 impl fmt::Display for Unsafety {
1542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543 fmt::Display::fmt(match *self {
1544 Unsafety::Normal => "normal",
1545 Unsafety::Unsafe => "unsafe",
1550 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1551 pub enum ImplPolarity {
1552 /// `impl Trait for Type`
1554 /// `impl !Trait for Type`
1558 impl fmt::Debug for ImplPolarity {
1559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1561 ImplPolarity::Positive => "positive".fmt(f),
1562 ImplPolarity::Negative => "negative".fmt(f),
1568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1569 pub enum FunctionRetTy {
1570 /// Return type is not specified.
1572 /// Functions default to `()` and
1573 /// closures default to inference. Span points to where return
1574 /// type would be inserted.
1580 impl FunctionRetTy {
1581 pub fn span(&self) -> Span {
1583 FunctionRetTy::Default(span) => span,
1584 FunctionRetTy::Ty(ref ty) => ty.span,
1589 /// Module declaration.
1591 /// E.g. `mod foo;` or `mod foo { .. }`
1592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1594 /// A span from the first token past `{` to the last token until `}`.
1595 /// For `mod foo;`, the inner span ranges from the first token
1596 /// to the last token in the external file.
1598 pub items: Vec<P<Item>>,
1601 /// Foreign module declaration.
1603 /// E.g. `extern { .. }` or `extern C { .. }`
1604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1605 pub struct ForeignMod {
1607 pub items: Vec<ForeignItem>,
1610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1611 pub struct EnumDef {
1612 pub variants: Vec<Variant>,
1615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1616 pub struct Variant_ {
1618 pub attrs: Vec<Attribute>,
1619 pub data: VariantData,
1620 /// Explicit discriminant, e.g. `Foo = 1`
1621 pub disr_expr: Option<P<Expr>>,
1624 pub type Variant = Spanned<Variant_>;
1626 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1627 pub struct PathListItem_ {
1629 /// renamed in list, e.g. `use foo::{bar as baz};`
1630 pub rename: Option<Ident>,
1634 pub type PathListItem = Spanned<PathListItem_>;
1636 pub type ViewPath = Spanned<ViewPath_>;
1638 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1639 pub enum ViewPath_ {
1641 /// `foo::bar::baz as quux`
1645 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1646 ViewPathSimple(Ident, Path),
1651 /// `foo::bar::{a,b,c}`
1652 ViewPathList(Path, Vec<PathListItem>)
1656 pub fn path(&self) -> &Path {
1658 ViewPathSimple(_, ref path) |
1659 ViewPathGlob (ref path) |
1660 ViewPathList(ref path, _) => path
1666 /// Distinguishes between Attributes that decorate items and Attributes that
1667 /// are contained as statements within items. These two cases need to be
1668 /// distinguished for pretty-printing.
1669 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1670 pub enum AttrStyle {
1675 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1676 pub struct AttrId(pub usize);
1678 /// Meta-data associated with an item
1679 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1680 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1681 pub struct Attribute {
1683 pub style: AttrStyle,
1684 pub value: MetaItem,
1685 pub is_sugared_doc: bool,
1689 /// TraitRef's appear in impls.
1691 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1692 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1693 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1694 /// same as the impl's node id).
1695 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1696 pub struct TraitRef {
1701 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1702 pub struct PolyTraitRef {
1703 /// The `'a` in `<'a> Foo<&'a T>`
1704 pub bound_lifetimes: Vec<LifetimeDef>,
1706 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1707 pub trait_ref: TraitRef,
1712 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1713 pub enum Visibility {
1716 Restricted { path: P<Path>, id: NodeId },
1720 /// Field of a struct.
1722 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1723 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1724 pub struct StructField {
1726 pub ident: Option<Ident>,
1727 pub vis: Visibility,
1730 pub attrs: Vec<Attribute>,
1733 /// Fields and Ids of enum variants and structs
1735 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1736 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1737 /// One shared Id can be successfully used for these two purposes.
1738 /// Id of the whole enum lives in `Item`.
1740 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1741 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1742 /// the variant itself" from enum variants.
1743 /// Id of the whole struct lives in `Item`.
1744 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1745 pub enum VariantData {
1748 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1749 Struct(Vec<StructField>, NodeId),
1752 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1753 Tuple(Vec<StructField>, NodeId),
1756 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1761 pub fn fields(&self) -> &[StructField] {
1763 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1767 pub fn id(&self) -> NodeId {
1769 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1772 pub fn is_struct(&self) -> bool {
1773 if let VariantData::Struct(..) = *self { true } else { false }
1775 pub fn is_tuple(&self) -> bool {
1776 if let VariantData::Tuple(..) = *self { true } else { false }
1778 pub fn is_unit(&self) -> bool {
1779 if let VariantData::Unit(..) = *self { true } else { false }
1785 /// The name might be a dummy name in case of anonymous items
1786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1789 pub attrs: Vec<Attribute>,
1792 pub vis: Visibility,
1796 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1798 /// An`extern crate` item, with optional original crate name.
1800 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1801 ExternCrate(Option<Name>),
1802 /// A use declaration (`use` or `pub use`) item.
1804 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1806 /// A static item (`static` or `pub static`).
1808 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1809 Static(P<Ty>, Mutability, P<Expr>),
1810 /// A constant item (`const` or `pub const`).
1812 /// E.g. `const FOO: i32 = 42;`
1813 Const(P<Ty>, P<Expr>),
1814 /// A function declaration (`fn` or `pub fn`).
1816 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1817 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1818 /// A module declaration (`mod` or `pub mod`).
1820 /// E.g. `mod foo;` or `mod foo { .. }`
1822 /// An external module (`extern` or `pub extern`).
1824 /// E.g. `extern {}` or `extern "C" {}`
1825 ForeignMod(ForeignMod),
1826 /// A type alias (`type` or `pub type`).
1828 /// E.g. `type Foo = Bar<u8>;`
1829 Ty(P<Ty>, Generics),
1830 /// An enum definition (`enum` or `pub enum`).
1832 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1833 Enum(EnumDef, Generics),
1834 /// A struct definition (`struct` or `pub struct`).
1836 /// E.g. `struct Foo<A> { x: A }`
1837 Struct(VariantData, Generics),
1838 /// A union definition (`union` or `pub union`).
1840 /// E.g. `union Foo<A, B> { x: A, y: B }`
1841 Union(VariantData, Generics),
1842 /// A Trait declaration (`trait` or `pub trait`).
1844 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1845 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1846 // Default trait implementation.
1848 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1849 DefaultImpl(Unsafety, TraitRef),
1850 /// An implementation.
1852 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1856 Option<TraitRef>, // (optional) trait this impl implements
1859 /// A macro invocation.
1861 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1864 /// A macro definition.
1865 MacroDef(ThinTokenStream),
1869 pub fn descriptive_variant(&self) -> &str {
1871 ItemKind::ExternCrate(..) => "extern crate",
1872 ItemKind::Use(..) => "use",
1873 ItemKind::Static(..) => "static item",
1874 ItemKind::Const(..) => "constant item",
1875 ItemKind::Fn(..) => "function",
1876 ItemKind::Mod(..) => "module",
1877 ItemKind::ForeignMod(..) => "foreign module",
1878 ItemKind::Ty(..) => "type alias",
1879 ItemKind::Enum(..) => "enum",
1880 ItemKind::Struct(..) => "struct",
1881 ItemKind::Union(..) => "union",
1882 ItemKind::Trait(..) => "trait",
1884 ItemKind::MacroDef(..) |
1885 ItemKind::Impl(..) |
1886 ItemKind::DefaultImpl(..) => "item"
1891 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1892 pub struct ForeignItem {
1894 pub attrs: Vec<Attribute>,
1895 pub node: ForeignItemKind,
1898 pub vis: Visibility,
1901 /// An item within an `extern` block
1902 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1903 pub enum ForeignItemKind {
1904 /// A foreign function
1905 Fn(P<FnDecl>, Generics),
1906 /// A foreign static item (`static ext: u8`), with optional mutability
1907 /// (the boolean is true when mutable)
1908 Static(P<Ty>, bool),
1911 impl ForeignItemKind {
1912 pub fn descriptive_variant(&self) -> &str {
1914 ForeignItemKind::Fn(..) => "foreign function",
1915 ForeignItemKind::Static(..) => "foreign static item"
1925 // are ASTs encodable?
1927 fn check_asts_encodable() {
1928 fn assert_encodable<T: serialize::Encodable>() {}
1929 assert_encodable::<Crate>();