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::IntTy::*;
24 pub use self::Item_::*;
25 pub use self::KleeneOp::*;
26 pub use self::Lit_::*;
27 pub use self::LitIntType::*;
28 pub use self::MacStmtStyle::*;
29 pub use self::MetaItem_::*;
30 pub use self::Mutability::*;
31 pub use self::Pat_::*;
32 pub use self::PathListItem_::*;
33 pub use self::PrimTy::*;
34 pub use self::Sign::*;
35 pub use self::Stmt_::*;
36 pub use self::StrStyle::*;
37 pub use self::StructFieldKind::*;
38 pub use self::TraitItem_::*;
40 pub use self::TyParamBound::*;
41 pub use self::UintTy::*;
42 pub use self::UnOp::*;
43 pub use self::UnsafeSource::*;
44 pub use self::ViewPath_::*;
45 pub use self::Visibility::*;
46 pub use self::PathParameters::*;
48 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
52 use ext::tt::macro_parser;
53 use owned_slice::OwnedSlice;
54 use parse::token::{InternedString, str_to_ident};
57 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
64 use std::hash::{Hash, Hasher};
65 use serialize::{Encodable, Decodable, Encoder, Decoder};
67 /// A name is a part of an identifier, representing a string or gensym. It's
68 /// the result of interning.
69 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
70 pub struct Name(pub u32);
72 /// A SyntaxContext represents a chain of macro-expandings
73 /// and renamings. Each macro expansion corresponds to
74 /// a fresh u32. This u32 is a reference to a table stored
75 // in thread-local storage.
76 // The special value EMPTY_CTXT is used to indicate an empty
78 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
79 pub struct SyntaxContext(pub u32);
81 /// An identifier contains a Name (index into the interner
82 /// table) and a SyntaxContext to track renaming and
83 /// macro expansion per Flatt et al., "Macros That Work Together"
84 #[derive(Clone, Copy, Eq)]
87 pub ctxt: SyntaxContext
91 pub fn as_str(self) -> token::InternedString {
92 token::InternedString::new_from_name(self)
96 impl fmt::Debug for Name {
97 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98 write!(f, "{}({})", self, self.0)
102 impl fmt::Display for Name {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104 fmt::Display::fmt(&self.as_str(), f)
108 impl Encodable for Name {
109 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
110 s.emit_str(&self.as_str())
114 impl Decodable for Name {
115 fn decode<D: Decoder>(d: &mut D) -> Result<Name, D::Error> {
116 Ok(token::intern(&try!(d.read_str())[..]))
120 pub const EMPTY_CTXT : SyntaxContext = SyntaxContext(0);
123 pub fn new(name: Name, ctxt: SyntaxContext) -> Ident {
124 Ident {name: name, ctxt: ctxt}
126 pub fn with_empty_ctxt(name: Name) -> Ident {
127 Ident {name: name, ctxt: EMPTY_CTXT}
131 impl PartialEq for Ident {
132 fn eq(&self, other: &Ident) -> bool {
133 if self.ctxt != other.ctxt {
134 // There's no one true way to compare Idents. They can be compared
135 // non-hygienically `id1.name == id2.name`, hygienically
136 // `mtwt::resolve(id1) == mtwt::resolve(id2)`, or even member-wise
137 // `(id1.name, id1.ctxt) == (id2.name, id2.ctxt)` depending on the situation.
138 // Ideally, PartialEq should not be implemented for Ident at all, but that
139 // would be too impractical, because many larger structures (Token, in particular)
140 // including Idents as their parts derive PartialEq and use it for non-hygienic
141 // comparisons. That's why PartialEq is implemented and defaults to non-hygienic
142 // comparison. Hash is implemented too and is consistent with PartialEq, i.e. only
143 // the name of Ident is hashed. Still try to avoid comparing idents in your code
144 // (especially as keys in hash maps), use one of the three methods listed above
147 // If you see this panic, then some idents from different contexts were compared
148 // non-hygienically. It's likely a bug. Use one of the three comparison methods
149 // listed above explicitly.
151 panic!("idents with different contexts are compared with operator `==`: \
152 {:?}, {:?}.", self, other);
155 self.name == other.name
159 impl Hash for Ident {
160 fn hash<H: Hasher>(&self, state: &mut H) {
161 self.name.hash(state)
165 impl fmt::Debug for Ident {
166 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
167 write!(f, "{}#{}", self.name, self.ctxt.0)
171 impl fmt::Display for Ident {
172 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
173 fmt::Display::fmt(&self.name, f)
177 impl Encodable for Ident {
178 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
183 impl Decodable for Ident {
184 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
185 Ok(Ident::with_empty_ctxt(try!(Name::decode(d))))
189 /// A mark represents a unique id associated with a macro expansion
192 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
193 pub struct Lifetime {
199 impl fmt::Debug for Lifetime {
200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
205 /// A lifetime definition, eg `'a: 'b+'c+'d`
206 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
207 pub struct LifetimeDef {
208 pub lifetime: Lifetime,
209 pub bounds: Vec<Lifetime>
212 /// A "Path" is essentially Rust's notion of a name; for instance:
213 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
214 /// along with a bunch of supporting information.
215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
218 /// A `::foo` path, is relative to the crate root rather than current
219 /// module (like paths in an import).
221 /// The segments in the path: the things separated by `::`.
222 pub segments: Vec<PathSegment>,
225 impl fmt::Debug for Path {
226 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
227 write!(f, "path({})", pprust::path_to_string(self))
231 impl fmt::Display for Path {
232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
233 write!(f, "{}", pprust::path_to_string(self))
237 /// A segment of a path: an identifier, an optional lifetime, and a set of
239 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
240 pub struct PathSegment {
241 /// The identifier portion of this path segment.
242 pub identifier: Ident,
244 /// Type/lifetime parameters attached to this path. They come in
245 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
246 /// this is more than just simple syntactic sugar; the use of
247 /// parens affects the region binding rules, so we preserve the
249 pub parameters: PathParameters,
252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
253 pub enum PathParameters {
254 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
255 AngleBracketedParameters(AngleBracketedParameterData),
256 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
257 ParenthesizedParameters(ParenthesizedParameterData),
260 impl PathParameters {
261 pub fn none() -> PathParameters {
262 AngleBracketedParameters(AngleBracketedParameterData {
263 lifetimes: Vec::new(),
264 types: OwnedSlice::empty(),
265 bindings: OwnedSlice::empty(),
269 pub fn is_empty(&self) -> bool {
271 AngleBracketedParameters(ref data) => data.is_empty(),
273 // Even if the user supplied no types, something like
274 // `X()` is equivalent to `X<(),()>`.
275 ParenthesizedParameters(..) => false,
279 pub fn has_lifetimes(&self) -> bool {
281 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
282 ParenthesizedParameters(_) => false,
286 pub fn has_types(&self) -> bool {
288 AngleBracketedParameters(ref data) => !data.types.is_empty(),
289 ParenthesizedParameters(..) => true,
293 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
294 /// parameters in the parenthesized case.
295 pub fn types(&self) -> Vec<&P<Ty>> {
297 AngleBracketedParameters(ref data) => {
298 data.types.iter().collect()
300 ParenthesizedParameters(ref data) => {
302 .chain(data.output.iter())
308 pub fn lifetimes(&self) -> Vec<&Lifetime> {
310 AngleBracketedParameters(ref data) => {
311 data.lifetimes.iter().collect()
313 ParenthesizedParameters(_) => {
319 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
321 AngleBracketedParameters(ref data) => {
322 data.bindings.iter().collect()
324 ParenthesizedParameters(_) => {
331 /// A path like `Foo<'a, T>`
332 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
333 pub struct AngleBracketedParameterData {
334 /// The lifetime parameters for this path segment.
335 pub lifetimes: Vec<Lifetime>,
336 /// The type parameters for this path segment, if present.
337 pub types: OwnedSlice<P<Ty>>,
338 /// Bindings (equality constraints) on associated types, if present.
339 /// E.g., `Foo<A=Bar>`.
340 pub bindings: OwnedSlice<P<TypeBinding>>,
343 impl AngleBracketedParameterData {
344 fn is_empty(&self) -> bool {
345 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
349 /// A path like `Foo(A,B) -> C`
350 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
351 pub struct ParenthesizedParameterData {
356 pub inputs: Vec<P<Ty>>,
359 pub output: Option<P<Ty>>,
362 pub type CrateNum = u32;
364 pub type NodeId = u32;
366 /// Node id used to represent the root of the crate.
367 pub const CRATE_NODE_ID: NodeId = 0;
369 /// When parsing and doing expansions, we initially give all AST nodes this AST
370 /// node value. Then later, in the renumber pass, we renumber them to have
371 /// small, positive ids.
372 pub const DUMMY_NODE_ID: NodeId = !0;
374 pub trait NodeIdAssigner {
375 fn next_node_id(&self) -> NodeId;
376 fn peek_node_id(&self) -> NodeId;
379 /// The AST represents all type param bounds as types.
380 /// typeck::collect::compute_bounds matches these against
381 /// the "special" built-in traits (see middle::lang_items) and
382 /// detects Copy, Send and Sync.
383 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
384 pub enum TyParamBound {
385 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
386 RegionTyParamBound(Lifetime)
389 /// A modifier on a bound, currently this is only used for `?Sized`, where the
390 /// modifier is `Maybe`. Negative bounds should also be handled here.
391 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
392 pub enum TraitBoundModifier {
397 pub type TyParamBounds = OwnedSlice<TyParamBound>;
399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
403 pub bounds: TyParamBounds,
404 pub default: Option<P<Ty>>,
408 /// Represents lifetimes and type parameters attached to a declaration
409 /// of a function, enum, trait, etc.
410 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
411 pub struct Generics {
412 pub lifetimes: Vec<LifetimeDef>,
413 pub ty_params: OwnedSlice<TyParam>,
414 pub where_clause: WhereClause,
418 pub fn is_lt_parameterized(&self) -> bool {
419 !self.lifetimes.is_empty()
421 pub fn is_type_parameterized(&self) -> bool {
422 !self.ty_params.is_empty()
424 pub fn is_parameterized(&self) -> bool {
425 self.is_lt_parameterized() || self.is_type_parameterized()
429 /// A `where` clause in a definition
430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
431 pub struct WhereClause {
433 pub predicates: Vec<WherePredicate>,
436 /// A single predicate in a `where` clause
437 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
438 pub enum WherePredicate {
439 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
440 BoundPredicate(WhereBoundPredicate),
441 /// A lifetime predicate, e.g. `'a: 'b+'c`
442 RegionPredicate(WhereRegionPredicate),
443 /// An equality predicate (unsupported)
444 EqPredicate(WhereEqPredicate),
447 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
448 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
449 pub struct WhereBoundPredicate {
451 /// Any lifetimes from a `for` binding
452 pub bound_lifetimes: Vec<LifetimeDef>,
453 /// The type being bounded
454 pub bounded_ty: P<Ty>,
455 /// Trait and lifetime bounds (`Clone+Send+'static`)
456 pub bounds: OwnedSlice<TyParamBound>,
459 /// A lifetime predicate, e.g. `'a: 'b+'c`
460 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
461 pub struct WhereRegionPredicate {
463 pub lifetime: Lifetime,
464 pub bounds: Vec<Lifetime>,
467 /// An equality predicate (unsupported), e.g. `T=int`
468 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
469 pub struct WhereEqPredicate {
476 /// The set of MetaItems that define the compilation environment of the crate,
477 /// used to drive conditional compilation
478 pub type CrateConfig = Vec<P<MetaItem>> ;
480 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
483 pub attrs: Vec<Attribute>,
484 pub config: CrateConfig,
486 pub exported_macros: Vec<MacroDef>,
489 pub type MetaItem = Spanned<MetaItem_>;
491 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
493 MetaWord(InternedString),
494 MetaList(InternedString, Vec<P<MetaItem>>),
495 MetaNameValue(InternedString, Lit),
498 // can't be derived because the MetaList requires an unordered comparison
499 impl PartialEq for MetaItem_ {
500 fn eq(&self, other: &MetaItem_) -> bool {
502 MetaWord(ref ns) => match *other {
503 MetaWord(ref no) => (*ns) == (*no),
506 MetaNameValue(ref ns, ref vs) => match *other {
507 MetaNameValue(ref no, ref vo) => {
508 (*ns) == (*no) && vs.node == vo.node
512 MetaList(ref ns, ref miss) => match *other {
513 MetaList(ref no, ref miso) => {
515 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
523 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
525 /// Statements in a block
526 pub stmts: Vec<P<Stmt>>,
527 /// An expression at the end of the block
528 /// without a semicolon, if any
529 pub expr: Option<P<Expr>>,
531 /// Distinguishes between `unsafe { ... }` and `{ ... }`
532 pub rules: BlockCheckMode,
536 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
543 impl fmt::Debug for Pat {
544 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
545 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
549 /// A single field in a struct pattern
551 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
552 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
553 /// except is_shorthand is true
554 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
555 pub struct FieldPat {
556 /// The identifier for the field
558 /// The pattern the field is destructured to
560 pub is_shorthand: bool,
563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
564 pub enum BindingMode {
565 BindByRef(Mutability),
566 BindByValue(Mutability),
569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
571 /// Represents a wildcard pattern (`_`)
574 /// A PatIdent may either be a new bound variable,
575 /// or a nullary enum (in which case the third field
578 /// In the nullary enum case, the parser can't determine
579 /// which it is. The resolver determines this, and
580 /// records this pattern's NodeId in an auxiliary
581 /// set (of "PatIdents that refer to nullary enums")
582 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
584 /// "None" means a `Variant(..)` pattern where we don't bind the fields to names.
585 PatEnum(Path, Option<Vec<P<Pat>>>),
587 /// An associated const named using the qualified path `<T>::CONST` or
588 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
589 /// referred to as simply `T::CONST`, in which case they will end up as
590 /// PatEnum, and the resolver will have to sort that out.
591 PatQPath(QSelf, Path),
593 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
594 /// The `bool` is `true` in the presence of a `..`
595 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
596 /// A tuple pattern `(a, b)`
600 /// A reference pattern, e.g. `&mut (a, b)`
601 PatRegion(P<Pat>, Mutability),
604 /// A range pattern, e.g. `1...2`
605 PatRange(P<Expr>, P<Expr>),
606 /// `[a, b, ..i, y, z]` is represented as:
607 /// `PatVec(box [a, b], Some(i), box [y, z])`
608 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
609 /// A macro pattern; pre-expansion
613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
614 pub enum Mutability {
619 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
621 /// The `+` operator (addition)
623 /// The `-` operator (subtraction)
625 /// The `*` operator (multiplication)
627 /// The `/` operator (division)
629 /// The `%` operator (modulus)
631 /// The `&&` operator (logical and)
633 /// The `||` operator (logical or)
635 /// The `^` operator (bitwise xor)
637 /// The `&` operator (bitwise and)
639 /// The `|` operator (bitwise or)
641 /// The `<<` operator (shift left)
643 /// The `>>` operator (shift right)
645 /// The `==` operator (equality)
647 /// The `<` operator (less than)
649 /// The `<=` operator (less than or equal to)
651 /// The `!=` operator (not equal to)
653 /// The `>=` operator (greater than or equal to)
655 /// The `>` operator (greater than)
659 pub type BinOp = Spanned<BinOp_>;
661 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
663 /// The `*` operator for dereferencing
665 /// The `!` operator for logical inversion
667 /// The `-` operator for negation
672 pub type Stmt = Spanned<Stmt_>;
674 impl fmt::Debug for Stmt {
675 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
676 write!(f, "stmt({}: {})",
677 ast_util::stmt_id(self)
678 .map_or(Cow::Borrowed("<macro>"),|id|Cow::Owned(id.to_string())),
679 pprust::stmt_to_string(self))
684 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
686 /// Could be an item or a local (let) binding:
687 StmtDecl(P<Decl>, NodeId),
689 /// Expr without trailing semi-colon (must have unit type):
690 StmtExpr(P<Expr>, NodeId),
692 /// Expr with trailing semi-colon (may have any type):
693 StmtSemi(P<Expr>, NodeId),
695 StmtMac(P<Mac>, MacStmtStyle),
697 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
698 pub enum MacStmtStyle {
699 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
700 /// `foo!(...);`, `foo![...];`
701 MacStmtWithSemicolon,
702 /// The macro statement had braces; e.g. foo! { ... }
704 /// The macro statement had parentheses or brackets and no semicolon; e.g.
705 /// `foo!(...)`. All of these will end up being converted into macro
707 MacStmtWithoutBraces,
710 // FIXME (pending discussion of #1697, #2178...): local should really be
711 // a refinement on pat.
712 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
713 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
716 pub ty: Option<P<Ty>>,
717 /// Initializer expression to set the value, if any
718 pub init: Option<P<Expr>>,
723 pub type Decl = Spanned<Decl_>;
725 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
727 /// A local (let) binding:
733 /// represents one arm of a 'match'
734 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
736 pub attrs: Vec<Attribute>,
737 pub pats: Vec<P<Pat>>,
738 pub guard: Option<P<Expr>>,
742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
744 pub ident: SpannedIdent,
749 pub type SpannedIdent = Spanned<Ident>;
751 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
752 pub enum BlockCheckMode {
754 UnsafeBlock(UnsafeSource),
757 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
758 pub enum UnsafeSource {
764 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
771 impl fmt::Debug for Expr {
772 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
773 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
777 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
779 /// A `box x` expression.
781 /// First expr is the place; second expr is the value.
782 ExprInPlace(P<Expr>, P<Expr>),
783 /// An array (`[a, b, c, d]`)
784 ExprVec(Vec<P<Expr>>),
787 /// The first field resolves to the function itself,
788 /// and the second field is the list of arguments
789 ExprCall(P<Expr>, Vec<P<Expr>>),
790 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
792 /// The `SpannedIdent` is the identifier for the method name.
793 /// The vector of `Ty`s are the ascripted type parameters for the method
794 /// (within the angle brackets).
796 /// The first element of the vector of `Expr`s is the expression that evaluates
797 /// to the object on which the method is being called on (the receiver),
798 /// and the remaining elements are the rest of the arguments.
800 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
801 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
802 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
803 /// A tuple (`(a, b, c ,d)`)
804 ExprTup(Vec<P<Expr>>),
805 /// A binary operation (For example: `a + b`, `a * b`)
806 ExprBinary(BinOp, P<Expr>, P<Expr>),
807 /// A unary operation (For example: `!x`, `*x`)
808 ExprUnary(UnOp, P<Expr>),
809 /// A literal (For example: `1u8`, `"foo"`)
811 /// A cast (`foo as f64`)
812 ExprCast(P<Expr>, P<Ty>),
813 /// An `if` block, with an optional else block
815 /// `if expr { block } else { expr }`
816 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
817 /// An `if let` expression with an optional else block
819 /// `if let pat = expr { block } else { expr }`
821 /// This is desugared to a `match` expression.
822 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
823 /// A while loop, with an optional label
825 /// `'label: while expr { block }`
826 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
827 /// A while-let loop, with an optional label
829 /// `'label: while let pat = expr { block }`
831 /// This is desugared to a combination of `loop` and `match` expressions.
832 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
833 /// A for loop, with an optional label
835 /// `'label: for pat in expr { block }`
837 /// This is desugared to a combination of `loop` and `match` expressions.
838 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
839 /// Conditionless loop (can be exited with break, continue, or return)
841 /// `'label: loop { block }`
842 ExprLoop(P<Block>, Option<Ident>),
844 ExprMatch(P<Expr>, Vec<Arm>),
845 /// A closure (for example, `move |a, b, c| {a + b + c}`)
846 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
847 /// A block (`{ ... }`)
850 /// An assignment (`a = foo()`)
851 ExprAssign(P<Expr>, P<Expr>),
852 /// An assignment with an operator
854 /// For example, `a += 1`.
855 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
856 /// Access of a named struct field (`obj.foo`)
857 ExprField(P<Expr>, SpannedIdent),
858 /// Access of an unnamed field of a struct or tuple-struct
860 /// For example, `foo.0`.
861 ExprTupField(P<Expr>, Spanned<usize>),
862 /// An indexing operation (`foo[2]`)
863 ExprIndex(P<Expr>, P<Expr>),
864 /// A range (`1..2`, `1..`, or `..2`)
865 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
867 /// Variable reference, possibly containing `::` and/or type
868 /// parameters, e.g. foo::bar::<baz>.
870 /// Optionally "qualified",
871 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
872 ExprPath(Option<QSelf>, Path),
874 /// A referencing operation (`&a` or `&mut a`)
875 ExprAddrOf(Mutability, P<Expr>),
876 /// A `break`, with an optional label to break
877 ExprBreak(Option<SpannedIdent>),
878 /// A `continue`, with an optional label
879 ExprAgain(Option<SpannedIdent>),
880 /// A `return`, with an optional value to be returned
881 ExprRet(Option<P<Expr>>),
883 /// Output of the `asm!()` macro
884 ExprInlineAsm(InlineAsm),
886 /// A macro invocation; pre-expansion
889 /// A struct literal expression.
891 /// For example, `Foo {x: 1, y: 2}`, or
892 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
893 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
895 /// An array literal constructed from one repeated element.
897 /// For example, `[1u8; 5]`. The first expression is the element
898 /// to be repeated; the second is the number of times to repeat it.
899 ExprRepeat(P<Expr>, P<Expr>),
901 /// No-op: used solely so we can pretty-print faithfully
905 /// The explicit Self type in a "qualified path". The actual
906 /// path, including the trait and the associated item, is stored
907 /// separately. `position` represents the index of the associated
908 /// item qualified with this Self type.
911 /// <Vec<T> as a::b::Trait>::AssociatedItem
912 /// ^~~~~ ~~~~~~~~~~~~~~^
915 /// <Vec<T>>::AssociatedItem
919 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
925 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
926 pub enum CaptureClause {
931 /// A delimited sequence of token trees
932 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
933 pub struct Delimited {
934 /// The type of delimiter
935 pub delim: token::DelimToken,
936 /// The span covering the opening delimiter
938 /// The delimited sequence of token trees
939 pub tts: Vec<TokenTree>,
940 /// The span covering the closing delimiter
941 pub close_span: Span,
945 /// Returns the opening delimiter as a token.
946 pub fn open_token(&self) -> token::Token {
947 token::OpenDelim(self.delim)
950 /// Returns the closing delimiter as a token.
951 pub fn close_token(&self) -> token::Token {
952 token::CloseDelim(self.delim)
955 /// Returns the opening delimiter as a token tree.
956 pub fn open_tt(&self) -> TokenTree {
957 TokenTree::Token(self.open_span, self.open_token())
960 /// Returns the closing delimiter as a token tree.
961 pub fn close_tt(&self) -> TokenTree {
962 TokenTree::Token(self.close_span, self.close_token())
966 /// A sequence of token treesee
967 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
968 pub struct SequenceRepetition {
969 /// The sequence of token trees
970 pub tts: Vec<TokenTree>,
971 /// The optional separator
972 pub separator: Option<token::Token>,
973 /// Whether the sequence can be repeated zero (*), or one or more times (+)
975 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
976 pub num_captures: usize,
979 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
980 /// for token sequences.
981 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
987 /// When the main rust parser encounters a syntax-extension invocation, it
988 /// parses the arguments to the invocation as a token-tree. This is a very
989 /// loose structure, such that all sorts of different AST-fragments can
990 /// be passed to syntax extensions using a uniform type.
992 /// If the syntax extension is an MBE macro, it will attempt to match its
993 /// LHS token tree against the provided token tree, and if it finds a
994 /// match, will transcribe the RHS token tree, splicing in any captured
995 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
997 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
998 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
999 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1000 pub enum TokenTree {
1002 Token(Span, token::Token),
1003 /// A delimited sequence of token trees
1004 Delimited(Span, Rc<Delimited>),
1006 // This only makes sense in MBE macros.
1008 /// A kleene-style repetition sequence with a span
1009 // FIXME(eddyb) #12938 Use DST.
1010 Sequence(Span, Rc<SequenceRepetition>),
1014 pub fn len(&self) -> usize {
1016 TokenTree::Token(_, token::DocComment(name)) => {
1017 match doc_comment_style(&name.as_str()) {
1018 AttrStyle::Outer => 2,
1019 AttrStyle::Inner => 3
1022 TokenTree::Token(_, token::SpecialVarNt(..)) => 2,
1023 TokenTree::Token(_, token::MatchNt(..)) => 3,
1024 TokenTree::Delimited(_, ref delimed) => {
1025 delimed.tts.len() + 2
1027 TokenTree::Sequence(_, ref seq) => {
1030 TokenTree::Token(..) => 0
1034 pub fn get_tt(&self, index: usize) -> TokenTree {
1035 match (self, index) {
1036 (&TokenTree::Token(sp, token::DocComment(_)), 0) => {
1037 TokenTree::Token(sp, token::Pound)
1039 (&TokenTree::Token(sp, token::DocComment(name)), 1)
1040 if doc_comment_style(&name.as_str()) == AttrStyle::Inner => {
1041 TokenTree::Token(sp, token::Not)
1043 (&TokenTree::Token(sp, token::DocComment(name)), _) => {
1044 let stripped = strip_doc_comment_decoration(&name.as_str());
1045 TokenTree::Delimited(sp, Rc::new(Delimited {
1046 delim: token::Bracket,
1048 tts: vec![TokenTree::Token(sp, token::Ident(token::str_to_ident("doc"),
1050 TokenTree::Token(sp, token::Eq),
1051 TokenTree::Token(sp, token::Literal(
1052 token::StrRaw(token::intern(&stripped), 0), None))],
1056 (&TokenTree::Delimited(_, ref delimed), _) => {
1058 return delimed.open_tt();
1060 if index == delimed.tts.len() + 1 {
1061 return delimed.close_tt();
1063 delimed.tts[index - 1].clone()
1065 (&TokenTree::Token(sp, token::SpecialVarNt(var)), _) => {
1066 let v = [TokenTree::Token(sp, token::Dollar),
1067 TokenTree::Token(sp, token::Ident(token::str_to_ident(var.as_str()),
1071 (&TokenTree::Token(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1072 let v = [TokenTree::Token(sp, token::SubstNt(name, name_st)),
1073 TokenTree::Token(sp, token::Colon),
1074 TokenTree::Token(sp, token::Ident(kind, kind_st))];
1077 (&TokenTree::Sequence(_, ref seq), _) => {
1078 seq.tts[index].clone()
1080 _ => panic!("Cannot expand a token tree")
1084 /// Returns the `Span` corresponding to this token tree.
1085 pub fn get_span(&self) -> Span {
1087 TokenTree::Token(span, _) => span,
1088 TokenTree::Delimited(span, _) => span,
1089 TokenTree::Sequence(span, _) => span,
1093 /// Use this token tree as a matcher to parse given tts.
1094 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1095 -> macro_parser::NamedParseResult {
1096 // `None` is because we're not interpolating
1097 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1100 tts.iter().cloned().collect(),
1102 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1106 pub type Mac = Spanned<Mac_>;
1108 /// Represents a macro invocation. The Path indicates which macro
1109 /// is being invoked, and the vector of token-trees contains the source
1110 /// of the macro invocation.
1112 /// NB: the additional ident for a macro_rules-style macro is actually
1113 /// stored in the enclosing item. Oog.
1114 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1117 pub tts: Vec<TokenTree>,
1118 pub ctxt: SyntaxContext,
1121 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1123 /// A regular string, like `"foo"`
1125 /// A raw string, like `r##"foo"##`
1127 /// The uint is the number of `#` symbols used
1132 pub type Lit = Spanned<Lit_>;
1134 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1141 pub fn new<T: IntSign>(n: T) -> Sign {
1147 fn sign(&self) -> Sign;
1150 ($($t:ident)*) => ($(impl IntSign for $t {
1151 #[allow(unused_comparisons)]
1152 fn sign(&self) -> Sign {
1153 if *self < 0 {Minus} else {Plus}
1157 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1159 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1160 pub enum LitIntType {
1161 SignedIntLit(IntTy, Sign),
1162 UnsignedIntLit(UintTy),
1163 UnsuffixedIntLit(Sign)
1166 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1168 /// A string literal (`"foo"`)
1169 LitStr(InternedString, StrStyle),
1170 /// A byte string (`b"foo"`)
1171 LitByteStr(Rc<Vec<u8>>),
1172 /// A byte char (`b'f'`)
1174 /// A character literal (`'a'`)
1176 /// An integer literal (`1u8`)
1177 LitInt(u64, LitIntType),
1178 /// A float literal (`1f64` or `1E10f64`)
1179 LitFloat(InternedString, FloatTy),
1180 /// A float literal without a suffix (`1.0 or 1.0E10`)
1181 LitFloatUnsuffixed(InternedString),
1182 /// A boolean literal
1186 // NB: If you change this, you'll probably want to change the corresponding
1187 // type structure in middle/ty.rs as well.
1188 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1191 pub mutbl: Mutability,
1194 /// Represents a method's signature in a trait declaration,
1195 /// or in an implementation.
1196 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1197 pub struct MethodSig {
1198 pub unsafety: Unsafety,
1199 pub constness: Constness,
1201 pub decl: P<FnDecl>,
1202 pub generics: Generics,
1203 pub explicit_self: ExplicitSelf,
1206 /// Represents a method declaration in a trait declaration, possibly including
1207 /// a default implementation A trait method is either required (meaning it
1208 /// doesn't have an implementation, just a signature) or provided (meaning it
1209 /// has a default implementation).
1210 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1211 pub struct TraitItem {
1214 pub attrs: Vec<Attribute>,
1215 pub node: TraitItem_,
1219 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1220 pub enum TraitItem_ {
1221 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1222 MethodTraitItem(MethodSig, Option<P<Block>>),
1223 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1226 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1227 pub struct ImplItem {
1230 pub vis: Visibility,
1231 pub attrs: Vec<Attribute>,
1232 pub node: ImplItemKind,
1236 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1237 pub enum ImplItemKind {
1238 Const(P<Ty>, P<Expr>),
1239 Method(MethodSig, P<Block>),
1244 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1253 impl fmt::Debug for IntTy {
1254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1255 fmt::Display::fmt(self, f)
1259 impl fmt::Display for IntTy {
1260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1261 write!(f, "{}", ast_util::int_ty_to_string(*self))
1266 pub fn bit_width(&self) -> Option<usize> {
1268 TyIs => return None,
1277 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1287 pub fn bit_width(&self) -> Option<usize> {
1289 TyUs => return None,
1298 impl fmt::Debug for UintTy {
1299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1300 fmt::Display::fmt(self, f)
1304 impl fmt::Display for UintTy {
1305 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1306 write!(f, "{}", ast_util::uint_ty_to_string(*self))
1310 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1316 impl fmt::Debug for FloatTy {
1317 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1318 fmt::Display::fmt(self, f)
1322 impl fmt::Display for FloatTy {
1323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1324 write!(f, "{}", ast_util::float_ty_to_string(*self))
1329 pub fn bit_width(&self) -> usize {
1337 // Bind a type to an associated type: `A=Foo`.
1338 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1339 pub struct TypeBinding {
1346 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1353 impl fmt::Debug for Ty {
1354 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1355 write!(f, "type({})", pprust::ty_to_string(self))
1359 /// Not represented directly in the AST, referred to by name through a ty_path.
1360 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1370 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1371 pub struct BareFnTy {
1372 pub unsafety: Unsafety,
1374 pub lifetimes: Vec<LifetimeDef>,
1378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1379 /// The different kinds of types recognized by the compiler
1382 /// A fixed length array (`[T; n]`)
1383 TyFixedLengthVec(P<Ty>, P<Expr>),
1384 /// A raw pointer (`*const T` or `*mut T`)
1386 /// A reference (`&'a T` or `&'a mut T`)
1387 TyRptr(Option<Lifetime>, MutTy),
1388 /// A bare function (e.g. `fn(usize) -> bool`)
1389 TyBareFn(P<BareFnTy>),
1390 /// A tuple (`(A, B, C, D,...)`)
1392 /// A path (`module::module::...::Type`), optionally
1393 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1395 /// Type parameters are stored in the Path itself
1396 TyPath(Option<QSelf>, Path),
1397 /// Something like `A+B`. Note that `B` must always be a path.
1398 TyObjectSum(P<Ty>, TyParamBounds),
1399 /// A type like `for<'a> Foo<&'a Bar>`
1400 TyPolyTraitRef(TyParamBounds),
1401 /// No-op; kept solely so that we can pretty-print faithfully
1405 /// TyInfer means the type should be inferred instead of it having been
1406 /// specified. This can appear anywhere in a type.
1408 // A macro in the type position.
1412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1413 pub enum AsmDialect {
1418 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1419 pub struct InlineAsm {
1420 pub asm: InternedString,
1421 pub asm_str_style: StrStyle,
1422 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1423 pub inputs: Vec<(InternedString, P<Expr>)>,
1424 pub clobbers: Vec<InternedString>,
1426 pub alignstack: bool,
1427 pub dialect: AsmDialect,
1428 pub expn_id: ExpnId,
1431 /// represents an argument in a function header
1432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1440 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1441 let path = Spanned{span:span,node:self_ident};
1443 // HACK(eddyb) fake type for the self argument.
1451 node: PatIdent(BindByValue(mutability), path, None),
1459 /// Represents the header (not the body) of a function declaration
1460 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1462 pub inputs: Vec<Arg>,
1463 pub output: FunctionRetTy,
1467 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1473 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1474 pub enum Constness {
1479 impl fmt::Display for Unsafety {
1480 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1481 fmt::Display::fmt(match *self {
1482 Unsafety::Normal => "normal",
1483 Unsafety::Unsafe => "unsafe",
1488 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1489 pub enum ImplPolarity {
1490 /// `impl Trait for Type`
1492 /// `impl !Trait for Type`
1496 impl fmt::Debug for ImplPolarity {
1497 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1499 ImplPolarity::Positive => "positive".fmt(f),
1500 ImplPolarity::Negative => "negative".fmt(f),
1506 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1507 pub enum FunctionRetTy {
1508 /// Functions with return type `!`that always
1509 /// raise an error or exit (i.e. never return to the caller)
1511 /// Return type is not specified.
1513 /// Functions default to `()` and
1514 /// closures default to inference. Span points to where return
1515 /// type would be inserted.
1516 DefaultReturn(Span),
1521 impl FunctionRetTy {
1522 pub fn span(&self) -> Span {
1524 NoReturn(span) => span,
1525 DefaultReturn(span) => span,
1526 Return(ref ty) => ty.span
1531 /// Represents the kind of 'self' associated with a method
1532 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1533 pub enum ExplicitSelf_ {
1538 /// `&'lt self`, `&'lt mut self`
1539 SelfRegion(Option<Lifetime>, Mutability, Ident),
1541 SelfExplicit(P<Ty>, Ident),
1544 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1546 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1548 /// A span from the first token past `{` to the last token until `}`.
1549 /// For `mod foo;`, the inner span ranges from the first token
1550 /// to the last token in the external file.
1552 pub items: Vec<P<Item>>,
1555 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1556 pub struct ForeignMod {
1558 pub items: Vec<P<ForeignItem>>,
1561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1562 pub struct EnumDef {
1563 pub variants: Vec<P<Variant>>,
1566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1567 pub struct Variant_ {
1569 pub attrs: Vec<Attribute>,
1570 pub data: VariantData,
1571 /// Explicit discriminant, eg `Foo = 1`
1572 pub disr_expr: Option<P<Expr>>,
1575 pub type Variant = Spanned<Variant_>;
1577 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1578 pub enum PathListItem_ {
1581 /// renamed in list, eg `use foo::{bar as baz};`
1582 rename: Option<Ident>,
1586 /// renamed in list, eg `use foo::{self as baz};`
1587 rename: Option<Ident>,
1592 impl PathListItem_ {
1593 pub fn id(&self) -> NodeId {
1595 PathListIdent { id, .. } | PathListMod { id, .. } => id
1599 pub fn name(&self) -> Option<Ident> {
1601 PathListIdent { name, .. } => Some(name),
1602 PathListMod { .. } => None,
1606 pub fn rename(&self) -> Option<Ident> {
1608 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1613 pub type PathListItem = Spanned<PathListItem_>;
1615 pub type ViewPath = Spanned<ViewPath_>;
1617 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1618 pub enum ViewPath_ {
1620 /// `foo::bar::baz as quux`
1624 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1625 ViewPathSimple(Ident, Path),
1630 /// `foo::bar::{a,b,c}`
1631 ViewPathList(Path, Vec<PathListItem>)
1634 /// Meta-data associated with an item
1635 pub type Attribute = Spanned<Attribute_>;
1637 /// Distinguishes between Attributes that decorate items and Attributes that
1638 /// are contained as statements within items. These two cases need to be
1639 /// distinguished for pretty-printing.
1640 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1641 pub enum AttrStyle {
1646 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1647 pub struct AttrId(pub usize);
1649 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1651 pub struct Attribute_ {
1653 pub style: AttrStyle,
1654 pub value: P<MetaItem>,
1655 pub is_sugared_doc: bool,
1658 /// TraitRef's appear in impls.
1660 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1661 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1662 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1663 /// same as the impl's node id).
1664 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1665 pub struct TraitRef {
1670 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1671 pub struct PolyTraitRef {
1672 /// The `'a` in `<'a> Foo<&'a T>`
1673 pub bound_lifetimes: Vec<LifetimeDef>,
1675 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1676 pub trait_ref: TraitRef,
1681 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1682 pub enum Visibility {
1688 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1690 Inherited => parent_visibility,
1696 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1697 pub struct StructField_ {
1698 pub kind: StructFieldKind,
1701 pub attrs: Vec<Attribute>,
1705 pub fn ident(&self) -> Option<Ident> {
1707 NamedField(ref ident, _) => Some(ident.clone()),
1708 UnnamedField(_) => None
1713 pub type StructField = Spanned<StructField_>;
1715 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1716 pub enum StructFieldKind {
1717 NamedField(Ident, Visibility),
1718 /// Element of a tuple-like struct
1719 UnnamedField(Visibility),
1722 impl StructFieldKind {
1723 pub fn is_unnamed(&self) -> bool {
1725 UnnamedField(..) => true,
1726 NamedField(..) => false,
1730 pub fn visibility(&self) -> Visibility {
1732 NamedField(_, vis) | UnnamedField(vis) => vis
1737 /// Fields and Ids of enum variants and structs
1739 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1740 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1741 /// One shared Id can be successfully used for these two purposes.
1742 /// Id of the whole enum lives in `Item`.
1744 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1745 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1746 /// the variant itself" from enum variants.
1747 /// Id of the whole struct lives in `Item`.
1748 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1749 pub enum VariantData {
1750 Struct(Vec<StructField>, NodeId),
1751 Tuple(Vec<StructField>, NodeId),
1756 pub fn fields(&self) -> &[StructField] {
1758 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1762 pub fn id(&self) -> NodeId {
1764 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1767 pub fn is_struct(&self) -> bool {
1768 if let VariantData::Struct(..) = *self { true } else { false }
1770 pub fn is_tuple(&self) -> bool {
1771 if let VariantData::Tuple(..) = *self { true } else { false }
1773 pub fn is_unit(&self) -> bool {
1774 if let VariantData::Unit(..) = *self { true } else { false }
1779 FIXME (#3300): Should allow items to be anonymous. Right now
1780 we just use dummy names for anon items.
1784 /// The name might be a dummy name in case of anonymous items
1785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1788 pub attrs: Vec<Attribute>,
1791 pub vis: Visibility,
1795 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1797 /// An`extern crate` item, with optional original crate name,
1799 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1800 ItemExternCrate(Option<Name>),
1801 /// A `use` or `pub use` item
1802 ItemUse(P<ViewPath>),
1805 ItemStatic(P<Ty>, Mutability, P<Expr>),
1807 ItemConst(P<Ty>, P<Expr>),
1808 /// A function declaration
1809 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1812 /// An external module
1813 ItemForeignMod(ForeignMod),
1814 /// A type alias, e.g. `type Foo = Bar<u8>`
1815 ItemTy(P<Ty>, Generics),
1816 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1817 ItemEnum(EnumDef, Generics),
1818 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1819 ItemStruct(VariantData, Generics),
1820 /// Represents a Trait Declaration
1826 // Default trait implementations
1828 // `impl Trait for .. {}`
1829 ItemDefaultImpl(Unsafety, TraitRef),
1830 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1834 Option<TraitRef>, // (optional) trait this impl implements
1837 /// A macro invocation (which includes macro definition)
1842 pub fn descriptive_variant(&self) -> &str {
1844 ItemExternCrate(..) => "extern crate",
1845 ItemUse(..) => "use",
1846 ItemStatic(..) => "static item",
1847 ItemConst(..) => "constant item",
1848 ItemFn(..) => "function",
1849 ItemMod(..) => "module",
1850 ItemForeignMod(..) => "foreign module",
1851 ItemTy(..) => "type alias",
1852 ItemEnum(..) => "enum",
1853 ItemStruct(..) => "struct",
1854 ItemTrait(..) => "trait",
1857 ItemDefaultImpl(..) => "item"
1862 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1863 pub struct ForeignItem {
1865 pub attrs: Vec<Attribute>,
1866 pub node: ForeignItem_,
1869 pub vis: Visibility,
1872 /// An item within an `extern` block
1873 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1874 pub enum ForeignItem_ {
1875 /// A foreign function
1876 ForeignItemFn(P<FnDecl>, Generics),
1877 /// A foreign static item (`static ext: u8`), with optional mutability
1878 /// (the boolean is true when mutable)
1879 ForeignItemStatic(P<Ty>, bool),
1883 pub fn descriptive_variant(&self) -> &str {
1885 ForeignItemFn(..) => "foreign function",
1886 ForeignItemStatic(..) => "foreign static item"
1891 /// A macro definition, in this crate or imported from another.
1893 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1894 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1895 pub struct MacroDef {
1897 pub attrs: Vec<Attribute>,
1900 pub imported_from: Option<Ident>,
1902 pub use_locally: bool,
1903 pub allow_internal_unstable: bool,
1904 pub body: Vec<TokenTree>,
1912 // are ASTs encodable?
1914 fn check_asts_encodable() {
1915 fn assert_encodable<T: serialize::Encodable>() {}
1916 assert_encodable::<Crate>();