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::AsmDialect::*;
14 pub use self::AttrStyle::*;
15 pub use self::BindingMode::*;
16 pub use self::BinOp_::*;
17 pub use self::BlockCheckMode::*;
18 pub use self::CaptureClause::*;
19 pub use self::Decl_::*;
20 pub use self::ExplicitSelf_::*;
21 pub use self::Expr_::*;
22 pub use self::FloatTy::*;
23 pub use self::FunctionRetTy::*;
24 pub use self::ForeignItem_::*;
25 pub use self::ImplItem_::*;
26 pub use self::IntTy::*;
27 pub use self::Item_::*;
28 pub use self::KleeneOp::*;
29 pub use self::Lit_::*;
30 pub use self::LitIntType::*;
31 pub use self::MacStmtStyle::*;
32 pub use self::MetaItem_::*;
33 pub use self::Mutability::*;
34 pub use self::Pat_::*;
35 pub use self::PathListItem_::*;
36 pub use self::PatWildKind::*;
37 pub use self::PrimTy::*;
38 pub use self::Sign::*;
39 pub use self::Stmt_::*;
40 pub use self::StrStyle::*;
41 pub use self::StructFieldKind::*;
42 pub use self::TokenTree::*;
43 pub use self::TraitItem_::*;
45 pub use self::TyParamBound::*;
46 pub use self::UintTy::*;
47 pub use self::UnOp::*;
48 pub use self::UnsafeSource::*;
49 pub use self::VariantKind::*;
50 pub use self::ViewPath_::*;
51 pub use self::Visibility::*;
52 pub use self::PathParameters::*;
54 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
58 use ext::tt::macro_parser;
59 use owned_slice::OwnedSlice;
60 use parse::token::{InternedString, str_to_ident};
63 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
69 use serialize::{Encodable, Decodable, Encoder, Decoder};
71 // FIXME #6993: in librustc, uses of "ident" should be replaced
74 /// An identifier contains a Name (index into the interner
75 /// table) and a SyntaxContext to track renaming and
76 /// macro expansion per Flatt et al., "Macros
77 /// That Work Together"
78 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
81 pub ctxt: SyntaxContext
85 /// Construct an identifier with the given name and an empty context:
86 pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
89 impl fmt::Debug for Ident {
90 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
91 write!(f, "{}#{}", self.name, self.ctxt)
95 impl fmt::Display for Ident {
96 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97 fmt::Display::fmt(&self.name, f)
101 impl fmt::Debug for Name {
102 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
103 let Name(nm) = *self;
104 write!(f, "{}({})", self, nm)
108 impl fmt::Display for Name {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110 fmt::Display::fmt(&self.as_str(), f)
114 impl PartialEq for Ident {
115 fn eq(&self, other: &Ident) -> bool {
116 if self.ctxt == other.ctxt {
117 self.name == other.name
119 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
120 // idents that have different contexts. You can't fix this without
121 // knowing whether the comparison should be hygienic or non-hygienic.
122 // if it should be non-hygienic (most things are), just compare the
123 // 'name' fields of the idents. Or, even better, replace the idents
126 // On the other hand, if the comparison does need to be hygienic,
127 // one example and its non-hygienic counterpart would be:
128 // syntax::parse::token::Token::mtwt_eq
129 // syntax::ext::tt::macro_parser::token_name_eq
130 panic!("not allowed to compare these idents: {:?}, {:?}. \
131 Probably related to issue \\#6993", self, other);
136 /// A SyntaxContext represents a chain of macro-expandings
137 /// and renamings. Each macro expansion corresponds to
140 // I'm representing this syntax context as an index into
141 // a table, in order to work around a compiler bug
142 // that's causing unreleased memory to cause core dumps
143 // and also perhaps to save some work in destructor checks.
144 // the special uint '0' will be used to indicate an empty
147 // this uint is a reference to a table stored in thread-local
149 pub type SyntaxContext = u32;
150 pub const EMPTY_CTXT : SyntaxContext = 0;
151 pub const ILLEGAL_CTXT : SyntaxContext = 1;
153 /// A name is a part of an identifier, representing a string or gensym. It's
154 /// the result of interning.
155 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
156 RustcEncodable, RustcDecodable, Clone, Copy)]
157 pub struct Name(pub u32);
159 impl<T: AsRef<str>> PartialEq<T> for Name {
160 fn eq(&self, other: &T) -> bool {
161 self.as_str() == other.as_ref()
166 pub fn as_str(&self) -> token::InternedString {
167 token::InternedString::new_from_name(*self)
170 pub fn usize(&self) -> usize {
171 let Name(nm) = *self;
175 pub fn ident(&self) -> Ident {
176 Ident { name: *self, ctxt: 0 }
180 /// A mark represents a unique id associated with a macro expansion
183 impl Encodable for Ident {
184 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
185 s.emit_str(&self.name.as_str())
189 impl Decodable for Ident {
190 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
191 Ok(str_to_ident(&try!(d.read_str())[..]))
195 /// Function name (not all functions have names)
196 pub type FnIdent = Option<Ident>;
198 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
199 pub struct Lifetime {
205 impl fmt::Debug for Lifetime {
206 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
211 /// A lifetime definition, eg `'a: 'b+'c+'d`
212 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
213 pub struct LifetimeDef {
214 pub lifetime: Lifetime,
215 pub bounds: Vec<Lifetime>
218 /// A "Path" is essentially Rust's notion of a name; for instance:
219 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
220 /// along with a bunch of supporting information.
221 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
224 /// A `::foo` path, is relative to the crate root rather than current
225 /// module (like paths in an import).
227 /// The segments in the path: the things separated by `::`.
228 pub segments: Vec<PathSegment>,
231 impl fmt::Debug for Path {
232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
233 write!(f, "path({})", pprust::path_to_string(self))
237 impl fmt::Display for Path {
238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239 write!(f, "{}", pprust::path_to_string(self))
243 /// A segment of a path: an identifier, an optional lifetime, and a set of
245 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
246 pub struct PathSegment {
247 /// The identifier portion of this path segment.
248 pub identifier: Ident,
250 /// Type/lifetime parameters attached to this path. They come in
251 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
252 /// this is more than just simple syntactic sugar; the use of
253 /// parens affects the region binding rules, so we preserve the
255 pub parameters: PathParameters,
258 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
259 pub enum PathParameters {
260 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
261 AngleBracketedParameters(AngleBracketedParameterData),
262 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
263 ParenthesizedParameters(ParenthesizedParameterData),
266 impl PathParameters {
267 pub fn none() -> PathParameters {
268 AngleBracketedParameters(AngleBracketedParameterData {
269 lifetimes: Vec::new(),
270 types: OwnedSlice::empty(),
271 bindings: OwnedSlice::empty(),
275 pub fn is_empty(&self) -> bool {
277 AngleBracketedParameters(ref data) => data.is_empty(),
279 // Even if the user supplied no types, something like
280 // `X()` is equivalent to `X<(),()>`.
281 ParenthesizedParameters(..) => false,
285 pub fn has_lifetimes(&self) -> bool {
287 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
288 ParenthesizedParameters(_) => false,
292 pub fn has_types(&self) -> bool {
294 AngleBracketedParameters(ref data) => !data.types.is_empty(),
295 ParenthesizedParameters(..) => true,
299 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
300 /// parameters in the parenthesized case.
301 pub fn types(&self) -> Vec<&P<Ty>> {
303 AngleBracketedParameters(ref data) => {
304 data.types.iter().collect()
306 ParenthesizedParameters(ref data) => {
308 .chain(data.output.iter())
314 pub fn lifetimes(&self) -> Vec<&Lifetime> {
316 AngleBracketedParameters(ref data) => {
317 data.lifetimes.iter().collect()
319 ParenthesizedParameters(_) => {
325 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
327 AngleBracketedParameters(ref data) => {
328 data.bindings.iter().collect()
330 ParenthesizedParameters(_) => {
337 /// A path like `Foo<'a, T>`
338 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
339 pub struct AngleBracketedParameterData {
340 /// The lifetime parameters for this path segment.
341 pub lifetimes: Vec<Lifetime>,
342 /// The type parameters for this path segment, if present.
343 pub types: OwnedSlice<P<Ty>>,
344 /// Bindings (equality constraints) on associated types, if present.
345 /// E.g., `Foo<A=Bar>`.
346 pub bindings: OwnedSlice<P<TypeBinding>>,
349 impl AngleBracketedParameterData {
350 fn is_empty(&self) -> bool {
351 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
355 /// A path like `Foo(A,B) -> C`
356 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
357 pub struct ParenthesizedParameterData {
362 pub inputs: Vec<P<Ty>>,
365 pub output: Option<P<Ty>>,
368 pub type CrateNum = u32;
370 pub type NodeId = u32;
372 /// Node id used to represent the root of the crate.
373 pub const CRATE_NODE_ID: NodeId = 0;
375 /// When parsing and doing expansions, we initially give all AST nodes this AST
376 /// node value. Then later, in the renumber pass, we renumber them to have
377 /// small, positive ids.
378 pub const DUMMY_NODE_ID: NodeId = !0;
380 /// The AST represents all type param bounds as types.
381 /// typeck::collect::compute_bounds matches these against
382 /// the "special" built-in traits (see middle::lang_items) and
383 /// detects Copy, Send and Sync.
384 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
385 pub enum TyParamBound {
386 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
387 RegionTyParamBound(Lifetime)
390 /// A modifier on a bound, currently this is only used for `?Sized`, where the
391 /// modifier is `Maybe`. Negative bounds should also be handled here.
392 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
393 pub enum TraitBoundModifier {
398 pub type TyParamBounds = OwnedSlice<TyParamBound>;
400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
404 pub bounds: TyParamBounds,
405 pub default: Option<P<Ty>>,
409 /// Represents lifetimes and type parameters attached to a declaration
410 /// of a function, enum, trait, etc.
411 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
412 pub struct Generics {
413 pub lifetimes: Vec<LifetimeDef>,
414 pub ty_params: OwnedSlice<TyParam>,
415 pub where_clause: WhereClause,
419 pub fn is_lt_parameterized(&self) -> bool {
420 !self.lifetimes.is_empty()
422 pub fn is_type_parameterized(&self) -> bool {
423 !self.ty_params.is_empty()
425 pub fn is_parameterized(&self) -> bool {
426 self.is_lt_parameterized() || self.is_type_parameterized()
430 /// A `where` clause in a definition
431 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
432 pub struct WhereClause {
434 pub predicates: Vec<WherePredicate>,
437 /// A single predicate in a `where` clause
438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub enum WherePredicate {
440 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
441 BoundPredicate(WhereBoundPredicate),
442 /// A lifetime predicate, e.g. `'a: 'b+'c`
443 RegionPredicate(WhereRegionPredicate),
444 /// An equality predicate (unsupported)
445 EqPredicate(WhereEqPredicate),
448 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
449 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
450 pub struct WhereBoundPredicate {
452 /// Any lifetimes from a `for` binding
453 pub bound_lifetimes: Vec<LifetimeDef>,
454 /// The type being bounded
455 pub bounded_ty: P<Ty>,
456 /// Trait and lifetime bounds (`Clone+Send+'static`)
457 pub bounds: OwnedSlice<TyParamBound>,
460 /// A lifetime predicate, e.g. `'a: 'b+'c`
461 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
462 pub struct WhereRegionPredicate {
464 pub lifetime: Lifetime,
465 pub bounds: Vec<Lifetime>,
468 /// An equality predicate (unsupported), e.g. `T=int`
469 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
470 pub struct WhereEqPredicate {
477 /// The set of MetaItems that define the compilation environment of the crate,
478 /// used to drive conditional compilation
479 pub type CrateConfig = Vec<P<MetaItem>> ;
481 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
484 pub attrs: Vec<Attribute>,
485 pub config: CrateConfig,
487 pub exported_macros: Vec<MacroDef>,
490 pub type MetaItem = Spanned<MetaItem_>;
492 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
494 MetaWord(InternedString),
495 MetaList(InternedString, Vec<P<MetaItem>>),
496 MetaNameValue(InternedString, Lit),
499 // can't be derived because the MetaList requires an unordered comparison
500 impl PartialEq for MetaItem_ {
501 fn eq(&self, other: &MetaItem_) -> bool {
503 MetaWord(ref ns) => match *other {
504 MetaWord(ref no) => (*ns) == (*no),
507 MetaNameValue(ref ns, ref vs) => match *other {
508 MetaNameValue(ref no, ref vo) => {
509 (*ns) == (*no) && vs.node == vo.node
513 MetaList(ref ns, ref miss) => match *other {
514 MetaList(ref no, ref miso) => {
516 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
524 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
526 /// Statements in a block
527 pub stmts: Vec<P<Stmt>>,
528 /// An expression at the end of the block
529 /// without a semicolon, if any
530 pub expr: Option<P<Expr>>,
532 /// Distinguishes between `unsafe { ... }` and `{ ... }`
533 pub rules: BlockCheckMode,
537 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
544 impl fmt::Debug for Pat {
545 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
546 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
550 /// A single field in a struct pattern
552 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
553 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
554 /// except is_shorthand is true
555 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
556 pub struct FieldPat {
557 /// The identifier for the field
559 /// The pattern the field is destructured to
561 pub is_shorthand: bool,
564 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
565 pub enum BindingMode {
566 BindByRef(Mutability),
567 BindByValue(Mutability),
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
571 pub enum PatWildKind {
572 /// Represents the wildcard pattern `_`
575 /// Represents the wildcard pattern `..`
579 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
581 /// Represents a wildcard pattern (either `_` or `..`)
582 PatWild(PatWildKind),
584 /// A PatIdent may either be a new bound variable,
585 /// or a nullary enum (in which case the third field
588 /// In the nullary enum case, the parser can't determine
589 /// which it is. The resolver determines this, and
590 /// records this pattern's NodeId in an auxiliary
591 /// set (of "PatIdents that refer to nullary enums")
592 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
594 /// "None" means a * pattern where we don't bind the fields to names.
595 PatEnum(Path, Option<Vec<P<Pat>>>),
597 /// An associated const named using the qualified path `<T>::CONST` or
598 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
599 /// referred to as simply `T::CONST`, in which case they will end up as
600 /// PatEnum, and the resolver will have to sort that out.
601 PatQPath(QSelf, Path),
603 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
604 /// The `bool` is `true` in the presence of a `..`
605 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
606 /// A tuple pattern `(a, b)`
610 /// A reference pattern, e.g. `&mut (a, b)`
611 PatRegion(P<Pat>, Mutability),
614 /// A range pattern, e.g. `1...2`
615 PatRange(P<Expr>, P<Expr>),
616 /// [a, b, ..i, y, z] is represented as:
617 /// PatVec(box [a, b], Some(i), box [y, z])
618 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
619 /// A macro pattern; pre-expansion
623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
624 pub enum Mutability {
629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
631 /// The `+` operator (addition)
633 /// The `-` operator (subtraction)
635 /// The `*` operator (multiplication)
637 /// The `/` operator (division)
639 /// The `%` operator (modulus)
641 /// The `&&` operator (logical and)
643 /// The `||` operator (logical or)
645 /// The `^` operator (bitwise xor)
647 /// The `&` operator (bitwise and)
649 /// The `|` operator (bitwise or)
651 /// The `<<` operator (shift left)
653 /// The `>>` operator (shift right)
655 /// The `==` operator (equality)
657 /// The `<` operator (less than)
659 /// The `<=` operator (less than or equal to)
661 /// The `!=` operator (not equal to)
663 /// The `>=` operator (greater than or equal to)
665 /// The `>` operator (greater than)
669 pub type BinOp = Spanned<BinOp_>;
671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
673 /// The `box` operator
675 /// The `*` operator for dereferencing
677 /// The `!` operator for logical inversion
679 /// The `-` operator for negation
684 pub type Stmt = Spanned<Stmt_>;
686 impl fmt::Debug for Stmt {
687 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
688 write!(f, "stmt({}: {})",
689 ast_util::stmt_id(self),
690 pprust::stmt_to_string(self))
695 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
697 /// Could be an item or a local (let) binding:
698 StmtDecl(P<Decl>, NodeId),
700 /// Expr without trailing semi-colon (must have unit type):
701 StmtExpr(P<Expr>, NodeId),
703 /// Expr with trailing semi-colon (may have any type):
704 StmtSemi(P<Expr>, NodeId),
706 StmtMac(P<Mac>, MacStmtStyle),
708 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
709 pub enum MacStmtStyle {
710 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
711 /// `foo!(...);`, `foo![...];`
712 MacStmtWithSemicolon,
713 /// The macro statement had braces; e.g. foo! { ... }
715 /// The macro statement had parentheses or brackets and no semicolon; e.g.
716 /// `foo!(...)`. All of these will end up being converted into macro
718 MacStmtWithoutBraces,
721 // FIXME (pending discussion of #1697, #2178...): local should really be
722 // a refinement on pat.
723 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
724 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
727 pub ty: Option<P<Ty>>,
728 /// Initializer expression to set the value, if any
729 pub init: Option<P<Expr>>,
734 pub type Decl = Spanned<Decl_>;
736 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
738 /// A local (let) binding:
744 /// represents one arm of a 'match'
745 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
747 pub attrs: Vec<Attribute>,
748 pub pats: Vec<P<Pat>>,
749 pub guard: Option<P<Expr>>,
753 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
755 pub ident: SpannedIdent,
760 pub type SpannedIdent = Spanned<Ident>;
762 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
763 pub enum BlockCheckMode {
765 UnsafeBlock(UnsafeSource),
766 PushUnsafeBlock(UnsafeSource),
767 PopUnsafeBlock(UnsafeSource),
770 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
771 pub enum UnsafeSource {
777 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
784 impl fmt::Debug for Expr {
785 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
786 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
790 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
792 /// First expr is the place; second expr is the value.
793 ExprBox(Option<P<Expr>>, P<Expr>),
794 /// An array (`[a, b, c, d]`)
795 ExprVec(Vec<P<Expr>>),
798 /// The first field resolves to the function itself,
799 /// and the second field is the list of arguments
800 ExprCall(P<Expr>, Vec<P<Expr>>),
801 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
803 /// The `SpannedIdent` is the identifier for the method name.
804 /// The vector of `Ty`s are the ascripted type parameters for the method
805 /// (within the angle brackets).
807 /// The first element of the vector of `Expr`s is the expression that evaluates
808 /// to the object on which the method is being called on (the receiver),
809 /// and the remaining elements are the rest of the arguments.
811 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
812 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
813 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
814 /// A tuple (`(a, b, c ,d)`)
815 ExprTup(Vec<P<Expr>>),
816 /// A binary operation (For example: `a + b`, `a * b`)
817 ExprBinary(BinOp, P<Expr>, P<Expr>),
818 /// A unary operation (For example: `!x`, `*x`)
819 ExprUnary(UnOp, P<Expr>),
820 /// A literal (For example: `1u8`, `"foo"`)
822 /// A cast (`foo as f64`)
823 ExprCast(P<Expr>, P<Ty>),
824 /// An `if` block, with an optional else block
826 /// `if expr { block } else { expr }`
827 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
828 /// An `if let` expression with an optional else block
830 /// `if let pat = expr { block } else { expr }`
832 /// This is desugared to a `match` expression.
833 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
834 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
835 /// A while loop, with an optional label
837 /// `'label: while expr { block }`
838 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
839 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
840 /// A while-let loop, with an optional label
842 /// `'label: while let pat = expr { block }`
844 /// This is desugared to a combination of `loop` and `match` expressions.
845 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
846 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
847 /// A for loop, with an optional label
849 /// `'label: for pat in expr { block }`
851 /// This is desugared to a combination of `loop` and `match` expressions.
852 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
853 /// Conditionless loop (can be exited with break, continue, or return)
855 /// `'label: loop { block }`
856 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
857 ExprLoop(P<Block>, Option<Ident>),
858 /// A `match` block, with a source that indicates whether or not it is
859 /// the result of a desugaring, and if so, which kind.
860 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
861 /// A closure (for example, `move |a, b, c| {a + b + c}`)
862 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
863 /// A block (`{ ... }`)
866 /// An assignment (`a = foo()`)
867 ExprAssign(P<Expr>, P<Expr>),
868 /// An assignment with an operator
870 /// For example, `a += 1`.
871 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
872 /// Access of a named struct field (`obj.foo`)
873 ExprField(P<Expr>, SpannedIdent),
874 /// Access of an unnamed field of a struct or tuple-struct
876 /// For example, `foo.0`.
877 ExprTupField(P<Expr>, Spanned<usize>),
878 /// An indexing operation (`foo[2]`)
879 ExprIndex(P<Expr>, P<Expr>),
880 /// A range (`1..2`, `1..`, or `..2`)
881 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
883 /// Variable reference, possibly containing `::` and/or type
884 /// parameters, e.g. foo::bar::<baz>.
886 /// Optionally "qualified",
887 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
888 ExprPath(Option<QSelf>, Path),
890 /// A referencing operation (`&a` or `&mut a`)
891 ExprAddrOf(Mutability, P<Expr>),
892 /// A `break`, with an optional label to break
893 ExprBreak(Option<SpannedIdent>),
894 /// A `continue`, with an optional label
895 ExprAgain(Option<SpannedIdent>),
896 /// A `return`, with an optional value to be returned
897 ExprRet(Option<P<Expr>>),
899 /// Output of the `asm!()` macro
900 ExprInlineAsm(InlineAsm),
902 /// A macro invocation; pre-expansion
905 /// A struct literal expression.
907 /// For example, `Foo {x: 1, y: 2}`, or
908 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
909 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
911 /// An array literal constructed from one repeated element.
913 /// For example, `[1u8; 5]`. The first expression is the element
914 /// to be repeated; the second is the number of times to repeat it.
915 ExprRepeat(P<Expr>, P<Expr>),
917 /// No-op: used solely so we can pretty-print faithfully
921 /// The explicit Self type in a "qualified path". The actual
922 /// path, including the trait and the associated item, is stored
923 /// separately. `position` represents the index of the associated
924 /// item qualified with this Self type.
926 /// <Vec<T> as a::b::Trait>::AssociatedItem
927 /// ^~~~~ ~~~~~~~~~~~~~~^
930 /// <Vec<T>>::AssociatedItem
933 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
939 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
940 pub enum MatchSource {
942 IfLetDesugar { contains_else_clause: bool },
947 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
948 pub enum CaptureClause {
953 /// A delimited sequence of token trees
954 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
955 pub struct Delimited {
956 /// The type of delimiter
957 pub delim: token::DelimToken,
958 /// The span covering the opening delimiter
960 /// The delimited sequence of token trees
961 pub tts: Vec<TokenTree>,
962 /// The span covering the closing delimiter
963 pub close_span: Span,
967 /// Returns the opening delimiter as a token.
968 pub fn open_token(&self) -> token::Token {
969 token::OpenDelim(self.delim)
972 /// Returns the closing delimiter as a token.
973 pub fn close_token(&self) -> token::Token {
974 token::CloseDelim(self.delim)
977 /// Returns the opening delimiter as a token tree.
978 pub fn open_tt(&self) -> TokenTree {
979 TtToken(self.open_span, self.open_token())
982 /// Returns the closing delimiter as a token tree.
983 pub fn close_tt(&self) -> TokenTree {
984 TtToken(self.close_span, self.close_token())
988 /// A sequence of token treesee
989 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
990 pub struct SequenceRepetition {
991 /// The sequence of token trees
992 pub tts: Vec<TokenTree>,
993 /// The optional separator
994 pub separator: Option<token::Token>,
995 /// Whether the sequence can be repeated zero (*), or one or more times (+)
997 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
998 pub num_captures: usize,
1001 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
1002 /// for token sequences.
1003 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1009 /// When the main rust parser encounters a syntax-extension invocation, it
1010 /// parses the arguments to the invocation as a token-tree. This is a very
1011 /// loose structure, such that all sorts of different AST-fragments can
1012 /// be passed to syntax extensions using a uniform type.
1014 /// If the syntax extension is an MBE macro, it will attempt to match its
1015 /// LHS token tree against the provided token tree, and if it finds a
1016 /// match, will transcribe the RHS token tree, splicing in any captured
1017 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1019 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1020 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1021 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1022 pub enum TokenTree {
1024 TtToken(Span, token::Token),
1025 /// A delimited sequence of token trees
1026 TtDelimited(Span, Rc<Delimited>),
1028 // This only makes sense in MBE macros.
1030 /// A kleene-style repetition sequence with a span
1031 // FIXME(eddyb) #12938 Use DST.
1032 TtSequence(Span, Rc<SequenceRepetition>),
1036 pub fn len(&self) -> usize {
1038 TtToken(_, token::DocComment(name)) => {
1039 match doc_comment_style(&name.as_str()) {
1044 TtToken(_, token::SpecialVarNt(..)) => 2,
1045 TtToken(_, token::MatchNt(..)) => 3,
1046 TtDelimited(_, ref delimed) => {
1047 delimed.tts.len() + 2
1049 TtSequence(_, ref seq) => {
1056 pub fn get_tt(&self, index: usize) -> TokenTree {
1057 match (self, index) {
1058 (&TtToken(sp, token::DocComment(_)), 0) => {
1059 TtToken(sp, token::Pound)
1061 (&TtToken(sp, token::DocComment(name)), 1)
1062 if doc_comment_style(&name.as_str()) == AttrInner => {
1063 TtToken(sp, token::Not)
1065 (&TtToken(sp, token::DocComment(name)), _) => {
1066 let stripped = strip_doc_comment_decoration(&name.as_str());
1067 TtDelimited(sp, Rc::new(Delimited {
1068 delim: token::Bracket,
1070 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1072 TtToken(sp, token::Eq),
1073 TtToken(sp, token::Literal(
1074 token::StrRaw(token::intern(&stripped), 0), None))],
1078 (&TtDelimited(_, ref delimed), _) => {
1080 return delimed.open_tt();
1082 if index == delimed.tts.len() + 1 {
1083 return delimed.close_tt();
1085 delimed.tts[index - 1].clone()
1087 (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1088 let v = [TtToken(sp, token::Dollar),
1089 TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1093 (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1094 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1095 TtToken(sp, token::Colon),
1096 TtToken(sp, token::Ident(kind, kind_st))];
1099 (&TtSequence(_, ref seq), _) => {
1100 seq.tts[index].clone()
1102 _ => panic!("Cannot expand a token tree")
1106 /// Returns the `Span` corresponding to this token tree.
1107 pub fn get_span(&self) -> Span {
1109 TtToken(span, _) => span,
1110 TtDelimited(span, _) => span,
1111 TtSequence(span, _) => span,
1115 /// Use this token tree as a matcher to parse given tts.
1116 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1117 -> macro_parser::NamedParseResult {
1118 // `None` is because we're not interpolating
1119 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1122 tts.iter().cloned().collect(),
1124 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1128 pub type Mac = Spanned<Mac_>;
1130 /// Represents a macro invocation. The Path indicates which macro
1131 /// is being invoked, and the vector of token-trees contains the source
1132 /// of the macro invocation.
1134 /// NB: the additional ident for a macro_rules-style macro is actually
1135 /// stored in the enclosing item. Oog.
1136 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1139 pub tts: Vec<TokenTree>,
1140 pub ctxt: SyntaxContext,
1143 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1145 /// A regular string, like `"foo"`
1147 /// A raw string, like `r##"foo"##`
1149 /// The uint is the number of `#` symbols used
1154 pub type Lit = Spanned<Lit_>;
1156 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1163 pub fn new<T: IntSign>(n: T) -> Sign {
1169 fn sign(&self) -> Sign;
1172 ($($t:ident)*) => ($(impl IntSign for $t {
1173 #[allow(unused_comparisons)]
1174 fn sign(&self) -> Sign {
1175 if *self < 0 {Minus} else {Plus}
1179 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1181 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1182 pub enum LitIntType {
1183 SignedIntLit(IntTy, Sign),
1184 UnsignedIntLit(UintTy),
1185 UnsuffixedIntLit(Sign)
1188 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1190 /// A string literal (`"foo"`)
1191 LitStr(InternedString, StrStyle),
1192 /// A byte string (`b"foo"`)
1193 LitByteStr(Rc<Vec<u8>>),
1194 /// A byte char (`b'f'`)
1196 /// A character literal (`'a'`)
1198 /// An integer literal (`1u8`)
1199 LitInt(u64, LitIntType),
1200 /// A float literal (`1f64` or `1E10f64`)
1201 LitFloat(InternedString, FloatTy),
1202 /// A float literal without a suffix (`1.0 or 1.0E10`)
1203 LitFloatUnsuffixed(InternedString),
1204 /// A boolean literal
1208 // NB: If you change this, you'll probably want to change the corresponding
1209 // type structure in middle/ty.rs as well.
1210 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1213 pub mutbl: Mutability,
1216 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1217 pub struct TypeField {
1223 /// Represents a method's signature in a trait declaration,
1224 /// or in an implementation.
1225 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1226 pub struct MethodSig {
1227 pub unsafety: Unsafety,
1228 pub constness: Constness,
1230 pub decl: P<FnDecl>,
1231 pub generics: Generics,
1232 pub explicit_self: ExplicitSelf,
1235 /// Represents a method declaration in a trait declaration, possibly including
1236 /// a default implementation A trait method is either required (meaning it
1237 /// doesn't have an implementation, just a signature) or provided (meaning it
1238 /// has a default implementation).
1239 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1240 pub struct TraitItem {
1243 pub attrs: Vec<Attribute>,
1244 pub node: TraitItem_,
1248 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1249 pub enum TraitItem_ {
1250 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1251 MethodTraitItem(MethodSig, Option<P<Block>>),
1252 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1255 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1256 pub struct ImplItem {
1259 pub vis: Visibility,
1260 pub attrs: Vec<Attribute>,
1261 pub node: ImplItem_,
1265 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1266 pub enum ImplItem_ {
1267 ConstImplItem(P<Ty>, P<Expr>),
1268 MethodImplItem(MethodSig, P<Block>),
1269 TypeImplItem(P<Ty>),
1273 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1282 impl fmt::Debug for IntTy {
1283 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1284 fmt::Display::fmt(self, f)
1288 impl fmt::Display for IntTy {
1289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1290 write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1295 pub fn bit_width(&self) -> Option<usize> {
1297 TyIs => return None,
1306 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1316 pub fn bit_width(&self) -> Option<usize> {
1318 TyUs => return None,
1327 impl fmt::Debug for UintTy {
1328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1329 fmt::Display::fmt(self, f)
1333 impl fmt::Display for UintTy {
1334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1335 write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1345 impl fmt::Debug for FloatTy {
1346 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1347 fmt::Display::fmt(self, f)
1351 impl fmt::Display for FloatTy {
1352 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1353 write!(f, "{}", ast_util::float_ty_to_string(*self))
1358 pub fn bit_width(&self) -> usize {
1366 // Bind a type to an associated type: `A=Foo`.
1367 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1368 pub struct TypeBinding {
1375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1382 impl fmt::Debug for Ty {
1383 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1384 write!(f, "type({})", pprust::ty_to_string(self))
1388 /// Not represented directly in the AST, referred to by name through a ty_path.
1389 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1400 pub struct BareFnTy {
1401 pub unsafety: Unsafety,
1403 pub lifetimes: Vec<LifetimeDef>,
1407 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1408 /// The different kinds of types recognized by the compiler
1411 /// A fixed length array (`[T; n]`)
1412 TyFixedLengthVec(P<Ty>, P<Expr>),
1413 /// A raw pointer (`*const T` or `*mut T`)
1415 /// A reference (`&'a T` or `&'a mut T`)
1416 TyRptr(Option<Lifetime>, MutTy),
1417 /// A bare function (e.g. `fn(usize) -> bool`)
1418 TyBareFn(P<BareFnTy>),
1419 /// A tuple (`(A, B, C, D,...)`)
1421 /// A path (`module::module::...::Type`), optionally
1422 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1424 /// Type parameters are stored in the Path itself
1425 TyPath(Option<QSelf>, Path),
1426 /// Something like `A+B`. Note that `B` must always be a path.
1427 TyObjectSum(P<Ty>, TyParamBounds),
1428 /// A type like `for<'a> Foo<&'a Bar>`
1429 TyPolyTraitRef(TyParamBounds),
1430 /// No-op; kept solely so that we can pretty-print faithfully
1434 /// TyInfer means the type should be inferred instead of it having been
1435 /// specified. This can appear anywhere in a type.
1437 // A macro in the type position.
1441 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1442 pub enum AsmDialect {
1447 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1448 pub struct InlineAsm {
1449 pub asm: InternedString,
1450 pub asm_str_style: StrStyle,
1451 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1452 pub inputs: Vec<(InternedString, P<Expr>)>,
1453 pub clobbers: Vec<InternedString>,
1455 pub alignstack: bool,
1456 pub dialect: AsmDialect,
1457 pub expn_id: ExpnId,
1460 /// represents an argument in a function header
1461 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1469 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1470 let path = Spanned{span:span,node:self_ident};
1472 // HACK(eddyb) fake type for the self argument.
1480 node: PatIdent(BindByValue(mutability), path, None),
1488 /// Represents the header (not the body) of a function declaration
1489 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1491 pub inputs: Vec<Arg>,
1492 pub output: FunctionRetTy,
1496 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1502 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1503 pub enum Constness {
1508 impl fmt::Display for Unsafety {
1509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1510 fmt::Display::fmt(match *self {
1511 Unsafety::Normal => "normal",
1512 Unsafety::Unsafe => "unsafe",
1517 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1518 pub enum ImplPolarity {
1519 /// `impl Trait for Type`
1521 /// `impl !Trait for Type`
1525 impl fmt::Debug for ImplPolarity {
1526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1528 ImplPolarity::Positive => "positive".fmt(f),
1529 ImplPolarity::Negative => "negative".fmt(f),
1535 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub enum FunctionRetTy {
1537 /// Functions with return type `!`that always
1538 /// raise an error or exit (i.e. never return to the caller)
1540 /// Return type is not specified.
1542 /// Functions default to `()` and
1543 /// closures default to inference. Span points to where return
1544 /// type would be inserted.
1545 DefaultReturn(Span),
1550 impl FunctionRetTy {
1551 pub fn span(&self) -> Span {
1553 NoReturn(span) => span,
1554 DefaultReturn(span) => span,
1555 Return(ref ty) => ty.span
1560 /// Represents the kind of 'self' associated with a method
1561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1562 pub enum ExplicitSelf_ {
1567 /// `&'lt self`, `&'lt mut self`
1568 SelfRegion(Option<Lifetime>, Mutability, Ident),
1570 SelfExplicit(P<Ty>, Ident),
1573 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1575 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1577 /// A span from the first token past `{` to the last token until `}`.
1578 /// For `mod foo;`, the inner span ranges from the first token
1579 /// to the last token in the external file.
1581 pub items: Vec<P<Item>>,
1584 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1585 pub struct ForeignMod {
1587 pub items: Vec<P<ForeignItem>>,
1590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1591 pub struct VariantArg {
1596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1597 pub enum VariantKind {
1598 /// Tuple variant, e.g. `Foo(A, B)`
1599 TupleVariantKind(Vec<VariantArg>),
1600 /// Struct variant, e.g. `Foo {x: A, y: B}`
1601 StructVariantKind(P<StructDef>),
1604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1605 pub struct EnumDef {
1606 pub variants: Vec<P<Variant>>,
1609 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1610 pub struct Variant_ {
1612 pub attrs: Vec<Attribute>,
1613 pub kind: VariantKind,
1615 /// Explicit discriminant, eg `Foo = 1`
1616 pub disr_expr: Option<P<Expr>>,
1619 pub type Variant = Spanned<Variant_>;
1621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1622 pub enum PathListItem_ {
1625 /// renamed in list, eg `use foo::{bar as baz};`
1626 rename: Option<Ident>,
1630 /// renamed in list, eg `use foo::{self as baz};`
1631 rename: Option<Ident>,
1636 impl PathListItem_ {
1637 pub fn id(&self) -> NodeId {
1639 PathListIdent { id, .. } | PathListMod { id, .. } => id
1643 pub fn rename(&self) -> Option<Ident> {
1645 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1650 pub type PathListItem = Spanned<PathListItem_>;
1652 pub type ViewPath = Spanned<ViewPath_>;
1654 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1655 pub enum ViewPath_ {
1657 /// `foo::bar::baz as quux`
1661 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1662 ViewPathSimple(Ident, Path),
1667 /// `foo::bar::{a,b,c}`
1668 ViewPathList(Path, Vec<PathListItem>)
1671 /// Meta-data associated with an item
1672 pub type Attribute = Spanned<Attribute_>;
1674 /// Distinguishes between Attributes that decorate items and Attributes that
1675 /// are contained as statements within items. These two cases need to be
1676 /// distinguished for pretty-printing.
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1678 pub enum AttrStyle {
1683 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1684 pub struct AttrId(pub usize);
1686 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1687 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1688 pub struct Attribute_ {
1690 pub style: AttrStyle,
1691 pub value: P<MetaItem>,
1692 pub is_sugared_doc: bool,
1695 /// TraitRef's appear in impls.
1697 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1698 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1699 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1700 /// same as the impl's node id).
1701 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1702 pub struct TraitRef {
1707 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1708 pub struct PolyTraitRef {
1709 /// The `'a` in `<'a> Foo<&'a T>`
1710 pub bound_lifetimes: Vec<LifetimeDef>,
1712 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1713 pub trait_ref: TraitRef,
1718 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1719 pub enum Visibility {
1725 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1727 &Inherited => parent_visibility,
1733 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1734 pub struct StructField_ {
1735 pub kind: StructFieldKind,
1738 pub attrs: Vec<Attribute>,
1742 pub fn ident(&self) -> Option<Ident> {
1744 NamedField(ref ident, _) => Some(ident.clone()),
1745 UnnamedField(_) => None
1750 pub type StructField = Spanned<StructField_>;
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1753 pub enum StructFieldKind {
1754 NamedField(Ident, Visibility),
1755 /// Element of a tuple-like struct
1756 UnnamedField(Visibility),
1759 impl StructFieldKind {
1760 pub fn is_unnamed(&self) -> bool {
1762 UnnamedField(..) => true,
1763 NamedField(..) => false,
1768 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1769 pub struct StructDef {
1770 /// Fields, not including ctor
1771 pub fields: Vec<StructField>,
1772 /// ID of the constructor. This is only used for tuple- or enum-like
1774 pub ctor_id: Option<NodeId>,
1778 FIXME (#3300): Should allow items to be anonymous. Right now
1779 we just use dummy names for anon items.
1783 /// The name might be a dummy name in case of anonymous items
1784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1787 pub attrs: Vec<Attribute>,
1790 pub vis: Visibility,
1794 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1796 /// An`extern crate` item, with optional original crate name,
1798 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1799 ItemExternCrate(Option<Name>),
1800 /// A `use` or `pub use` item
1801 ItemUse(P<ViewPath>),
1804 ItemStatic(P<Ty>, Mutability, P<Expr>),
1806 ItemConst(P<Ty>, P<Expr>),
1807 /// A function declaration
1808 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1811 /// An external module
1812 ItemForeignMod(ForeignMod),
1813 /// A type alias, e.g. `type Foo = Bar<u8>`
1814 ItemTy(P<Ty>, Generics),
1815 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1816 ItemEnum(EnumDef, Generics),
1817 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1818 ItemStruct(P<StructDef>, Generics),
1819 /// Represents a Trait Declaration
1825 // Default trait implementations
1827 // `impl Trait for .. {}`
1828 ItemDefaultImpl(Unsafety, TraitRef),
1829 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1833 Option<TraitRef>, // (optional) trait this impl implements
1836 /// A macro invocation (which includes macro definition)
1841 pub fn descriptive_variant(&self) -> &str {
1843 ItemExternCrate(..) => "extern crate",
1844 ItemUse(..) => "use",
1845 ItemStatic(..) => "static item",
1846 ItemConst(..) => "constant item",
1847 ItemFn(..) => "function",
1848 ItemMod(..) => "module",
1849 ItemForeignMod(..) => "foreign module",
1850 ItemTy(..) => "type alias",
1851 ItemEnum(..) => "enum",
1852 ItemStruct(..) => "struct",
1853 ItemTrait(..) => "trait",
1856 ItemDefaultImpl(..) => "item"
1861 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1862 pub struct ForeignItem {
1864 pub attrs: Vec<Attribute>,
1865 pub node: ForeignItem_,
1868 pub vis: Visibility,
1871 /// An item within an `extern` block
1872 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1873 pub enum ForeignItem_ {
1874 /// A foreign function
1875 ForeignItemFn(P<FnDecl>, Generics),
1876 /// A foreign static item (`static ext: u8`), with optional mutability
1877 /// (the boolean is true when mutable)
1878 ForeignItemStatic(P<Ty>, bool),
1882 pub fn descriptive_variant(&self) -> &str {
1884 ForeignItemFn(..) => "foreign function",
1885 ForeignItemStatic(..) => "foreign static item"
1890 /// A macro definition, in this crate or imported from another.
1892 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1893 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1894 pub struct MacroDef {
1896 pub attrs: Vec<Attribute>,
1899 pub imported_from: Option<Ident>,
1901 pub use_locally: bool,
1902 pub allow_internal_unstable: bool,
1903 pub body: Vec<TokenTree>,
1911 // are ASTs encodable?
1913 fn check_asts_encodable() {
1914 fn assert_encodable<T: serialize::Encodable>() {}
1915 assert_encodable::<Crate>();