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::AttrStyle::*;
14 pub use self::BindingMode::*;
15 pub use self::BinOp_::*;
16 pub use self::BlockCheckMode::*;
17 pub use self::CaptureClause::*;
18 pub use self::Decl_::*;
19 pub use self::ExplicitSelf_::*;
20 pub use self::Expr_::*;
21 pub use self::FloatTy::*;
22 pub use self::FunctionRetTy::*;
23 pub use self::ForeignItem_::*;
24 pub use self::ImplItem_::*;
25 pub use self::IntTy::*;
26 pub use self::Item_::*;
27 pub use self::KleeneOp::*;
28 pub use self::Lit_::*;
29 pub use self::LitIntType::*;
30 pub use self::MacStmtStyle::*;
31 pub use self::MetaItem_::*;
32 pub use self::Mutability::*;
33 pub use self::Pat_::*;
34 pub use self::PathListItem_::*;
35 pub use self::PatWildKind::*;
36 pub use self::PrimTy::*;
37 pub use self::Sign::*;
38 pub use self::Stmt_::*;
39 pub use self::StrStyle::*;
40 pub use self::StructFieldKind::*;
41 pub use self::TokenTree::*;
42 pub use self::TraitItem_::*;
44 pub use self::TyParamBound::*;
45 pub use self::UintTy::*;
46 pub use self::UnOp::*;
47 pub use self::UnsafeSource::*;
48 pub use self::VariantKind::*;
49 pub use self::ViewPath_::*;
50 pub use self::Visibility::*;
51 pub use self::PathParameters::*;
53 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
57 use ext::tt::macro_parser;
58 use owned_slice::OwnedSlice;
59 use parse::token::{InternedString, str_to_ident};
62 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> {
169 s.emit_str(&self.name.as_str())
173 impl Decodable for Ident {
174 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
175 Ok(str_to_ident(&try!(d.read_str())[..]))
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 pprust::stmt_to_string(self))
677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
679 /// Could be an item or a local (let) binding:
680 StmtDecl(P<Decl>, NodeId),
682 /// Expr without trailing semi-colon (must have unit type):
683 StmtExpr(P<Expr>, NodeId),
685 /// Expr with trailing semi-colon (may have any type):
686 StmtSemi(P<Expr>, NodeId),
688 StmtMac(P<Mac>, MacStmtStyle),
690 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
691 pub enum MacStmtStyle {
692 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
693 /// `foo!(...);`, `foo![...];`
694 MacStmtWithSemicolon,
695 /// The macro statement had braces; e.g. foo! { ... }
697 /// The macro statement had parentheses or brackets and no semicolon; e.g.
698 /// `foo!(...)`. All of these will end up being converted into macro
700 MacStmtWithoutBraces,
703 // FIXME (pending discussion of #1697, #2178...): local should really be
704 // a refinement on pat.
705 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
706 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
709 pub ty: Option<P<Ty>>,
710 /// Initializer expression to set the value, if any
711 pub init: Option<P<Expr>>,
716 pub type Decl = Spanned<Decl_>;
718 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
720 /// A local (let) binding:
726 /// represents one arm of a 'match'
727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
729 pub attrs: Vec<Attribute>,
730 pub pats: Vec<P<Pat>>,
731 pub guard: Option<P<Expr>>,
735 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
737 pub ident: SpannedIdent,
742 pub type SpannedIdent = Spanned<Ident>;
744 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
745 pub enum BlockCheckMode {
747 UnsafeBlock(UnsafeSource),
748 PushUnsafeBlock(UnsafeSource),
749 PopUnsafeBlock(UnsafeSource),
752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
753 pub enum UnsafeSource {
759 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
766 impl fmt::Debug for Expr {
767 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
768 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
772 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
774 /// A `box x` expression.
776 /// First expr is the place; second expr is the value.
777 ExprInPlace(P<Expr>, P<Expr>),
778 /// An array (`[a, b, c, d]`)
779 ExprVec(Vec<P<Expr>>),
782 /// The first field resolves to the function itself,
783 /// and the second field is the list of arguments
784 ExprCall(P<Expr>, Vec<P<Expr>>),
785 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
787 /// The `SpannedIdent` is the identifier for the method name.
788 /// The vector of `Ty`s are the ascripted type parameters for the method
789 /// (within the angle brackets).
791 /// The first element of the vector of `Expr`s is the expression that evaluates
792 /// to the object on which the method is being called on (the receiver),
793 /// and the remaining elements are the rest of the arguments.
795 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
796 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
797 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
798 /// A tuple (`(a, b, c ,d)`)
799 ExprTup(Vec<P<Expr>>),
800 /// A binary operation (For example: `a + b`, `a * b`)
801 ExprBinary(BinOp, P<Expr>, P<Expr>),
802 /// A unary operation (For example: `!x`, `*x`)
803 ExprUnary(UnOp, P<Expr>),
804 /// A literal (For example: `1u8`, `"foo"`)
806 /// A cast (`foo as f64`)
807 ExprCast(P<Expr>, P<Ty>),
808 /// An `if` block, with an optional else block
810 /// `if expr { block } else { expr }`
811 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
812 /// An `if let` expression with an optional else block
814 /// `if let pat = expr { block } else { expr }`
816 /// This is desugared to a `match` expression.
817 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
818 /// A while loop, with an optional label
820 /// `'label: while expr { block }`
821 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
822 /// A while-let loop, with an optional label
824 /// `'label: while let pat = expr { block }`
826 /// This is desugared to a combination of `loop` and `match` expressions.
827 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
828 /// A for loop, with an optional label
830 /// `'label: for pat in expr { block }`
832 /// This is desugared to a combination of `loop` and `match` expressions.
833 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
834 /// Conditionless loop (can be exited with break, continue, or return)
836 /// `'label: loop { block }`
837 ExprLoop(P<Block>, Option<Ident>),
838 /// A `match` block, with a source that indicates whether or not it is
839 /// the result of a desugaring, and if so, which kind.
840 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
841 /// A closure (for example, `move |a, b, c| {a + b + c}`)
842 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
843 /// A block (`{ ... }`)
846 /// An assignment (`a = foo()`)
847 ExprAssign(P<Expr>, P<Expr>),
848 /// An assignment with an operator
850 /// For example, `a += 1`.
851 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
852 /// Access of a named struct field (`obj.foo`)
853 ExprField(P<Expr>, SpannedIdent),
854 /// Access of an unnamed field of a struct or tuple-struct
856 /// For example, `foo.0`.
857 ExprTupField(P<Expr>, Spanned<usize>),
858 /// An indexing operation (`foo[2]`)
859 ExprIndex(P<Expr>, P<Expr>),
860 /// A range (`1..2`, `1..`, or `..2`)
861 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
863 /// Variable reference, possibly containing `::` and/or type
864 /// parameters, e.g. foo::bar::<baz>.
866 /// Optionally "qualified",
867 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
868 ExprPath(Option<QSelf>, Path),
870 /// A referencing operation (`&a` or `&mut a`)
871 ExprAddrOf(Mutability, P<Expr>),
872 /// A `break`, with an optional label to break
873 ExprBreak(Option<SpannedIdent>),
874 /// A `continue`, with an optional label
875 ExprAgain(Option<SpannedIdent>),
876 /// A `return`, with an optional value to be returned
877 ExprRet(Option<P<Expr>>),
879 /// Output of the `asm!()` macro
880 ExprInlineAsm(InlineAsm),
882 /// A macro invocation; pre-expansion
885 /// A struct literal expression.
887 /// For example, `Foo {x: 1, y: 2}`, or
888 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
889 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
891 /// An array literal constructed from one repeated element.
893 /// For example, `[1u8; 5]`. The first expression is the element
894 /// to be repeated; the second is the number of times to repeat it.
895 ExprRepeat(P<Expr>, P<Expr>),
897 /// No-op: used solely so we can pretty-print faithfully
901 /// The explicit Self type in a "qualified path". The actual
902 /// path, including the trait and the associated item, is stored
903 /// separately. `position` represents the index of the associated
904 /// item qualified with this Self type.
906 /// <Vec<T> as a::b::Trait>::AssociatedItem
907 /// ^~~~~ ~~~~~~~~~~~~~~^
910 /// <Vec<T>>::AssociatedItem
913 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
919 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
920 pub enum MatchSource {
922 IfLetDesugar { contains_else_clause: bool },
927 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
928 pub enum CaptureClause {
933 /// A delimited sequence of token trees
934 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
935 pub struct Delimited {
936 /// The type of delimiter
937 pub delim: token::DelimToken,
938 /// The span covering the opening delimiter
940 /// The delimited sequence of token trees
941 pub tts: Vec<TokenTree>,
942 /// The span covering the closing delimiter
943 pub close_span: Span,
947 /// Returns the opening delimiter as a token.
948 pub fn open_token(&self) -> token::Token {
949 token::OpenDelim(self.delim)
952 /// Returns the closing delimiter as a token.
953 pub fn close_token(&self) -> token::Token {
954 token::CloseDelim(self.delim)
957 /// Returns the opening delimiter as a token tree.
958 pub fn open_tt(&self) -> TokenTree {
959 TtToken(self.open_span, self.open_token())
962 /// Returns the closing delimiter as a token tree.
963 pub fn close_tt(&self) -> TokenTree {
964 TtToken(self.close_span, self.close_token())
968 /// A sequence of token treesee
969 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
970 pub struct SequenceRepetition {
971 /// The sequence of token trees
972 pub tts: Vec<TokenTree>,
973 /// The optional separator
974 pub separator: Option<token::Token>,
975 /// Whether the sequence can be repeated zero (*), or one or more times (+)
977 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
978 pub num_captures: usize,
981 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
982 /// for token sequences.
983 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
989 /// When the main rust parser encounters a syntax-extension invocation, it
990 /// parses the arguments to the invocation as a token-tree. This is a very
991 /// loose structure, such that all sorts of different AST-fragments can
992 /// be passed to syntax extensions using a uniform type.
994 /// If the syntax extension is an MBE macro, it will attempt to match its
995 /// LHS token tree against the provided token tree, and if it finds a
996 /// match, will transcribe the RHS token tree, splicing in any captured
997 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
999 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1000 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1001 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1002 pub enum TokenTree {
1004 TtToken(Span, token::Token),
1005 /// A delimited sequence of token trees
1006 TtDelimited(Span, Rc<Delimited>),
1008 // This only makes sense in MBE macros.
1010 /// A kleene-style repetition sequence with a span
1011 // FIXME(eddyb) #12938 Use DST.
1012 TtSequence(Span, Rc<SequenceRepetition>),
1016 pub fn len(&self) -> usize {
1018 TtToken(_, token::DocComment(name)) => {
1019 match doc_comment_style(&name.as_str()) {
1024 TtToken(_, token::SpecialVarNt(..)) => 2,
1025 TtToken(_, token::MatchNt(..)) => 3,
1026 TtDelimited(_, ref delimed) => {
1027 delimed.tts.len() + 2
1029 TtSequence(_, ref seq) => {
1036 pub fn get_tt(&self, index: usize) -> TokenTree {
1037 match (self, index) {
1038 (&TtToken(sp, token::DocComment(_)), 0) => {
1039 TtToken(sp, token::Pound)
1041 (&TtToken(sp, token::DocComment(name)), 1)
1042 if doc_comment_style(&name.as_str()) == AttrInner => {
1043 TtToken(sp, token::Not)
1045 (&TtToken(sp, token::DocComment(name)), _) => {
1046 let stripped = strip_doc_comment_decoration(&name.as_str());
1047 TtDelimited(sp, Rc::new(Delimited {
1048 delim: token::Bracket,
1050 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1052 TtToken(sp, token::Eq),
1053 TtToken(sp, token::Literal(
1054 token::StrRaw(token::intern(&stripped), 0), None))],
1058 (&TtDelimited(_, ref delimed), _) => {
1060 return delimed.open_tt();
1062 if index == delimed.tts.len() + 1 {
1063 return delimed.close_tt();
1065 delimed.tts[index - 1].clone()
1067 (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1068 let v = [TtToken(sp, token::Dollar),
1069 TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1073 (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1074 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1075 TtToken(sp, token::Colon),
1076 TtToken(sp, token::Ident(kind, kind_st))];
1079 (&TtSequence(_, ref seq), _) => {
1080 seq.tts[index].clone()
1082 _ => panic!("Cannot expand a token tree")
1086 /// Returns the `Span` corresponding to this token tree.
1087 pub fn get_span(&self) -> Span {
1089 TtToken(span, _) => span,
1090 TtDelimited(span, _) => span,
1091 TtSequence(span, _) => span,
1095 /// Use this token tree as a matcher to parse given tts.
1096 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1097 -> macro_parser::NamedParseResult {
1098 // `None` is because we're not interpolating
1099 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1102 tts.iter().cloned().collect(),
1104 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1108 pub type Mac = Spanned<Mac_>;
1110 /// Represents a macro invocation. The Path indicates which macro
1111 /// is being invoked, and the vector of token-trees contains the source
1112 /// of the macro invocation.
1114 /// NB: the additional ident for a macro_rules-style macro is actually
1115 /// stored in the enclosing item. Oog.
1116 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1119 pub tts: Vec<TokenTree>,
1120 pub ctxt: SyntaxContext,
1123 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1125 /// A regular string, like `"foo"`
1127 /// A raw string, like `r##"foo"##`
1129 /// The uint is the number of `#` symbols used
1134 pub type Lit = Spanned<Lit_>;
1136 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1143 pub fn new<T: IntSign>(n: T) -> Sign {
1149 fn sign(&self) -> Sign;
1152 ($($t:ident)*) => ($(impl IntSign for $t {
1153 #[allow(unused_comparisons)]
1154 fn sign(&self) -> Sign {
1155 if *self < 0 {Minus} else {Plus}
1159 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1161 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1162 pub enum LitIntType {
1163 SignedIntLit(IntTy, Sign),
1164 UnsignedIntLit(UintTy),
1165 UnsuffixedIntLit(Sign)
1168 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1170 /// A string literal (`"foo"`)
1171 LitStr(InternedString, StrStyle),
1172 /// A byte string (`b"foo"`)
1173 LitByteStr(Rc<Vec<u8>>),
1174 /// A byte char (`b'f'`)
1176 /// A character literal (`'a'`)
1178 /// An integer literal (`1u8`)
1179 LitInt(u64, LitIntType),
1180 /// A float literal (`1f64` or `1E10f64`)
1181 LitFloat(InternedString, FloatTy),
1182 /// A float literal without a suffix (`1.0 or 1.0E10`)
1183 LitFloatUnsuffixed(InternedString),
1184 /// A boolean literal
1188 // NB: If you change this, you'll probably want to change the corresponding
1189 // type structure in middle/ty.rs as well.
1190 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1193 pub mutbl: Mutability,
1196 /// Represents a method's signature in a trait declaration,
1197 /// or in an implementation.
1198 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1199 pub struct MethodSig {
1200 pub unsafety: Unsafety,
1201 pub constness: Constness,
1203 pub decl: P<FnDecl>,
1204 pub generics: Generics,
1205 pub explicit_self: ExplicitSelf,
1208 /// Represents a method declaration in a trait declaration, possibly including
1209 /// a default implementation A trait method is either required (meaning it
1210 /// doesn't have an implementation, just a signature) or provided (meaning it
1211 /// has a default implementation).
1212 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1213 pub struct TraitItem {
1216 pub attrs: Vec<Attribute>,
1217 pub node: TraitItem_,
1221 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1222 pub enum TraitItem_ {
1223 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1224 MethodTraitItem(MethodSig, Option<P<Block>>),
1225 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1229 pub struct ImplItem {
1232 pub vis: Visibility,
1233 pub attrs: Vec<Attribute>,
1234 pub node: ImplItem_,
1238 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1239 pub enum ImplItem_ {
1240 ConstImplItem(P<Ty>, P<Expr>),
1241 MethodImplItem(MethodSig, P<Block>),
1242 TypeImplItem(P<Ty>),
1246 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1255 impl fmt::Debug for IntTy {
1256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1257 fmt::Display::fmt(self, f)
1261 impl fmt::Display for IntTy {
1262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1263 write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1268 pub fn bit_width(&self) -> Option<usize> {
1270 TyIs => return None,
1279 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1289 pub fn bit_width(&self) -> Option<usize> {
1291 TyUs => return None,
1300 impl fmt::Debug for UintTy {
1301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1302 fmt::Display::fmt(self, f)
1306 impl fmt::Display for UintTy {
1307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1308 write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1312 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1318 impl fmt::Debug for FloatTy {
1319 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1320 fmt::Display::fmt(self, f)
1324 impl fmt::Display for FloatTy {
1325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1326 write!(f, "{}", ast_util::float_ty_to_string(*self))
1331 pub fn bit_width(&self) -> usize {
1339 // Bind a type to an associated type: `A=Foo`.
1340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1341 pub struct TypeBinding {
1348 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1355 impl fmt::Debug for Ty {
1356 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1357 write!(f, "type({})", pprust::ty_to_string(self))
1361 /// Not represented directly in the AST, referred to by name through a ty_path.
1362 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1372 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1373 pub struct BareFnTy {
1374 pub unsafety: Unsafety,
1376 pub lifetimes: Vec<LifetimeDef>,
1380 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1381 /// The different kinds of types recognized by the compiler
1384 /// A fixed length array (`[T; n]`)
1385 TyFixedLengthVec(P<Ty>, P<Expr>),
1386 /// A raw pointer (`*const T` or `*mut T`)
1388 /// A reference (`&'a T` or `&'a mut T`)
1389 TyRptr(Option<Lifetime>, MutTy),
1390 /// A bare function (e.g. `fn(usize) -> bool`)
1391 TyBareFn(P<BareFnTy>),
1392 /// A tuple (`(A, B, C, D,...)`)
1394 /// A path (`module::module::...::Type`), optionally
1395 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1397 /// Type parameters are stored in the Path itself
1398 TyPath(Option<QSelf>, Path),
1399 /// Something like `A+B`. Note that `B` must always be a path.
1400 TyObjectSum(P<Ty>, TyParamBounds),
1401 /// A type like `for<'a> Foo<&'a Bar>`
1402 TyPolyTraitRef(TyParamBounds),
1403 /// No-op; kept solely so that we can pretty-print faithfully
1407 /// TyInfer means the type should be inferred instead of it having been
1408 /// specified. This can appear anywhere in a type.
1410 // A macro in the type position.
1414 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1415 pub enum AsmDialect {
1420 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1421 pub struct InlineAsm {
1422 pub asm: InternedString,
1423 pub asm_str_style: StrStyle,
1424 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1425 pub inputs: Vec<(InternedString, P<Expr>)>,
1426 pub clobbers: Vec<InternedString>,
1428 pub alignstack: bool,
1429 pub dialect: AsmDialect,
1430 pub expn_id: ExpnId,
1433 /// represents an argument in a function header
1434 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1442 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1443 let path = Spanned{span:span,node:self_ident};
1445 // HACK(eddyb) fake type for the self argument.
1453 node: PatIdent(BindByValue(mutability), path, None),
1461 /// Represents the header (not the body) of a function declaration
1462 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1464 pub inputs: Vec<Arg>,
1465 pub output: FunctionRetTy,
1469 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1475 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1476 pub enum Constness {
1481 impl fmt::Display for Unsafety {
1482 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1483 fmt::Display::fmt(match *self {
1484 Unsafety::Normal => "normal",
1485 Unsafety::Unsafe => "unsafe",
1490 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1491 pub enum ImplPolarity {
1492 /// `impl Trait for Type`
1494 /// `impl !Trait for Type`
1498 impl fmt::Debug for ImplPolarity {
1499 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1501 ImplPolarity::Positive => "positive".fmt(f),
1502 ImplPolarity::Negative => "negative".fmt(f),
1508 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1509 pub enum FunctionRetTy {
1510 /// Functions with return type `!`that always
1511 /// raise an error or exit (i.e. never return to the caller)
1513 /// Return type is not specified.
1515 /// Functions default to `()` and
1516 /// closures default to inference. Span points to where return
1517 /// type would be inserted.
1518 DefaultReturn(Span),
1523 impl FunctionRetTy {
1524 pub fn span(&self) -> Span {
1526 NoReturn(span) => span,
1527 DefaultReturn(span) => span,
1528 Return(ref ty) => ty.span
1533 /// Represents the kind of 'self' associated with a method
1534 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1535 pub enum ExplicitSelf_ {
1540 /// `&'lt self`, `&'lt mut self`
1541 SelfRegion(Option<Lifetime>, Mutability, Ident),
1543 SelfExplicit(P<Ty>, Ident),
1546 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1548 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1550 /// A span from the first token past `{` to the last token until `}`.
1551 /// For `mod foo;`, the inner span ranges from the first token
1552 /// to the last token in the external file.
1554 pub items: Vec<P<Item>>,
1557 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1558 pub struct ForeignMod {
1560 pub items: Vec<P<ForeignItem>>,
1563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1564 pub struct VariantArg {
1569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1570 pub enum VariantKind {
1571 /// Tuple variant, e.g. `Foo(A, B)`
1572 TupleVariantKind(Vec<VariantArg>),
1573 /// Struct variant, e.g. `Foo {x: A, y: B}`
1574 StructVariantKind(P<StructDef>),
1577 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1578 pub struct EnumDef {
1579 pub variants: Vec<P<Variant>>,
1582 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1583 pub struct Variant_ {
1585 pub attrs: Vec<Attribute>,
1586 pub kind: VariantKind,
1588 /// Explicit discriminant, eg `Foo = 1`
1589 pub disr_expr: Option<P<Expr>>,
1592 pub type Variant = Spanned<Variant_>;
1594 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1595 pub enum PathListItem_ {
1598 /// renamed in list, eg `use foo::{bar as baz};`
1599 rename: Option<Ident>,
1603 /// renamed in list, eg `use foo::{self as baz};`
1604 rename: Option<Ident>,
1609 impl PathListItem_ {
1610 pub fn id(&self) -> NodeId {
1612 PathListIdent { id, .. } | PathListMod { id, .. } => id
1616 pub fn rename(&self) -> Option<Ident> {
1618 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1623 pub type PathListItem = Spanned<PathListItem_>;
1625 pub type ViewPath = Spanned<ViewPath_>;
1627 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1628 pub enum ViewPath_ {
1630 /// `foo::bar::baz as quux`
1634 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1635 ViewPathSimple(Ident, Path),
1640 /// `foo::bar::{a,b,c}`
1641 ViewPathList(Path, Vec<PathListItem>)
1644 /// Meta-data associated with an item
1645 pub type Attribute = Spanned<Attribute_>;
1647 /// Distinguishes between Attributes that decorate items and Attributes that
1648 /// are contained as statements within items. These two cases need to be
1649 /// distinguished for pretty-printing.
1650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1651 pub enum AttrStyle {
1656 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1657 pub struct AttrId(pub usize);
1659 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1660 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1661 pub struct Attribute_ {
1663 pub style: AttrStyle,
1664 pub value: P<MetaItem>,
1665 pub is_sugared_doc: bool,
1668 /// TraitRef's appear in impls.
1670 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1671 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1672 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1673 /// same as the impl's node id).
1674 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1675 pub struct TraitRef {
1680 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1681 pub struct PolyTraitRef {
1682 /// The `'a` in `<'a> Foo<&'a T>`
1683 pub bound_lifetimes: Vec<LifetimeDef>,
1685 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1686 pub trait_ref: TraitRef,
1691 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1692 pub enum Visibility {
1698 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1700 &Inherited => parent_visibility,
1706 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1707 pub struct StructField_ {
1708 pub kind: StructFieldKind,
1711 pub attrs: Vec<Attribute>,
1715 pub fn ident(&self) -> Option<Ident> {
1717 NamedField(ref ident, _) => Some(ident.clone()),
1718 UnnamedField(_) => None
1723 pub type StructField = Spanned<StructField_>;
1725 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1726 pub enum StructFieldKind {
1727 NamedField(Ident, Visibility),
1728 /// Element of a tuple-like struct
1729 UnnamedField(Visibility),
1732 impl StructFieldKind {
1733 pub fn is_unnamed(&self) -> bool {
1735 UnnamedField(..) => true,
1736 NamedField(..) => false,
1741 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1742 pub struct StructDef {
1743 /// Fields, not including ctor
1744 pub fields: Vec<StructField>,
1745 /// ID of the constructor. This is only used for tuple- or enum-like
1747 pub ctor_id: Option<NodeId>,
1751 FIXME (#3300): Should allow items to be anonymous. Right now
1752 we just use dummy names for anon items.
1756 /// The name might be a dummy name in case of anonymous items
1757 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1760 pub attrs: Vec<Attribute>,
1763 pub vis: Visibility,
1767 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1769 /// An`extern crate` item, with optional original crate name,
1771 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1772 ItemExternCrate(Option<Name>),
1773 /// A `use` or `pub use` item
1774 ItemUse(P<ViewPath>),
1777 ItemStatic(P<Ty>, Mutability, P<Expr>),
1779 ItemConst(P<Ty>, P<Expr>),
1780 /// A function declaration
1781 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1784 /// An external module
1785 ItemForeignMod(ForeignMod),
1786 /// A type alias, e.g. `type Foo = Bar<u8>`
1787 ItemTy(P<Ty>, Generics),
1788 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1789 ItemEnum(EnumDef, Generics),
1790 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1791 ItemStruct(P<StructDef>, Generics),
1792 /// Represents a Trait Declaration
1798 // Default trait implementations
1800 // `impl Trait for .. {}`
1801 ItemDefaultImpl(Unsafety, TraitRef),
1802 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1806 Option<TraitRef>, // (optional) trait this impl implements
1809 /// A macro invocation (which includes macro definition)
1814 pub fn descriptive_variant(&self) -> &str {
1816 ItemExternCrate(..) => "extern crate",
1817 ItemUse(..) => "use",
1818 ItemStatic(..) => "static item",
1819 ItemConst(..) => "constant item",
1820 ItemFn(..) => "function",
1821 ItemMod(..) => "module",
1822 ItemForeignMod(..) => "foreign module",
1823 ItemTy(..) => "type alias",
1824 ItemEnum(..) => "enum",
1825 ItemStruct(..) => "struct",
1826 ItemTrait(..) => "trait",
1829 ItemDefaultImpl(..) => "item"
1834 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1835 pub struct ForeignItem {
1837 pub attrs: Vec<Attribute>,
1838 pub node: ForeignItem_,
1841 pub vis: Visibility,
1844 /// An item within an `extern` block
1845 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1846 pub enum ForeignItem_ {
1847 /// A foreign function
1848 ForeignItemFn(P<FnDecl>, Generics),
1849 /// A foreign static item (`static ext: u8`), with optional mutability
1850 /// (the boolean is true when mutable)
1851 ForeignItemStatic(P<Ty>, bool),
1855 pub fn descriptive_variant(&self) -> &str {
1857 ForeignItemFn(..) => "foreign function",
1858 ForeignItemStatic(..) => "foreign static item"
1863 /// A macro definition, in this crate or imported from another.
1865 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1866 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1867 pub struct MacroDef {
1869 pub attrs: Vec<Attribute>,
1872 pub imported_from: Option<Ident>,
1874 pub use_locally: bool,
1875 pub allow_internal_unstable: bool,
1876 pub body: Vec<TokenTree>,
1884 // are ASTs encodable?
1886 fn check_asts_encodable() {
1887 fn assert_encodable<T: serialize::Encodable>() {}
1888 assert_encodable::<Crate>();