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::PatWildKind::*;
35 pub use self::PrimTy::*;
36 pub use self::Sign::*;
37 pub use self::Stmt_::*;
38 pub use self::StrStyle::*;
39 pub use self::StructFieldKind::*;
40 pub use self::TokenTree::*;
41 pub use self::TraitItem_::*;
43 pub use self::TyParamBound::*;
44 pub use self::UintTy::*;
45 pub use self::UnOp::*;
46 pub use self::UnsafeSource::*;
47 pub use self::VariantKind::*;
48 pub use self::ViewPath_::*;
49 pub use self::Visibility::*;
50 pub use self::PathParameters::*;
52 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
56 use ext::tt::macro_parser;
57 use owned_slice::OwnedSlice;
58 use parse::token::{InternedString, str_to_ident};
61 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
68 use serialize::{Encodable, Decodable, Encoder, Decoder};
70 /// A name is a part of an identifier, representing a string or gensym. It's
71 /// the result of interning.
72 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
73 pub struct Name(pub u32);
75 /// A SyntaxContext represents a chain of macro-expandings
76 /// and renamings. Each macro expansion corresponds to
77 /// a fresh u32. This u32 is a reference to a table stored
78 // in thread-local storage.
79 // The special value EMPTY_CTXT is used to indicate an empty
81 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
82 pub struct SyntaxContext(pub u32);
84 /// An identifier contains a Name (index into the interner
85 /// table) and a SyntaxContext to track renaming and
86 /// macro expansion per Flatt et al., "Macros That Work Together"
87 #[derive(Clone, Copy, Eq, Hash)]
90 pub ctxt: SyntaxContext
94 pub fn as_str(self) -> token::InternedString {
95 token::InternedString::new_from_name(self)
99 impl fmt::Debug for Name {
100 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101 write!(f, "{}({})", self, self.0)
105 impl fmt::Display for Name {
106 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107 fmt::Display::fmt(&self.as_str(), f)
111 impl Encodable for Name {
112 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
113 s.emit_str(&self.as_str())
117 impl Decodable for Name {
118 fn decode<D: Decoder>(d: &mut D) -> Result<Name, D::Error> {
119 Ok(token::intern(&try!(d.read_str())[..]))
123 pub const EMPTY_CTXT : SyntaxContext = SyntaxContext(0);
126 pub fn new(name: Name, ctxt: SyntaxContext) -> Ident {
127 Ident {name: name, ctxt: ctxt}
129 pub fn with_empty_ctxt(name: Name) -> Ident {
130 Ident {name: name, ctxt: EMPTY_CTXT}
134 impl PartialEq for Ident {
135 fn eq(&self, other: &Ident) -> bool {
136 if self.ctxt == other.ctxt {
137 self.name == other.name
139 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
140 // idents that have different contexts. You can't fix this without
141 // knowing whether the comparison should be hygienic or non-hygienic.
142 // if it should be non-hygienic (most things are), just compare the
143 // 'name' fields of the idents.
145 // On the other hand, if the comparison does need to be hygienic,
146 // one example and its non-hygienic counterpart would be:
147 // syntax::parse::token::Token::mtwt_eq
148 // syntax::ext::tt::macro_parser::token_name_eq
149 panic!("idents with different contexts are compared with operator `==`: \
150 {:?}, {:?}.", self, other);
155 impl fmt::Debug for Ident {
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157 write!(f, "{}#{}", self.name, self.ctxt.0)
161 impl fmt::Display for Ident {
162 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
163 fmt::Display::fmt(&self.name, f)
167 impl Encodable for Ident {
168 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
173 impl Decodable for Ident {
174 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
175 Ok(Ident::with_empty_ctxt(try!(Name::decode(d))))
179 /// A mark represents a unique id associated with a macro expansion
182 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
183 pub struct Lifetime {
189 impl fmt::Debug for Lifetime {
190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
191 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
195 /// A lifetime definition, eg `'a: 'b+'c+'d`
196 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
197 pub struct LifetimeDef {
198 pub lifetime: Lifetime,
199 pub bounds: Vec<Lifetime>
202 /// A "Path" is essentially Rust's notion of a name; for instance:
203 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
204 /// along with a bunch of supporting information.
205 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
208 /// A `::foo` path, is relative to the crate root rather than current
209 /// module (like paths in an import).
211 /// The segments in the path: the things separated by `::`.
212 pub segments: Vec<PathSegment>,
215 impl fmt::Debug for Path {
216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217 write!(f, "path({})", pprust::path_to_string(self))
221 impl fmt::Display for Path {
222 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223 write!(f, "{}", pprust::path_to_string(self))
227 /// A segment of a path: an identifier, an optional lifetime, and a set of
229 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
230 pub struct PathSegment {
231 /// The identifier portion of this path segment.
232 pub identifier: Ident,
234 /// Type/lifetime parameters attached to this path. They come in
235 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
236 /// this is more than just simple syntactic sugar; the use of
237 /// parens affects the region binding rules, so we preserve the
239 pub parameters: PathParameters,
242 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
243 pub enum PathParameters {
244 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
245 AngleBracketedParameters(AngleBracketedParameterData),
246 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
247 ParenthesizedParameters(ParenthesizedParameterData),
250 impl PathParameters {
251 pub fn none() -> PathParameters {
252 AngleBracketedParameters(AngleBracketedParameterData {
253 lifetimes: Vec::new(),
254 types: OwnedSlice::empty(),
255 bindings: OwnedSlice::empty(),
259 pub fn is_empty(&self) -> bool {
261 AngleBracketedParameters(ref data) => data.is_empty(),
263 // Even if the user supplied no types, something like
264 // `X()` is equivalent to `X<(),()>`.
265 ParenthesizedParameters(..) => false,
269 pub fn has_lifetimes(&self) -> bool {
271 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
272 ParenthesizedParameters(_) => false,
276 pub fn has_types(&self) -> bool {
278 AngleBracketedParameters(ref data) => !data.types.is_empty(),
279 ParenthesizedParameters(..) => true,
283 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
284 /// parameters in the parenthesized case.
285 pub fn types(&self) -> Vec<&P<Ty>> {
287 AngleBracketedParameters(ref data) => {
288 data.types.iter().collect()
290 ParenthesizedParameters(ref data) => {
292 .chain(data.output.iter())
298 pub fn lifetimes(&self) -> Vec<&Lifetime> {
300 AngleBracketedParameters(ref data) => {
301 data.lifetimes.iter().collect()
303 ParenthesizedParameters(_) => {
309 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
311 AngleBracketedParameters(ref data) => {
312 data.bindings.iter().collect()
314 ParenthesizedParameters(_) => {
321 /// A path like `Foo<'a, T>`
322 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
323 pub struct AngleBracketedParameterData {
324 /// The lifetime parameters for this path segment.
325 pub lifetimes: Vec<Lifetime>,
326 /// The type parameters for this path segment, if present.
327 pub types: OwnedSlice<P<Ty>>,
328 /// Bindings (equality constraints) on associated types, if present.
329 /// E.g., `Foo<A=Bar>`.
330 pub bindings: OwnedSlice<P<TypeBinding>>,
333 impl AngleBracketedParameterData {
334 fn is_empty(&self) -> bool {
335 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
339 /// A path like `Foo(A,B) -> C`
340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
341 pub struct ParenthesizedParameterData {
346 pub inputs: Vec<P<Ty>>,
349 pub output: Option<P<Ty>>,
352 pub type CrateNum = u32;
354 pub type NodeId = u32;
356 /// Node id used to represent the root of the crate.
357 pub const CRATE_NODE_ID: NodeId = 0;
359 /// When parsing and doing expansions, we initially give all AST nodes this AST
360 /// node value. Then later, in the renumber pass, we renumber them to have
361 /// small, positive ids.
362 pub const DUMMY_NODE_ID: NodeId = !0;
364 /// The AST represents all type param bounds as types.
365 /// typeck::collect::compute_bounds matches these against
366 /// the "special" built-in traits (see middle::lang_items) and
367 /// detects Copy, Send and Sync.
368 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
369 pub enum TyParamBound {
370 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
371 RegionTyParamBound(Lifetime)
374 /// A modifier on a bound, currently this is only used for `?Sized`, where the
375 /// modifier is `Maybe`. Negative bounds should also be handled here.
376 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
377 pub enum TraitBoundModifier {
382 pub type TyParamBounds = OwnedSlice<TyParamBound>;
384 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
388 pub bounds: TyParamBounds,
389 pub default: Option<P<Ty>>,
393 /// Represents lifetimes and type parameters attached to a declaration
394 /// of a function, enum, trait, etc.
395 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
396 pub struct Generics {
397 pub lifetimes: Vec<LifetimeDef>,
398 pub ty_params: OwnedSlice<TyParam>,
399 pub where_clause: WhereClause,
403 pub fn is_lt_parameterized(&self) -> bool {
404 !self.lifetimes.is_empty()
406 pub fn is_type_parameterized(&self) -> bool {
407 !self.ty_params.is_empty()
409 pub fn is_parameterized(&self) -> bool {
410 self.is_lt_parameterized() || self.is_type_parameterized()
414 /// A `where` clause in a definition
415 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
416 pub struct WhereClause {
418 pub predicates: Vec<WherePredicate>,
421 /// A single predicate in a `where` clause
422 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
423 pub enum WherePredicate {
424 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
425 BoundPredicate(WhereBoundPredicate),
426 /// A lifetime predicate, e.g. `'a: 'b+'c`
427 RegionPredicate(WhereRegionPredicate),
428 /// An equality predicate (unsupported)
429 EqPredicate(WhereEqPredicate),
432 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
433 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
434 pub struct WhereBoundPredicate {
436 /// Any lifetimes from a `for` binding
437 pub bound_lifetimes: Vec<LifetimeDef>,
438 /// The type being bounded
439 pub bounded_ty: P<Ty>,
440 /// Trait and lifetime bounds (`Clone+Send+'static`)
441 pub bounds: OwnedSlice<TyParamBound>,
444 /// A lifetime predicate, e.g. `'a: 'b+'c`
445 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
446 pub struct WhereRegionPredicate {
448 pub lifetime: Lifetime,
449 pub bounds: Vec<Lifetime>,
452 /// An equality predicate (unsupported), e.g. `T=int`
453 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
454 pub struct WhereEqPredicate {
461 /// The set of MetaItems that define the compilation environment of the crate,
462 /// used to drive conditional compilation
463 pub type CrateConfig = Vec<P<MetaItem>> ;
465 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
468 pub attrs: Vec<Attribute>,
469 pub config: CrateConfig,
471 pub exported_macros: Vec<MacroDef>,
474 pub type MetaItem = Spanned<MetaItem_>;
476 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
478 MetaWord(InternedString),
479 MetaList(InternedString, Vec<P<MetaItem>>),
480 MetaNameValue(InternedString, Lit),
483 // can't be derived because the MetaList requires an unordered comparison
484 impl PartialEq for MetaItem_ {
485 fn eq(&self, other: &MetaItem_) -> bool {
487 MetaWord(ref ns) => match *other {
488 MetaWord(ref no) => (*ns) == (*no),
491 MetaNameValue(ref ns, ref vs) => match *other {
492 MetaNameValue(ref no, ref vo) => {
493 (*ns) == (*no) && vs.node == vo.node
497 MetaList(ref ns, ref miss) => match *other {
498 MetaList(ref no, ref miso) => {
500 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
508 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
510 /// Statements in a block
511 pub stmts: Vec<P<Stmt>>,
512 /// An expression at the end of the block
513 /// without a semicolon, if any
514 pub expr: Option<P<Expr>>,
516 /// Distinguishes between `unsafe { ... }` and `{ ... }`
517 pub rules: BlockCheckMode,
521 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
528 impl fmt::Debug for Pat {
529 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
530 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
534 /// A single field in a struct pattern
536 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
537 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
538 /// except is_shorthand is true
539 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
540 pub struct FieldPat {
541 /// The identifier for the field
543 /// The pattern the field is destructured to
545 pub is_shorthand: bool,
548 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
549 pub enum BindingMode {
550 BindByRef(Mutability),
551 BindByValue(Mutability),
554 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
555 pub enum PatWildKind {
556 /// Represents the wildcard pattern `_`
559 /// Represents the wildcard pattern `..`
563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
565 /// Represents a wildcard pattern (either `_` or `..`)
566 PatWild(PatWildKind),
568 /// A PatIdent may either be a new bound variable,
569 /// or a nullary enum (in which case the third field
572 /// In the nullary enum case, the parser can't determine
573 /// which it is. The resolver determines this, and
574 /// records this pattern's NodeId in an auxiliary
575 /// set (of "PatIdents that refer to nullary enums")
576 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
578 /// "None" means a * pattern where we don't bind the fields to names.
579 PatEnum(Path, Option<Vec<P<Pat>>>),
581 /// An associated const named using the qualified path `<T>::CONST` or
582 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
583 /// referred to as simply `T::CONST`, in which case they will end up as
584 /// PatEnum, and the resolver will have to sort that out.
585 PatQPath(QSelf, Path),
587 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
588 /// The `bool` is `true` in the presence of a `..`
589 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
590 /// A tuple pattern `(a, b)`
594 /// A reference pattern, e.g. `&mut (a, b)`
595 PatRegion(P<Pat>, Mutability),
598 /// A range pattern, e.g. `1...2`
599 PatRange(P<Expr>, P<Expr>),
600 /// [a, b, ..i, y, z] is represented as:
601 /// PatVec(box [a, b], Some(i), box [y, z])
602 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
603 /// A macro pattern; pre-expansion
607 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
608 pub enum Mutability {
613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
615 /// The `+` operator (addition)
617 /// The `-` operator (subtraction)
619 /// The `*` operator (multiplication)
621 /// The `/` operator (division)
623 /// The `%` operator (modulus)
625 /// The `&&` operator (logical and)
627 /// The `||` operator (logical or)
629 /// The `^` operator (bitwise xor)
631 /// The `&` operator (bitwise and)
633 /// The `|` operator (bitwise or)
635 /// The `<<` operator (shift left)
637 /// The `>>` operator (shift right)
639 /// The `==` operator (equality)
641 /// The `<` operator (less than)
643 /// The `<=` operator (less than or equal to)
645 /// The `!=` operator (not equal to)
647 /// The `>=` operator (greater than or equal to)
649 /// The `>` operator (greater than)
653 pub type BinOp = Spanned<BinOp_>;
655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
657 /// The `*` operator for dereferencing
659 /// The `!` operator for logical inversion
661 /// The `-` operator for negation
666 pub type Stmt = Spanned<Stmt_>;
668 impl fmt::Debug for Stmt {
669 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
670 write!(f, "stmt({}: {})",
671 ast_util::stmt_id(self)
672 .map_or(Cow::Borrowed("<macro>"),|id|Cow::Owned(id.to_string())),
673 pprust::stmt_to_string(self))
678 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
680 /// Could be an item or a local (let) binding:
681 StmtDecl(P<Decl>, NodeId),
683 /// Expr without trailing semi-colon (must have unit type):
684 StmtExpr(P<Expr>, NodeId),
686 /// Expr with trailing semi-colon (may have any type):
687 StmtSemi(P<Expr>, NodeId),
689 StmtMac(P<Mac>, MacStmtStyle),
691 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
692 pub enum MacStmtStyle {
693 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
694 /// `foo!(...);`, `foo![...];`
695 MacStmtWithSemicolon,
696 /// The macro statement had braces; e.g. foo! { ... }
698 /// The macro statement had parentheses or brackets and no semicolon; e.g.
699 /// `foo!(...)`. All of these will end up being converted into macro
701 MacStmtWithoutBraces,
704 // FIXME (pending discussion of #1697, #2178...): local should really be
705 // a refinement on pat.
706 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
707 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
710 pub ty: Option<P<Ty>>,
711 /// Initializer expression to set the value, if any
712 pub init: Option<P<Expr>>,
717 pub type Decl = Spanned<Decl_>;
719 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
721 /// A local (let) binding:
727 /// represents one arm of a 'match'
728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
730 pub attrs: Vec<Attribute>,
731 pub pats: Vec<P<Pat>>,
732 pub guard: Option<P<Expr>>,
736 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
738 pub ident: SpannedIdent,
743 pub type SpannedIdent = Spanned<Ident>;
745 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
746 pub enum BlockCheckMode {
748 UnsafeBlock(UnsafeSource),
749 PushUnsafeBlock(UnsafeSource),
750 PopUnsafeBlock(UnsafeSource),
753 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
754 pub enum UnsafeSource {
760 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
767 impl fmt::Debug for Expr {
768 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
769 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
773 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
775 /// A `box x` expression.
777 /// First expr is the place; second expr is the value.
778 ExprInPlace(P<Expr>, P<Expr>),
779 /// An array (`[a, b, c, d]`)
780 ExprVec(Vec<P<Expr>>),
783 /// The first field resolves to the function itself,
784 /// and the second field is the list of arguments
785 ExprCall(P<Expr>, Vec<P<Expr>>),
786 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
788 /// The `SpannedIdent` is the identifier for the method name.
789 /// The vector of `Ty`s are the ascripted type parameters for the method
790 /// (within the angle brackets).
792 /// The first element of the vector of `Expr`s is the expression that evaluates
793 /// to the object on which the method is being called on (the receiver),
794 /// and the remaining elements are the rest of the arguments.
796 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
797 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
798 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
799 /// A tuple (`(a, b, c ,d)`)
800 ExprTup(Vec<P<Expr>>),
801 /// A binary operation (For example: `a + b`, `a * b`)
802 ExprBinary(BinOp, P<Expr>, P<Expr>),
803 /// A unary operation (For example: `!x`, `*x`)
804 ExprUnary(UnOp, P<Expr>),
805 /// A literal (For example: `1u8`, `"foo"`)
807 /// A cast (`foo as f64`)
808 ExprCast(P<Expr>, P<Ty>),
809 /// An `if` block, with an optional else block
811 /// `if expr { block } else { expr }`
812 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
813 /// An `if let` expression with an optional else block
815 /// `if let pat = expr { block } else { expr }`
817 /// This is desugared to a `match` expression.
818 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
819 /// A while loop, with an optional label
821 /// `'label: while expr { block }`
822 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
823 /// A while-let loop, with an optional label
825 /// `'label: while let pat = expr { block }`
827 /// This is desugared to a combination of `loop` and `match` expressions.
828 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
829 /// A for loop, with an optional label
831 /// `'label: for pat in expr { block }`
833 /// This is desugared to a combination of `loop` and `match` expressions.
834 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
835 /// Conditionless loop (can be exited with break, continue, or return)
837 /// `'label: loop { block }`
838 ExprLoop(P<Block>, Option<Ident>),
839 /// A `match` block, with a source that indicates whether or not it is
840 /// the result of a desugaring, and if so, which kind.
841 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
842 /// A closure (for example, `move |a, b, c| {a + b + c}`)
843 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
844 /// A block (`{ ... }`)
847 /// An assignment (`a = foo()`)
848 ExprAssign(P<Expr>, P<Expr>),
849 /// An assignment with an operator
851 /// For example, `a += 1`.
852 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
853 /// Access of a named struct field (`obj.foo`)
854 ExprField(P<Expr>, SpannedIdent),
855 /// Access of an unnamed field of a struct or tuple-struct
857 /// For example, `foo.0`.
858 ExprTupField(P<Expr>, Spanned<usize>),
859 /// An indexing operation (`foo[2]`)
860 ExprIndex(P<Expr>, P<Expr>),
861 /// A range (`1..2`, `1..`, or `..2`)
862 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
864 /// Variable reference, possibly containing `::` and/or type
865 /// parameters, e.g. foo::bar::<baz>.
867 /// Optionally "qualified",
868 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
869 ExprPath(Option<QSelf>, Path),
871 /// A referencing operation (`&a` or `&mut a`)
872 ExprAddrOf(Mutability, P<Expr>),
873 /// A `break`, with an optional label to break
874 ExprBreak(Option<SpannedIdent>),
875 /// A `continue`, with an optional label
876 ExprAgain(Option<SpannedIdent>),
877 /// A `return`, with an optional value to be returned
878 ExprRet(Option<P<Expr>>),
880 /// Output of the `asm!()` macro
881 ExprInlineAsm(InlineAsm),
883 /// A macro invocation; pre-expansion
886 /// A struct literal expression.
888 /// For example, `Foo {x: 1, y: 2}`, or
889 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
890 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
892 /// An array literal constructed from one repeated element.
894 /// For example, `[1u8; 5]`. The first expression is the element
895 /// to be repeated; the second is the number of times to repeat it.
896 ExprRepeat(P<Expr>, P<Expr>),
898 /// No-op: used solely so we can pretty-print faithfully
902 /// The explicit Self type in a "qualified path". The actual
903 /// path, including the trait and the associated item, is stored
904 /// separately. `position` represents the index of the associated
905 /// item qualified with this Self type.
907 /// <Vec<T> as a::b::Trait>::AssociatedItem
908 /// ^~~~~ ~~~~~~~~~~~~~~^
911 /// <Vec<T>>::AssociatedItem
914 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
920 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
921 pub enum MatchSource {
923 IfLetDesugar { contains_else_clause: bool },
928 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
929 pub enum CaptureClause {
934 /// A delimited sequence of token trees
935 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
936 pub struct Delimited {
937 /// The type of delimiter
938 pub delim: token::DelimToken,
939 /// The span covering the opening delimiter
941 /// The delimited sequence of token trees
942 pub tts: Vec<TokenTree>,
943 /// The span covering the closing delimiter
944 pub close_span: Span,
948 /// Returns the opening delimiter as a token.
949 pub fn open_token(&self) -> token::Token {
950 token::OpenDelim(self.delim)
953 /// Returns the closing delimiter as a token.
954 pub fn close_token(&self) -> token::Token {
955 token::CloseDelim(self.delim)
958 /// Returns the opening delimiter as a token tree.
959 pub fn open_tt(&self) -> TokenTree {
960 TtToken(self.open_span, self.open_token())
963 /// Returns the closing delimiter as a token tree.
964 pub fn close_tt(&self) -> TokenTree {
965 TtToken(self.close_span, self.close_token())
969 /// A sequence of token treesee
970 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
971 pub struct SequenceRepetition {
972 /// The sequence of token trees
973 pub tts: Vec<TokenTree>,
974 /// The optional separator
975 pub separator: Option<token::Token>,
976 /// Whether the sequence can be repeated zero (*), or one or more times (+)
978 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
979 pub num_captures: usize,
982 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
983 /// for token sequences.
984 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
990 /// When the main rust parser encounters a syntax-extension invocation, it
991 /// parses the arguments to the invocation as a token-tree. This is a very
992 /// loose structure, such that all sorts of different AST-fragments can
993 /// be passed to syntax extensions using a uniform type.
995 /// If the syntax extension is an MBE macro, it will attempt to match its
996 /// LHS token tree against the provided token tree, and if it finds a
997 /// match, will transcribe the RHS token tree, splicing in any captured
998 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1000 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1001 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1002 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1003 pub enum TokenTree {
1005 TtToken(Span, token::Token),
1006 /// A delimited sequence of token trees
1007 TtDelimited(Span, Rc<Delimited>),
1009 // This only makes sense in MBE macros.
1011 /// A kleene-style repetition sequence with a span
1012 // FIXME(eddyb) #12938 Use DST.
1013 TtSequence(Span, Rc<SequenceRepetition>),
1017 pub fn len(&self) -> usize {
1019 TtToken(_, token::DocComment(name)) => {
1020 match doc_comment_style(&name.as_str()) {
1021 AttrStyle::Outer => 2,
1022 AttrStyle::Inner => 3
1025 TtToken(_, token::SpecialVarNt(..)) => 2,
1026 TtToken(_, token::MatchNt(..)) => 3,
1027 TtDelimited(_, ref delimed) => {
1028 delimed.tts.len() + 2
1030 TtSequence(_, ref seq) => {
1037 pub fn get_tt(&self, index: usize) -> TokenTree {
1038 match (self, index) {
1039 (&TtToken(sp, token::DocComment(_)), 0) => {
1040 TtToken(sp, token::Pound)
1042 (&TtToken(sp, token::DocComment(name)), 1)
1043 if doc_comment_style(&name.as_str()) == AttrStyle::Inner => {
1044 TtToken(sp, token::Not)
1046 (&TtToken(sp, token::DocComment(name)), _) => {
1047 let stripped = strip_doc_comment_decoration(&name.as_str());
1048 TtDelimited(sp, Rc::new(Delimited {
1049 delim: token::Bracket,
1051 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1053 TtToken(sp, token::Eq),
1054 TtToken(sp, token::Literal(
1055 token::StrRaw(token::intern(&stripped), 0), None))],
1059 (&TtDelimited(_, ref delimed), _) => {
1061 return delimed.open_tt();
1063 if index == delimed.tts.len() + 1 {
1064 return delimed.close_tt();
1066 delimed.tts[index - 1].clone()
1068 (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1069 let v = [TtToken(sp, token::Dollar),
1070 TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1074 (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1075 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1076 TtToken(sp, token::Colon),
1077 TtToken(sp, token::Ident(kind, kind_st))];
1080 (&TtSequence(_, ref seq), _) => {
1081 seq.tts[index].clone()
1083 _ => panic!("Cannot expand a token tree")
1087 /// Returns the `Span` corresponding to this token tree.
1088 pub fn get_span(&self) -> Span {
1090 TtToken(span, _) => span,
1091 TtDelimited(span, _) => span,
1092 TtSequence(span, _) => span,
1096 /// Use this token tree as a matcher to parse given tts.
1097 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1098 -> macro_parser::NamedParseResult {
1099 // `None` is because we're not interpolating
1100 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1103 tts.iter().cloned().collect(),
1105 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1109 pub type Mac = Spanned<Mac_>;
1111 /// Represents a macro invocation. The Path indicates which macro
1112 /// is being invoked, and the vector of token-trees contains the source
1113 /// of the macro invocation.
1115 /// NB: the additional ident for a macro_rules-style macro is actually
1116 /// stored in the enclosing item. Oog.
1117 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1120 pub tts: Vec<TokenTree>,
1121 pub ctxt: SyntaxContext,
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: IntSign>(n: T) -> Sign {
1150 fn sign(&self) -> Sign;
1153 ($($t:ident)*) => ($(impl IntSign for $t {
1154 #[allow(unused_comparisons)]
1155 fn sign(&self) -> Sign {
1156 if *self < 0 {Minus} else {Plus}
1160 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1162 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1163 pub enum LitIntType {
1164 SignedIntLit(IntTy, Sign),
1165 UnsignedIntLit(UintTy),
1166 UnsuffixedIntLit(Sign)
1169 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1171 /// A string literal (`"foo"`)
1172 LitStr(InternedString, StrStyle),
1173 /// A byte string (`b"foo"`)
1174 LitByteStr(Rc<Vec<u8>>),
1175 /// A byte char (`b'f'`)
1177 /// A character literal (`'a'`)
1179 /// An integer literal (`1u8`)
1180 LitInt(u64, LitIntType),
1181 /// A float literal (`1f64` or `1E10f64`)
1182 LitFloat(InternedString, FloatTy),
1183 /// A float literal without a suffix (`1.0 or 1.0E10`)
1184 LitFloatUnsuffixed(InternedString),
1185 /// A boolean literal
1189 // NB: If you change this, you'll probably want to change the corresponding
1190 // type structure in middle/ty.rs as well.
1191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1194 pub mutbl: Mutability,
1197 /// Represents a method's signature in a trait declaration,
1198 /// or in an implementation.
1199 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1200 pub struct MethodSig {
1201 pub unsafety: Unsafety,
1202 pub constness: Constness,
1204 pub decl: P<FnDecl>,
1205 pub generics: Generics,
1206 pub explicit_self: ExplicitSelf,
1209 /// Represents a method declaration in a trait declaration, possibly including
1210 /// a default implementation A trait method is either required (meaning it
1211 /// doesn't have an implementation, just a signature) or provided (meaning it
1212 /// has a default implementation).
1213 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1214 pub struct TraitItem {
1217 pub attrs: Vec<Attribute>,
1218 pub node: TraitItem_,
1222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1223 pub enum TraitItem_ {
1224 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1225 MethodTraitItem(MethodSig, Option<P<Block>>),
1226 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1229 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1230 pub struct ImplItem {
1233 pub vis: Visibility,
1234 pub attrs: Vec<Attribute>,
1235 pub node: ImplItem_,
1239 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1240 pub enum ImplItem_ {
1241 ConstImplItem(P<Ty>, P<Expr>),
1242 MethodImplItem(MethodSig, P<Block>),
1243 TypeImplItem(P<Ty>),
1247 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1256 impl fmt::Debug for IntTy {
1257 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1258 fmt::Display::fmt(self, f)
1262 impl fmt::Display for IntTy {
1263 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1264 write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1269 pub fn bit_width(&self) -> Option<usize> {
1271 TyIs => return None,
1280 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1290 pub fn bit_width(&self) -> Option<usize> {
1292 TyUs => return None,
1301 impl fmt::Debug for UintTy {
1302 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1303 fmt::Display::fmt(self, f)
1307 impl fmt::Display for UintTy {
1308 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1309 write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1313 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1319 impl fmt::Debug for FloatTy {
1320 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1321 fmt::Display::fmt(self, f)
1325 impl fmt::Display for FloatTy {
1326 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1327 write!(f, "{}", ast_util::float_ty_to_string(*self))
1332 pub fn bit_width(&self) -> usize {
1340 // Bind a type to an associated type: `A=Foo`.
1341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1342 pub struct TypeBinding {
1349 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1356 impl fmt::Debug for Ty {
1357 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1358 write!(f, "type({})", pprust::ty_to_string(self))
1362 /// Not represented directly in the AST, referred to by name through a ty_path.
1363 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1373 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1374 pub struct BareFnTy {
1375 pub unsafety: Unsafety,
1377 pub lifetimes: Vec<LifetimeDef>,
1381 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1382 /// The different kinds of types recognized by the compiler
1385 /// A fixed length array (`[T; n]`)
1386 TyFixedLengthVec(P<Ty>, P<Expr>),
1387 /// A raw pointer (`*const T` or `*mut T`)
1389 /// A reference (`&'a T` or `&'a mut T`)
1390 TyRptr(Option<Lifetime>, MutTy),
1391 /// A bare function (e.g. `fn(usize) -> bool`)
1392 TyBareFn(P<BareFnTy>),
1393 /// A tuple (`(A, B, C, D,...)`)
1395 /// A path (`module::module::...::Type`), optionally
1396 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1398 /// Type parameters are stored in the Path itself
1399 TyPath(Option<QSelf>, Path),
1400 /// Something like `A+B`. Note that `B` must always be a path.
1401 TyObjectSum(P<Ty>, TyParamBounds),
1402 /// A type like `for<'a> Foo<&'a Bar>`
1403 TyPolyTraitRef(TyParamBounds),
1404 /// No-op; kept solely so that we can pretty-print faithfully
1408 /// TyInfer means the type should be inferred instead of it having been
1409 /// specified. This can appear anywhere in a type.
1411 // A macro in the type position.
1415 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1416 pub enum AsmDialect {
1421 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1422 pub struct InlineAsm {
1423 pub asm: InternedString,
1424 pub asm_str_style: StrStyle,
1425 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1426 pub inputs: Vec<(InternedString, P<Expr>)>,
1427 pub clobbers: Vec<InternedString>,
1429 pub alignstack: bool,
1430 pub dialect: AsmDialect,
1431 pub expn_id: ExpnId,
1434 /// represents an argument in a function header
1435 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1443 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1444 let path = Spanned{span:span,node:self_ident};
1446 // HACK(eddyb) fake type for the self argument.
1454 node: PatIdent(BindByValue(mutability), path, None),
1462 /// Represents the header (not the body) of a function declaration
1463 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1465 pub inputs: Vec<Arg>,
1466 pub output: FunctionRetTy,
1470 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1476 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1477 pub enum Constness {
1482 impl fmt::Display for Unsafety {
1483 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1484 fmt::Display::fmt(match *self {
1485 Unsafety::Normal => "normal",
1486 Unsafety::Unsafe => "unsafe",
1491 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1492 pub enum ImplPolarity {
1493 /// `impl Trait for Type`
1495 /// `impl !Trait for Type`
1499 impl fmt::Debug for ImplPolarity {
1500 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1502 ImplPolarity::Positive => "positive".fmt(f),
1503 ImplPolarity::Negative => "negative".fmt(f),
1509 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1510 pub enum FunctionRetTy {
1511 /// Functions with return type `!`that always
1512 /// raise an error or exit (i.e. never return to the caller)
1514 /// Return type is not specified.
1516 /// Functions default to `()` and
1517 /// closures default to inference. Span points to where return
1518 /// type would be inserted.
1519 DefaultReturn(Span),
1524 impl FunctionRetTy {
1525 pub fn span(&self) -> Span {
1527 NoReturn(span) => span,
1528 DefaultReturn(span) => span,
1529 Return(ref ty) => ty.span
1534 /// Represents the kind of 'self' associated with a method
1535 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub enum ExplicitSelf_ {
1541 /// `&'lt self`, `&'lt mut self`
1542 SelfRegion(Option<Lifetime>, Mutability, Ident),
1544 SelfExplicit(P<Ty>, Ident),
1547 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1549 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1551 /// A span from the first token past `{` to the last token until `}`.
1552 /// For `mod foo;`, the inner span ranges from the first token
1553 /// to the last token in the external file.
1555 pub items: Vec<P<Item>>,
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1559 pub struct ForeignMod {
1561 pub items: Vec<P<ForeignItem>>,
1564 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1565 pub struct VariantArg {
1570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1571 pub enum VariantKind {
1572 /// Tuple variant, e.g. `Foo(A, B)`
1573 TupleVariantKind(Vec<VariantArg>),
1574 /// Struct variant, e.g. `Foo {x: A, y: B}`
1575 StructVariantKind(P<StructDef>),
1578 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1579 pub struct EnumDef {
1580 pub variants: Vec<P<Variant>>,
1583 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1584 pub struct Variant_ {
1586 pub attrs: Vec<Attribute>,
1587 pub kind: VariantKind,
1589 /// Explicit discriminant, eg `Foo = 1`
1590 pub disr_expr: Option<P<Expr>>,
1593 pub type Variant = Spanned<Variant_>;
1595 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1596 pub enum PathListItem_ {
1599 /// renamed in list, eg `use foo::{bar as baz};`
1600 rename: Option<Ident>,
1604 /// renamed in list, eg `use foo::{self as baz};`
1605 rename: Option<Ident>,
1610 impl PathListItem_ {
1611 pub fn id(&self) -> NodeId {
1613 PathListIdent { id, .. } | PathListMod { id, .. } => id
1617 pub fn name(&self) -> Option<Ident> {
1619 PathListIdent { name, .. } => Some(name),
1620 PathListMod { .. } => None,
1624 pub fn rename(&self) -> Option<Ident> {
1626 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1631 pub type PathListItem = Spanned<PathListItem_>;
1633 pub type ViewPath = Spanned<ViewPath_>;
1635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1636 pub enum ViewPath_ {
1638 /// `foo::bar::baz as quux`
1642 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1643 ViewPathSimple(Ident, Path),
1648 /// `foo::bar::{a,b,c}`
1649 ViewPathList(Path, Vec<PathListItem>)
1652 /// Meta-data associated with an item
1653 pub type Attribute = Spanned<Attribute_>;
1655 /// Distinguishes between Attributes that decorate items and Attributes that
1656 /// are contained as statements within items. These two cases need to be
1657 /// distinguished for pretty-printing.
1658 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1659 pub enum AttrStyle {
1664 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1665 pub struct AttrId(pub usize);
1667 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1668 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1669 pub struct Attribute_ {
1671 pub style: AttrStyle,
1672 pub value: P<MetaItem>,
1673 pub is_sugared_doc: bool,
1676 /// TraitRef's appear in impls.
1678 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1679 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1680 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1681 /// same as the impl's node id).
1682 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1683 pub struct TraitRef {
1688 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1689 pub struct PolyTraitRef {
1690 /// The `'a` in `<'a> Foo<&'a T>`
1691 pub bound_lifetimes: Vec<LifetimeDef>,
1693 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1694 pub trait_ref: TraitRef,
1699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1700 pub enum Visibility {
1706 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1708 &Inherited => parent_visibility,
1714 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1715 pub struct StructField_ {
1716 pub kind: StructFieldKind,
1719 pub attrs: Vec<Attribute>,
1723 pub fn ident(&self) -> Option<Ident> {
1725 NamedField(ref ident, _) => Some(ident.clone()),
1726 UnnamedField(_) => None
1731 pub type StructField = Spanned<StructField_>;
1733 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1734 pub enum StructFieldKind {
1735 NamedField(Ident, Visibility),
1736 /// Element of a tuple-like struct
1737 UnnamedField(Visibility),
1740 impl StructFieldKind {
1741 pub fn is_unnamed(&self) -> bool {
1743 UnnamedField(..) => true,
1744 NamedField(..) => false,
1749 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1750 pub struct StructDef {
1751 /// Fields, not including ctor
1752 pub fields: Vec<StructField>,
1753 /// ID of the constructor. This is only used for tuple- or enum-like
1755 pub ctor_id: Option<NodeId>,
1759 FIXME (#3300): Should allow items to be anonymous. Right now
1760 we just use dummy names for anon items.
1764 /// The name might be a dummy name in case of anonymous items
1765 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1768 pub attrs: Vec<Attribute>,
1771 pub vis: Visibility,
1775 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1777 /// An`extern crate` item, with optional original crate name,
1779 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1780 ItemExternCrate(Option<Name>),
1781 /// A `use` or `pub use` item
1782 ItemUse(P<ViewPath>),
1785 ItemStatic(P<Ty>, Mutability, P<Expr>),
1787 ItemConst(P<Ty>, P<Expr>),
1788 /// A function declaration
1789 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1792 /// An external module
1793 ItemForeignMod(ForeignMod),
1794 /// A type alias, e.g. `type Foo = Bar<u8>`
1795 ItemTy(P<Ty>, Generics),
1796 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1797 ItemEnum(EnumDef, Generics),
1798 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1799 ItemStruct(P<StructDef>, Generics),
1800 /// Represents a Trait Declaration
1806 // Default trait implementations
1808 // `impl Trait for .. {}`
1809 ItemDefaultImpl(Unsafety, TraitRef),
1810 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1814 Option<TraitRef>, // (optional) trait this impl implements
1817 /// A macro invocation (which includes macro definition)
1822 pub fn descriptive_variant(&self) -> &str {
1824 ItemExternCrate(..) => "extern crate",
1825 ItemUse(..) => "use",
1826 ItemStatic(..) => "static item",
1827 ItemConst(..) => "constant item",
1828 ItemFn(..) => "function",
1829 ItemMod(..) => "module",
1830 ItemForeignMod(..) => "foreign module",
1831 ItemTy(..) => "type alias",
1832 ItemEnum(..) => "enum",
1833 ItemStruct(..) => "struct",
1834 ItemTrait(..) => "trait",
1837 ItemDefaultImpl(..) => "item"
1842 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1843 pub struct ForeignItem {
1845 pub attrs: Vec<Attribute>,
1846 pub node: ForeignItem_,
1849 pub vis: Visibility,
1852 /// An item within an `extern` block
1853 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1854 pub enum ForeignItem_ {
1855 /// A foreign function
1856 ForeignItemFn(P<FnDecl>, Generics),
1857 /// A foreign static item (`static ext: u8`), with optional mutability
1858 /// (the boolean is true when mutable)
1859 ForeignItemStatic(P<Ty>, bool),
1863 pub fn descriptive_variant(&self) -> &str {
1865 ForeignItemFn(..) => "foreign function",
1866 ForeignItemStatic(..) => "foreign static item"
1871 /// A macro definition, in this crate or imported from another.
1873 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1874 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1875 pub struct MacroDef {
1877 pub attrs: Vec<Attribute>,
1880 pub imported_from: Option<Ident>,
1882 pub use_locally: bool,
1883 pub allow_internal_unstable: bool,
1884 pub body: Vec<TokenTree>,
1892 // are ASTs encodable?
1894 fn check_asts_encodable() {
1895 fn assert_encodable<T: serialize::Encodable>() {}
1896 assert_encodable::<Crate>();