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::BindingMode::*;
14 pub use self::BinOp_::*;
15 pub use self::BlockCheckMode::*;
16 pub use self::CaptureClause::*;
17 pub use self::Decl_::*;
18 pub use self::ExplicitSelf_::*;
19 pub use self::Expr_::*;
20 pub use self::FloatTy::*;
21 pub use self::FunctionRetTy::*;
22 pub use self::ForeignItem_::*;
23 pub use self::ImplItem_::*;
24 pub use self::IntTy::*;
25 pub use self::Item_::*;
26 pub use self::KleeneOp::*;
27 pub use self::Lit_::*;
28 pub use self::LitIntType::*;
29 pub use self::MacStmtStyle::*;
30 pub use self::MetaItem_::*;
31 pub use self::Mutability::*;
32 pub use self::Pat_::*;
33 pub use self::PathListItem_::*;
34 pub use self::PrimTy::*;
35 pub use self::Sign::*;
36 pub use self::Stmt_::*;
37 pub use self::StrStyle::*;
38 pub use self::StructFieldKind::*;
39 pub use self::TraitItem_::*;
41 pub use self::TyParamBound::*;
42 pub use self::UintTy::*;
43 pub use self::UnOp::*;
44 pub use self::UnsafeSource::*;
45 pub use self::ViewPath_::*;
46 pub use self::Visibility::*;
47 pub use self::PathParameters::*;
49 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
53 use ext::tt::macro_parser;
54 use owned_slice::OwnedSlice;
55 use parse::token::{InternedString, str_to_ident};
58 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
65 use std::hash::{Hash, Hasher};
66 use serialize::{Encodable, Decodable, Encoder, Decoder};
68 /// A name is a part of an identifier, representing a string or gensym. It's
69 /// the result of interning.
70 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
71 pub struct Name(pub u32);
73 /// A SyntaxContext represents a chain of macro-expandings
74 /// and renamings. Each macro expansion corresponds to
75 /// a fresh u32. This u32 is a reference to a table stored
76 // in thread-local storage.
77 // The special value EMPTY_CTXT is used to indicate an empty
79 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
80 pub struct SyntaxContext(pub u32);
82 /// An identifier contains a Name (index into the interner
83 /// table) and a SyntaxContext to track renaming and
84 /// macro expansion per Flatt et al., "Macros That Work Together"
85 #[derive(Clone, Copy, Eq)]
88 pub ctxt: SyntaxContext
92 pub fn as_str(self) -> token::InternedString {
93 token::InternedString::new_from_name(self)
97 impl fmt::Debug for Name {
98 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99 write!(f, "{}({})", self, self.0)
103 impl fmt::Display for Name {
104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105 fmt::Display::fmt(&self.as_str(), f)
109 impl Encodable for Name {
110 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
111 s.emit_str(&self.as_str())
115 impl Decodable for Name {
116 fn decode<D: Decoder>(d: &mut D) -> Result<Name, D::Error> {
117 Ok(token::intern(&try!(d.read_str())[..]))
121 pub const EMPTY_CTXT : SyntaxContext = SyntaxContext(0);
124 pub fn new(name: Name, ctxt: SyntaxContext) -> Ident {
125 Ident {name: name, ctxt: ctxt}
127 pub fn with_empty_ctxt(name: Name) -> Ident {
128 Ident {name: name, ctxt: EMPTY_CTXT}
132 impl PartialEq for Ident {
133 fn eq(&self, other: &Ident) -> bool {
134 if self.ctxt != other.ctxt {
135 // There's no one true way to compare Idents. They can be compared
136 // non-hygienically `id1.name == id2.name`, hygienically
137 // `mtwt::resolve(id1) == mtwt::resolve(id2)`, or even member-wise
138 // `(id1.name, id1.ctxt) == (id2.name, id2.ctxt)` depending on the situation.
139 // Ideally, PartialEq should not be implemented for Ident at all, but that
140 // would be too impractical, because many larger structures (Token, in particular)
141 // including Idents as their parts derive PartialEq and use it for non-hygienic
142 // comparisons. That's why PartialEq is implemented and defaults to non-hygienic
143 // comparison. Hash is implemented too and is consistent with PartialEq, i.e. only
144 // the name of Ident is hashed. Still try to avoid comparing idents in your code
145 // (especially as keys in hash maps), use one of the three methods listed above
148 // If you see this panic, then some idents from different contexts were compared
149 // non-hygienically. It's likely a bug. Use one of the three comparison methods
150 // listed above explicitly.
152 panic!("idents with different contexts are compared with operator `==`: \
153 {:?}, {:?}.", self, other);
156 self.name == other.name
160 impl Hash for Ident {
161 fn hash<H: Hasher>(&self, state: &mut H) {
162 self.name.hash(state)
166 impl fmt::Debug for Ident {
167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
168 write!(f, "{}#{}", self.name, self.ctxt.0)
172 impl fmt::Display for Ident {
173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
174 fmt::Display::fmt(&self.name, f)
178 impl Encodable for Ident {
179 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
184 impl Decodable for Ident {
185 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
186 Ok(Ident::with_empty_ctxt(try!(Name::decode(d))))
190 /// A mark represents a unique id associated with a macro expansion
193 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
194 pub struct Lifetime {
200 impl fmt::Debug for Lifetime {
201 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
202 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
206 /// A lifetime definition, eg `'a: 'b+'c+'d`
207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
208 pub struct LifetimeDef {
209 pub lifetime: Lifetime,
210 pub bounds: Vec<Lifetime>
213 /// A "Path" is essentially Rust's notion of a name; for instance:
214 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
215 /// along with a bunch of supporting information.
216 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
219 /// A `::foo` path, is relative to the crate root rather than current
220 /// module (like paths in an import).
222 /// The segments in the path: the things separated by `::`.
223 pub segments: Vec<PathSegment>,
226 impl fmt::Debug for Path {
227 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
228 write!(f, "path({})", pprust::path_to_string(self))
232 impl fmt::Display for Path {
233 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
234 write!(f, "{}", pprust::path_to_string(self))
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 /// Node id used to represent the root of the crate.
368 pub const CRATE_NODE_ID: NodeId = 0;
370 /// When parsing and doing expansions, we initially give all AST nodes this AST
371 /// node value. Then later, in the renumber pass, we renumber them to have
372 /// small, positive ids.
373 pub const DUMMY_NODE_ID: NodeId = !0;
375 pub trait NodeIdAssigner {
376 fn next_node_id(&self) -> NodeId;
377 fn peek_node_id(&self) -> NodeId;
380 /// The AST represents all type param bounds as types.
381 /// typeck::collect::compute_bounds matches these against
382 /// the "special" built-in traits (see middle::lang_items) and
383 /// detects Copy, Send and Sync.
384 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
385 pub enum TyParamBound {
386 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
387 RegionTyParamBound(Lifetime)
390 /// A modifier on a bound, currently this is only used for `?Sized`, where the
391 /// modifier is `Maybe`. Negative bounds should also be handled here.
392 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
393 pub enum TraitBoundModifier {
398 pub type TyParamBounds = OwnedSlice<TyParamBound>;
400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
404 pub bounds: TyParamBounds,
405 pub default: Option<P<Ty>>,
409 /// Represents lifetimes and type parameters attached to a declaration
410 /// of a function, enum, trait, etc.
411 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
412 pub struct Generics {
413 pub lifetimes: Vec<LifetimeDef>,
414 pub ty_params: OwnedSlice<TyParam>,
415 pub where_clause: WhereClause,
419 pub fn is_lt_parameterized(&self) -> bool {
420 !self.lifetimes.is_empty()
422 pub fn is_type_parameterized(&self) -> bool {
423 !self.ty_params.is_empty()
425 pub fn is_parameterized(&self) -> bool {
426 self.is_lt_parameterized() || self.is_type_parameterized()
430 /// A `where` clause in a definition
431 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
432 pub struct WhereClause {
434 pub predicates: Vec<WherePredicate>,
437 /// A single predicate in a `where` clause
438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub enum WherePredicate {
440 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
441 BoundPredicate(WhereBoundPredicate),
442 /// A lifetime predicate, e.g. `'a: 'b+'c`
443 RegionPredicate(WhereRegionPredicate),
444 /// An equality predicate (unsupported)
445 EqPredicate(WhereEqPredicate),
448 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
449 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
450 pub struct WhereBoundPredicate {
452 /// Any lifetimes from a `for` binding
453 pub bound_lifetimes: Vec<LifetimeDef>,
454 /// The type being bounded
455 pub bounded_ty: P<Ty>,
456 /// Trait and lifetime bounds (`Clone+Send+'static`)
457 pub bounds: OwnedSlice<TyParamBound>,
460 /// A lifetime predicate, e.g. `'a: 'b+'c`
461 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
462 pub struct WhereRegionPredicate {
464 pub lifetime: Lifetime,
465 pub bounds: Vec<Lifetime>,
468 /// An equality predicate (unsupported), e.g. `T=int`
469 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
470 pub struct WhereEqPredicate {
477 /// The set of MetaItems that define the compilation environment of the crate,
478 /// used to drive conditional compilation
479 pub type CrateConfig = Vec<P<MetaItem>> ;
481 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
484 pub attrs: Vec<Attribute>,
485 pub config: CrateConfig,
487 pub exported_macros: Vec<MacroDef>,
490 pub type MetaItem = Spanned<MetaItem_>;
492 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
494 MetaWord(InternedString),
495 MetaList(InternedString, Vec<P<MetaItem>>),
496 MetaNameValue(InternedString, Lit),
499 // can't be derived because the MetaList requires an unordered comparison
500 impl PartialEq for MetaItem_ {
501 fn eq(&self, other: &MetaItem_) -> bool {
503 MetaWord(ref ns) => match *other {
504 MetaWord(ref no) => (*ns) == (*no),
507 MetaNameValue(ref ns, ref vs) => match *other {
508 MetaNameValue(ref no, ref vo) => {
509 (*ns) == (*no) && vs.node == vo.node
513 MetaList(ref ns, ref miss) => match *other {
514 MetaList(ref no, ref miso) => {
516 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
524 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
526 /// Statements in a block
527 pub stmts: Vec<P<Stmt>>,
528 /// An expression at the end of the block
529 /// without a semicolon, if any
530 pub expr: Option<P<Expr>>,
532 /// Distinguishes between `unsafe { ... }` and `{ ... }`
533 pub rules: BlockCheckMode,
537 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
544 impl fmt::Debug for Pat {
545 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
546 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
550 /// A single field in a struct pattern
552 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
553 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
554 /// except is_shorthand is true
555 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
556 pub struct FieldPat {
557 /// The identifier for the field
559 /// The pattern the field is destructured to
561 pub is_shorthand: bool,
564 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
565 pub enum BindingMode {
566 BindByRef(Mutability),
567 BindByValue(Mutability),
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
572 /// Represents a wildcard pattern (`_`)
575 /// A PatIdent may either be a new bound variable,
576 /// or a nullary enum (in which case the third field
579 /// In the nullary enum case, the parser can't determine
580 /// which it is. The resolver determines this, and
581 /// records this pattern's NodeId in an auxiliary
582 /// set (of "PatIdents that refer to nullary enums")
583 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
585 /// "None" means a `Variant(..)` pattern where we don't bind the fields to names.
586 PatEnum(Path, Option<Vec<P<Pat>>>),
588 /// An associated const named using the qualified path `<T>::CONST` or
589 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
590 /// referred to as simply `T::CONST`, in which case they will end up as
591 /// PatEnum, and the resolver will have to sort that out.
592 PatQPath(QSelf, Path),
594 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
595 /// The `bool` is `true` in the presence of a `..`
596 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
597 /// A tuple pattern `(a, b)`
601 /// A reference pattern, e.g. `&mut (a, b)`
602 PatRegion(P<Pat>, Mutability),
605 /// A range pattern, e.g. `1...2`
606 PatRange(P<Expr>, P<Expr>),
607 /// `[a, b, ..i, y, z]` is represented as:
608 /// `PatVec(box [a, b], Some(i), box [y, z])`
609 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
610 /// A macro pattern; pre-expansion
614 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
615 pub enum Mutability {
620 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
622 /// The `+` operator (addition)
624 /// The `-` operator (subtraction)
626 /// The `*` operator (multiplication)
628 /// The `/` operator (division)
630 /// The `%` operator (modulus)
632 /// The `&&` operator (logical and)
634 /// The `||` operator (logical or)
636 /// The `^` operator (bitwise xor)
638 /// The `&` operator (bitwise and)
640 /// The `|` operator (bitwise or)
642 /// The `<<` operator (shift left)
644 /// The `>>` operator (shift right)
646 /// The `==` operator (equality)
648 /// The `<` operator (less than)
650 /// The `<=` operator (less than or equal to)
652 /// The `!=` operator (not equal to)
654 /// The `>=` operator (greater than or equal to)
656 /// The `>` operator (greater than)
660 pub type BinOp = Spanned<BinOp_>;
662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
664 /// The `*` operator for dereferencing
666 /// The `!` operator for logical inversion
668 /// The `-` operator for negation
673 pub type Stmt = Spanned<Stmt_>;
675 impl fmt::Debug for Stmt {
676 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
677 write!(f, "stmt({}: {})",
678 ast_util::stmt_id(self)
679 .map_or(Cow::Borrowed("<macro>"),|id|Cow::Owned(id.to_string())),
680 pprust::stmt_to_string(self))
685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
687 /// Could be an item or a local (let) binding:
688 StmtDecl(P<Decl>, NodeId),
690 /// Expr without trailing semi-colon (must have unit type):
691 StmtExpr(P<Expr>, NodeId),
693 /// Expr with trailing semi-colon (may have any type):
694 StmtSemi(P<Expr>, NodeId),
696 StmtMac(P<Mac>, MacStmtStyle),
698 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
699 pub enum MacStmtStyle {
700 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
701 /// `foo!(...);`, `foo![...];`
702 MacStmtWithSemicolon,
703 /// The macro statement had braces; e.g. foo! { ... }
705 /// The macro statement had parentheses or brackets and no semicolon; e.g.
706 /// `foo!(...)`. All of these will end up being converted into macro
708 MacStmtWithoutBraces,
711 // FIXME (pending discussion of #1697, #2178...): local should really be
712 // a refinement on pat.
713 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
714 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
717 pub ty: Option<P<Ty>>,
718 /// Initializer expression to set the value, if any
719 pub init: Option<P<Expr>>,
724 pub type Decl = Spanned<Decl_>;
726 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
728 /// A local (let) binding:
734 /// represents one arm of a 'match'
735 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
737 pub attrs: Vec<Attribute>,
738 pub pats: Vec<P<Pat>>,
739 pub guard: Option<P<Expr>>,
743 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
745 pub ident: SpannedIdent,
750 pub type SpannedIdent = Spanned<Ident>;
752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
753 pub enum BlockCheckMode {
755 UnsafeBlock(UnsafeSource),
758 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
759 pub enum UnsafeSource {
765 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
772 impl fmt::Debug for Expr {
773 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
774 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
778 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
780 /// A `box x` expression.
782 /// First expr is the place; second expr is the value.
783 ExprInPlace(P<Expr>, P<Expr>),
784 /// An array (`[a, b, c, d]`)
785 ExprVec(Vec<P<Expr>>),
788 /// The first field resolves to the function itself,
789 /// and the second field is the list of arguments
790 ExprCall(P<Expr>, Vec<P<Expr>>),
791 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
793 /// The `SpannedIdent` is the identifier for the method name.
794 /// The vector of `Ty`s are the ascripted type parameters for the method
795 /// (within the angle brackets).
797 /// The first element of the vector of `Expr`s is the expression that evaluates
798 /// to the object on which the method is being called on (the receiver),
799 /// and the remaining elements are the rest of the arguments.
801 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
802 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
803 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
804 /// A tuple (`(a, b, c ,d)`)
805 ExprTup(Vec<P<Expr>>),
806 /// A binary operation (For example: `a + b`, `a * b`)
807 ExprBinary(BinOp, P<Expr>, P<Expr>),
808 /// A unary operation (For example: `!x`, `*x`)
809 ExprUnary(UnOp, P<Expr>),
810 /// A literal (For example: `1u8`, `"foo"`)
812 /// A cast (`foo as f64`)
813 ExprCast(P<Expr>, P<Ty>),
814 /// An `if` block, with an optional else block
816 /// `if expr { block } else { expr }`
817 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
818 /// An `if let` expression with an optional else block
820 /// `if let pat = expr { block } else { expr }`
822 /// This is desugared to a `match` expression.
823 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
824 /// A while loop, with an optional label
826 /// `'label: while expr { block }`
827 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
828 /// A while-let loop, with an optional label
830 /// `'label: while let pat = expr { block }`
832 /// This is desugared to a combination of `loop` and `match` expressions.
833 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
834 /// A for loop, with an optional label
836 /// `'label: for pat in expr { block }`
838 /// This is desugared to a combination of `loop` and `match` expressions.
839 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
840 /// Conditionless loop (can be exited with break, continue, or return)
842 /// `'label: loop { block }`
843 ExprLoop(P<Block>, Option<Ident>),
845 ExprMatch(P<Expr>, Vec<Arm>),
846 /// A closure (for example, `move |a, b, c| {a + b + c}`)
847 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
848 /// A block (`{ ... }`)
851 /// An assignment (`a = foo()`)
852 ExprAssign(P<Expr>, P<Expr>),
853 /// An assignment with an operator
855 /// For example, `a += 1`.
856 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
857 /// Access of a named struct field (`obj.foo`)
858 ExprField(P<Expr>, SpannedIdent),
859 /// Access of an unnamed field of a struct or tuple-struct
861 /// For example, `foo.0`.
862 ExprTupField(P<Expr>, Spanned<usize>),
863 /// An indexing operation (`foo[2]`)
864 ExprIndex(P<Expr>, P<Expr>),
865 /// A range (`1..2`, `1..`, or `..2`)
866 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
868 /// Variable reference, possibly containing `::` and/or type
869 /// parameters, e.g. foo::bar::<baz>.
871 /// Optionally "qualified",
872 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
873 ExprPath(Option<QSelf>, Path),
875 /// A referencing operation (`&a` or `&mut a`)
876 ExprAddrOf(Mutability, P<Expr>),
877 /// A `break`, with an optional label to break
878 ExprBreak(Option<SpannedIdent>),
879 /// A `continue`, with an optional label
880 ExprAgain(Option<SpannedIdent>),
881 /// A `return`, with an optional value to be returned
882 ExprRet(Option<P<Expr>>),
884 /// Output of the `asm!()` macro
885 ExprInlineAsm(InlineAsm),
887 /// A macro invocation; pre-expansion
890 /// A struct literal expression.
892 /// For example, `Foo {x: 1, y: 2}`, or
893 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
894 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
896 /// An array literal constructed from one repeated element.
898 /// For example, `[1u8; 5]`. The first expression is the element
899 /// to be repeated; the second is the number of times to repeat it.
900 ExprRepeat(P<Expr>, P<Expr>),
902 /// No-op: used solely so we can pretty-print faithfully
906 /// The explicit Self type in a "qualified path". The actual
907 /// path, including the trait and the associated item, is stored
908 /// separately. `position` represents the index of the associated
909 /// item qualified with this Self type.
912 /// <Vec<T> as a::b::Trait>::AssociatedItem
913 /// ^~~~~ ~~~~~~~~~~~~~~^
916 /// <Vec<T>>::AssociatedItem
920 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
926 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
927 pub enum CaptureClause {
932 /// A delimited sequence of token trees
933 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
934 pub struct Delimited {
935 /// The type of delimiter
936 pub delim: token::DelimToken,
937 /// The span covering the opening delimiter
939 /// The delimited sequence of token trees
940 pub tts: Vec<TokenTree>,
941 /// The span covering the closing delimiter
942 pub close_span: Span,
946 /// Returns the opening delimiter as a token.
947 pub fn open_token(&self) -> token::Token {
948 token::OpenDelim(self.delim)
951 /// Returns the closing delimiter as a token.
952 pub fn close_token(&self) -> token::Token {
953 token::CloseDelim(self.delim)
956 /// Returns the opening delimiter as a token tree.
957 pub fn open_tt(&self) -> TokenTree {
958 TokenTree::Token(self.open_span, self.open_token())
961 /// Returns the closing delimiter as a token tree.
962 pub fn close_tt(&self) -> TokenTree {
963 TokenTree::Token(self.close_span, self.close_token())
967 /// A sequence of token treesee
968 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
969 pub struct SequenceRepetition {
970 /// The sequence of token trees
971 pub tts: Vec<TokenTree>,
972 /// The optional separator
973 pub separator: Option<token::Token>,
974 /// Whether the sequence can be repeated zero (*), or one or more times (+)
976 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
977 pub num_captures: usize,
980 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
981 /// for token sequences.
982 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
988 /// When the main rust parser encounters a syntax-extension invocation, it
989 /// parses the arguments to the invocation as a token-tree. This is a very
990 /// loose structure, such that all sorts of different AST-fragments can
991 /// be passed to syntax extensions using a uniform type.
993 /// If the syntax extension is an MBE macro, it will attempt to match its
994 /// LHS token tree against the provided token tree, and if it finds a
995 /// match, will transcribe the RHS token tree, splicing in any captured
996 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
998 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
999 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1000 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1001 pub enum TokenTree {
1003 Token(Span, token::Token),
1004 /// A delimited sequence of token trees
1005 Delimited(Span, Rc<Delimited>),
1007 // This only makes sense in MBE macros.
1009 /// A kleene-style repetition sequence with a span
1010 // FIXME(eddyb) #12938 Use DST.
1011 Sequence(Span, Rc<SequenceRepetition>),
1015 pub fn len(&self) -> usize {
1017 TokenTree::Token(_, token::DocComment(name)) => {
1018 match doc_comment_style(&name.as_str()) {
1019 AttrStyle::Outer => 2,
1020 AttrStyle::Inner => 3
1023 TokenTree::Token(_, token::SpecialVarNt(..)) => 2,
1024 TokenTree::Token(_, token::MatchNt(..)) => 3,
1025 TokenTree::Delimited(_, ref delimed) => {
1026 delimed.tts.len() + 2
1028 TokenTree::Sequence(_, ref seq) => {
1031 TokenTree::Token(..) => 0
1035 pub fn get_tt(&self, index: usize) -> TokenTree {
1036 match (self, index) {
1037 (&TokenTree::Token(sp, token::DocComment(_)), 0) => {
1038 TokenTree::Token(sp, token::Pound)
1040 (&TokenTree::Token(sp, token::DocComment(name)), 1)
1041 if doc_comment_style(&name.as_str()) == AttrStyle::Inner => {
1042 TokenTree::Token(sp, token::Not)
1044 (&TokenTree::Token(sp, token::DocComment(name)), _) => {
1045 let stripped = strip_doc_comment_decoration(&name.as_str());
1046 TokenTree::Delimited(sp, Rc::new(Delimited {
1047 delim: token::Bracket,
1049 tts: vec![TokenTree::Token(sp, token::Ident(token::str_to_ident("doc"),
1051 TokenTree::Token(sp, token::Eq),
1052 TokenTree::Token(sp, token::Literal(
1053 token::StrRaw(token::intern(&stripped), 0), None))],
1057 (&TokenTree::Delimited(_, ref delimed), _) => {
1059 return delimed.open_tt();
1061 if index == delimed.tts.len() + 1 {
1062 return delimed.close_tt();
1064 delimed.tts[index - 1].clone()
1066 (&TokenTree::Token(sp, token::SpecialVarNt(var)), _) => {
1067 let v = [TokenTree::Token(sp, token::Dollar),
1068 TokenTree::Token(sp, token::Ident(token::str_to_ident(var.as_str()),
1072 (&TokenTree::Token(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1073 let v = [TokenTree::Token(sp, token::SubstNt(name, name_st)),
1074 TokenTree::Token(sp, token::Colon),
1075 TokenTree::Token(sp, token::Ident(kind, kind_st))];
1078 (&TokenTree::Sequence(_, ref seq), _) => {
1079 seq.tts[index].clone()
1081 _ => panic!("Cannot expand a token tree")
1085 /// Returns the `Span` corresponding to this token tree.
1086 pub fn get_span(&self) -> Span {
1088 TokenTree::Token(span, _) => span,
1089 TokenTree::Delimited(span, _) => span,
1090 TokenTree::Sequence(span, _) => span,
1094 /// Use this token tree as a matcher to parse given tts.
1095 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1096 -> macro_parser::NamedParseResult {
1097 // `None` is because we're not interpolating
1098 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1101 tts.iter().cloned().collect(),
1103 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1107 pub type Mac = Spanned<Mac_>;
1109 /// Represents a macro invocation. The Path indicates which macro
1110 /// is being invoked, and the vector of token-trees contains the source
1111 /// of the macro invocation.
1113 /// NB: the additional ident for a macro_rules-style macro is actually
1114 /// stored in the enclosing item. Oog.
1115 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1118 pub tts: Vec<TokenTree>,
1119 pub ctxt: SyntaxContext,
1122 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1124 /// A regular string, like `"foo"`
1126 /// A raw string, like `r##"foo"##`
1128 /// The uint is the number of `#` symbols used
1133 pub type Lit = Spanned<Lit_>;
1135 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1142 pub fn new<T: IntSign>(n: T) -> Sign {
1148 fn sign(&self) -> Sign;
1151 ($($t:ident)*) => ($(impl IntSign for $t {
1152 #[allow(unused_comparisons)]
1153 fn sign(&self) -> Sign {
1154 if *self < 0 {Minus} else {Plus}
1158 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1160 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1161 pub enum LitIntType {
1162 SignedIntLit(IntTy, Sign),
1163 UnsignedIntLit(UintTy),
1164 UnsuffixedIntLit(Sign)
1167 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1169 /// A string literal (`"foo"`)
1170 LitStr(InternedString, StrStyle),
1171 /// A byte string (`b"foo"`)
1172 LitByteStr(Rc<Vec<u8>>),
1173 /// A byte char (`b'f'`)
1175 /// A character literal (`'a'`)
1177 /// An integer literal (`1u8`)
1178 LitInt(u64, LitIntType),
1179 /// A float literal (`1f64` or `1E10f64`)
1180 LitFloat(InternedString, FloatTy),
1181 /// A float literal without a suffix (`1.0 or 1.0E10`)
1182 LitFloatUnsuffixed(InternedString),
1183 /// A boolean literal
1187 // NB: If you change this, you'll probably want to change the corresponding
1188 // type structure in middle/ty.rs as well.
1189 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1192 pub mutbl: Mutability,
1195 /// Represents a method's signature in a trait declaration,
1196 /// or in an implementation.
1197 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1198 pub struct MethodSig {
1199 pub unsafety: Unsafety,
1200 pub constness: Constness,
1202 pub decl: P<FnDecl>,
1203 pub generics: Generics,
1204 pub explicit_self: ExplicitSelf,
1207 /// Represents a method declaration in a trait declaration, possibly including
1208 /// a default implementation A trait method is either required (meaning it
1209 /// doesn't have an implementation, just a signature) or provided (meaning it
1210 /// has a default implementation).
1211 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1212 pub struct TraitItem {
1215 pub attrs: Vec<Attribute>,
1216 pub node: TraitItem_,
1220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1221 pub enum TraitItem_ {
1222 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1223 MethodTraitItem(MethodSig, Option<P<Block>>),
1224 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1227 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1228 pub struct ImplItem {
1231 pub vis: Visibility,
1232 pub attrs: Vec<Attribute>,
1233 pub node: ImplItem_,
1237 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1238 pub enum ImplItem_ {
1239 ConstImplItem(P<Ty>, P<Expr>),
1240 MethodImplItem(MethodSig, P<Block>),
1241 TypeImplItem(P<Ty>),
1245 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1254 impl fmt::Debug for IntTy {
1255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1256 fmt::Display::fmt(self, f)
1260 impl fmt::Display for IntTy {
1261 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1262 write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1267 pub fn bit_width(&self) -> Option<usize> {
1269 TyIs => return None,
1278 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1288 pub fn bit_width(&self) -> Option<usize> {
1290 TyUs => return None,
1299 impl fmt::Debug for UintTy {
1300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1301 fmt::Display::fmt(self, f)
1305 impl fmt::Display for UintTy {
1306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1307 write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1311 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1317 impl fmt::Debug for FloatTy {
1318 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1319 fmt::Display::fmt(self, f)
1323 impl fmt::Display for FloatTy {
1324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1325 write!(f, "{}", ast_util::float_ty_to_string(*self))
1330 pub fn bit_width(&self) -> usize {
1338 // Bind a type to an associated type: `A=Foo`.
1339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1340 pub struct TypeBinding {
1347 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1354 impl fmt::Debug for Ty {
1355 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1356 write!(f, "type({})", pprust::ty_to_string(self))
1360 /// Not represented directly in the AST, referred to by name through a ty_path.
1361 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1371 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1372 pub struct BareFnTy {
1373 pub unsafety: Unsafety,
1375 pub lifetimes: Vec<LifetimeDef>,
1379 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1380 /// The different kinds of types recognized by the compiler
1383 /// A fixed length array (`[T; n]`)
1384 TyFixedLengthVec(P<Ty>, P<Expr>),
1385 /// A raw pointer (`*const T` or `*mut T`)
1387 /// A reference (`&'a T` or `&'a mut T`)
1388 TyRptr(Option<Lifetime>, MutTy),
1389 /// A bare function (e.g. `fn(usize) -> bool`)
1390 TyBareFn(P<BareFnTy>),
1391 /// A tuple (`(A, B, C, D,...)`)
1393 /// A path (`module::module::...::Type`), optionally
1394 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1396 /// Type parameters are stored in the Path itself
1397 TyPath(Option<QSelf>, Path),
1398 /// Something like `A+B`. Note that `B` must always be a path.
1399 TyObjectSum(P<Ty>, TyParamBounds),
1400 /// A type like `for<'a> Foo<&'a Bar>`
1401 TyPolyTraitRef(TyParamBounds),
1402 /// No-op; kept solely so that we can pretty-print faithfully
1406 /// TyInfer means the type should be inferred instead of it having been
1407 /// specified. This can appear anywhere in a type.
1409 // A macro in the type position.
1413 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1414 pub enum AsmDialect {
1419 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1420 pub struct InlineAsm {
1421 pub asm: InternedString,
1422 pub asm_str_style: StrStyle,
1423 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1424 pub inputs: Vec<(InternedString, P<Expr>)>,
1425 pub clobbers: Vec<InternedString>,
1427 pub alignstack: bool,
1428 pub dialect: AsmDialect,
1429 pub expn_id: ExpnId,
1432 /// represents an argument in a function header
1433 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1441 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1442 let path = Spanned{span:span,node:self_ident};
1444 // HACK(eddyb) fake type for the self argument.
1452 node: PatIdent(BindByValue(mutability), path, None),
1460 /// Represents the header (not the body) of a function declaration
1461 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1463 pub inputs: Vec<Arg>,
1464 pub output: FunctionRetTy,
1468 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1474 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1475 pub enum Constness {
1480 impl fmt::Display for Unsafety {
1481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1482 fmt::Display::fmt(match *self {
1483 Unsafety::Normal => "normal",
1484 Unsafety::Unsafe => "unsafe",
1489 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1490 pub enum ImplPolarity {
1491 /// `impl Trait for Type`
1493 /// `impl !Trait for Type`
1497 impl fmt::Debug for ImplPolarity {
1498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1500 ImplPolarity::Positive => "positive".fmt(f),
1501 ImplPolarity::Negative => "negative".fmt(f),
1507 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1508 pub enum FunctionRetTy {
1509 /// Functions with return type `!`that always
1510 /// raise an error or exit (i.e. never return to the caller)
1512 /// Return type is not specified.
1514 /// Functions default to `()` and
1515 /// closures default to inference. Span points to where return
1516 /// type would be inserted.
1517 DefaultReturn(Span),
1522 impl FunctionRetTy {
1523 pub fn span(&self) -> Span {
1525 NoReturn(span) => span,
1526 DefaultReturn(span) => span,
1527 Return(ref ty) => ty.span
1532 /// Represents the kind of 'self' associated with a method
1533 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1534 pub enum ExplicitSelf_ {
1539 /// `&'lt self`, `&'lt mut self`
1540 SelfRegion(Option<Lifetime>, Mutability, Ident),
1542 SelfExplicit(P<Ty>, Ident),
1545 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1547 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1549 /// A span from the first token past `{` to the last token until `}`.
1550 /// For `mod foo;`, the inner span ranges from the first token
1551 /// to the last token in the external file.
1553 pub items: Vec<P<Item>>,
1556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1557 pub struct ForeignMod {
1559 pub items: Vec<P<ForeignItem>>,
1562 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1563 pub struct EnumDef {
1564 pub variants: Vec<P<Variant>>,
1567 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1568 pub struct Variant_ {
1570 pub attrs: Vec<Attribute>,
1571 pub data: VariantData,
1572 /// Explicit discriminant, eg `Foo = 1`
1573 pub disr_expr: Option<P<Expr>>,
1576 pub type Variant = Spanned<Variant_>;
1578 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1579 pub enum PathListItem_ {
1582 /// renamed in list, eg `use foo::{bar as baz};`
1583 rename: Option<Ident>,
1587 /// renamed in list, eg `use foo::{self as baz};`
1588 rename: Option<Ident>,
1593 impl PathListItem_ {
1594 pub fn id(&self) -> NodeId {
1596 PathListIdent { id, .. } | PathListMod { id, .. } => id
1600 pub fn name(&self) -> Option<Ident> {
1602 PathListIdent { name, .. } => Some(name),
1603 PathListMod { .. } => None,
1607 pub fn rename(&self) -> Option<Ident> {
1609 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1614 pub type PathListItem = Spanned<PathListItem_>;
1616 pub type ViewPath = Spanned<ViewPath_>;
1618 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1619 pub enum ViewPath_ {
1621 /// `foo::bar::baz as quux`
1625 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1626 ViewPathSimple(Ident, Path),
1631 /// `foo::bar::{a,b,c}`
1632 ViewPathList(Path, Vec<PathListItem>)
1635 /// Meta-data associated with an item
1636 pub type Attribute = Spanned<Attribute_>;
1638 /// Distinguishes between Attributes that decorate items and Attributes that
1639 /// are contained as statements within items. These two cases need to be
1640 /// distinguished for pretty-printing.
1641 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1642 pub enum AttrStyle {
1647 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1648 pub struct AttrId(pub usize);
1650 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1651 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1652 pub struct Attribute_ {
1654 pub style: AttrStyle,
1655 pub value: P<MetaItem>,
1656 pub is_sugared_doc: bool,
1659 /// TraitRef's appear in impls.
1661 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1662 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1663 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1664 /// same as the impl's node id).
1665 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1666 pub struct TraitRef {
1671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1672 pub struct PolyTraitRef {
1673 /// The `'a` in `<'a> Foo<&'a T>`
1674 pub bound_lifetimes: Vec<LifetimeDef>,
1676 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1677 pub trait_ref: TraitRef,
1682 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1683 pub enum Visibility {
1689 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1691 &Inherited => parent_visibility,
1697 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1698 pub struct StructField_ {
1699 pub kind: StructFieldKind,
1702 pub attrs: Vec<Attribute>,
1706 pub fn ident(&self) -> Option<Ident> {
1708 NamedField(ref ident, _) => Some(ident.clone()),
1709 UnnamedField(_) => None
1714 pub type StructField = Spanned<StructField_>;
1716 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1717 pub enum StructFieldKind {
1718 NamedField(Ident, Visibility),
1719 /// Element of a tuple-like struct
1720 UnnamedField(Visibility),
1723 impl StructFieldKind {
1724 pub fn is_unnamed(&self) -> bool {
1726 UnnamedField(..) => true,
1727 NamedField(..) => false,
1731 pub fn visibility(&self) -> Visibility {
1733 NamedField(_, vis) | UnnamedField(vis) => vis
1738 /// Fields and Ids of enum variants and structs
1740 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1741 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1742 /// One shared Id can be successfully used for these two purposes.
1743 /// Id of the whole enum lives in `Item`.
1745 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1746 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1747 /// the variant itself" from enum variants.
1748 /// Id of the whole struct lives in `Item`.
1749 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1750 pub enum VariantData {
1751 Struct(Vec<StructField>, NodeId),
1752 Tuple(Vec<StructField>, NodeId),
1757 pub fn fields(&self) -> &[StructField] {
1759 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1763 pub fn id(&self) -> NodeId {
1765 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1768 pub fn is_struct(&self) -> bool {
1769 if let VariantData::Struct(..) = *self { true } else { false }
1771 pub fn is_tuple(&self) -> bool {
1772 if let VariantData::Tuple(..) = *self { true } else { false }
1774 pub fn is_unit(&self) -> bool {
1775 if let VariantData::Unit(..) = *self { true } else { false }
1780 FIXME (#3300): Should allow items to be anonymous. Right now
1781 we just use dummy names for anon items.
1785 /// The name might be a dummy name in case of anonymous items
1786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1789 pub attrs: Vec<Attribute>,
1792 pub vis: Visibility,
1796 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1798 /// An`extern crate` item, with optional original crate name,
1800 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1801 ItemExternCrate(Option<Name>),
1802 /// A `use` or `pub use` item
1803 ItemUse(P<ViewPath>),
1806 ItemStatic(P<Ty>, Mutability, P<Expr>),
1808 ItemConst(P<Ty>, P<Expr>),
1809 /// A function declaration
1810 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1813 /// An external module
1814 ItemForeignMod(ForeignMod),
1815 /// A type alias, e.g. `type Foo = Bar<u8>`
1816 ItemTy(P<Ty>, Generics),
1817 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1818 ItemEnum(EnumDef, Generics),
1819 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1820 ItemStruct(VariantData, Generics),
1821 /// Represents a Trait Declaration
1827 // Default trait implementations
1829 // `impl Trait for .. {}`
1830 ItemDefaultImpl(Unsafety, TraitRef),
1831 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1835 Option<TraitRef>, // (optional) trait this impl implements
1838 /// A macro invocation (which includes macro definition)
1843 pub fn descriptive_variant(&self) -> &str {
1845 ItemExternCrate(..) => "extern crate",
1846 ItemUse(..) => "use",
1847 ItemStatic(..) => "static item",
1848 ItemConst(..) => "constant item",
1849 ItemFn(..) => "function",
1850 ItemMod(..) => "module",
1851 ItemForeignMod(..) => "foreign module",
1852 ItemTy(..) => "type alias",
1853 ItemEnum(..) => "enum",
1854 ItemStruct(..) => "struct",
1855 ItemTrait(..) => "trait",
1858 ItemDefaultImpl(..) => "item"
1863 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1864 pub struct ForeignItem {
1866 pub attrs: Vec<Attribute>,
1867 pub node: ForeignItem_,
1870 pub vis: Visibility,
1873 /// An item within an `extern` block
1874 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1875 pub enum ForeignItem_ {
1876 /// A foreign function
1877 ForeignItemFn(P<FnDecl>, Generics),
1878 /// A foreign static item (`static ext: u8`), with optional mutability
1879 /// (the boolean is true when mutable)
1880 ForeignItemStatic(P<Ty>, bool),
1884 pub fn descriptive_variant(&self) -> &str {
1886 ForeignItemFn(..) => "foreign function",
1887 ForeignItemStatic(..) => "foreign static item"
1892 /// A macro definition, in this crate or imported from another.
1894 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1896 pub struct MacroDef {
1898 pub attrs: Vec<Attribute>,
1901 pub imported_from: Option<Ident>,
1903 pub use_locally: bool,
1904 pub allow_internal_unstable: bool,
1905 pub body: Vec<TokenTree>,
1913 // are ASTs encodable?
1915 fn check_asts_encodable() {
1916 fn assert_encodable<T: serialize::Encodable>() {}
1917 assert_encodable::<Crate>();