1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // The Rust abstract syntax tree.
13 pub use self::AsmDialect::*;
14 pub use self::AttrStyle::*;
15 pub use self::BindingMode::*;
16 pub use self::BinOp_::*;
17 pub use self::BlockCheckMode::*;
18 pub use self::CaptureClause::*;
19 pub use self::Decl_::*;
20 pub use self::ExplicitSelf_::*;
21 pub use self::Expr_::*;
22 pub use self::FloatTy::*;
23 pub use self::FunctionRetTy::*;
24 pub use self::ForeignItem_::*;
25 pub use self::ImplItem_::*;
26 pub use self::IntTy::*;
27 pub use self::Item_::*;
28 pub use self::KleeneOp::*;
29 pub use self::Lit_::*;
30 pub use self::LitIntType::*;
31 pub use self::Mac_::*;
32 pub use self::MacStmtStyle::*;
33 pub use self::MetaItem_::*;
34 pub use self::Mutability::*;
35 pub use self::Pat_::*;
36 pub use self::PathListItem_::*;
37 pub use self::PatWildKind::*;
38 pub use self::PrimTy::*;
39 pub use self::Sign::*;
40 pub use self::Stmt_::*;
41 pub use self::StrStyle::*;
42 pub use self::StructFieldKind::*;
43 pub use self::TokenTree::*;
44 pub use self::TraitItem_::*;
46 pub use self::TyParamBound::*;
47 pub use self::UintTy::*;
48 pub use self::UnOp::*;
49 pub use self::UnsafeSource::*;
50 pub use self::VariantKind::*;
51 pub use self::ViewPath_::*;
52 pub use self::Visibility::*;
53 pub use self::PathParameters::*;
55 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
59 use ext::tt::macro_parser;
60 use owned_slice::OwnedSlice;
61 use parse::token::{InternedString, str_to_ident};
64 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
71 use serialize::{Encodable, Decodable, Encoder, Decoder};
73 // FIXME #6993: in librustc, uses of "ident" should be replaced
76 /// An identifier contains a Name (index into the interner
77 /// table) and a SyntaxContext to track renaming and
78 /// macro expansion per Flatt et al., "Macros
79 /// That Work Together"
80 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
83 pub ctxt: SyntaxContext
87 /// Construct an identifier with the given name and an empty context:
88 pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
91 impl fmt::Debug for Ident {
92 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 write!(f, "{}#{}", self.name, self.ctxt)
97 impl fmt::Display for Ident {
98 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99 fmt::Display::fmt(&self.name, f)
103 impl fmt::Debug for Name {
104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105 let Name(nm) = *self;
106 write!(f, "{}({})", self, nm)
110 impl fmt::Display for Name {
111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
112 fmt::Display::fmt(&self.as_str(), f)
116 impl PartialEq for Ident {
117 fn eq(&self, other: &Ident) -> bool {
118 if self.ctxt == other.ctxt {
119 self.name == other.name
121 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
122 // idents that have different contexts. You can't fix this without
123 // knowing whether the comparison should be hygienic or non-hygienic.
124 // if it should be non-hygienic (most things are), just compare the
125 // 'name' fields of the idents. Or, even better, replace the idents
128 // On the other hand, if the comparison does need to be hygienic,
129 // one example and its non-hygienic counterpart would be:
130 // syntax::parse::token::Token::mtwt_eq
131 // syntax::ext::tt::macro_parser::token_name_eq
132 panic!("not allowed to compare these idents: {:?}, {:?}. \
133 Probably related to issue \\#6993", self, other);
138 /// A SyntaxContext represents a chain of macro-expandings
139 /// and renamings. Each macro expansion corresponds to
142 // I'm representing this syntax context as an index into
143 // a table, in order to work around a compiler bug
144 // that's causing unreleased memory to cause core dumps
145 // and also perhaps to save some work in destructor checks.
146 // the special uint '0' will be used to indicate an empty
149 // this uint is a reference to a table stored in thread-local
151 pub type SyntaxContext = u32;
152 pub const EMPTY_CTXT : SyntaxContext = 0;
153 pub const ILLEGAL_CTXT : SyntaxContext = 1;
155 /// A name is a part of an identifier, representing a string or gensym. It's
156 /// the result of interning.
157 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
158 RustcEncodable, RustcDecodable, Clone, Copy)]
159 pub struct Name(pub u32);
161 impl<T: AsRef<str>> PartialEq<T> for Name {
162 fn eq(&self, other: &T) -> bool {
163 self.as_str() == other.as_ref()
168 pub fn as_str(&self) -> token::InternedString {
169 token::InternedString::new_from_name(*self)
172 pub fn usize(&self) -> usize {
173 let Name(nm) = *self;
177 pub fn ident(&self) -> Ident {
178 Ident { name: *self, ctxt: 0 }
182 /// A mark represents a unique id associated with a macro expansion
185 impl Encodable for Ident {
186 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
187 s.emit_str(&self.name.as_str())
191 impl Decodable for Ident {
192 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
193 Ok(str_to_ident(&try!(d.read_str())[..]))
197 /// Function name (not all functions have names)
198 pub type FnIdent = Option<Ident>;
200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
201 pub struct Lifetime {
207 impl fmt::Debug for Lifetime {
208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
209 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
213 /// A lifetime definition, eg `'a: 'b+'c+'d`
214 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
215 pub struct LifetimeDef {
216 pub lifetime: Lifetime,
217 pub bounds: Vec<Lifetime>
220 /// A "Path" is essentially Rust's notion of a name; for instance:
221 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
222 /// along with a bunch of supporting information.
223 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
226 /// A `::foo` path, is relative to the crate root rather than current
227 /// module (like paths in an import).
229 /// The segments in the path: the things separated by `::`.
230 pub segments: Vec<PathSegment>,
233 impl fmt::Debug for Path {
234 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
235 write!(f, "path({})", pprust::path_to_string(self))
239 impl fmt::Display for Path {
240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
241 write!(f, "{}", pprust::path_to_string(self))
245 /// A segment of a path: an identifier, an optional lifetime, and a set of
247 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
248 pub struct PathSegment {
249 /// The identifier portion of this path segment.
250 pub identifier: Ident,
252 /// Type/lifetime parameters attached to this path. They come in
253 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
254 /// this is more than just simple syntactic sugar; the use of
255 /// parens affects the region binding rules, so we preserve the
257 pub parameters: PathParameters,
260 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
261 pub enum PathParameters {
262 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
263 AngleBracketedParameters(AngleBracketedParameterData),
264 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
265 ParenthesizedParameters(ParenthesizedParameterData),
268 impl PathParameters {
269 pub fn none() -> PathParameters {
270 AngleBracketedParameters(AngleBracketedParameterData {
271 lifetimes: Vec::new(),
272 types: OwnedSlice::empty(),
273 bindings: OwnedSlice::empty(),
277 pub fn is_empty(&self) -> bool {
279 AngleBracketedParameters(ref data) => data.is_empty(),
281 // Even if the user supplied no types, something like
282 // `X()` is equivalent to `X<(),()>`.
283 ParenthesizedParameters(..) => false,
287 pub fn has_lifetimes(&self) -> bool {
289 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
290 ParenthesizedParameters(_) => false,
294 pub fn has_types(&self) -> bool {
296 AngleBracketedParameters(ref data) => !data.types.is_empty(),
297 ParenthesizedParameters(..) => true,
301 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
302 /// parameters in the parenthesized case.
303 pub fn types(&self) -> Vec<&P<Ty>> {
305 AngleBracketedParameters(ref data) => {
306 data.types.iter().collect()
308 ParenthesizedParameters(ref data) => {
310 .chain(data.output.iter())
316 pub fn lifetimes(&self) -> Vec<&Lifetime> {
318 AngleBracketedParameters(ref data) => {
319 data.lifetimes.iter().collect()
321 ParenthesizedParameters(_) => {
327 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
329 AngleBracketedParameters(ref data) => {
330 data.bindings.iter().collect()
332 ParenthesizedParameters(_) => {
339 /// A path like `Foo<'a, T>`
340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
341 pub struct AngleBracketedParameterData {
342 /// The lifetime parameters for this path segment.
343 pub lifetimes: Vec<Lifetime>,
344 /// The type parameters for this path segment, if present.
345 pub types: OwnedSlice<P<Ty>>,
346 /// Bindings (equality constraints) on associated types, if present.
347 /// E.g., `Foo<A=Bar>`.
348 pub bindings: OwnedSlice<P<TypeBinding>>,
351 impl AngleBracketedParameterData {
352 fn is_empty(&self) -> bool {
353 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
357 /// A path like `Foo(A,B) -> C`
358 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
359 pub struct ParenthesizedParameterData {
364 pub inputs: Vec<P<Ty>>,
367 pub output: Option<P<Ty>>,
370 pub type CrateNum = u32;
372 pub type NodeId = u32;
374 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
375 RustcDecodable, Hash, Copy)]
381 fn default_def_id_debug(_: DefId, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
383 thread_local!(pub static DEF_ID_DEBUG: Cell<fn(DefId, &mut fmt::Formatter) -> fmt::Result> =
384 Cell::new(default_def_id_debug));
386 impl fmt::Debug for DefId {
387 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
388 try!(write!(f, "DefId {{ krate: {}, node: {} }}",
389 self.krate, self.node));
390 DEF_ID_DEBUG.with(|def_id_debug| def_id_debug.get()(*self, f))
395 /// Read the node id, asserting that this def-id is krate-local.
396 pub fn local_id(&self) -> NodeId {
397 assert_eq!(self.krate, LOCAL_CRATE);
402 /// Item definitions in the currently-compiled crate would have the CrateNum
403 /// LOCAL_CRATE in their DefId.
404 pub const LOCAL_CRATE: CrateNum = 0;
405 pub const CRATE_NODE_ID: NodeId = 0;
407 /// When parsing and doing expansions, we initially give all AST nodes this AST
408 /// node value. Then later, in the renumber pass, we renumber them to have
409 /// small, positive ids.
410 pub const DUMMY_NODE_ID: NodeId = !0;
412 /// The AST represents all type param bounds as types.
413 /// typeck::collect::compute_bounds matches these against
414 /// the "special" built-in traits (see middle::lang_items) and
415 /// detects Copy, Send and Sync.
416 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
417 pub enum TyParamBound {
418 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
419 RegionTyParamBound(Lifetime)
422 /// A modifier on a bound, currently this is only used for `?Sized`, where the
423 /// modifier is `Maybe`. Negative bounds should also be handled here.
424 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
425 pub enum TraitBoundModifier {
430 pub type TyParamBounds = OwnedSlice<TyParamBound>;
432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
436 pub bounds: TyParamBounds,
437 pub default: Option<P<Ty>>,
441 /// Represents lifetimes and type parameters attached to a declaration
442 /// of a function, enum, trait, etc.
443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
444 pub struct Generics {
445 pub lifetimes: Vec<LifetimeDef>,
446 pub ty_params: OwnedSlice<TyParam>,
447 pub where_clause: WhereClause,
451 pub fn is_lt_parameterized(&self) -> bool {
452 !self.lifetimes.is_empty()
454 pub fn is_type_parameterized(&self) -> bool {
455 !self.ty_params.is_empty()
457 pub fn is_parameterized(&self) -> bool {
458 self.is_lt_parameterized() || self.is_type_parameterized()
462 /// A `where` clause in a definition
463 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
464 pub struct WhereClause {
466 pub predicates: Vec<WherePredicate>,
469 /// A single predicate in a `where` clause
470 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
471 pub enum WherePredicate {
472 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
473 BoundPredicate(WhereBoundPredicate),
474 /// A lifetime predicate, e.g. `'a: 'b+'c`
475 RegionPredicate(WhereRegionPredicate),
476 /// An equality predicate (unsupported)
477 EqPredicate(WhereEqPredicate),
480 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
481 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
482 pub struct WhereBoundPredicate {
484 /// Any lifetimes from a `for` binding
485 pub bound_lifetimes: Vec<LifetimeDef>,
486 /// The type being bounded
487 pub bounded_ty: P<Ty>,
488 /// Trait and lifetime bounds (`Clone+Send+'static`)
489 pub bounds: OwnedSlice<TyParamBound>,
492 /// A lifetime predicate, e.g. `'a: 'b+'c`
493 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
494 pub struct WhereRegionPredicate {
496 pub lifetime: Lifetime,
497 pub bounds: Vec<Lifetime>,
500 /// An equality predicate (unsupported), e.g. `T=int`
501 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
502 pub struct WhereEqPredicate {
509 /// The set of MetaItems that define the compilation environment of the crate,
510 /// used to drive conditional compilation
511 pub type CrateConfig = Vec<P<MetaItem>> ;
513 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
516 pub attrs: Vec<Attribute>,
517 pub config: CrateConfig,
519 pub exported_macros: Vec<MacroDef>,
522 pub type MetaItem = Spanned<MetaItem_>;
524 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
526 MetaWord(InternedString),
527 MetaList(InternedString, Vec<P<MetaItem>>),
528 MetaNameValue(InternedString, Lit),
531 // can't be derived because the MetaList requires an unordered comparison
532 impl PartialEq for MetaItem_ {
533 fn eq(&self, other: &MetaItem_) -> bool {
535 MetaWord(ref ns) => match *other {
536 MetaWord(ref no) => (*ns) == (*no),
539 MetaNameValue(ref ns, ref vs) => match *other {
540 MetaNameValue(ref no, ref vo) => {
541 (*ns) == (*no) && vs.node == vo.node
545 MetaList(ref ns, ref miss) => match *other {
546 MetaList(ref no, ref miso) => {
548 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
558 /// Statements in a block
559 pub stmts: Vec<P<Stmt>>,
560 /// An expression at the end of the block
561 /// without a semicolon, if any
562 pub expr: Option<P<Expr>>,
564 /// Distinguishes between `unsafe { ... }` and `{ ... }`
565 pub rules: BlockCheckMode,
569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
576 impl fmt::Debug for Pat {
577 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
578 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
582 /// A single field in a struct pattern
584 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
585 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
586 /// except is_shorthand is true
587 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
588 pub struct FieldPat {
589 /// The identifier for the field
591 /// The pattern the field is destructured to
593 pub is_shorthand: bool,
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
597 pub enum BindingMode {
598 BindByRef(Mutability),
599 BindByValue(Mutability),
602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
603 pub enum PatWildKind {
604 /// Represents the wildcard pattern `_`
607 /// Represents the wildcard pattern `..`
611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
613 /// Represents a wildcard pattern (either `_` or `..`)
614 PatWild(PatWildKind),
616 /// A PatIdent may either be a new bound variable,
617 /// or a nullary enum (in which case the third field
620 /// In the nullary enum case, the parser can't determine
621 /// which it is. The resolver determines this, and
622 /// records this pattern's NodeId in an auxiliary
623 /// set (of "PatIdents that refer to nullary enums")
624 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
626 /// "None" means a * pattern where we don't bind the fields to names.
627 PatEnum(Path, Option<Vec<P<Pat>>>),
629 /// An associated const named using the qualified path `<T>::CONST` or
630 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
631 /// referred to as simply `T::CONST`, in which case they will end up as
632 /// PatEnum, and the resolver will have to sort that out.
633 PatQPath(QSelf, Path),
635 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
636 /// The `bool` is `true` in the presence of a `..`
637 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
638 /// A tuple pattern `(a, b)`
642 /// A reference pattern, e.g. `&mut (a, b)`
643 PatRegion(P<Pat>, Mutability),
646 /// A range pattern, e.g. `1...2`
647 PatRange(P<Expr>, P<Expr>),
648 /// [a, b, ..i, y, z] is represented as:
649 /// PatVec(box [a, b], Some(i), box [y, z])
650 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
651 /// A macro pattern; pre-expansion
655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
656 pub enum Mutability {
661 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
663 /// The `+` operator (addition)
665 /// The `-` operator (subtraction)
667 /// The `*` operator (multiplication)
669 /// The `/` operator (division)
671 /// The `%` operator (modulus)
673 /// The `&&` operator (logical and)
675 /// The `||` operator (logical or)
677 /// The `^` operator (bitwise xor)
679 /// The `&` operator (bitwise and)
681 /// The `|` operator (bitwise or)
683 /// The `<<` operator (shift left)
685 /// The `>>` operator (shift right)
687 /// The `==` operator (equality)
689 /// The `<` operator (less than)
691 /// The `<=` operator (less than or equal to)
693 /// The `!=` operator (not equal to)
695 /// The `>=` operator (greater than or equal to)
697 /// The `>` operator (greater than)
701 pub type BinOp = Spanned<BinOp_>;
703 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
705 /// The `box` operator
707 /// The `*` operator for dereferencing
709 /// The `!` operator for logical inversion
711 /// The `-` operator for negation
716 pub type Stmt = Spanned<Stmt_>;
718 impl fmt::Debug for Stmt {
719 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
720 write!(f, "stmt({}: {})",
721 ast_util::stmt_id(self),
722 pprust::stmt_to_string(self))
727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
729 /// Could be an item or a local (let) binding:
730 StmtDecl(P<Decl>, NodeId),
732 /// Expr without trailing semi-colon (must have unit type):
733 StmtExpr(P<Expr>, NodeId),
735 /// Expr with trailing semi-colon (may have any type):
736 StmtSemi(P<Expr>, NodeId),
738 StmtMac(P<Mac>, MacStmtStyle),
740 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
741 pub enum MacStmtStyle {
742 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
743 /// `foo!(...);`, `foo![...];`
744 MacStmtWithSemicolon,
745 /// The macro statement had braces; e.g. foo! { ... }
747 /// The macro statement had parentheses or brackets and no semicolon; e.g.
748 /// `foo!(...)`. All of these will end up being converted into macro
750 MacStmtWithoutBraces,
753 // FIXME (pending discussion of #1697, #2178...): local should really be
754 // a refinement on pat.
755 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
756 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
759 pub ty: Option<P<Ty>>,
760 /// Initializer expression to set the value, if any
761 pub init: Option<P<Expr>>,
766 pub type Decl = Spanned<Decl_>;
768 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
770 /// A local (let) binding:
776 /// represents one arm of a 'match'
777 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
779 pub attrs: Vec<Attribute>,
780 pub pats: Vec<P<Pat>>,
781 pub guard: Option<P<Expr>>,
785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
787 pub ident: SpannedIdent,
792 pub type SpannedIdent = Spanned<Ident>;
794 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
795 pub enum BlockCheckMode {
797 UnsafeBlock(UnsafeSource),
798 PushUnsafeBlock(UnsafeSource),
799 PopUnsafeBlock(UnsafeSource),
802 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
803 pub enum UnsafeSource {
809 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
816 impl fmt::Debug for Expr {
817 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
818 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
824 /// First expr is the place; second expr is the value.
825 ExprBox(Option<P<Expr>>, P<Expr>),
826 /// An array (`[a, b, c, d]`)
827 ExprVec(Vec<P<Expr>>),
830 /// The first field resolves to the function itself,
831 /// and the second field is the list of arguments
832 ExprCall(P<Expr>, Vec<P<Expr>>),
833 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
835 /// The `SpannedIdent` is the identifier for the method name.
836 /// The vector of `Ty`s are the ascripted type parameters for the method
837 /// (within the angle brackets).
839 /// The first element of the vector of `Expr`s is the expression that evaluates
840 /// to the object on which the method is being called on (the receiver),
841 /// and the remaining elements are the rest of the arguments.
843 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
844 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
845 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
846 /// A tuple (`(a, b, c ,d)`)
847 ExprTup(Vec<P<Expr>>),
848 /// A binary operation (For example: `a + b`, `a * b`)
849 ExprBinary(BinOp, P<Expr>, P<Expr>),
850 /// A unary operation (For example: `!x`, `*x`)
851 ExprUnary(UnOp, P<Expr>),
852 /// A literal (For example: `1u8`, `"foo"`)
854 /// A cast (`foo as f64`)
855 ExprCast(P<Expr>, P<Ty>),
856 /// An `if` block, with an optional else block
858 /// `if expr { block } else { expr }`
859 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
860 /// An `if let` expression with an optional else block
862 /// `if let pat = expr { block } else { expr }`
864 /// This is desugared to a `match` expression.
865 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
866 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
867 /// A while loop, with an optional label
869 /// `'label: while expr { block }`
870 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
871 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
872 /// A while-let loop, with an optional label
874 /// `'label: while let pat = expr { block }`
876 /// This is desugared to a combination of `loop` and `match` expressions.
877 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
878 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
879 /// A for loop, with an optional label
881 /// `'label: for pat in expr { block }`
883 /// This is desugared to a combination of `loop` and `match` expressions.
884 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
885 /// Conditionless loop (can be exited with break, continue, or return)
887 /// `'label: loop { block }`
888 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
889 ExprLoop(P<Block>, Option<Ident>),
890 /// A `match` block, with a source that indicates whether or not it is
891 /// the result of a desugaring, and if so, which kind.
892 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
893 /// A closure (for example, `move |a, b, c| {a + b + c}`)
894 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
895 /// A block (`{ ... }`)
898 /// An assignment (`a = foo()`)
899 ExprAssign(P<Expr>, P<Expr>),
900 /// An assignment with an operator
902 /// For example, `a += 1`.
903 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
904 /// Access of a named struct field (`obj.foo`)
905 ExprField(P<Expr>, SpannedIdent),
906 /// Access of an unnamed field of a struct or tuple-struct
908 /// For example, `foo.0`.
909 ExprTupField(P<Expr>, Spanned<usize>),
910 /// An indexing operation (`foo[2]`)
911 ExprIndex(P<Expr>, P<Expr>),
912 /// A range (`1..2`, `1..`, or `..2`)
913 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
915 /// Variable reference, possibly containing `::` and/or type
916 /// parameters, e.g. foo::bar::<baz>.
918 /// Optionally "qualified",
919 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
920 ExprPath(Option<QSelf>, Path),
922 /// A referencing operation (`&a` or `&mut a`)
923 ExprAddrOf(Mutability, P<Expr>),
924 /// A `break`, with an optional label to break
925 ExprBreak(Option<Ident>),
926 /// A `continue`, with an optional label
927 ExprAgain(Option<Ident>),
928 /// A `return`, with an optional value to be returned
929 ExprRet(Option<P<Expr>>),
931 /// Output of the `asm!()` macro
932 ExprInlineAsm(InlineAsm),
934 /// A macro invocation; pre-expansion
937 /// A struct literal expression.
939 /// For example, `Foo {x: 1, y: 2}`, or
940 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
941 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
943 /// An array literal constructed from one repeated element.
945 /// For example, `[1u8; 5]`. The first expression is the element
946 /// to be repeated; the second is the number of times to repeat it.
947 ExprRepeat(P<Expr>, P<Expr>),
949 /// No-op: used solely so we can pretty-print faithfully
953 /// The explicit Self type in a "qualified path". The actual
954 /// path, including the trait and the associated item, is stored
955 /// separately. `position` represents the index of the associated
956 /// item qualified with this Self type.
958 /// <Vec<T> as a::b::Trait>::AssociatedItem
959 /// ^~~~~ ~~~~~~~~~~~~~~^
962 /// <Vec<T>>::AssociatedItem
965 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
971 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
972 pub enum MatchSource {
974 IfLetDesugar { contains_else_clause: bool },
979 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
980 pub enum CaptureClause {
985 /// A delimited sequence of token trees
986 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
987 pub struct Delimited {
988 /// The type of delimiter
989 pub delim: token::DelimToken,
990 /// The span covering the opening delimiter
992 /// The delimited sequence of token trees
993 pub tts: Vec<TokenTree>,
994 /// The span covering the closing delimiter
995 pub close_span: Span,
999 /// Returns the opening delimiter as a token.
1000 pub fn open_token(&self) -> token::Token {
1001 token::OpenDelim(self.delim)
1004 /// Returns the closing delimiter as a token.
1005 pub fn close_token(&self) -> token::Token {
1006 token::CloseDelim(self.delim)
1009 /// Returns the opening delimiter as a token tree.
1010 pub fn open_tt(&self) -> TokenTree {
1011 TtToken(self.open_span, self.open_token())
1014 /// Returns the closing delimiter as a token tree.
1015 pub fn close_tt(&self) -> TokenTree {
1016 TtToken(self.close_span, self.close_token())
1020 /// A sequence of token treesee
1021 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1022 pub struct SequenceRepetition {
1023 /// The sequence of token trees
1024 pub tts: Vec<TokenTree>,
1025 /// The optional separator
1026 pub separator: Option<token::Token>,
1027 /// Whether the sequence can be repeated zero (*), or one or more times (+)
1029 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
1030 pub num_captures: usize,
1033 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
1034 /// for token sequences.
1035 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1041 /// When the main rust parser encounters a syntax-extension invocation, it
1042 /// parses the arguments to the invocation as a token-tree. This is a very
1043 /// loose structure, such that all sorts of different AST-fragments can
1044 /// be passed to syntax extensions using a uniform type.
1046 /// If the syntax extension is an MBE macro, it will attempt to match its
1047 /// LHS token tree against the provided token tree, and if it finds a
1048 /// match, will transcribe the RHS token tree, splicing in any captured
1049 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1051 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1052 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1053 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1054 pub enum TokenTree {
1056 TtToken(Span, token::Token),
1057 /// A delimited sequence of token trees
1058 TtDelimited(Span, Rc<Delimited>),
1060 // This only makes sense in MBE macros.
1062 /// A kleene-style repetition sequence with a span
1063 // FIXME(eddyb) #12938 Use DST.
1064 TtSequence(Span, Rc<SequenceRepetition>),
1068 pub fn len(&self) -> usize {
1070 TtToken(_, token::DocComment(name)) => {
1071 match doc_comment_style(&name.as_str()) {
1076 TtToken(_, token::SpecialVarNt(..)) => 2,
1077 TtToken(_, token::MatchNt(..)) => 3,
1078 TtDelimited(_, ref delimed) => {
1079 delimed.tts.len() + 2
1081 TtSequence(_, ref seq) => {
1088 pub fn get_tt(&self, index: usize) -> TokenTree {
1089 match (self, index) {
1090 (&TtToken(sp, token::DocComment(_)), 0) => {
1091 TtToken(sp, token::Pound)
1093 (&TtToken(sp, token::DocComment(name)), 1)
1094 if doc_comment_style(&name.as_str()) == AttrInner => {
1095 TtToken(sp, token::Not)
1097 (&TtToken(sp, token::DocComment(name)), _) => {
1098 let stripped = strip_doc_comment_decoration(&name.as_str());
1099 TtDelimited(sp, Rc::new(Delimited {
1100 delim: token::Bracket,
1102 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1104 TtToken(sp, token::Eq),
1105 TtToken(sp, token::Literal(
1106 token::StrRaw(token::intern(&stripped), 0), None))],
1110 (&TtDelimited(_, ref delimed), _) => {
1112 return delimed.open_tt();
1114 if index == delimed.tts.len() + 1 {
1115 return delimed.close_tt();
1117 delimed.tts[index - 1].clone()
1119 (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1120 let v = [TtToken(sp, token::Dollar),
1121 TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1125 (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1126 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1127 TtToken(sp, token::Colon),
1128 TtToken(sp, token::Ident(kind, kind_st))];
1131 (&TtSequence(_, ref seq), _) => {
1132 seq.tts[index].clone()
1134 _ => panic!("Cannot expand a token tree")
1138 /// Returns the `Span` corresponding to this token tree.
1139 pub fn get_span(&self) -> Span {
1141 TtToken(span, _) => span,
1142 TtDelimited(span, _) => span,
1143 TtSequence(span, _) => span,
1147 /// Use this token tree as a matcher to parse given tts.
1148 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1149 -> macro_parser::NamedParseResult {
1150 // `None` is because we're not interpolating
1151 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1154 tts.iter().cloned().collect(),
1156 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1160 pub type Mac = Spanned<Mac_>;
1162 /// Represents a macro invocation. The Path indicates which macro
1163 /// is being invoked, and the vector of token-trees contains the source
1164 /// of the macro invocation.
1166 /// There's only one flavor, now, so this could presumably be simplified.
1167 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1169 // NB: the additional ident for a macro_rules-style macro is actually
1170 // stored in the enclosing item. Oog.
1171 MacInvocTT(Path, Vec<TokenTree>, SyntaxContext), // new macro-invocation
1174 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1176 /// A regular string, like `"foo"`
1178 /// A raw string, like `r##"foo"##`
1180 /// The uint is the number of `#` symbols used
1185 pub type Lit = Spanned<Lit_>;
1187 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1194 pub fn new<T: IntSign>(n: T) -> Sign {
1200 fn sign(&self) -> Sign;
1203 ($($t:ident)*) => ($(impl IntSign for $t {
1204 #[allow(unused_comparisons)]
1205 fn sign(&self) -> Sign {
1206 if *self < 0 {Minus} else {Plus}
1210 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1212 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1213 pub enum LitIntType {
1214 SignedIntLit(IntTy, Sign),
1215 UnsignedIntLit(UintTy),
1216 UnsuffixedIntLit(Sign)
1219 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1221 /// A string literal (`"foo"`)
1222 LitStr(InternedString, StrStyle),
1223 /// A byte string (`b"foo"`)
1224 LitBinary(Rc<Vec<u8>>),
1225 /// A byte char (`b'f'`)
1227 /// A character literal (`'a'`)
1229 /// An integer literal (`1u8`)
1230 LitInt(u64, LitIntType),
1231 /// A float literal (`1f64` or `1E10f64`)
1232 LitFloat(InternedString, FloatTy),
1233 /// A float literal without a suffix (`1.0 or 1.0E10`)
1234 LitFloatUnsuffixed(InternedString),
1235 /// A boolean literal
1239 // NB: If you change this, you'll probably want to change the corresponding
1240 // type structure in middle/ty.rs as well.
1241 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1244 pub mutbl: Mutability,
1247 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1248 pub struct TypeField {
1254 /// Represents a method's signature in a trait declaration,
1255 /// or in an implementation.
1256 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1257 pub struct MethodSig {
1258 pub unsafety: Unsafety,
1259 pub constness: Constness,
1261 pub decl: P<FnDecl>,
1262 pub generics: Generics,
1263 pub explicit_self: ExplicitSelf,
1266 /// Represents a method declaration in a trait declaration, possibly including
1267 /// a default implementation A trait method is either required (meaning it
1268 /// doesn't have an implementation, just a signature) or provided (meaning it
1269 /// has a default implementation).
1270 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1271 pub struct TraitItem {
1274 pub attrs: Vec<Attribute>,
1275 pub node: TraitItem_,
1279 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1280 pub enum TraitItem_ {
1281 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1282 MethodTraitItem(MethodSig, Option<P<Block>>),
1283 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1286 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1287 pub struct ImplItem {
1290 pub vis: Visibility,
1291 pub attrs: Vec<Attribute>,
1292 pub node: ImplItem_,
1296 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1297 pub enum ImplItem_ {
1298 ConstImplItem(P<Ty>, P<Expr>),
1299 MethodImplItem(MethodSig, P<Block>),
1300 TypeImplItem(P<Ty>),
1304 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1313 impl fmt::Debug for IntTy {
1314 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1315 fmt::Display::fmt(self, f)
1319 impl fmt::Display for IntTy {
1320 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1321 write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1326 pub fn bit_width(&self) -> Option<usize> {
1328 TyIs => return None,
1337 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1347 pub fn bit_width(&self) -> Option<usize> {
1349 TyUs => return None,
1358 impl fmt::Debug for UintTy {
1359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1360 fmt::Display::fmt(self, f)
1364 impl fmt::Display for UintTy {
1365 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1366 write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1370 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1376 impl fmt::Debug for FloatTy {
1377 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1378 fmt::Display::fmt(self, f)
1382 impl fmt::Display for FloatTy {
1383 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1384 write!(f, "{}", ast_util::float_ty_to_string(*self))
1389 pub fn bit_width(&self) -> usize {
1397 // Bind a type to an associated type: `A=Foo`.
1398 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1399 pub struct TypeBinding {
1407 // NB PartialEq method appears below.
1408 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1415 impl fmt::Debug for Ty {
1416 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1417 write!(f, "type({})", pprust::ty_to_string(self))
1421 /// Not represented directly in the AST, referred to by name through a ty_path.
1422 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1433 pub struct BareFnTy {
1434 pub unsafety: Unsafety,
1436 pub lifetimes: Vec<LifetimeDef>,
1440 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1441 /// The different kinds of types recognized by the compiler
1444 /// A fixed length array (`[T; n]`)
1445 TyFixedLengthVec(P<Ty>, P<Expr>),
1446 /// A raw pointer (`*const T` or `*mut T`)
1448 /// A reference (`&'a T` or `&'a mut T`)
1449 TyRptr(Option<Lifetime>, MutTy),
1450 /// A bare function (e.g. `fn(usize) -> bool`)
1451 TyBareFn(P<BareFnTy>),
1452 /// A tuple (`(A, B, C, D,...)`)
1454 /// A path (`module::module::...::Type`), optionally
1455 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1457 /// Type parameters are stored in the Path itself
1458 TyPath(Option<QSelf>, Path),
1459 /// Something like `A+B`. Note that `B` must always be a path.
1460 TyObjectSum(P<Ty>, TyParamBounds),
1461 /// A type like `for<'a> Foo<&'a Bar>`
1462 TyPolyTraitRef(TyParamBounds),
1463 /// No-op; kept solely so that we can pretty-print faithfully
1467 /// TyInfer means the type should be inferred instead of it having been
1468 /// specified. This can appear anywhere in a type.
1470 // A macro in the type position.
1474 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1475 pub enum AsmDialect {
1480 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1481 pub struct InlineAsm {
1482 pub asm: InternedString,
1483 pub asm_str_style: StrStyle,
1484 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1485 pub inputs: Vec<(InternedString, P<Expr>)>,
1486 pub clobbers: Vec<InternedString>,
1488 pub alignstack: bool,
1489 pub dialect: AsmDialect,
1490 pub expn_id: ExpnId,
1493 /// represents an argument in a function header
1494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1502 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1503 let path = Spanned{span:span,node:self_ident};
1505 // HACK(eddyb) fake type for the self argument.
1513 node: PatIdent(BindByValue(mutability), path, None),
1521 /// Represents the header (not the body) of a function declaration
1522 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1524 pub inputs: Vec<Arg>,
1525 pub output: FunctionRetTy,
1529 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1535 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub enum Constness {
1541 impl fmt::Display for Unsafety {
1542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543 fmt::Display::fmt(match *self {
1544 Unsafety::Normal => "normal",
1545 Unsafety::Unsafe => "unsafe",
1550 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1551 pub enum ImplPolarity {
1552 /// `impl Trait for Type`
1554 /// `impl !Trait for Type`
1558 impl fmt::Debug for ImplPolarity {
1559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1561 ImplPolarity::Positive => "positive".fmt(f),
1562 ImplPolarity::Negative => "negative".fmt(f),
1568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1569 pub enum FunctionRetTy {
1570 /// Functions with return type `!`that always
1571 /// raise an error or exit (i.e. never return to the caller)
1573 /// Return type is not specified.
1575 /// Functions default to `()` and
1576 /// closures default to inference. Span points to where return
1577 /// type would be inserted.
1578 DefaultReturn(Span),
1583 impl FunctionRetTy {
1584 pub fn span(&self) -> Span {
1586 NoReturn(span) => span,
1587 DefaultReturn(span) => span,
1588 Return(ref ty) => ty.span
1593 /// Represents the kind of 'self' associated with a method
1594 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1595 pub enum ExplicitSelf_ {
1600 /// `&'lt self`, `&'lt mut self`
1601 SelfRegion(Option<Lifetime>, Mutability, Ident),
1603 SelfExplicit(P<Ty>, Ident),
1606 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1610 /// A span from the first token past `{` to the last token until `}`.
1611 /// For `mod foo;`, the inner span ranges from the first token
1612 /// to the last token in the external file.
1614 pub items: Vec<P<Item>>,
1617 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1618 pub struct ForeignMod {
1620 pub items: Vec<P<ForeignItem>>,
1623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1624 pub struct VariantArg {
1629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1630 pub enum VariantKind {
1631 /// Tuple variant, e.g. `Foo(A, B)`
1632 TupleVariantKind(Vec<VariantArg>),
1633 /// Struct variant, e.g. `Foo {x: A, y: B}`
1634 StructVariantKind(P<StructDef>),
1637 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1638 pub struct EnumDef {
1639 pub variants: Vec<P<Variant>>,
1642 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1643 pub struct Variant_ {
1645 pub attrs: Vec<Attribute>,
1646 pub kind: VariantKind,
1648 /// Explicit discriminant, eg `Foo = 1`
1649 pub disr_expr: Option<P<Expr>>,
1650 pub vis: Visibility,
1653 pub type Variant = Spanned<Variant_>;
1655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1656 pub enum PathListItem_ {
1659 /// renamed in list, eg `use foo::{bar as baz};`
1660 rename: Option<Ident>,
1664 /// renamed in list, eg `use foo::{self as baz};`
1665 rename: Option<Ident>,
1670 impl PathListItem_ {
1671 pub fn id(&self) -> NodeId {
1673 PathListIdent { id, .. } | PathListMod { id, .. } => id
1677 pub fn rename(&self) -> Option<Ident> {
1679 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1684 pub type PathListItem = Spanned<PathListItem_>;
1686 pub type ViewPath = Spanned<ViewPath_>;
1688 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1689 pub enum ViewPath_ {
1691 /// `foo::bar::baz as quux`
1695 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1696 ViewPathSimple(Ident, Path),
1701 /// `foo::bar::{a,b,c}`
1702 ViewPathList(Path, Vec<PathListItem>)
1705 /// Meta-data associated with an item
1706 pub type Attribute = Spanned<Attribute_>;
1708 /// Distinguishes between Attributes that decorate items and Attributes that
1709 /// are contained as statements within items. These two cases need to be
1710 /// distinguished for pretty-printing.
1711 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1712 pub enum AttrStyle {
1717 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1718 pub struct AttrId(pub usize);
1720 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1722 pub struct Attribute_ {
1724 pub style: AttrStyle,
1725 pub value: P<MetaItem>,
1726 pub is_sugared_doc: bool,
1729 /// TraitRef's appear in impls.
1731 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1732 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1733 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1734 /// same as the impl's node id).
1735 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1736 pub struct TraitRef {
1741 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1742 pub struct PolyTraitRef {
1743 /// The `'a` in `<'a> Foo<&'a T>`
1744 pub bound_lifetimes: Vec<LifetimeDef>,
1746 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1747 pub trait_ref: TraitRef,
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1753 pub enum Visibility {
1759 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1761 &Inherited => parent_visibility,
1767 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1768 pub struct StructField_ {
1769 pub kind: StructFieldKind,
1772 pub attrs: Vec<Attribute>,
1776 pub fn ident(&self) -> Option<Ident> {
1778 NamedField(ref ident, _) => Some(ident.clone()),
1779 UnnamedField(_) => None
1784 pub type StructField = Spanned<StructField_>;
1786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1787 pub enum StructFieldKind {
1788 NamedField(Ident, Visibility),
1789 /// Element of a tuple-like struct
1790 UnnamedField(Visibility),
1793 impl StructFieldKind {
1794 pub fn is_unnamed(&self) -> bool {
1796 UnnamedField(..) => true,
1797 NamedField(..) => false,
1802 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1803 pub struct StructDef {
1804 /// Fields, not including ctor
1805 pub fields: Vec<StructField>,
1806 /// ID of the constructor. This is only used for tuple- or enum-like
1808 pub ctor_id: Option<NodeId>,
1812 FIXME (#3300): Should allow items to be anonymous. Right now
1813 we just use dummy names for anon items.
1817 /// The name might be a dummy name in case of anonymous items
1818 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1821 pub attrs: Vec<Attribute>,
1824 pub vis: Visibility,
1828 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1830 /// An`extern crate` item, with optional original crate name,
1832 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1833 ItemExternCrate(Option<Name>),
1834 /// A `use` or `pub use` item
1835 ItemUse(P<ViewPath>),
1838 ItemStatic(P<Ty>, Mutability, P<Expr>),
1840 ItemConst(P<Ty>, P<Expr>),
1841 /// A function declaration
1842 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1845 /// An external module
1846 ItemForeignMod(ForeignMod),
1847 /// A type alias, e.g. `type Foo = Bar<u8>`
1848 ItemTy(P<Ty>, Generics),
1849 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1850 ItemEnum(EnumDef, Generics),
1851 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1852 ItemStruct(P<StructDef>, Generics),
1853 /// Represents a Trait Declaration
1859 // Default trait implementations
1861 // `impl Trait for .. {}`
1862 ItemDefaultImpl(Unsafety, TraitRef),
1863 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1867 Option<TraitRef>, // (optional) trait this impl implements
1870 /// A macro invocation (which includes macro definition)
1875 pub fn descriptive_variant(&self) -> &str {
1877 ItemExternCrate(..) => "extern crate",
1878 ItemUse(..) => "use",
1879 ItemStatic(..) => "static item",
1880 ItemConst(..) => "constant item",
1881 ItemFn(..) => "function",
1882 ItemMod(..) => "module",
1883 ItemForeignMod(..) => "foreign module",
1884 ItemTy(..) => "type alias",
1885 ItemEnum(..) => "enum",
1886 ItemStruct(..) => "struct",
1887 ItemTrait(..) => "trait",
1890 ItemDefaultImpl(..) => "item"
1895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1896 pub struct ForeignItem {
1898 pub attrs: Vec<Attribute>,
1899 pub node: ForeignItem_,
1902 pub vis: Visibility,
1905 /// An item within an `extern` block
1906 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1907 pub enum ForeignItem_ {
1908 /// A foreign function
1909 ForeignItemFn(P<FnDecl>, Generics),
1910 /// A foreign static item (`static ext: u8`), with optional mutability
1911 /// (the boolean is true when mutable)
1912 ForeignItemStatic(P<Ty>, bool),
1916 pub fn descriptive_variant(&self) -> &str {
1918 ForeignItemFn(..) => "foreign function",
1919 ForeignItemStatic(..) => "foreign static item"
1924 /// A macro definition, in this crate or imported from another.
1926 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1927 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1928 pub struct MacroDef {
1930 pub attrs: Vec<Attribute>,
1933 pub imported_from: Option<Ident>,
1935 pub use_locally: bool,
1936 pub allow_internal_unstable: bool,
1937 pub body: Vec<TokenTree>,
1945 // are ASTs encodable?
1947 fn check_asts_encodable() {
1948 fn assert_encodable<T: serialize::Encodable>() {}
1949 assert_encodable::<Crate>();