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::InlinedItem::*;
27 pub use self::IntTy::*;
28 pub use self::Item_::*;
29 pub use self::KleeneOp::*;
30 pub use self::Lit_::*;
31 pub use self::LitIntType::*;
32 pub use self::LocalSource::*;
33 pub use self::Mac_::*;
34 pub use self::MacStmtStyle::*;
35 pub use self::MetaItem_::*;
36 pub use self::Mutability::*;
37 pub use self::Pat_::*;
38 pub use self::PathListItem_::*;
39 pub use self::PatWildKind::*;
40 pub use self::PrimTy::*;
41 pub use self::Sign::*;
42 pub use self::Stmt_::*;
43 pub use self::StrStyle::*;
44 pub use self::StructFieldKind::*;
45 pub use self::TokenTree::*;
46 pub use self::TraitItem_::*;
48 pub use self::TyParamBound::*;
49 pub use self::UintTy::*;
50 pub use self::UnOp::*;
51 pub use self::UnsafeSource::*;
52 pub use self::VariantKind::*;
53 pub use self::ViewPath_::*;
54 pub use self::Visibility::*;
55 pub use self::PathParameters::*;
57 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
61 use ext::tt::macro_parser;
62 use owned_slice::OwnedSlice;
63 use parse::token::{InternedString, str_to_ident};
72 use serialize::{Encodable, Decodable, Encoder, Decoder};
74 // FIXME #6993: in librustc, uses of "ident" should be replaced
77 /// An identifier contains a Name (index into the interner
78 /// table) and a SyntaxContext to track renaming and
79 /// macro expansion per Flatt et al., "Macros
80 /// That Work Together"
81 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
84 pub ctxt: SyntaxContext
88 /// Construct an identifier with the given name and an empty context:
89 pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
91 pub fn as_str<'a>(&'a self) -> &'a str {
95 pub fn encode_with_hygiene(&self) -> String {
96 format!("\x00name_{},ctxt_{}\x00",
102 impl fmt::Debug for Ident {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104 write!(f, "{}#{}", self.name, self.ctxt)
108 impl fmt::Display for Ident {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110 fmt::Display::fmt(&self.name, f)
114 impl fmt::Debug for Name {
115 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
116 let Name(nm) = *self;
117 write!(f, "{:?}({})", token::get_name(*self), nm)
121 impl fmt::Display for Name {
122 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123 fmt::Display::fmt(&token::get_name(*self), f)
127 impl PartialEq for Ident {
128 fn eq(&self, other: &Ident) -> bool {
129 if self.ctxt == other.ctxt {
130 self.name == other.name
132 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
133 // idents that have different contexts. You can't fix this without
134 // knowing whether the comparison should be hygienic or non-hygienic.
135 // if it should be non-hygienic (most things are), just compare the
136 // 'name' fields of the idents. Or, even better, replace the idents
139 // On the other hand, if the comparison does need to be hygienic,
140 // one example and its non-hygienic counterpart would be:
141 // syntax::parse::token::Token::mtwt_eq
142 // syntax::ext::tt::macro_parser::token_name_eq
143 panic!("not allowed to compare these idents: {}, {}. \
144 Probably related to issue \\#6993", self, other);
147 fn ne(&self, other: &Ident) -> bool {
152 /// A SyntaxContext represents a chain of macro-expandings
153 /// and renamings. Each macro expansion corresponds to
156 // I'm representing this syntax context as an index into
157 // a table, in order to work around a compiler bug
158 // that's causing unreleased memory to cause core dumps
159 // and also perhaps to save some work in destructor checks.
160 // the special uint '0' will be used to indicate an empty
163 // this uint is a reference to a table stored in thread-local
165 pub type SyntaxContext = u32;
166 pub const EMPTY_CTXT : SyntaxContext = 0;
167 pub const ILLEGAL_CTXT : SyntaxContext = 1;
169 /// A name is a part of an identifier, representing a string or gensym. It's
170 /// the result of interning.
171 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
172 RustcEncodable, RustcDecodable, Clone, Copy)]
173 pub struct Name(pub u32);
176 pub fn as_str<'a>(&'a self) -> &'a str {
178 // FIXME #12938: can't use copy_lifetime since &str isn't a &T
179 ::std::mem::transmute::<&str,&str>(&token::get_name(*self))
183 pub fn usize(&self) -> usize {
184 let Name(nm) = *self;
188 pub fn ident(&self) -> Ident {
189 Ident { name: *self, ctxt: 0 }
193 /// A mark represents a unique id associated with a macro expansion
196 impl Encodable for Ident {
197 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
198 s.emit_str(&token::get_ident(*self))
202 impl Decodable for Ident {
203 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
204 Ok(str_to_ident(&try!(d.read_str())[..]))
208 /// Function name (not all functions have names)
209 pub type FnIdent = Option<Ident>;
211 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,
213 pub struct Lifetime {
219 /// A lifetime definition, eg `'a: 'b+'c+'d`
220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
221 pub struct LifetimeDef {
222 pub lifetime: Lifetime,
223 pub bounds: Vec<Lifetime>
226 /// A "Path" is essentially Rust's notion of a name; for instance:
227 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
228 /// along with a bunch of supporting information.
229 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
232 /// A `::foo` path, is relative to the crate root rather than current
233 /// module (like paths in an import).
235 /// The segments in the path: the things separated by `::`.
236 pub segments: Vec<PathSegment>,
239 /// A segment of a path: an identifier, an optional lifetime, and a set of
241 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
242 pub struct PathSegment {
243 /// The identifier portion of this path segment.
244 pub identifier: Ident,
246 /// Type/lifetime parameters attached to this path. They come in
247 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
248 /// this is more than just simple syntactic sugar; the use of
249 /// parens affects the region binding rules, so we preserve the
251 pub parameters: PathParameters,
254 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
255 pub enum PathParameters {
256 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
257 AngleBracketedParameters(AngleBracketedParameterData),
258 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
259 ParenthesizedParameters(ParenthesizedParameterData),
262 impl PathParameters {
263 pub fn none() -> PathParameters {
264 AngleBracketedParameters(AngleBracketedParameterData {
265 lifetimes: Vec::new(),
266 types: OwnedSlice::empty(),
267 bindings: OwnedSlice::empty(),
271 pub fn is_empty(&self) -> bool {
273 AngleBracketedParameters(ref data) => data.is_empty(),
275 // Even if the user supplied no types, something like
276 // `X()` is equivalent to `X<(),()>`.
277 ParenthesizedParameters(..) => false,
281 pub fn has_lifetimes(&self) -> bool {
283 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
284 ParenthesizedParameters(_) => false,
288 pub fn has_types(&self) -> bool {
290 AngleBracketedParameters(ref data) => !data.types.is_empty(),
291 ParenthesizedParameters(..) => true,
295 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
296 /// parameters in the parenthesized case.
297 pub fn types(&self) -> Vec<&P<Ty>> {
299 AngleBracketedParameters(ref data) => {
300 data.types.iter().collect()
302 ParenthesizedParameters(ref data) => {
304 .chain(data.output.iter())
310 pub fn lifetimes(&self) -> Vec<&Lifetime> {
312 AngleBracketedParameters(ref data) => {
313 data.lifetimes.iter().collect()
315 ParenthesizedParameters(_) => {
321 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
323 AngleBracketedParameters(ref data) => {
324 data.bindings.iter().collect()
326 ParenthesizedParameters(_) => {
333 /// A path like `Foo<'a, T>`
334 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
335 pub struct AngleBracketedParameterData {
336 /// The lifetime parameters for this path segment.
337 pub lifetimes: Vec<Lifetime>,
338 /// The type parameters for this path segment, if present.
339 pub types: OwnedSlice<P<Ty>>,
340 /// Bindings (equality constraints) on associated types, if present.
341 /// E.g., `Foo<A=Bar>`.
342 pub bindings: OwnedSlice<P<TypeBinding>>,
345 impl AngleBracketedParameterData {
346 fn is_empty(&self) -> bool {
347 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
351 /// A path like `Foo(A,B) -> C`
352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
353 pub struct ParenthesizedParameterData {
358 pub inputs: Vec<P<Ty>>,
361 pub output: Option<P<Ty>>,
364 pub type CrateNum = u32;
366 pub type NodeId = u32;
368 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
369 RustcDecodable, Hash, Debug, Copy)]
376 /// Read the node id, asserting that this def-id is krate-local.
377 pub fn local_id(&self) -> NodeId {
378 assert_eq!(self.krate, LOCAL_CRATE);
383 /// Item definitions in the currently-compiled crate would have the CrateNum
384 /// LOCAL_CRATE in their DefId.
385 pub const LOCAL_CRATE: CrateNum = 0;
386 pub const CRATE_NODE_ID: NodeId = 0;
388 /// When parsing and doing expansions, we initially give all AST nodes this AST
389 /// node value. Then later, in the renumber pass, we renumber them to have
390 /// small, positive ids.
391 pub const DUMMY_NODE_ID: NodeId = -1;
393 /// The AST represents all type param bounds as types.
394 /// typeck::collect::compute_bounds matches these against
395 /// the "special" built-in traits (see middle::lang_items) and
396 /// detects Copy, Send and Sync.
397 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
398 pub enum TyParamBound {
399 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
400 RegionTyParamBound(Lifetime)
403 /// A modifier on a bound, currently this is only used for `?Sized`, where the
404 /// modifier is `Maybe`. Negative bounds should also be handled here.
405 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
406 pub enum TraitBoundModifier {
411 pub type TyParamBounds = OwnedSlice<TyParamBound>;
413 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
417 pub bounds: TyParamBounds,
418 pub default: Option<P<Ty>>,
422 /// Represents lifetimes and type parameters attached to a declaration
423 /// of a function, enum, trait, etc.
424 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
425 pub struct Generics {
426 pub lifetimes: Vec<LifetimeDef>,
427 pub ty_params: OwnedSlice<TyParam>,
428 pub where_clause: WhereClause,
432 pub fn is_parameterized(&self) -> bool {
433 self.lifetimes.len() + self.ty_params.len() > 0
435 pub fn is_lt_parameterized(&self) -> bool {
436 self.lifetimes.len() > 0
438 pub fn is_type_parameterized(&self) -> bool {
439 self.ty_params.len() > 0
443 /// A `where` clause in a definition
444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
445 pub struct WhereClause {
447 pub predicates: Vec<WherePredicate>,
450 /// A single predicate in a `where` clause
451 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
452 pub enum WherePredicate {
453 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
454 BoundPredicate(WhereBoundPredicate),
455 /// A lifetime predicate, e.g. `'a: 'b+'c`
456 RegionPredicate(WhereRegionPredicate),
457 /// An equality predicate (unsupported)
458 EqPredicate(WhereEqPredicate)
461 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
462 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
463 pub struct WhereBoundPredicate {
465 /// Any lifetimes from a `for` binding
466 pub bound_lifetimes: Vec<LifetimeDef>,
467 /// The type being bounded
468 pub bounded_ty: P<Ty>,
469 /// Trait and lifetime bounds (`Clone+Send+'static`)
470 pub bounds: OwnedSlice<TyParamBound>,
473 /// A lifetime predicate, e.g. `'a: 'b+'c`
474 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
475 pub struct WhereRegionPredicate {
477 pub lifetime: Lifetime,
478 pub bounds: Vec<Lifetime>,
481 /// An equality predicate (unsupported), e.g. `T=int`
482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
483 pub struct WhereEqPredicate {
490 /// The set of MetaItems that define the compilation environment of the crate,
491 /// used to drive conditional compilation
492 pub type CrateConfig = Vec<P<MetaItem>> ;
494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
497 pub attrs: Vec<Attribute>,
498 pub config: CrateConfig,
500 pub exported_macros: Vec<MacroDef>,
503 pub type MetaItem = Spanned<MetaItem_>;
505 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
507 MetaWord(InternedString),
508 MetaList(InternedString, Vec<P<MetaItem>>),
509 MetaNameValue(InternedString, Lit),
512 // can't be derived because the MetaList requires an unordered comparison
513 impl PartialEq for MetaItem_ {
514 fn eq(&self, other: &MetaItem_) -> bool {
516 MetaWord(ref ns) => match *other {
517 MetaWord(ref no) => (*ns) == (*no),
520 MetaNameValue(ref ns, ref vs) => match *other {
521 MetaNameValue(ref no, ref vo) => {
522 (*ns) == (*no) && vs.node == vo.node
526 MetaList(ref ns, ref miss) => match *other {
527 MetaList(ref no, ref miso) => {
529 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
537 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
539 /// Statements in a block
540 pub stmts: Vec<P<Stmt>>,
541 /// An expression at the end of the block
542 /// without a semicolon, if any
543 pub expr: Option<P<Expr>>,
545 /// Distinguishes between `unsafe { ... }` and `{ ... }`
546 pub rules: BlockCheckMode,
550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
557 /// A single field in a struct pattern
559 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
560 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
561 /// except is_shorthand is true
562 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
563 pub struct FieldPat {
564 /// The identifier for the field
566 /// The pattern the field is destructured to
568 pub is_shorthand: bool,
571 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
572 pub enum BindingMode {
573 BindByRef(Mutability),
574 BindByValue(Mutability),
577 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
578 pub enum PatWildKind {
579 /// Represents the wildcard pattern `_`
582 /// Represents the wildcard pattern `..`
586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
588 /// Represents a wildcard pattern (either `_` or `..`)
589 PatWild(PatWildKind),
591 /// A PatIdent may either be a new bound variable,
592 /// or a nullary enum (in which case the third field
595 /// In the nullary enum case, the parser can't determine
596 /// which it is. The resolver determines this, and
597 /// records this pattern's NodeId in an auxiliary
598 /// set (of "PatIdents that refer to nullary enums")
599 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
601 /// "None" means a * pattern where we don't bind the fields to names.
602 PatEnum(Path, Option<Vec<P<Pat>>>),
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 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
689 /// Could be an item or a local (let) binding:
690 StmtDecl(P<Decl>, NodeId),
692 /// Expr without trailing semi-colon (must have unit type):
693 StmtExpr(P<Expr>, NodeId),
695 /// Expr with trailing semi-colon (may have any type):
696 StmtSemi(P<Expr>, NodeId),
698 StmtMac(P<Mac>, MacStmtStyle),
701 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
702 pub enum MacStmtStyle {
703 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
704 /// `foo!(...);`, `foo![...];`
705 MacStmtWithSemicolon,
706 /// The macro statement had braces; e.g. foo! { ... }
708 /// The macro statement had parentheses or brackets and no semicolon; e.g.
709 /// `foo!(...)`. All of these will end up being converted into macro
711 MacStmtWithoutBraces,
714 /// Where a local declaration came from: either a true `let ... =
715 /// ...;`, or one desugared from the pattern of a for loop.
716 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
717 pub enum LocalSource {
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>>,
733 pub source: LocalSource,
736 pub type Decl = Spanned<Decl_>;
738 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
740 /// A local (let) binding:
746 /// represents one arm of a 'match'
747 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
749 pub attrs: Vec<Attribute>,
750 pub pats: Vec<P<Pat>>,
751 pub guard: Option<P<Expr>>,
755 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
757 pub ident: SpannedIdent,
762 pub type SpannedIdent = Spanned<Ident>;
764 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
765 pub enum BlockCheckMode {
767 UnsafeBlock(UnsafeSource),
770 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
771 pub enum UnsafeSource {
777 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
786 /// First expr is the place; second expr is the value.
787 ExprBox(Option<P<Expr>>, P<Expr>),
788 /// An array (`[a, b, c, d]`)
789 ExprVec(Vec<P<Expr>>),
792 /// The first field resolves to the function itself,
793 /// and the second field is the list of arguments
794 ExprCall(P<Expr>, Vec<P<Expr>>),
795 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
797 /// The `SpannedIdent` is the identifier for the method name.
798 /// The vector of `Ty`s are the ascripted type parameters for the method
799 /// (within the angle brackets).
801 /// The first element of the vector of `Expr`s is the expression that evaluates
802 /// to the object on which the method is being called on (the receiver),
803 /// and the remaining elements are the rest of the arguments.
805 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
806 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
807 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
808 /// A tuple (`(a, b, c ,d)`)
809 ExprTup(Vec<P<Expr>>),
810 /// A binary operation (For example: `a + b`, `a * b`)
811 ExprBinary(BinOp, P<Expr>, P<Expr>),
812 /// A unary operation (For example: `!x`, `*x`)
813 ExprUnary(UnOp, P<Expr>),
814 /// A literal (For example: `1u8`, `"foo"`)
816 /// A cast (`foo as f64`)
817 ExprCast(P<Expr>, P<Ty>),
818 /// An `if` block, with an optional else block
820 /// `if expr { block } else { expr }`
821 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
822 /// An `if let` expression with an optional else block
824 /// `if let pat = expr { block } else { expr }`
826 /// This is desugared to a `match` expression.
827 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
828 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
829 /// A while loop, with an optional label
831 /// `'label: while expr { block }`
832 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
833 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
834 /// A while-let loop, with an optional label
836 /// `'label: while let pat = expr { block }`
838 /// This is desugared to a combination of `loop` and `match` expressions.
839 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
840 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
841 /// A for loop, with an optional label
843 /// `'label: for pat in expr { block }`
845 /// This is desugared to a combination of `loop` and `match` expressions.
846 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
847 /// Conditionless loop (can be exited with break, continue, or return)
849 /// `'label: loop { block }`
850 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
851 ExprLoop(P<Block>, Option<Ident>),
852 /// A `match` block, with a source that indicates whether or not it is
853 /// the result of a desugaring, and if so, which kind.
854 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
855 /// A closure (for example, `move |a, b, c| {a + b + c}`)
856 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
857 /// A block (`{ ... }`)
860 /// An assignment (`a = foo()`)
861 ExprAssign(P<Expr>, P<Expr>),
862 /// An assignment with an operator
864 /// For example, `a += 1`.
865 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
866 /// Access of a named struct field (`obj.foo`)
867 ExprField(P<Expr>, SpannedIdent),
868 /// Access of an unnamed field of a struct or tuple-struct
870 /// For example, `foo.0`.
871 ExprTupField(P<Expr>, Spanned<usize>),
872 /// An indexing operation (`foo[2]`)
873 ExprIndex(P<Expr>, P<Expr>),
874 /// A range (`1..2`, `1..`, or `..2`)
875 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
877 /// Variable reference, possibly containing `::` and/or type
878 /// parameters, e.g. foo::bar::<baz>.
880 /// Optionally "qualified",
881 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
882 ExprPath(Option<QSelf>, Path),
884 /// A referencing operation (`&a` or `&mut a`)
885 ExprAddrOf(Mutability, P<Expr>),
886 /// A `break`, with an optional label to break
887 ExprBreak(Option<Ident>),
888 /// A `continue`, with an optional label
889 ExprAgain(Option<Ident>),
890 /// A `return`, with an optional value to be returned
891 ExprRet(Option<P<Expr>>),
893 /// Output of the `asm!()` macro
894 ExprInlineAsm(InlineAsm),
896 /// A macro invocation; pre-expansion
899 /// A struct literal expression.
901 /// For example, `Foo {x: 1, y: 2}`, or
902 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
903 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
905 /// A vector literal constructed from one repeated element.
907 /// For example, `[1u8; 5]`. The first expression is the element
908 /// to be repeated; the second is the number of times to repeat it.
909 ExprRepeat(P<Expr>, P<Expr>),
911 /// No-op: used solely so we can pretty-print faithfully
915 /// The explicit Self type in a "qualified path". The actual
916 /// path, including the trait and the associated item, is stored
917 /// separately. `position` represents the index of the associated
918 /// item qualified with this Self type.
920 /// <Vec<T> as a::b::Trait>::AssociatedItem
921 /// ^~~~~ ~~~~~~~~~~~~~~^
924 /// <Vec<T>>::AssociatedItem
927 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
933 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
934 pub enum MatchSource {
936 IfLetDesugar { contains_else_clause: bool },
941 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
942 pub enum CaptureClause {
947 /// A delimited sequence of token trees
948 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
949 pub struct Delimited {
950 /// The type of delimiter
951 pub delim: token::DelimToken,
952 /// The span covering the opening delimiter
954 /// The delimited sequence of token trees
955 pub tts: Vec<TokenTree>,
956 /// The span covering the closing delimiter
957 pub close_span: Span,
961 /// Returns the opening delimiter as a token.
962 pub fn open_token(&self) -> token::Token {
963 token::OpenDelim(self.delim)
966 /// Returns the closing delimiter as a token.
967 pub fn close_token(&self) -> token::Token {
968 token::CloseDelim(self.delim)
971 /// Returns the opening delimiter as a token tree.
972 pub fn open_tt(&self) -> TokenTree {
973 TtToken(self.open_span, self.open_token())
976 /// Returns the closing delimiter as a token tree.
977 pub fn close_tt(&self) -> TokenTree {
978 TtToken(self.close_span, self.close_token())
982 /// A sequence of token treesee
983 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
984 pub struct SequenceRepetition {
985 /// The sequence of token trees
986 pub tts: Vec<TokenTree>,
987 /// The optional separator
988 pub separator: Option<token::Token>,
989 /// Whether the sequence can be repeated zero (*), or one or more times (+)
991 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
992 pub num_captures: usize,
995 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
996 /// for token sequences.
997 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1003 /// When the main rust parser encounters a syntax-extension invocation, it
1004 /// parses the arguments to the invocation as a token-tree. This is a very
1005 /// loose structure, such that all sorts of different AST-fragments can
1006 /// be passed to syntax extensions using a uniform type.
1008 /// If the syntax extension is an MBE macro, it will attempt to match its
1009 /// LHS token tree against the provided token tree, and if it finds a
1010 /// match, will transcribe the RHS token tree, splicing in any captured
1011 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1013 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1014 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1015 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1016 pub enum TokenTree {
1018 TtToken(Span, token::Token),
1019 /// A delimited sequence of token trees
1020 TtDelimited(Span, Rc<Delimited>),
1022 // This only makes sense in MBE macros.
1024 /// A kleene-style repetition sequence with a span
1025 // FIXME(eddyb) #12938 Use DST.
1026 TtSequence(Span, Rc<SequenceRepetition>),
1030 pub fn len(&self) -> usize {
1032 TtToken(_, token::DocComment(_)) => 2,
1033 TtToken(_, token::SpecialVarNt(..)) => 2,
1034 TtToken(_, token::MatchNt(..)) => 3,
1035 TtDelimited(_, ref delimed) => {
1036 delimed.tts.len() + 2
1038 TtSequence(_, ref seq) => {
1045 pub fn get_tt(&self, index: usize) -> TokenTree {
1046 match (self, index) {
1047 (&TtToken(sp, token::DocComment(_)), 0) => {
1048 TtToken(sp, token::Pound)
1050 (&TtToken(sp, token::DocComment(name)), 1) => {
1051 TtDelimited(sp, Rc::new(Delimited {
1052 delim: token::Bracket,
1054 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1056 TtToken(sp, token::Eq),
1057 TtToken(sp, token::Literal(token::Str_(name), None))],
1061 (&TtDelimited(_, ref delimed), _) => {
1063 return delimed.open_tt();
1065 if index == delimed.tts.len() + 1 {
1066 return delimed.close_tt();
1068 delimed.tts[index - 1].clone()
1070 (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1071 let v = [TtToken(sp, token::Dollar),
1072 TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1076 (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1077 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1078 TtToken(sp, token::Colon),
1079 TtToken(sp, token::Ident(kind, kind_st))];
1082 (&TtSequence(_, ref seq), _) => {
1083 seq.tts[index].clone()
1085 _ => panic!("Cannot expand a token tree")
1089 /// Returns the `Span` corresponding to this token tree.
1090 pub fn get_span(&self) -> Span {
1092 TtToken(span, _) => span,
1093 TtDelimited(span, _) => span,
1094 TtSequence(span, _) => span,
1098 /// Use this token tree as a matcher to parse given tts.
1099 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1100 -> macro_parser::NamedParseResult {
1101 // `None` is because we're not interpolating
1102 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1105 tts.iter().cloned().collect(),
1107 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1111 pub type Mac = Spanned<Mac_>;
1113 /// Represents a macro invocation. The Path indicates which macro
1114 /// is being invoked, and the vector of token-trees contains the source
1115 /// of the macro invocation.
1117 /// There's only one flavor, now, so this could presumably be simplified.
1118 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1120 // NB: the additional ident for a macro_rules-style macro is actually
1121 // stored in the enclosing item. Oog.
1122 MacInvocTT(Path, Vec<TokenTree>, SyntaxContext), // new macro-invocation
1125 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1127 /// A regular string, like `"foo"`
1129 /// A raw string, like `r##"foo"##`
1131 /// The uint is the number of `#` symbols used
1136 pub type Lit = Spanned<Lit_>;
1138 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1145 #[allow(deprecated)] // Int
1146 pub fn new<T:Int>(n: T) -> Sign {
1147 if n < Int::zero() {
1155 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1156 pub enum LitIntType {
1157 SignedIntLit(IntTy, Sign),
1158 UnsignedIntLit(UintTy),
1159 UnsuffixedIntLit(Sign)
1163 pub fn suffix_len(&self) -> usize {
1165 UnsuffixedIntLit(_) => 0,
1166 SignedIntLit(s, _) => s.suffix_len(),
1167 UnsignedIntLit(u) => u.suffix_len()
1172 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1174 /// A string literal (`"foo"`)
1175 LitStr(InternedString, StrStyle),
1176 /// A byte string (`b"foo"`)
1177 LitBinary(Rc<Vec<u8>>),
1178 /// A byte char (`b'f'`)
1180 /// A character literal (`'a'`)
1182 /// An integer literal (`1u8`)
1183 LitInt(u64, LitIntType),
1184 /// A float literal (`1f64` or `1E10f64`)
1185 LitFloat(InternedString, FloatTy),
1186 /// A float literal without a suffix (`1.0 or 1.0E10`)
1187 LitFloatUnsuffixed(InternedString),
1188 /// A boolean literal
1192 // NB: If you change this, you'll probably want to change the corresponding
1193 // type structure in middle/ty.rs as well.
1194 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1197 pub mutbl: Mutability,
1200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1201 pub struct TypeField {
1207 /// Represents a method's signature in a trait declaration,
1208 /// or in an implementation.
1209 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1210 pub struct MethodSig {
1211 pub unsafety: Unsafety,
1213 pub decl: P<FnDecl>,
1214 pub generics: Generics,
1215 pub explicit_self: ExplicitSelf,
1218 /// Represents a method declaration in a trait declaration, possibly including
1219 /// a default implementation A trait method is either required (meaning it
1220 /// doesn't have an implementation, just a signature) or provided (meaning it
1221 /// has a default implementation).
1222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1223 pub struct TraitItem {
1226 pub attrs: Vec<Attribute>,
1227 pub node: TraitItem_,
1231 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1232 pub enum TraitItem_ {
1233 MethodTraitItem(MethodSig, Option<P<Block>>),
1234 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1237 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1238 pub struct ImplItem {
1241 pub vis: Visibility,
1242 pub attrs: Vec<Attribute>,
1243 pub node: ImplItem_,
1247 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1248 pub enum ImplItem_ {
1249 MethodImplItem(MethodSig, P<Block>),
1250 TypeImplItem(P<Ty>),
1254 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1263 impl fmt::Debug for IntTy {
1264 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1265 fmt::Display::fmt(self, f)
1269 impl fmt::Display for IntTy {
1270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1271 write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1276 pub fn suffix_len(&self) -> usize {
1279 TyI16 | TyI32 | TyI64 => 3,
1284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1294 pub fn suffix_len(&self) -> usize {
1297 TyU16 | TyU32 | TyU64 => 3,
1302 impl fmt::Debug for UintTy {
1303 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1304 fmt::Display::fmt(self, f)
1308 impl fmt::Display for UintTy {
1309 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1310 write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1314 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1320 impl fmt::Debug for FloatTy {
1321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1322 fmt::Display::fmt(self, f)
1326 impl fmt::Display for FloatTy {
1327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1328 write!(f, "{}", ast_util::float_ty_to_string(*self))
1333 pub fn suffix_len(&self) -> usize {
1335 TyF32 | TyF64 => 3, // add F128 handling here
1340 // Bind a type to an associated type: `A=Foo`.
1341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1342 pub struct TypeBinding {
1350 // NB PartialEq method appears below.
1351 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1358 /// Not represented directly in the AST, referred to by name through a ty_path.
1359 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1370 pub struct BareFnTy {
1371 pub unsafety: Unsafety,
1373 pub lifetimes: Vec<LifetimeDef>,
1377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1378 /// The different kinds of types recognized by the compiler
1381 /// A fixed length array (`[T; n]`)
1382 TyFixedLengthVec(P<Ty>, P<Expr>),
1383 /// A raw pointer (`*const T` or `*mut T`)
1385 /// A reference (`&'a T` or `&'a mut T`)
1386 TyRptr(Option<Lifetime>, MutTy),
1387 /// A bare function (e.g. `fn(usize) -> bool`)
1388 TyBareFn(P<BareFnTy>),
1389 /// A tuple (`(A, B, C, D,...)`)
1391 /// A path (`module::module::...::Type`), optionally
1392 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1394 /// Type parameters are stored in the Path itself
1395 TyPath(Option<QSelf>, Path),
1396 /// Something like `A+B`. Note that `B` must always be a path.
1397 TyObjectSum(P<Ty>, TyParamBounds),
1398 /// A type like `for<'a> Foo<&'a Bar>`
1399 TyPolyTraitRef(TyParamBounds),
1400 /// No-op; kept solely so that we can pretty-print faithfully
1404 /// TyInfer means the type should be inferred instead of it having been
1405 /// specified. This can appear anywhere in a type.
1409 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1410 pub enum AsmDialect {
1415 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1416 pub struct InlineAsm {
1417 pub asm: InternedString,
1418 pub asm_str_style: StrStyle,
1419 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1420 pub inputs: Vec<(InternedString, P<Expr>)>,
1421 pub clobbers: Vec<InternedString>,
1423 pub alignstack: bool,
1424 pub dialect: AsmDialect,
1425 pub expn_id: ExpnId,
1428 /// represents an argument in a function header
1429 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1437 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1438 let path = Spanned{span:span,node:self_ident};
1440 // HACK(eddyb) fake type for the self argument.
1448 node: PatIdent(BindByValue(mutability), path, None),
1456 /// Represents the header (not the body) of a function declaration
1457 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1459 pub inputs: Vec<Arg>,
1460 pub output: FunctionRetTy,
1464 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1470 impl fmt::Display for Unsafety {
1471 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1472 fmt::Display::fmt(match *self {
1473 Unsafety::Normal => "normal",
1474 Unsafety::Unsafe => "unsafe",
1479 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1480 pub enum ImplPolarity {
1481 /// `impl Trait for Type`
1483 /// `impl !Trait for Type`
1487 impl fmt::Debug for ImplPolarity {
1488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1490 ImplPolarity::Positive => "positive".fmt(f),
1491 ImplPolarity::Negative => "negative".fmt(f),
1497 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1498 pub enum FunctionRetTy {
1499 /// Functions with return type `!`that always
1500 /// raise an error or exit (i.e. never return to the caller)
1502 /// Return type is not specified.
1504 /// Functions default to `()` and
1505 /// closures default to inference. Span points to where return
1506 /// type would be inserted.
1507 DefaultReturn(Span),
1512 impl FunctionRetTy {
1513 pub fn span(&self) -> Span {
1515 NoReturn(span) => span,
1516 DefaultReturn(span) => span,
1517 Return(ref ty) => ty.span
1522 /// Represents the kind of 'self' associated with a method
1523 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1524 pub enum ExplicitSelf_ {
1529 /// `&'lt self`, `&'lt mut self`
1530 SelfRegion(Option<Lifetime>, Mutability, Ident),
1532 SelfExplicit(P<Ty>, Ident),
1535 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1537 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1539 /// A span from the first token past `{` to the last token until `}`.
1540 /// For `mod foo;`, the inner span ranges from the first token
1541 /// to the last token in the external file.
1543 pub items: Vec<P<Item>>,
1546 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1547 pub struct ForeignMod {
1549 pub items: Vec<P<ForeignItem>>,
1552 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1553 pub struct VariantArg {
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1559 pub enum VariantKind {
1560 /// Tuple variant, e.g. `Foo(A, B)`
1561 TupleVariantKind(Vec<VariantArg>),
1562 /// Struct variant, e.g. `Foo {x: A, y: B}`
1563 StructVariantKind(P<StructDef>),
1566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1567 pub struct EnumDef {
1568 pub variants: Vec<P<Variant>>,
1571 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1572 pub struct Variant_ {
1574 pub attrs: Vec<Attribute>,
1575 pub kind: VariantKind,
1577 /// Explicit discriminant, eg `Foo = 1`
1578 pub disr_expr: Option<P<Expr>>,
1579 pub vis: Visibility,
1582 pub type Variant = Spanned<Variant_>;
1584 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1585 pub enum PathListItem_ {
1586 PathListIdent { name: Ident, id: NodeId },
1587 PathListMod { id: NodeId }
1590 impl PathListItem_ {
1591 pub fn id(&self) -> NodeId {
1593 PathListIdent { id, .. } | PathListMod { id } => id
1598 pub type PathListItem = Spanned<PathListItem_>;
1600 pub type ViewPath = Spanned<ViewPath_>;
1602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1603 pub enum ViewPath_ {
1605 /// `foo::bar::baz as quux`
1609 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1610 ViewPathSimple(Ident, Path),
1615 /// `foo::bar::{a,b,c}`
1616 ViewPathList(Path, Vec<PathListItem>)
1619 /// Meta-data associated with an item
1620 pub type Attribute = Spanned<Attribute_>;
1622 /// Distinguishes between Attributes that decorate items and Attributes that
1623 /// are contained as statements within items. These two cases need to be
1624 /// distinguished for pretty-printing.
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1626 pub enum AttrStyle {
1631 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1632 pub struct AttrId(pub usize);
1634 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1636 pub struct Attribute_ {
1638 pub style: AttrStyle,
1639 pub value: P<MetaItem>,
1640 pub is_sugared_doc: bool,
1643 /// TraitRef's appear in impls.
1645 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1646 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1647 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1648 /// same as the impl's node id).
1649 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1650 pub struct TraitRef {
1655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1656 pub struct PolyTraitRef {
1657 /// The `'a` in `<'a> Foo<&'a T>`
1658 pub bound_lifetimes: Vec<LifetimeDef>,
1660 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1661 pub trait_ref: TraitRef,
1666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1667 pub enum Visibility {
1673 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1675 &Inherited => parent_visibility,
1681 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1682 pub struct StructField_ {
1683 pub kind: StructFieldKind,
1686 pub attrs: Vec<Attribute>,
1690 pub fn ident(&self) -> Option<Ident> {
1692 NamedField(ref ident, _) => Some(ident.clone()),
1693 UnnamedField(_) => None
1698 pub type StructField = Spanned<StructField_>;
1700 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1701 pub enum StructFieldKind {
1702 NamedField(Ident, Visibility),
1703 /// Element of a tuple-like struct
1704 UnnamedField(Visibility),
1707 impl StructFieldKind {
1708 pub fn is_unnamed(&self) -> bool {
1710 UnnamedField(..) => true,
1711 NamedField(..) => false,
1716 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1717 pub struct StructDef {
1718 /// Fields, not including ctor
1719 pub fields: Vec<StructField>,
1720 /// ID of the constructor. This is only used for tuple- or enum-like
1722 pub ctor_id: Option<NodeId>,
1726 FIXME (#3300): Should allow items to be anonymous. Right now
1727 we just use dummy names for anon items.
1731 /// The name might be a dummy name in case of anonymous items
1732 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1735 pub attrs: Vec<Attribute>,
1738 pub vis: Visibility,
1742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1744 /// An`extern crate` item, with optional original crate name,
1746 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1747 ItemExternCrate(Option<Name>),
1748 /// A `use` or `pub use` item
1749 ItemUse(P<ViewPath>),
1752 ItemStatic(P<Ty>, Mutability, P<Expr>),
1754 ItemConst(P<Ty>, P<Expr>),
1755 /// A function declaration
1756 ItemFn(P<FnDecl>, Unsafety, Abi, Generics, P<Block>),
1759 /// An external module
1760 ItemForeignMod(ForeignMod),
1761 /// A type alias, e.g. `type Foo = Bar<u8>`
1762 ItemTy(P<Ty>, Generics),
1763 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1764 ItemEnum(EnumDef, Generics),
1765 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1766 ItemStruct(P<StructDef>, Generics),
1767 /// Represents a Trait Declaration
1773 // Default trait implementations
1775 // `impl Trait for .. {}`
1776 ItemDefaultImpl(Unsafety, TraitRef),
1777 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1781 Option<TraitRef>, // (optional) trait this impl implements
1784 /// A macro invocation (which includes macro definition)
1789 pub fn descriptive_variant(&self) -> &str {
1791 ItemExternCrate(..) => "extern crate",
1792 ItemUse(..) => "use",
1793 ItemStatic(..) => "static item",
1794 ItemConst(..) => "constant item",
1795 ItemFn(..) => "function",
1796 ItemMod(..) => "module",
1797 ItemForeignMod(..) => "foreign module",
1798 ItemTy(..) => "type alias",
1799 ItemEnum(..) => "enum",
1800 ItemStruct(..) => "struct",
1801 ItemTrait(..) => "trait",
1804 ItemDefaultImpl(..) => "item"
1809 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1810 pub struct ForeignItem {
1812 pub attrs: Vec<Attribute>,
1813 pub node: ForeignItem_,
1816 pub vis: Visibility,
1819 /// An item within an `extern` block
1820 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1821 pub enum ForeignItem_ {
1822 /// A foreign function
1823 ForeignItemFn(P<FnDecl>, Generics),
1824 /// A foreign static item (`static ext: u8`), with optional mutability
1825 /// (the boolean is true when mutable)
1826 ForeignItemStatic(P<Ty>, bool),
1830 pub fn descriptive_variant(&self) -> &str {
1832 ForeignItemFn(..) => "foreign function",
1833 ForeignItemStatic(..) => "foreign static item"
1838 /// The data we save and restore about an inlined item or method. This is not
1839 /// part of the AST that we parse from a file, but it becomes part of the tree
1841 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1842 pub enum InlinedItem {
1844 IITraitItem(DefId /* impl id */, P<TraitItem>),
1845 IIImplItem(DefId /* impl id */, P<ImplItem>),
1846 IIForeign(P<ForeignItem>),
1849 /// A macro definition, in this crate or imported from another.
1851 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1852 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1853 pub struct MacroDef {
1855 pub attrs: Vec<Attribute>,
1858 pub imported_from: Option<Ident>,
1860 pub use_locally: bool,
1861 pub allow_internal_unstable: bool,
1862 pub body: Vec<TokenTree>,
1870 // are ASTs encodable?
1872 fn check_asts_encodable() {
1873 fn assert_encodable<T: serialize::Encodable>() {}
1874 assert_encodable::<Crate>();