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::Mac_::*;
32 pub use self::MacStmtStyle::*;
33 pub use self::MetaItem_::*;
34 pub use self::Mutability::*;
35 pub use self::Pat_::*;
36 pub use self::PathListItem_::*;
37 pub use self::PatWildKind::*;
38 pub use self::PrimTy::*;
39 pub use self::Sign::*;
40 pub use self::Stmt_::*;
41 pub use self::StrStyle::*;
42 pub use self::StructFieldKind::*;
43 pub use self::TokenTree::*;
44 pub use self::TraitItem_::*;
46 pub use self::TyParamBound::*;
47 pub use self::UintTy::*;
48 pub use self::UnOp::*;
49 pub use self::UnsafeSource::*;
50 pub use self::VariantKind::*;
51 pub use self::ViewPath_::*;
52 pub use self::Visibility::*;
53 pub use self::PathParameters::*;
55 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
59 use ext::tt::macro_parser;
60 use owned_slice::OwnedSlice;
61 use parse::token::{InternedString, str_to_ident};
64 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
70 use serialize::{Encodable, Decodable, Encoder, Decoder};
72 // FIXME #6993: in librustc, uses of "ident" should be replaced
75 /// An identifier contains a Name (index into the interner
76 /// table) and a SyntaxContext to track renaming and
77 /// macro expansion per Flatt et al., "Macros
78 /// That Work Together"
79 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
82 pub ctxt: SyntaxContext
86 /// Construct an identifier with the given name and an empty context:
87 pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
90 impl fmt::Debug for Ident {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 write!(f, "{}#{}", self.name, self.ctxt)
96 impl fmt::Display for Ident {
97 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98 fmt::Display::fmt(&self.name, f)
102 impl fmt::Debug for Name {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104 let Name(nm) = *self;
105 write!(f, "{}({})", self, nm)
109 impl fmt::Display for Name {
110 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111 fmt::Display::fmt(&self.as_str(), f)
115 impl PartialEq for Ident {
116 fn eq(&self, other: &Ident) -> bool {
117 if self.ctxt == other.ctxt {
118 self.name == other.name
120 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
121 // idents that have different contexts. You can't fix this without
122 // knowing whether the comparison should be hygienic or non-hygienic.
123 // if it should be non-hygienic (most things are), just compare the
124 // 'name' fields of the idents. Or, even better, replace the idents
127 // On the other hand, if the comparison does need to be hygienic,
128 // one example and its non-hygienic counterpart would be:
129 // syntax::parse::token::Token::mtwt_eq
130 // syntax::ext::tt::macro_parser::token_name_eq
131 panic!("not allowed to compare these idents: {:?}, {:?}. \
132 Probably related to issue \\#6993", self, other);
137 /// A SyntaxContext represents a chain of macro-expandings
138 /// and renamings. Each macro expansion corresponds to
141 // I'm representing this syntax context as an index into
142 // a table, in order to work around a compiler bug
143 // that's causing unreleased memory to cause core dumps
144 // and also perhaps to save some work in destructor checks.
145 // the special uint '0' will be used to indicate an empty
148 // this uint is a reference to a table stored in thread-local
150 pub type SyntaxContext = u32;
151 pub const EMPTY_CTXT : SyntaxContext = 0;
152 pub const ILLEGAL_CTXT : SyntaxContext = 1;
154 /// A name is a part of an identifier, representing a string or gensym. It's
155 /// the result of interning.
156 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
157 RustcEncodable, RustcDecodable, Clone, Copy)]
158 pub struct Name(pub u32);
160 impl<T: AsRef<str>> PartialEq<T> for Name {
161 fn eq(&self, other: &T) -> bool {
162 self.as_str() == other.as_ref()
167 pub fn as_str(&self) -> token::InternedString {
168 token::InternedString::new_from_name(*self)
171 pub fn usize(&self) -> usize {
172 let Name(nm) = *self;
176 pub fn ident(&self) -> Ident {
177 Ident { name: *self, ctxt: 0 }
181 /// A mark represents a unique id associated with a macro expansion
184 impl Encodable for Ident {
185 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
186 s.emit_str(&self.name.as_str())
190 impl Decodable for Ident {
191 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
192 Ok(str_to_ident(&try!(d.read_str())[..]))
196 /// Function name (not all functions have names)
197 pub type FnIdent = Option<Ident>;
199 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
200 pub struct Lifetime {
206 impl fmt::Debug for Lifetime {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
212 /// A lifetime definition, eg `'a: 'b+'c+'d`
213 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
214 pub struct LifetimeDef {
215 pub lifetime: Lifetime,
216 pub bounds: Vec<Lifetime>
219 /// A "Path" is essentially Rust's notion of a name; for instance:
220 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
221 /// along with a bunch of supporting information.
222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
225 /// A `::foo` path, is relative to the crate root rather than current
226 /// module (like paths in an import).
228 /// The segments in the path: the things separated by `::`.
229 pub segments: Vec<PathSegment>,
232 impl fmt::Debug for Path {
233 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
234 write!(f, "path({})", pprust::path_to_string(self))
238 impl fmt::Display for Path {
239 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
240 write!(f, "{}", pprust::path_to_string(self))
244 /// A segment of a path: an identifier, an optional lifetime, and a set of
246 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
247 pub struct PathSegment {
248 /// The identifier portion of this path segment.
249 pub identifier: Ident,
251 /// Type/lifetime parameters attached to this path. They come in
252 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
253 /// this is more than just simple syntactic sugar; the use of
254 /// parens affects the region binding rules, so we preserve the
256 pub parameters: PathParameters,
259 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
260 pub enum PathParameters {
261 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
262 AngleBracketedParameters(AngleBracketedParameterData),
263 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
264 ParenthesizedParameters(ParenthesizedParameterData),
267 impl PathParameters {
268 pub fn none() -> PathParameters {
269 AngleBracketedParameters(AngleBracketedParameterData {
270 lifetimes: Vec::new(),
271 types: OwnedSlice::empty(),
272 bindings: OwnedSlice::empty(),
276 pub fn is_empty(&self) -> bool {
278 AngleBracketedParameters(ref data) => data.is_empty(),
280 // Even if the user supplied no types, something like
281 // `X()` is equivalent to `X<(),()>`.
282 ParenthesizedParameters(..) => false,
286 pub fn has_lifetimes(&self) -> bool {
288 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
289 ParenthesizedParameters(_) => false,
293 pub fn has_types(&self) -> bool {
295 AngleBracketedParameters(ref data) => !data.types.is_empty(),
296 ParenthesizedParameters(..) => true,
300 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
301 /// parameters in the parenthesized case.
302 pub fn types(&self) -> Vec<&P<Ty>> {
304 AngleBracketedParameters(ref data) => {
305 data.types.iter().collect()
307 ParenthesizedParameters(ref data) => {
309 .chain(data.output.iter())
315 pub fn lifetimes(&self) -> Vec<&Lifetime> {
317 AngleBracketedParameters(ref data) => {
318 data.lifetimes.iter().collect()
320 ParenthesizedParameters(_) => {
326 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
328 AngleBracketedParameters(ref data) => {
329 data.bindings.iter().collect()
331 ParenthesizedParameters(_) => {
338 /// A path like `Foo<'a, T>`
339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
340 pub struct AngleBracketedParameterData {
341 /// The lifetime parameters for this path segment.
342 pub lifetimes: Vec<Lifetime>,
343 /// The type parameters for this path segment, if present.
344 pub types: OwnedSlice<P<Ty>>,
345 /// Bindings (equality constraints) on associated types, if present.
346 /// E.g., `Foo<A=Bar>`.
347 pub bindings: OwnedSlice<P<TypeBinding>>,
350 impl AngleBracketedParameterData {
351 fn is_empty(&self) -> bool {
352 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
356 /// A path like `Foo(A,B) -> C`
357 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
358 pub struct ParenthesizedParameterData {
363 pub inputs: Vec<P<Ty>>,
366 pub output: Option<P<Ty>>,
369 pub type CrateNum = u32;
371 pub type NodeId = u32;
373 /// Node id used to represent the root of the crate.
374 pub const CRATE_NODE_ID: NodeId = 0;
376 /// When parsing and doing expansions, we initially give all AST nodes this AST
377 /// node value. Then later, in the renumber pass, we renumber them to have
378 /// small, positive ids.
379 pub const DUMMY_NODE_ID: NodeId = !0;
381 /// The AST represents all type param bounds as types.
382 /// typeck::collect::compute_bounds matches these against
383 /// the "special" built-in traits (see middle::lang_items) and
384 /// detects Copy, Send and Sync.
385 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
386 pub enum TyParamBound {
387 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
388 RegionTyParamBound(Lifetime)
391 /// A modifier on a bound, currently this is only used for `?Sized`, where the
392 /// modifier is `Maybe`. Negative bounds should also be handled here.
393 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
394 pub enum TraitBoundModifier {
399 pub type TyParamBounds = OwnedSlice<TyParamBound>;
401 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
405 pub bounds: TyParamBounds,
406 pub default: Option<P<Ty>>,
410 /// Represents lifetimes and type parameters attached to a declaration
411 /// of a function, enum, trait, etc.
412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
413 pub struct Generics {
414 pub lifetimes: Vec<LifetimeDef>,
415 pub ty_params: OwnedSlice<TyParam>,
416 pub where_clause: WhereClause,
420 pub fn is_lt_parameterized(&self) -> bool {
421 !self.lifetimes.is_empty()
423 pub fn is_type_parameterized(&self) -> bool {
424 !self.ty_params.is_empty()
426 pub fn is_parameterized(&self) -> bool {
427 self.is_lt_parameterized() || self.is_type_parameterized()
431 /// A `where` clause in a definition
432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
433 pub struct WhereClause {
435 pub predicates: Vec<WherePredicate>,
438 /// A single predicate in a `where` clause
439 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
440 pub enum WherePredicate {
441 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
442 BoundPredicate(WhereBoundPredicate),
443 /// A lifetime predicate, e.g. `'a: 'b+'c`
444 RegionPredicate(WhereRegionPredicate),
445 /// An equality predicate (unsupported)
446 EqPredicate(WhereEqPredicate),
449 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
450 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
451 pub struct WhereBoundPredicate {
453 /// Any lifetimes from a `for` binding
454 pub bound_lifetimes: Vec<LifetimeDef>,
455 /// The type being bounded
456 pub bounded_ty: P<Ty>,
457 /// Trait and lifetime bounds (`Clone+Send+'static`)
458 pub bounds: OwnedSlice<TyParamBound>,
461 /// A lifetime predicate, e.g. `'a: 'b+'c`
462 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
463 pub struct WhereRegionPredicate {
465 pub lifetime: Lifetime,
466 pub bounds: Vec<Lifetime>,
469 /// An equality predicate (unsupported), e.g. `T=int`
470 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
471 pub struct WhereEqPredicate {
478 /// The set of MetaItems that define the compilation environment of the crate,
479 /// used to drive conditional compilation
480 pub type CrateConfig = Vec<P<MetaItem>> ;
482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
485 pub attrs: Vec<Attribute>,
486 pub config: CrateConfig,
488 pub exported_macros: Vec<MacroDef>,
491 pub type MetaItem = Spanned<MetaItem_>;
493 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
495 MetaWord(InternedString),
496 MetaList(InternedString, Vec<P<MetaItem>>),
497 MetaNameValue(InternedString, Lit),
500 // can't be derived because the MetaList requires an unordered comparison
501 impl PartialEq for MetaItem_ {
502 fn eq(&self, other: &MetaItem_) -> bool {
504 MetaWord(ref ns) => match *other {
505 MetaWord(ref no) => (*ns) == (*no),
508 MetaNameValue(ref ns, ref vs) => match *other {
509 MetaNameValue(ref no, ref vo) => {
510 (*ns) == (*no) && vs.node == vo.node
514 MetaList(ref ns, ref miss) => match *other {
515 MetaList(ref no, ref miso) => {
517 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
525 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
527 /// Statements in a block
528 pub stmts: Vec<P<Stmt>>,
529 /// An expression at the end of the block
530 /// without a semicolon, if any
531 pub expr: Option<P<Expr>>,
533 /// Distinguishes between `unsafe { ... }` and `{ ... }`
534 pub rules: BlockCheckMode,
538 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
545 impl fmt::Debug for Pat {
546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
547 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
551 /// A single field in a struct pattern
553 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
554 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
555 /// except is_shorthand is true
556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
557 pub struct FieldPat {
558 /// The identifier for the field
560 /// The pattern the field is destructured to
562 pub is_shorthand: bool,
565 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
566 pub enum BindingMode {
567 BindByRef(Mutability),
568 BindByValue(Mutability),
571 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
572 pub enum PatWildKind {
573 /// Represents the wildcard pattern `_`
576 /// Represents the wildcard pattern `..`
580 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
582 /// Represents a wildcard pattern (either `_` or `..`)
583 PatWild(PatWildKind),
585 /// A PatIdent may either be a new bound variable,
586 /// or a nullary enum (in which case the third field
589 /// In the nullary enum case, the parser can't determine
590 /// which it is. The resolver determines this, and
591 /// records this pattern's NodeId in an auxiliary
592 /// set (of "PatIdents that refer to nullary enums")
593 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
595 /// "None" means a * pattern where we don't bind the fields to names.
596 PatEnum(Path, Option<Vec<P<Pat>>>),
598 /// An associated const named using the qualified path `<T>::CONST` or
599 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
600 /// referred to as simply `T::CONST`, in which case they will end up as
601 /// PatEnum, and the resolver will have to sort that out.
602 PatQPath(QSelf, Path),
604 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
605 /// The `bool` is `true` in the presence of a `..`
606 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
607 /// A tuple pattern `(a, b)`
611 /// A reference pattern, e.g. `&mut (a, b)`
612 PatRegion(P<Pat>, Mutability),
615 /// A range pattern, e.g. `1...2`
616 PatRange(P<Expr>, P<Expr>),
617 /// [a, b, ..i, y, z] is represented as:
618 /// PatVec(box [a, b], Some(i), box [y, z])
619 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
620 /// A macro pattern; pre-expansion
624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
625 pub enum Mutability {
630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
632 /// The `+` operator (addition)
634 /// The `-` operator (subtraction)
636 /// The `*` operator (multiplication)
638 /// The `/` operator (division)
640 /// The `%` operator (modulus)
642 /// The `&&` operator (logical and)
644 /// The `||` operator (logical or)
646 /// The `^` operator (bitwise xor)
648 /// The `&` operator (bitwise and)
650 /// The `|` operator (bitwise or)
652 /// The `<<` operator (shift left)
654 /// The `>>` operator (shift right)
656 /// The `==` operator (equality)
658 /// The `<` operator (less than)
660 /// The `<=` operator (less than or equal to)
662 /// The `!=` operator (not equal to)
664 /// The `>=` operator (greater than or equal to)
666 /// The `>` operator (greater than)
670 pub type BinOp = Spanned<BinOp_>;
672 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
674 /// The `box` operator
676 /// The `*` operator for dereferencing
678 /// The `!` operator for logical inversion
680 /// The `-` operator for negation
685 pub type Stmt = Spanned<Stmt_>;
687 impl fmt::Debug for Stmt {
688 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
689 write!(f, "stmt({}: {})",
690 ast_util::stmt_id(self),
691 pprust::stmt_to_string(self))
696 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
698 /// Could be an item or a local (let) binding:
699 StmtDecl(P<Decl>, NodeId),
701 /// Expr without trailing semi-colon (must have unit type):
702 StmtExpr(P<Expr>, NodeId),
704 /// Expr with trailing semi-colon (may have any type):
705 StmtSemi(P<Expr>, NodeId),
707 StmtMac(P<Mac>, MacStmtStyle),
709 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
710 pub enum MacStmtStyle {
711 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
712 /// `foo!(...);`, `foo![...];`
713 MacStmtWithSemicolon,
714 /// The macro statement had braces; e.g. foo! { ... }
716 /// The macro statement had parentheses or brackets and no semicolon; e.g.
717 /// `foo!(...)`. All of these will end up being converted into macro
719 MacStmtWithoutBraces,
722 // FIXME (pending discussion of #1697, #2178...): local should really be
723 // a refinement on pat.
724 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
725 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
728 pub ty: Option<P<Ty>>,
729 /// Initializer expression to set the value, if any
730 pub init: Option<P<Expr>>,
735 pub type Decl = Spanned<Decl_>;
737 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
739 /// A local (let) binding:
745 /// represents one arm of a 'match'
746 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
748 pub attrs: Vec<Attribute>,
749 pub pats: Vec<P<Pat>>,
750 pub guard: Option<P<Expr>>,
754 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
756 pub ident: SpannedIdent,
761 pub type SpannedIdent = Spanned<Ident>;
763 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
764 pub enum BlockCheckMode {
766 UnsafeBlock(UnsafeSource),
767 PushUnsafeBlock(UnsafeSource),
768 PopUnsafeBlock(UnsafeSource),
771 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
772 pub enum UnsafeSource {
778 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
785 impl fmt::Debug for Expr {
786 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
787 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
791 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
793 /// First expr is the place; second expr is the value.
794 ExprBox(Option<P<Expr>>, P<Expr>),
795 /// An array (`[a, b, c, d]`)
796 ExprVec(Vec<P<Expr>>),
799 /// The first field resolves to the function itself,
800 /// and the second field is the list of arguments
801 ExprCall(P<Expr>, Vec<P<Expr>>),
802 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
804 /// The `SpannedIdent` is the identifier for the method name.
805 /// The vector of `Ty`s are the ascripted type parameters for the method
806 /// (within the angle brackets).
808 /// The first element of the vector of `Expr`s is the expression that evaluates
809 /// to the object on which the method is being called on (the receiver),
810 /// and the remaining elements are the rest of the arguments.
812 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
813 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
814 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
815 /// A tuple (`(a, b, c ,d)`)
816 ExprTup(Vec<P<Expr>>),
817 /// A binary operation (For example: `a + b`, `a * b`)
818 ExprBinary(BinOp, P<Expr>, P<Expr>),
819 /// A unary operation (For example: `!x`, `*x`)
820 ExprUnary(UnOp, P<Expr>),
821 /// A literal (For example: `1u8`, `"foo"`)
823 /// A cast (`foo as f64`)
824 ExprCast(P<Expr>, P<Ty>),
825 /// An `if` block, with an optional else block
827 /// `if expr { block } else { expr }`
828 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
829 /// An `if let` expression with an optional else block
831 /// `if let pat = expr { block } else { expr }`
833 /// This is desugared to a `match` expression.
834 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
835 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
836 /// A while loop, with an optional label
838 /// `'label: while expr { block }`
839 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
840 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
841 /// A while-let loop, with an optional label
843 /// `'label: while let pat = expr { block }`
845 /// This is desugared to a combination of `loop` and `match` expressions.
846 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
847 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
848 /// A for loop, with an optional label
850 /// `'label: for pat in expr { block }`
852 /// This is desugared to a combination of `loop` and `match` expressions.
853 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
854 /// Conditionless loop (can be exited with break, continue, or return)
856 /// `'label: loop { block }`
857 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
858 ExprLoop(P<Block>, Option<Ident>),
859 /// A `match` block, with a source that indicates whether or not it is
860 /// the result of a desugaring, and if so, which kind.
861 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
862 /// A closure (for example, `move |a, b, c| {a + b + c}`)
863 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
864 /// A block (`{ ... }`)
867 /// An assignment (`a = foo()`)
868 ExprAssign(P<Expr>, P<Expr>),
869 /// An assignment with an operator
871 /// For example, `a += 1`.
872 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
873 /// Access of a named struct field (`obj.foo`)
874 ExprField(P<Expr>, SpannedIdent),
875 /// Access of an unnamed field of a struct or tuple-struct
877 /// For example, `foo.0`.
878 ExprTupField(P<Expr>, Spanned<usize>),
879 /// An indexing operation (`foo[2]`)
880 ExprIndex(P<Expr>, P<Expr>),
881 /// A range (`1..2`, `1..`, or `..2`)
882 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
884 /// Variable reference, possibly containing `::` and/or type
885 /// parameters, e.g. foo::bar::<baz>.
887 /// Optionally "qualified",
888 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
889 ExprPath(Option<QSelf>, Path),
891 /// A referencing operation (`&a` or `&mut a`)
892 ExprAddrOf(Mutability, P<Expr>),
893 /// A `break`, with an optional label to break
894 ExprBreak(Option<Ident>),
895 /// A `continue`, with an optional label
896 ExprAgain(Option<Ident>),
897 /// A `return`, with an optional value to be returned
898 ExprRet(Option<P<Expr>>),
900 /// Output of the `asm!()` macro
901 ExprInlineAsm(InlineAsm),
903 /// A macro invocation; pre-expansion
906 /// A struct literal expression.
908 /// For example, `Foo {x: 1, y: 2}`, or
909 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
910 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
912 /// An array literal constructed from one repeated element.
914 /// For example, `[1u8; 5]`. The first expression is the element
915 /// to be repeated; the second is the number of times to repeat it.
916 ExprRepeat(P<Expr>, P<Expr>),
918 /// No-op: used solely so we can pretty-print faithfully
922 /// The explicit Self type in a "qualified path". The actual
923 /// path, including the trait and the associated item, is stored
924 /// separately. `position` represents the index of the associated
925 /// item qualified with this Self type.
927 /// <Vec<T> as a::b::Trait>::AssociatedItem
928 /// ^~~~~ ~~~~~~~~~~~~~~^
931 /// <Vec<T>>::AssociatedItem
934 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
940 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
941 pub enum MatchSource {
943 IfLetDesugar { contains_else_clause: bool },
948 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
949 pub enum CaptureClause {
954 /// A delimited sequence of token trees
955 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
956 pub struct Delimited {
957 /// The type of delimiter
958 pub delim: token::DelimToken,
959 /// The span covering the opening delimiter
961 /// The delimited sequence of token trees
962 pub tts: Vec<TokenTree>,
963 /// The span covering the closing delimiter
964 pub close_span: Span,
968 /// Returns the opening delimiter as a token.
969 pub fn open_token(&self) -> token::Token {
970 token::OpenDelim(self.delim)
973 /// Returns the closing delimiter as a token.
974 pub fn close_token(&self) -> token::Token {
975 token::CloseDelim(self.delim)
978 /// Returns the opening delimiter as a token tree.
979 pub fn open_tt(&self) -> TokenTree {
980 TtToken(self.open_span, self.open_token())
983 /// Returns the closing delimiter as a token tree.
984 pub fn close_tt(&self) -> TokenTree {
985 TtToken(self.close_span, self.close_token())
989 /// A sequence of token treesee
990 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
991 pub struct SequenceRepetition {
992 /// The sequence of token trees
993 pub tts: Vec<TokenTree>,
994 /// The optional separator
995 pub separator: Option<token::Token>,
996 /// Whether the sequence can be repeated zero (*), or one or more times (+)
998 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
999 pub num_captures: usize,
1002 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
1003 /// for token sequences.
1004 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1010 /// When the main rust parser encounters a syntax-extension invocation, it
1011 /// parses the arguments to the invocation as a token-tree. This is a very
1012 /// loose structure, such that all sorts of different AST-fragments can
1013 /// be passed to syntax extensions using a uniform type.
1015 /// If the syntax extension is an MBE macro, it will attempt to match its
1016 /// LHS token tree against the provided token tree, and if it finds a
1017 /// match, will transcribe the RHS token tree, splicing in any captured
1018 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1020 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1021 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1022 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1023 pub enum TokenTree {
1025 TtToken(Span, token::Token),
1026 /// A delimited sequence of token trees
1027 TtDelimited(Span, Rc<Delimited>),
1029 // This only makes sense in MBE macros.
1031 /// A kleene-style repetition sequence with a span
1032 // FIXME(eddyb) #12938 Use DST.
1033 TtSequence(Span, Rc<SequenceRepetition>),
1037 pub fn len(&self) -> usize {
1039 TtToken(_, token::DocComment(name)) => {
1040 match doc_comment_style(&name.as_str()) {
1045 TtToken(_, token::SpecialVarNt(..)) => 2,
1046 TtToken(_, token::MatchNt(..)) => 3,
1047 TtDelimited(_, ref delimed) => {
1048 delimed.tts.len() + 2
1050 TtSequence(_, ref seq) => {
1057 pub fn get_tt(&self, index: usize) -> TokenTree {
1058 match (self, index) {
1059 (&TtToken(sp, token::DocComment(_)), 0) => {
1060 TtToken(sp, token::Pound)
1062 (&TtToken(sp, token::DocComment(name)), 1)
1063 if doc_comment_style(&name.as_str()) == AttrInner => {
1064 TtToken(sp, token::Not)
1066 (&TtToken(sp, token::DocComment(name)), _) => {
1067 let stripped = strip_doc_comment_decoration(&name.as_str());
1068 TtDelimited(sp, Rc::new(Delimited {
1069 delim: token::Bracket,
1071 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1073 TtToken(sp, token::Eq),
1074 TtToken(sp, token::Literal(
1075 token::StrRaw(token::intern(&stripped), 0), None))],
1079 (&TtDelimited(_, ref delimed), _) => {
1081 return delimed.open_tt();
1083 if index == delimed.tts.len() + 1 {
1084 return delimed.close_tt();
1086 delimed.tts[index - 1].clone()
1088 (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1089 let v = [TtToken(sp, token::Dollar),
1090 TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1094 (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1095 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1096 TtToken(sp, token::Colon),
1097 TtToken(sp, token::Ident(kind, kind_st))];
1100 (&TtSequence(_, ref seq), _) => {
1101 seq.tts[index].clone()
1103 _ => panic!("Cannot expand a token tree")
1107 /// Returns the `Span` corresponding to this token tree.
1108 pub fn get_span(&self) -> Span {
1110 TtToken(span, _) => span,
1111 TtDelimited(span, _) => span,
1112 TtSequence(span, _) => span,
1116 /// Use this token tree as a matcher to parse given tts.
1117 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1118 -> macro_parser::NamedParseResult {
1119 // `None` is because we're not interpolating
1120 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1123 tts.iter().cloned().collect(),
1125 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1129 pub type Mac = Spanned<Mac_>;
1131 /// Represents a macro invocation. The Path indicates which macro
1132 /// is being invoked, and the vector of token-trees contains the source
1133 /// of the macro invocation.
1135 /// There's only one flavor, now, so this could presumably be simplified.
1136 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1138 // NB: the additional ident for a macro_rules-style macro is actually
1139 // stored in the enclosing item. Oog.
1140 MacInvocTT(Path, Vec<TokenTree>, SyntaxContext), // new macro-invocation
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 LitBinary(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 {
1376 // NB PartialEq method appears below.
1377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1384 impl fmt::Debug for Ty {
1385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1386 write!(f, "type({})", pprust::ty_to_string(self))
1390 /// Not represented directly in the AST, referred to by name through a ty_path.
1391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1401 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1402 pub struct BareFnTy {
1403 pub unsafety: Unsafety,
1405 pub lifetimes: Vec<LifetimeDef>,
1409 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1410 /// The different kinds of types recognized by the compiler
1413 /// A fixed length array (`[T; n]`)
1414 TyFixedLengthVec(P<Ty>, P<Expr>),
1415 /// A raw pointer (`*const T` or `*mut T`)
1417 /// A reference (`&'a T` or `&'a mut T`)
1418 TyRptr(Option<Lifetime>, MutTy),
1419 /// A bare function (e.g. `fn(usize) -> bool`)
1420 TyBareFn(P<BareFnTy>),
1421 /// A tuple (`(A, B, C, D,...)`)
1423 /// A path (`module::module::...::Type`), optionally
1424 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1426 /// Type parameters are stored in the Path itself
1427 TyPath(Option<QSelf>, Path),
1428 /// Something like `A+B`. Note that `B` must always be a path.
1429 TyObjectSum(P<Ty>, TyParamBounds),
1430 /// A type like `for<'a> Foo<&'a Bar>`
1431 TyPolyTraitRef(TyParamBounds),
1432 /// No-op; kept solely so that we can pretty-print faithfully
1436 /// TyInfer means the type should be inferred instead of it having been
1437 /// specified. This can appear anywhere in a type.
1439 // A macro in the type position.
1443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1444 pub enum AsmDialect {
1449 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1450 pub struct InlineAsm {
1451 pub asm: InternedString,
1452 pub asm_str_style: StrStyle,
1453 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1454 pub inputs: Vec<(InternedString, P<Expr>)>,
1455 pub clobbers: Vec<InternedString>,
1457 pub alignstack: bool,
1458 pub dialect: AsmDialect,
1459 pub expn_id: ExpnId,
1462 /// represents an argument in a function header
1463 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1471 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1472 let path = Spanned{span:span,node:self_ident};
1474 // HACK(eddyb) fake type for the self argument.
1482 node: PatIdent(BindByValue(mutability), path, None),
1490 /// Represents the header (not the body) of a function declaration
1491 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1493 pub inputs: Vec<Arg>,
1494 pub output: FunctionRetTy,
1498 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1504 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1505 pub enum Constness {
1510 impl fmt::Display for Unsafety {
1511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1512 fmt::Display::fmt(match *self {
1513 Unsafety::Normal => "normal",
1514 Unsafety::Unsafe => "unsafe",
1519 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1520 pub enum ImplPolarity {
1521 /// `impl Trait for Type`
1523 /// `impl !Trait for Type`
1527 impl fmt::Debug for ImplPolarity {
1528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1530 ImplPolarity::Positive => "positive".fmt(f),
1531 ImplPolarity::Negative => "negative".fmt(f),
1537 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1538 pub enum FunctionRetTy {
1539 /// Functions with return type `!`that always
1540 /// raise an error or exit (i.e. never return to the caller)
1542 /// Return type is not specified.
1544 /// Functions default to `()` and
1545 /// closures default to inference. Span points to where return
1546 /// type would be inserted.
1547 DefaultReturn(Span),
1552 impl FunctionRetTy {
1553 pub fn span(&self) -> Span {
1555 NoReturn(span) => span,
1556 DefaultReturn(span) => span,
1557 Return(ref ty) => ty.span
1562 /// Represents the kind of 'self' associated with a method
1563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1564 pub enum ExplicitSelf_ {
1569 /// `&'lt self`, `&'lt mut self`
1570 SelfRegion(Option<Lifetime>, Mutability, Ident),
1572 SelfExplicit(P<Ty>, Ident),
1575 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1577 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1579 /// A span from the first token past `{` to the last token until `}`.
1580 /// For `mod foo;`, the inner span ranges from the first token
1581 /// to the last token in the external file.
1583 pub items: Vec<P<Item>>,
1586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1587 pub struct ForeignMod {
1589 pub items: Vec<P<ForeignItem>>,
1592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1593 pub struct VariantArg {
1598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1599 pub enum VariantKind {
1600 /// Tuple variant, e.g. `Foo(A, B)`
1601 TupleVariantKind(Vec<VariantArg>),
1602 /// Struct variant, e.g. `Foo {x: A, y: B}`
1603 StructVariantKind(P<StructDef>),
1606 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1607 pub struct EnumDef {
1608 pub variants: Vec<P<Variant>>,
1611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1612 pub struct Variant_ {
1614 pub attrs: Vec<Attribute>,
1615 pub kind: VariantKind,
1617 /// Explicit discriminant, eg `Foo = 1`
1618 pub disr_expr: Option<P<Expr>>,
1619 pub vis: Visibility,
1622 pub type Variant = Spanned<Variant_>;
1624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1625 pub enum PathListItem_ {
1628 /// renamed in list, eg `use foo::{bar as baz};`
1629 rename: Option<Ident>,
1633 /// renamed in list, eg `use foo::{self as baz};`
1634 rename: Option<Ident>,
1639 impl PathListItem_ {
1640 pub fn id(&self) -> NodeId {
1642 PathListIdent { id, .. } | PathListMod { id, .. } => id
1646 pub fn rename(&self) -> Option<Ident> {
1648 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1653 pub type PathListItem = Spanned<PathListItem_>;
1655 pub type ViewPath = Spanned<ViewPath_>;
1657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1658 pub enum ViewPath_ {
1660 /// `foo::bar::baz as quux`
1664 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1665 ViewPathSimple(Ident, Path),
1670 /// `foo::bar::{a,b,c}`
1671 ViewPathList(Path, Vec<PathListItem>)
1674 /// Meta-data associated with an item
1675 pub type Attribute = Spanned<Attribute_>;
1677 /// Distinguishes between Attributes that decorate items and Attributes that
1678 /// are contained as statements within items. These two cases need to be
1679 /// distinguished for pretty-printing.
1680 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1681 pub enum AttrStyle {
1686 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1687 pub struct AttrId(pub usize);
1689 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1690 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1691 pub struct Attribute_ {
1693 pub style: AttrStyle,
1694 pub value: P<MetaItem>,
1695 pub is_sugared_doc: bool,
1698 /// TraitRef's appear in impls.
1700 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1701 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1702 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1703 /// same as the impl's node id).
1704 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1705 pub struct TraitRef {
1710 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1711 pub struct PolyTraitRef {
1712 /// The `'a` in `<'a> Foo<&'a T>`
1713 pub bound_lifetimes: Vec<LifetimeDef>,
1715 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1716 pub trait_ref: TraitRef,
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1722 pub enum Visibility {
1728 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1730 &Inherited => parent_visibility,
1736 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1737 pub struct StructField_ {
1738 pub kind: StructFieldKind,
1741 pub attrs: Vec<Attribute>,
1745 pub fn ident(&self) -> Option<Ident> {
1747 NamedField(ref ident, _) => Some(ident.clone()),
1748 UnnamedField(_) => None
1753 pub type StructField = Spanned<StructField_>;
1755 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1756 pub enum StructFieldKind {
1757 NamedField(Ident, Visibility),
1758 /// Element of a tuple-like struct
1759 UnnamedField(Visibility),
1762 impl StructFieldKind {
1763 pub fn is_unnamed(&self) -> bool {
1765 UnnamedField(..) => true,
1766 NamedField(..) => false,
1771 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1772 pub struct StructDef {
1773 /// Fields, not including ctor
1774 pub fields: Vec<StructField>,
1775 /// ID of the constructor. This is only used for tuple- or enum-like
1777 pub ctor_id: Option<NodeId>,
1781 FIXME (#3300): Should allow items to be anonymous. Right now
1782 we just use dummy names for anon items.
1786 /// The name might be a dummy name in case of anonymous items
1787 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1790 pub attrs: Vec<Attribute>,
1793 pub vis: Visibility,
1797 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1799 /// An`extern crate` item, with optional original crate name,
1801 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1802 ItemExternCrate(Option<Name>),
1803 /// A `use` or `pub use` item
1804 ItemUse(P<ViewPath>),
1807 ItemStatic(P<Ty>, Mutability, P<Expr>),
1809 ItemConst(P<Ty>, P<Expr>),
1810 /// A function declaration
1811 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1814 /// An external module
1815 ItemForeignMod(ForeignMod),
1816 /// A type alias, e.g. `type Foo = Bar<u8>`
1817 ItemTy(P<Ty>, Generics),
1818 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1819 ItemEnum(EnumDef, Generics),
1820 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1821 ItemStruct(P<StructDef>, Generics),
1822 /// Represents a Trait Declaration
1828 // Default trait implementations
1830 // `impl Trait for .. {}`
1831 ItemDefaultImpl(Unsafety, TraitRef),
1832 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1836 Option<TraitRef>, // (optional) trait this impl implements
1839 /// A macro invocation (which includes macro definition)
1844 pub fn descriptive_variant(&self) -> &str {
1846 ItemExternCrate(..) => "extern crate",
1847 ItemUse(..) => "use",
1848 ItemStatic(..) => "static item",
1849 ItemConst(..) => "constant item",
1850 ItemFn(..) => "function",
1851 ItemMod(..) => "module",
1852 ItemForeignMod(..) => "foreign module",
1853 ItemTy(..) => "type alias",
1854 ItemEnum(..) => "enum",
1855 ItemStruct(..) => "struct",
1856 ItemTrait(..) => "trait",
1859 ItemDefaultImpl(..) => "item"
1864 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1865 pub struct ForeignItem {
1867 pub attrs: Vec<Attribute>,
1868 pub node: ForeignItem_,
1871 pub vis: Visibility,
1874 /// An item within an `extern` block
1875 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1876 pub enum ForeignItem_ {
1877 /// A foreign function
1878 ForeignItemFn(P<FnDecl>, Generics),
1879 /// A foreign static item (`static ext: u8`), with optional mutability
1880 /// (the boolean is true when mutable)
1881 ForeignItemStatic(P<Ty>, bool),
1885 pub fn descriptive_variant(&self) -> &str {
1887 ForeignItemFn(..) => "foreign function",
1888 ForeignItemStatic(..) => "foreign static item"
1893 /// A macro definition, in this crate or imported from another.
1895 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1896 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1897 pub struct MacroDef {
1899 pub attrs: Vec<Attribute>,
1902 pub imported_from: Option<Ident>,
1904 pub use_locally: bool,
1905 pub allow_internal_unstable: bool,
1906 pub body: Vec<TokenTree>,
1914 // are ASTs encodable?
1916 fn check_asts_encodable() {
1917 fn assert_encodable<T: serialize::Encodable>() {}
1918 assert_encodable::<Crate>();