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};
71 use serialize::{Encodable, Decodable, Encoder, Decoder};
73 // FIXME #6993: in librustc, uses of "ident" should be replaced
76 /// An identifier contains a Name (index into the interner
77 /// table) and a SyntaxContext to track renaming and
78 /// macro expansion per Flatt et al., "Macros
79 /// That Work Together"
80 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
83 pub ctxt: SyntaxContext
87 /// Construct an identifier with the given name and an empty context:
88 pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
90 pub fn as_str<'a>(&'a self) -> &'a str {
94 pub fn encode_with_hygiene(&self) -> String {
95 format!("\x00name_{},ctxt_{}\x00",
101 impl fmt::Debug for Ident {
102 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
103 write!(f, "{}#{}", self.name, self.ctxt)
107 impl fmt::Display for Ident {
108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 fmt::Display::fmt(&self.name, f)
113 impl fmt::Debug for Name {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 let Name(nm) = *self;
116 write!(f, "{:?}({})", token::get_name(*self), nm)
120 impl fmt::Display for Name {
121 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
122 fmt::Display::fmt(&token::get_name(*self), f)
126 impl PartialEq for Ident {
127 fn eq(&self, other: &Ident) -> bool {
128 if self.ctxt == other.ctxt {
129 self.name == other.name
131 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
132 // idents that have different contexts. You can't fix this without
133 // knowing whether the comparison should be hygienic or non-hygienic.
134 // if it should be non-hygienic (most things are), just compare the
135 // 'name' fields of the idents. Or, even better, replace the idents
138 // On the other hand, if the comparison does need to be hygienic,
139 // one example and its non-hygienic counterpart would be:
140 // syntax::parse::token::Token::mtwt_eq
141 // syntax::ext::tt::macro_parser::token_name_eq
142 panic!("not allowed to compare these idents: {}, {}. \
143 Probably related to issue \\#6993", self, other);
146 fn ne(&self, other: &Ident) -> bool {
151 /// A SyntaxContext represents a chain of macro-expandings
152 /// and renamings. Each macro expansion corresponds to
155 // I'm representing this syntax context as an index into
156 // a table, in order to work around a compiler bug
157 // that's causing unreleased memory to cause core dumps
158 // and also perhaps to save some work in destructor checks.
159 // the special uint '0' will be used to indicate an empty
162 // this uint is a reference to a table stored in thread-local
164 pub type SyntaxContext = u32;
165 pub const EMPTY_CTXT : SyntaxContext = 0;
166 pub const ILLEGAL_CTXT : SyntaxContext = 1;
168 /// A name is a part of an identifier, representing a string or gensym. It's
169 /// the result of interning.
170 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
171 RustcEncodable, RustcDecodable, Clone, Copy)]
172 pub struct Name(pub u32);
175 pub fn as_str<'a>(&'a self) -> &'a str {
177 // FIXME #12938: can't use copy_lifetime since &str isn't a &T
178 ::std::mem::transmute::<&str,&str>(&token::get_name(*self))
182 pub fn usize(&self) -> usize {
183 let Name(nm) = *self;
187 pub fn ident(&self) -> Ident {
188 Ident { name: *self, ctxt: 0 }
192 /// A mark represents a unique id associated with a macro expansion
195 impl Encodable for Ident {
196 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
197 s.emit_str(&token::get_ident(*self))
201 impl Decodable for Ident {
202 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
203 Ok(str_to_ident(&try!(d.read_str())[..]))
207 /// Function name (not all functions have names)
208 pub type FnIdent = Option<Ident>;
210 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,
212 pub struct Lifetime {
218 /// A lifetime definition, eg `'a: 'b+'c+'d`
219 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
220 pub struct LifetimeDef {
221 pub lifetime: Lifetime,
222 pub bounds: Vec<Lifetime>
225 /// A "Path" is essentially Rust's notion of a name; for instance:
226 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
227 /// along with a bunch of supporting information.
228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
231 /// A `::foo` path, is relative to the crate root rather than current
232 /// module (like paths in an import).
234 /// The segments in the path: the things separated by `::`.
235 pub segments: Vec<PathSegment>,
238 /// A segment of a path: an identifier, an optional lifetime, and a set of
240 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
241 pub struct PathSegment {
242 /// The identifier portion of this path segment.
243 pub identifier: Ident,
245 /// Type/lifetime parameters attached to this path. They come in
246 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
247 /// this is more than just simple syntactic sugar; the use of
248 /// parens affects the region binding rules, so we preserve the
250 pub parameters: PathParameters,
253 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
254 pub enum PathParameters {
255 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
256 AngleBracketedParameters(AngleBracketedParameterData),
257 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
258 ParenthesizedParameters(ParenthesizedParameterData),
261 impl PathParameters {
262 pub fn none() -> PathParameters {
263 AngleBracketedParameters(AngleBracketedParameterData {
264 lifetimes: Vec::new(),
265 types: OwnedSlice::empty(),
266 bindings: OwnedSlice::empty(),
270 pub fn is_empty(&self) -> bool {
272 AngleBracketedParameters(ref data) => data.is_empty(),
274 // Even if the user supplied no types, something like
275 // `X()` is equivalent to `X<(),()>`.
276 ParenthesizedParameters(..) => false,
280 pub fn has_lifetimes(&self) -> bool {
282 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
283 ParenthesizedParameters(_) => false,
287 pub fn has_types(&self) -> bool {
289 AngleBracketedParameters(ref data) => !data.types.is_empty(),
290 ParenthesizedParameters(..) => true,
294 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
295 /// parameters in the parenthesized case.
296 pub fn types(&self) -> Vec<&P<Ty>> {
298 AngleBracketedParameters(ref data) => {
299 data.types.iter().collect()
301 ParenthesizedParameters(ref data) => {
303 .chain(data.output.iter())
309 pub fn lifetimes(&self) -> Vec<&Lifetime> {
311 AngleBracketedParameters(ref data) => {
312 data.lifetimes.iter().collect()
314 ParenthesizedParameters(_) => {
320 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
322 AngleBracketedParameters(ref data) => {
323 data.bindings.iter().collect()
325 ParenthesizedParameters(_) => {
332 /// A path like `Foo<'a, T>`
333 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
334 pub struct AngleBracketedParameterData {
335 /// The lifetime parameters for this path segment.
336 pub lifetimes: Vec<Lifetime>,
337 /// The type parameters for this path segment, if present.
338 pub types: OwnedSlice<P<Ty>>,
339 /// Bindings (equality constraints) on associated types, if present.
340 /// E.g., `Foo<A=Bar>`.
341 pub bindings: OwnedSlice<P<TypeBinding>>,
344 impl AngleBracketedParameterData {
345 fn is_empty(&self) -> bool {
346 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
350 /// A path like `Foo(A,B) -> C`
351 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
352 pub struct ParenthesizedParameterData {
357 pub inputs: Vec<P<Ty>>,
360 pub output: Option<P<Ty>>,
363 pub type CrateNum = u32;
365 pub type NodeId = u32;
367 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
368 RustcDecodable, Hash, Debug, Copy)]
375 /// Read the node id, asserting that this def-id is krate-local.
376 pub fn local_id(&self) -> NodeId {
377 assert_eq!(self.krate, LOCAL_CRATE);
382 /// Item definitions in the currently-compiled crate would have the CrateNum
383 /// LOCAL_CRATE in their DefId.
384 pub const LOCAL_CRATE: CrateNum = 0;
385 pub const CRATE_NODE_ID: NodeId = 0;
387 /// When parsing and doing expansions, we initially give all AST nodes this AST
388 /// node value. Then later, in the renumber pass, we renumber them to have
389 /// small, positive ids.
390 pub const DUMMY_NODE_ID: NodeId = -1;
392 /// The AST represents all type param bounds as types.
393 /// typeck::collect::compute_bounds matches these against
394 /// the "special" built-in traits (see middle::lang_items) and
395 /// detects Copy, Send and Sync.
396 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
397 pub enum TyParamBound {
398 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
399 RegionTyParamBound(Lifetime)
402 /// A modifier on a bound, currently this is only used for `?Sized`, where the
403 /// modifier is `Maybe`. Negative bounds should also be handled here.
404 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
405 pub enum TraitBoundModifier {
410 pub type TyParamBounds = OwnedSlice<TyParamBound>;
412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
416 pub bounds: TyParamBounds,
417 pub default: Option<P<Ty>>,
421 /// Represents lifetimes and type parameters attached to a declaration
422 /// of a function, enum, trait, etc.
423 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
424 pub struct Generics {
425 pub lifetimes: Vec<LifetimeDef>,
426 pub ty_params: OwnedSlice<TyParam>,
427 pub where_clause: WhereClause,
431 pub fn is_parameterized(&self) -> bool {
432 self.lifetimes.len() + self.ty_params.len() > 0
434 pub fn is_lt_parameterized(&self) -> bool {
435 self.lifetimes.len() > 0
437 pub fn is_type_parameterized(&self) -> bool {
438 self.ty_params.len() > 0
442 /// A `where` clause in a definition
443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
444 pub struct WhereClause {
446 pub predicates: Vec<WherePredicate>,
449 /// A single predicate in a `where` clause
450 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
451 pub enum WherePredicate {
452 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
453 BoundPredicate(WhereBoundPredicate),
454 /// A lifetime predicate, e.g. `'a: 'b+'c`
455 RegionPredicate(WhereRegionPredicate),
456 /// An equality predicate (unsupported)
457 EqPredicate(WhereEqPredicate)
460 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
461 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
462 pub struct WhereBoundPredicate {
464 /// Any lifetimes from a `for` binding
465 pub bound_lifetimes: Vec<LifetimeDef>,
466 /// The type being bounded
467 pub bounded_ty: P<Ty>,
468 /// Trait and lifetime bounds (`Clone+Send+'static`)
469 pub bounds: OwnedSlice<TyParamBound>,
472 /// A lifetime predicate, e.g. `'a: 'b+'c`
473 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
474 pub struct WhereRegionPredicate {
476 pub lifetime: Lifetime,
477 pub bounds: Vec<Lifetime>,
480 /// An equality predicate (unsupported), e.g. `T=int`
481 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
482 pub struct WhereEqPredicate {
489 /// The set of MetaItems that define the compilation environment of the crate,
490 /// used to drive conditional compilation
491 pub type CrateConfig = Vec<P<MetaItem>> ;
493 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
496 pub attrs: Vec<Attribute>,
497 pub config: CrateConfig,
499 pub exported_macros: Vec<MacroDef>,
502 pub type MetaItem = Spanned<MetaItem_>;
504 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
506 MetaWord(InternedString),
507 MetaList(InternedString, Vec<P<MetaItem>>),
508 MetaNameValue(InternedString, Lit),
511 // can't be derived because the MetaList requires an unordered comparison
512 impl PartialEq for MetaItem_ {
513 fn eq(&self, other: &MetaItem_) -> bool {
515 MetaWord(ref ns) => match *other {
516 MetaWord(ref no) => (*ns) == (*no),
519 MetaNameValue(ref ns, ref vs) => match *other {
520 MetaNameValue(ref no, ref vo) => {
521 (*ns) == (*no) && vs.node == vo.node
525 MetaList(ref ns, ref miss) => match *other {
526 MetaList(ref no, ref miso) => {
528 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
536 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
538 /// Statements in a block
539 pub stmts: Vec<P<Stmt>>,
540 /// An expression at the end of the block
541 /// without a semicolon, if any
542 pub expr: Option<P<Expr>>,
544 /// Distinguishes between `unsafe { ... }` and `{ ... }`
545 pub rules: BlockCheckMode,
549 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
556 /// A single field in a struct pattern
558 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
559 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
560 /// except is_shorthand is true
561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
562 pub struct FieldPat {
563 /// The identifier for the field
565 /// The pattern the field is destructured to
567 pub is_shorthand: bool,
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
571 pub enum BindingMode {
572 BindByRef(Mutability),
573 BindByValue(Mutability),
576 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
577 pub enum PatWildKind {
578 /// Represents the wildcard pattern `_`
581 /// Represents the wildcard pattern `..`
585 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
587 /// Represents a wildcard pattern (either `_` or `..`)
588 PatWild(PatWildKind),
590 /// A PatIdent may either be a new bound variable,
591 /// or a nullary enum (in which case the third field
594 /// In the nullary enum case, the parser can't determine
595 /// which it is. The resolver determines this, and
596 /// records this pattern's NodeId in an auxiliary
597 /// set (of "PatIdents that refer to nullary enums")
598 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
600 /// "None" means a * pattern where we don't bind the fields to names.
601 PatEnum(Path, Option<Vec<P<Pat>>>),
603 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
604 /// The `bool` is `true` in the presence of a `..`
605 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
606 /// A tuple pattern `(a, b)`
610 /// A reference pattern, e.g. `&mut (a, b)`
611 PatRegion(P<Pat>, Mutability),
614 /// A range pattern, e.g. `1...2`
615 PatRange(P<Expr>, P<Expr>),
616 /// [a, b, ..i, y, z] is represented as:
617 /// PatVec(box [a, b], Some(i), box [y, z])
618 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
619 /// A macro pattern; pre-expansion
623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
624 pub enum Mutability {
629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
631 /// The `+` operator (addition)
633 /// The `-` operator (subtraction)
635 /// The `*` operator (multiplication)
637 /// The `/` operator (division)
639 /// The `%` operator (modulus)
641 /// The `&&` operator (logical and)
643 /// The `||` operator (logical or)
645 /// The `^` operator (bitwise xor)
647 /// The `&` operator (bitwise and)
649 /// The `|` operator (bitwise or)
651 /// The `<<` operator (shift left)
653 /// The `>>` operator (shift right)
655 /// The `==` operator (equality)
657 /// The `<` operator (less than)
659 /// The `<=` operator (less than or equal to)
661 /// The `!=` operator (not equal to)
663 /// The `>=` operator (greater than or equal to)
665 /// The `>` operator (greater than)
669 pub type BinOp = Spanned<BinOp_>;
671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
673 /// The `box` operator
675 /// The `*` operator for dereferencing
677 /// The `!` operator for logical inversion
679 /// The `-` operator for negation
684 pub type Stmt = Spanned<Stmt_>;
686 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
688 /// Could be an item or a local (let) binding:
689 StmtDecl(P<Decl>, NodeId),
691 /// Expr without trailing semi-colon (must have unit type):
692 StmtExpr(P<Expr>, NodeId),
694 /// Expr with trailing semi-colon (may have any type):
695 StmtSemi(P<Expr>, NodeId),
697 StmtMac(P<Mac>, MacStmtStyle),
700 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
701 pub enum MacStmtStyle {
702 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
703 /// `foo!(...);`, `foo![...];`
704 MacStmtWithSemicolon,
705 /// The macro statement had braces; e.g. foo! { ... }
707 /// The macro statement had parentheses or brackets and no semicolon; e.g.
708 /// `foo!(...)`. All of these will end up being converted into macro
710 MacStmtWithoutBraces,
713 /// Where a local declaration came from: either a true `let ... =
714 /// ...;`, or one desugared from the pattern of a for loop.
715 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
716 pub enum LocalSource {
721 // FIXME (pending discussion of #1697, #2178...): local should really be
722 // a refinement on pat.
723 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
724 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
727 pub ty: Option<P<Ty>>,
728 /// Initializer expression to set the value, if any
729 pub init: Option<P<Expr>>,
732 pub source: LocalSource,
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),
769 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
770 pub enum UnsafeSource {
776 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
783 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
785 /// First expr is the place; second expr is the value.
786 ExprBox(Option<P<Expr>>, P<Expr>),
787 /// An array (`[a, b, c, d]`)
788 ExprVec(Vec<P<Expr>>),
791 /// The first field resolves to the function itself,
792 /// and the second field is the list of arguments
793 ExprCall(P<Expr>, Vec<P<Expr>>),
794 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
796 /// The `SpannedIdent` is the identifier for the method name.
797 /// The vector of `Ty`s are the ascripted type parameters for the method
798 /// (within the angle brackets).
800 /// The first element of the vector of `Expr`s is the expression that evaluates
801 /// to the object on which the method is being called on (the receiver),
802 /// and the remaining elements are the rest of the arguments.
804 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
805 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
806 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
807 /// A tuple (`(a, b, c ,d)`)
808 ExprTup(Vec<P<Expr>>),
809 /// A binary operation (For example: `a + b`, `a * b`)
810 ExprBinary(BinOp, P<Expr>, P<Expr>),
811 /// A unary operation (For example: `!x`, `*x`)
812 ExprUnary(UnOp, P<Expr>),
813 /// A literal (For example: `1u8`, `"foo"`)
815 /// A cast (`foo as f64`)
816 ExprCast(P<Expr>, P<Ty>),
817 /// An `if` block, with an optional else block
819 /// `if expr { block } else { expr }`
820 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
821 /// An `if let` expression with an optional else block
823 /// `if let pat = expr { block } else { expr }`
825 /// This is desugared to a `match` expression.
826 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
827 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
828 /// A while loop, with an optional label
830 /// `'label: while expr { block }`
831 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
832 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
833 /// A while-let loop, with an optional label
835 /// `'label: while let pat = expr { block }`
837 /// This is desugared to a combination of `loop` and `match` expressions.
838 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
839 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
840 /// A for loop, with an optional label
842 /// `'label: for pat in expr { block }`
844 /// This is desugared to a combination of `loop` and `match` expressions.
845 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
846 /// Conditionless loop (can be exited with break, continue, or return)
848 /// `'label: loop { block }`
849 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
850 ExprLoop(P<Block>, Option<Ident>),
851 /// A `match` block, with a source that indicates whether or not it is
852 /// the result of a desugaring, and if so, which kind.
853 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
854 /// A closure (for example, `move |a, b, c| {a + b + c}`)
855 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
856 /// A block (`{ ... }`)
859 /// An assignment (`a = foo()`)
860 ExprAssign(P<Expr>, P<Expr>),
861 /// An assignment with an operator
863 /// For example, `a += 1`.
864 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
865 /// Access of a named struct field (`obj.foo`)
866 ExprField(P<Expr>, SpannedIdent),
867 /// Access of an unnamed field of a struct or tuple-struct
869 /// For example, `foo.0`.
870 ExprTupField(P<Expr>, Spanned<usize>),
871 /// An indexing operation (`foo[2]`)
872 ExprIndex(P<Expr>, P<Expr>),
873 /// A range (`1..2`, `1..`, or `..2`)
874 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
876 /// Variable reference, possibly containing `::` and/or type
877 /// parameters, e.g. foo::bar::<baz>.
879 /// Optionally "qualified",
880 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
881 ExprPath(Option<QSelf>, Path),
883 /// A referencing operation (`&a` or `&mut a`)
884 ExprAddrOf(Mutability, P<Expr>),
885 /// A `break`, with an optional label to break
886 ExprBreak(Option<Ident>),
887 /// A `continue`, with an optional label
888 ExprAgain(Option<Ident>),
889 /// A `return`, with an optional value to be returned
890 ExprRet(Option<P<Expr>>),
892 /// Output of the `asm!()` macro
893 ExprInlineAsm(InlineAsm),
895 /// A macro invocation; pre-expansion
898 /// A struct literal expression.
900 /// For example, `Foo {x: 1, y: 2}`, or
901 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
902 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
904 /// A vector literal constructed from one repeated element.
906 /// For example, `[1u8; 5]`. The first expression is the element
907 /// to be repeated; the second is the number of times to repeat it.
908 ExprRepeat(P<Expr>, P<Expr>),
910 /// No-op: used solely so we can pretty-print faithfully
914 /// The explicit Self type in a "qualified path". The actual
915 /// path, including the trait and the associated item, is stored
916 /// separately. `position` represents the index of the associated
917 /// item qualified with this Self type.
919 /// <Vec<T> as a::b::Trait>::AssociatedItem
920 /// ^~~~~ ~~~~~~~~~~~~~~^
923 /// <Vec<T>>::AssociatedItem
926 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
932 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
933 pub enum MatchSource {
935 IfLetDesugar { contains_else_clause: bool },
940 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
941 pub enum CaptureClause {
946 /// A delimited sequence of token trees
947 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
948 pub struct Delimited {
949 /// The type of delimiter
950 pub delim: token::DelimToken,
951 /// The span covering the opening delimiter
953 /// The delimited sequence of token trees
954 pub tts: Vec<TokenTree>,
955 /// The span covering the closing delimiter
956 pub close_span: Span,
960 /// Returns the opening delimiter as a token.
961 pub fn open_token(&self) -> token::Token {
962 token::OpenDelim(self.delim)
965 /// Returns the closing delimiter as a token.
966 pub fn close_token(&self) -> token::Token {
967 token::CloseDelim(self.delim)
970 /// Returns the opening delimiter as a token tree.
971 pub fn open_tt(&self) -> TokenTree {
972 TtToken(self.open_span, self.open_token())
975 /// Returns the closing delimiter as a token tree.
976 pub fn close_tt(&self) -> TokenTree {
977 TtToken(self.close_span, self.close_token())
981 /// A sequence of token treesee
982 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
983 pub struct SequenceRepetition {
984 /// The sequence of token trees
985 pub tts: Vec<TokenTree>,
986 /// The optional separator
987 pub separator: Option<token::Token>,
988 /// Whether the sequence can be repeated zero (*), or one or more times (+)
990 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
991 pub num_captures: usize,
994 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
995 /// for token sequences.
996 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1002 /// When the main rust parser encounters a syntax-extension invocation, it
1003 /// parses the arguments to the invocation as a token-tree. This is a very
1004 /// loose structure, such that all sorts of different AST-fragments can
1005 /// be passed to syntax extensions using a uniform type.
1007 /// If the syntax extension is an MBE macro, it will attempt to match its
1008 /// LHS token tree against the provided token tree, and if it finds a
1009 /// match, will transcribe the RHS token tree, splicing in any captured
1010 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1012 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1013 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1014 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1015 pub enum TokenTree {
1017 TtToken(Span, token::Token),
1018 /// A delimited sequence of token trees
1019 TtDelimited(Span, Rc<Delimited>),
1021 // This only makes sense in MBE macros.
1023 /// A kleene-style repetition sequence with a span
1024 // FIXME(eddyb) #12938 Use DST.
1025 TtSequence(Span, Rc<SequenceRepetition>),
1029 pub fn len(&self) -> usize {
1031 TtToken(_, token::DocComment(_)) => 2,
1032 TtToken(_, token::SpecialVarNt(..)) => 2,
1033 TtToken(_, token::MatchNt(..)) => 3,
1034 TtDelimited(_, ref delimed) => {
1035 delimed.tts.len() + 2
1037 TtSequence(_, ref seq) => {
1044 pub fn get_tt(&self, index: usize) -> TokenTree {
1045 match (self, index) {
1046 (&TtToken(sp, token::DocComment(_)), 0) => {
1047 TtToken(sp, token::Pound)
1049 (&TtToken(sp, token::DocComment(name)), 1) => {
1050 TtDelimited(sp, Rc::new(Delimited {
1051 delim: token::Bracket,
1053 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1055 TtToken(sp, token::Eq),
1056 TtToken(sp, token::Literal(token::Str_(name), None))],
1060 (&TtDelimited(_, ref delimed), _) => {
1062 return delimed.open_tt();
1064 if index == delimed.tts.len() + 1 {
1065 return delimed.close_tt();
1067 delimed.tts[index - 1].clone()
1069 (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1070 let v = [TtToken(sp, token::Dollar),
1071 TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1075 (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1076 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1077 TtToken(sp, token::Colon),
1078 TtToken(sp, token::Ident(kind, kind_st))];
1081 (&TtSequence(_, ref seq), _) => {
1082 seq.tts[index].clone()
1084 _ => panic!("Cannot expand a token tree")
1088 /// Returns the `Span` corresponding to this token tree.
1089 pub fn get_span(&self) -> Span {
1091 TtToken(span, _) => span,
1092 TtDelimited(span, _) => span,
1093 TtSequence(span, _) => span,
1097 /// Use this token tree as a matcher to parse given tts.
1098 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1099 -> macro_parser::NamedParseResult {
1100 // `None` is because we're not interpolating
1101 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1104 tts.iter().cloned().collect(),
1106 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1110 pub type Mac = Spanned<Mac_>;
1112 /// Represents a macro invocation. The Path indicates which macro
1113 /// is being invoked, and the vector of token-trees contains the source
1114 /// of the macro invocation.
1116 /// There's only one flavor, now, so this could presumably be simplified.
1117 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1119 // NB: the additional ident for a macro_rules-style macro is actually
1120 // stored in the enclosing item. Oog.
1121 MacInvocTT(Path, Vec<TokenTree>, SyntaxContext), // new macro-invocation
1124 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1126 /// A regular string, like `"foo"`
1128 /// A raw string, like `r##"foo"##`
1130 /// The uint is the number of `#` symbols used
1135 pub type Lit = Spanned<Lit_>;
1137 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1144 pub fn new<T:Int>(n: T) -> Sign {
1145 if n < Int::zero() {
1153 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1154 pub enum LitIntType {
1155 SignedIntLit(IntTy, Sign),
1156 UnsignedIntLit(UintTy),
1157 UnsuffixedIntLit(Sign)
1161 pub fn suffix_len(&self) -> usize {
1163 UnsuffixedIntLit(_) => 0,
1164 SignedIntLit(s, _) => s.suffix_len(),
1165 UnsignedIntLit(u) => u.suffix_len()
1170 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1172 /// A string literal (`"foo"`)
1173 LitStr(InternedString, StrStyle),
1174 /// A byte string (`b"foo"`)
1175 LitBinary(Rc<Vec<u8>>),
1176 /// A byte char (`b'f'`)
1178 /// A character literal (`'a'`)
1180 /// An integer literal (`1u8`)
1181 LitInt(u64, LitIntType),
1182 /// A float literal (`1f64` or `1E10f64`)
1183 LitFloat(InternedString, FloatTy),
1184 /// A float literal without a suffix (`1.0 or 1.0E10`)
1185 LitFloatUnsuffixed(InternedString),
1186 /// A boolean literal
1190 // NB: If you change this, you'll probably want to change the corresponding
1191 // type structure in middle/ty.rs as well.
1192 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1195 pub mutbl: Mutability,
1198 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1199 pub struct TypeField {
1205 /// Represents a method's signature in a trait declaration,
1206 /// or in an implementation.
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1208 pub struct MethodSig {
1209 pub unsafety: Unsafety,
1211 pub decl: P<FnDecl>,
1212 pub generics: Generics,
1213 pub explicit_self: ExplicitSelf,
1216 /// Represents a method declaration in a trait declaration, possibly including
1217 /// a default implementation A trait method is either required (meaning it
1218 /// doesn't have an implementation, just a signature) or provided (meaning it
1219 /// has a default implementation).
1220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1221 pub struct TraitItem {
1224 pub attrs: Vec<Attribute>,
1225 pub node: TraitItem_,
1229 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1230 pub enum TraitItem_ {
1231 MethodTraitItem(MethodSig, Option<P<Block>>),
1232 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1235 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1236 pub struct ImplItem {
1239 pub vis: Visibility,
1240 pub attrs: Vec<Attribute>,
1241 pub node: ImplItem_,
1245 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1246 pub enum ImplItem_ {
1247 MethodImplItem(MethodSig, P<Block>),
1248 TypeImplItem(P<Ty>),
1252 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1254 TyIs(bool /* is this deprecated `int`? */),
1261 impl PartialEq for IntTy {
1262 fn eq(&self, other: &IntTy) -> bool {
1263 match (*self, *other) {
1264 // true/false need to compare the same, so this can't be derived
1265 (TyIs(_), TyIs(_)) |
1269 (TyI64, TyI64) => true,
1275 impl fmt::Debug for IntTy {
1276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1277 fmt::Display::fmt(self, f)
1281 impl fmt::Display for IntTy {
1282 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1283 write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1288 pub fn suffix_len(&self) -> usize {
1290 TyIs(true) /* i */ => 1,
1291 TyIs(false) /* is */ | TyI8 => 2,
1292 TyI16 | TyI32 | TyI64 => 3,
1297 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1299 TyUs(bool /* is this deprecated uint? */),
1306 impl PartialEq for UintTy {
1307 fn eq(&self, other: &UintTy) -> bool {
1308 match (*self, *other) {
1309 // true/false need to compare the same, so this can't be derived
1310 (TyUs(_), TyUs(_)) |
1314 (TyU64, TyU64) => true,
1321 pub fn suffix_len(&self) -> usize {
1323 TyUs(true) /* u */ => 1,
1324 TyUs(false) /* us */ | TyU8 => 2,
1325 TyU16 | TyU32 | TyU64 => 3,
1330 impl fmt::Debug for UintTy {
1331 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1332 fmt::Display::fmt(self, f)
1336 impl fmt::Display for UintTy {
1337 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1338 write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1342 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1348 impl fmt::Debug for FloatTy {
1349 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1350 fmt::Display::fmt(self, f)
1354 impl fmt::Display for FloatTy {
1355 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1356 write!(f, "{}", ast_util::float_ty_to_string(*self))
1361 pub fn suffix_len(&self) -> usize {
1363 TyF32 | TyF64 => 3, // add F128 handling here
1368 // Bind a type to an associated type: `A=Foo`.
1369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1370 pub struct TypeBinding {
1378 // NB PartialEq method appears below.
1379 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1386 /// Not represented directly in the AST, referred to by name through a ty_path.
1387 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1397 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1398 pub struct BareFnTy {
1399 pub unsafety: Unsafety,
1401 pub lifetimes: Vec<LifetimeDef>,
1405 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1406 /// The different kinds of types recognized by the compiler
1409 /// A fixed length array (`[T; n]`)
1410 TyFixedLengthVec(P<Ty>, P<Expr>),
1411 /// A raw pointer (`*const T` or `*mut T`)
1413 /// A reference (`&'a T` or `&'a mut T`)
1414 TyRptr(Option<Lifetime>, MutTy),
1415 /// A bare function (e.g. `fn(usize) -> bool`)
1416 TyBareFn(P<BareFnTy>),
1417 /// A tuple (`(A, B, C, D,...)`)
1419 /// A path (`module::module::...::Type`), optionally
1420 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1422 /// Type parameters are stored in the Path itself
1423 TyPath(Option<QSelf>, Path),
1424 /// Something like `A+B`. Note that `B` must always be a path.
1425 TyObjectSum(P<Ty>, TyParamBounds),
1426 /// A type like `for<'a> Foo<&'a Bar>`
1427 TyPolyTraitRef(TyParamBounds),
1428 /// No-op; kept solely so that we can pretty-print faithfully
1432 /// TyInfer means the type should be inferred instead of it having been
1433 /// specified. This can appear anywhere in a type.
1437 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1438 pub enum AsmDialect {
1443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1444 pub struct InlineAsm {
1445 pub asm: InternedString,
1446 pub asm_str_style: StrStyle,
1447 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1448 pub inputs: Vec<(InternedString, P<Expr>)>,
1449 pub clobbers: Vec<InternedString>,
1451 pub alignstack: bool,
1452 pub dialect: AsmDialect,
1453 pub expn_id: ExpnId,
1456 /// represents an argument in a function header
1457 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1465 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1466 let path = Spanned{span:span,node:self_ident};
1468 // HACK(eddyb) fake type for the self argument.
1476 node: PatIdent(BindByValue(mutability), path, None),
1484 /// Represents the header (not the body) of a function declaration
1485 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1487 pub inputs: Vec<Arg>,
1488 pub output: FunctionRetTy,
1492 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1498 impl fmt::Display for Unsafety {
1499 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1500 fmt::Display::fmt(match *self {
1501 Unsafety::Normal => "normal",
1502 Unsafety::Unsafe => "unsafe",
1507 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1508 pub enum ImplPolarity {
1509 /// `impl Trait for Type`
1511 /// `impl !Trait for Type`
1515 impl fmt::Debug for ImplPolarity {
1516 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1518 ImplPolarity::Positive => "positive".fmt(f),
1519 ImplPolarity::Negative => "negative".fmt(f),
1525 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1526 pub enum FunctionRetTy {
1527 /// Functions with return type `!`that always
1528 /// raise an error or exit (i.e. never return to the caller)
1530 /// Return type is not specified.
1532 /// Functions default to `()` and
1533 /// closures default to inference. Span points to where return
1534 /// type would be inserted.
1535 DefaultReturn(Span),
1540 impl FunctionRetTy {
1541 pub fn span(&self) -> Span {
1543 NoReturn(span) => span,
1544 DefaultReturn(span) => span,
1545 Return(ref ty) => ty.span
1550 /// Represents the kind of 'self' associated with a method
1551 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1552 pub enum ExplicitSelf_ {
1557 /// `&'lt self`, `&'lt mut self`
1558 SelfRegion(Option<Lifetime>, Mutability, Ident),
1560 SelfExplicit(P<Ty>, Ident),
1563 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1565 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1567 /// A span from the first token past `{` to the last token until `}`.
1568 /// For `mod foo;`, the inner span ranges from the first token
1569 /// to the last token in the external file.
1571 pub items: Vec<P<Item>>,
1574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1575 pub struct ForeignMod {
1577 pub items: Vec<P<ForeignItem>>,
1580 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1581 pub struct VariantArg {
1586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1587 pub enum VariantKind {
1588 /// Tuple variant, e.g. `Foo(A, B)`
1589 TupleVariantKind(Vec<VariantArg>),
1590 /// Struct variant, e.g. `Foo {x: A, y: B}`
1591 StructVariantKind(P<StructDef>),
1594 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1595 pub struct EnumDef {
1596 pub variants: Vec<P<Variant>>,
1599 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1600 pub struct Variant_ {
1602 pub attrs: Vec<Attribute>,
1603 pub kind: VariantKind,
1605 /// Explicit discriminant, eg `Foo = 1`
1606 pub disr_expr: Option<P<Expr>>,
1607 pub vis: Visibility,
1610 pub type Variant = Spanned<Variant_>;
1612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1613 pub enum PathListItem_ {
1614 PathListIdent { name: Ident, id: NodeId },
1615 PathListMod { id: NodeId }
1618 impl PathListItem_ {
1619 pub fn id(&self) -> NodeId {
1621 PathListIdent { id, .. } | PathListMod { id } => id
1626 pub type PathListItem = Spanned<PathListItem_>;
1628 pub type ViewPath = Spanned<ViewPath_>;
1630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1631 pub enum ViewPath_ {
1633 /// `foo::bar::baz as quux`
1637 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1638 ViewPathSimple(Ident, Path),
1643 /// `foo::bar::{a,b,c}`
1644 ViewPathList(Path, Vec<PathListItem>)
1647 /// Meta-data associated with an item
1648 pub type Attribute = Spanned<Attribute_>;
1650 /// Distinguishes between Attributes that decorate items and Attributes that
1651 /// are contained as statements within items. These two cases need to be
1652 /// distinguished for pretty-printing.
1653 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1654 pub enum AttrStyle {
1659 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1660 pub struct AttrId(pub usize);
1662 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1663 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1664 pub struct Attribute_ {
1666 pub style: AttrStyle,
1667 pub value: P<MetaItem>,
1668 pub is_sugared_doc: bool,
1671 /// TraitRef's appear in impls.
1673 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1674 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1675 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1676 /// same as the impl's node id).
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 pub struct TraitRef {
1683 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1684 pub struct PolyTraitRef {
1685 /// The `'a` in `<'a> Foo<&'a T>`
1686 pub bound_lifetimes: Vec<LifetimeDef>,
1688 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1689 pub trait_ref: TraitRef,
1694 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1695 pub enum Visibility {
1701 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1703 &Inherited => parent_visibility,
1709 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1710 pub struct StructField_ {
1711 pub kind: StructFieldKind,
1714 pub attrs: Vec<Attribute>,
1718 pub fn ident(&self) -> Option<Ident> {
1720 NamedField(ref ident, _) => Some(ident.clone()),
1721 UnnamedField(_) => None
1726 pub type StructField = Spanned<StructField_>;
1728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1729 pub enum StructFieldKind {
1730 NamedField(Ident, Visibility),
1731 /// Element of a tuple-like struct
1732 UnnamedField(Visibility),
1735 impl StructFieldKind {
1736 pub fn is_unnamed(&self) -> bool {
1738 UnnamedField(..) => true,
1739 NamedField(..) => false,
1744 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1745 pub struct StructDef {
1746 /// Fields, not including ctor
1747 pub fields: Vec<StructField>,
1748 /// ID of the constructor. This is only used for tuple- or enum-like
1750 pub ctor_id: Option<NodeId>,
1754 FIXME (#3300): Should allow items to be anonymous. Right now
1755 we just use dummy names for anon items.
1759 /// The name might be a dummy name in case of anonymous items
1760 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1763 pub attrs: Vec<Attribute>,
1766 pub vis: Visibility,
1770 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1772 /// An`extern crate` item, with optional original crate name,
1774 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1775 ItemExternCrate(Option<Name>),
1776 /// A `use` or `pub use` item
1777 ItemUse(P<ViewPath>),
1780 ItemStatic(P<Ty>, Mutability, P<Expr>),
1782 ItemConst(P<Ty>, P<Expr>),
1783 /// A function declaration
1784 ItemFn(P<FnDecl>, Unsafety, Abi, Generics, P<Block>),
1787 /// An external module
1788 ItemForeignMod(ForeignMod),
1789 /// A type alias, e.g. `type Foo = Bar<u8>`
1790 ItemTy(P<Ty>, Generics),
1791 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1792 ItemEnum(EnumDef, Generics),
1793 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1794 ItemStruct(P<StructDef>, Generics),
1795 /// Represents a Trait Declaration
1801 // Default trait implementations
1803 // `impl Trait for .. {}`
1804 ItemDefaultImpl(Unsafety, TraitRef),
1805 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1809 Option<TraitRef>, // (optional) trait this impl implements
1812 /// A macro invocation (which includes macro definition)
1817 pub fn descriptive_variant(&self) -> &str {
1819 ItemExternCrate(..) => "extern crate",
1820 ItemUse(..) => "use",
1821 ItemStatic(..) => "static item",
1822 ItemConst(..) => "constant item",
1823 ItemFn(..) => "function",
1824 ItemMod(..) => "module",
1825 ItemForeignMod(..) => "foreign module",
1826 ItemTy(..) => "type alias",
1827 ItemEnum(..) => "enum",
1828 ItemStruct(..) => "struct",
1829 ItemTrait(..) => "trait",
1832 ItemDefaultImpl(..) => "item"
1837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1838 pub struct ForeignItem {
1840 pub attrs: Vec<Attribute>,
1841 pub node: ForeignItem_,
1844 pub vis: Visibility,
1847 /// An item within an `extern` block
1848 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1849 pub enum ForeignItem_ {
1850 /// A foreign function
1851 ForeignItemFn(P<FnDecl>, Generics),
1852 /// A foreign static item (`static ext: u8`), with optional mutability
1853 /// (the boolean is true when mutable)
1854 ForeignItemStatic(P<Ty>, bool),
1858 pub fn descriptive_variant(&self) -> &str {
1860 ForeignItemFn(..) => "foreign function",
1861 ForeignItemStatic(..) => "foreign static item"
1866 /// The data we save and restore about an inlined item or method. This is not
1867 /// part of the AST that we parse from a file, but it becomes part of the tree
1869 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1870 pub enum InlinedItem {
1872 IITraitItem(DefId /* impl id */, P<TraitItem>),
1873 IIImplItem(DefId /* impl id */, P<ImplItem>),
1874 IIForeign(P<ForeignItem>),
1877 /// A macro definition, in this crate or imported from another.
1879 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1880 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1881 pub struct MacroDef {
1883 pub attrs: Vec<Attribute>,
1886 pub imported_from: Option<Ident>,
1888 pub use_locally: bool,
1889 pub allow_internal_unstable: bool,
1890 pub body: Vec<TokenTree>,
1898 // are ASTs encodable?
1900 fn check_asts_encodable() {
1901 fn assert_encodable<T: serialize::Encodable>() {}
1902 assert_encodable::<Crate>();