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::BinOp_::*;
14 pub use self::BlockCheckMode::*;
15 pub use self::CaptureClause::*;
16 pub use self::Decl_::*;
17 pub use self::ExplicitSelf_::*;
18 pub use self::Expr_::*;
19 pub use self::FloatTy::*;
20 pub use self::FunctionRetTy::*;
21 pub use self::ForeignItem_::*;
22 pub use self::IntTy::*;
23 pub use self::Item_::*;
24 pub use self::KleeneOp::*;
25 pub use self::Lit_::*;
26 pub use self::LitIntType::*;
27 pub use self::MacStmtStyle::*;
28 pub use self::MetaItem_::*;
29 pub use self::Mutability::*;
30 pub use self::Pat_::*;
31 pub use self::PathListItem_::*;
32 pub use self::PrimTy::*;
33 pub use self::Sign::*;
34 pub use self::Stmt_::*;
35 pub use self::StrStyle::*;
36 pub use self::StructFieldKind::*;
37 pub use self::TraitItem_::*;
39 pub use self::TyParamBound::*;
40 pub use self::UintTy::*;
41 pub use self::UnOp::*;
42 pub use self::UnsafeSource::*;
43 pub use self::ViewPath_::*;
44 pub use self::Visibility::*;
45 pub use self::PathParameters::*;
47 use attr::ThinAttributes;
48 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
51 use ext::tt::macro_parser;
52 use parse::token::InternedString;
55 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
62 use std::hash::{Hash, Hasher};
63 use serialize::{Encodable, Decodable, Encoder, Decoder};
65 /// A name is a part of an identifier, representing a string or gensym. It's
66 /// the result of interning.
67 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
68 pub struct Name(pub u32);
70 /// A SyntaxContext represents a chain of macro-expandings
71 /// and renamings. Each macro expansion corresponds to
72 /// a fresh u32. This u32 is a reference to a table stored
73 /// in thread-local storage.
74 /// The special value EMPTY_CTXT is used to indicate an empty
76 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
77 pub struct SyntaxContext(pub u32);
79 /// An identifier contains a Name (index into the interner
80 /// table) and a SyntaxContext to track renaming and
81 /// macro expansion per Flatt et al., "Macros That Work Together"
82 #[derive(Clone, Copy, Eq)]
85 pub ctxt: SyntaxContext
89 pub fn as_str(self) -> token::InternedString {
90 token::InternedString::new_from_name(self)
94 impl fmt::Debug for Name {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 write!(f, "{}({})", self, self.0)
100 impl fmt::Display for Name {
101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102 fmt::Display::fmt(&self.as_str(), f)
106 impl Encodable for Name {
107 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
108 s.emit_str(&self.as_str())
112 impl Decodable for Name {
113 fn decode<D: Decoder>(d: &mut D) -> Result<Name, D::Error> {
114 Ok(token::intern(&try!(d.read_str())[..]))
118 pub const EMPTY_CTXT : SyntaxContext = SyntaxContext(0);
121 pub fn new(name: Name, ctxt: SyntaxContext) -> Ident {
122 Ident {name: name, ctxt: ctxt}
124 pub fn with_empty_ctxt(name: Name) -> Ident {
125 Ident {name: name, ctxt: EMPTY_CTXT}
129 impl PartialEq for Ident {
130 fn eq(&self, other: &Ident) -> bool {
131 if self.ctxt != other.ctxt {
132 // There's no one true way to compare Idents. They can be compared
133 // non-hygienically `id1.name == id2.name`, hygienically
134 // `mtwt::resolve(id1) == mtwt::resolve(id2)`, or even member-wise
135 // `(id1.name, id1.ctxt) == (id2.name, id2.ctxt)` depending on the situation.
136 // Ideally, PartialEq should not be implemented for Ident at all, but that
137 // would be too impractical, because many larger structures (Token, in particular)
138 // including Idents as their parts derive PartialEq and use it for non-hygienic
139 // comparisons. That's why PartialEq is implemented and defaults to non-hygienic
140 // comparison. Hash is implemented too and is consistent with PartialEq, i.e. only
141 // the name of Ident is hashed. Still try to avoid comparing idents in your code
142 // (especially as keys in hash maps), use one of the three methods listed above
145 // If you see this panic, then some idents from different contexts were compared
146 // non-hygienically. It's likely a bug. Use one of the three comparison methods
147 // listed above explicitly.
149 panic!("idents with different contexts are compared with operator `==`: \
150 {:?}, {:?}.", self, other);
153 self.name == other.name
157 impl Hash for Ident {
158 fn hash<H: Hasher>(&self, state: &mut H) {
159 self.name.hash(state)
163 impl fmt::Debug for Ident {
164 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165 write!(f, "{}#{}", self.name, self.ctxt.0)
169 impl fmt::Display for Ident {
170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 fmt::Display::fmt(&self.name, f)
175 impl Encodable for Ident {
176 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
181 impl Decodable for Ident {
182 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
183 Ok(Ident::with_empty_ctxt(try!(Name::decode(d))))
187 /// A mark represents a unique id associated with a macro expansion
190 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
191 pub struct Lifetime {
197 impl fmt::Debug for Lifetime {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
203 /// A lifetime definition, eg `'a: 'b+'c+'d`
204 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
205 pub struct LifetimeDef {
206 pub lifetime: Lifetime,
207 pub bounds: Vec<Lifetime>
210 /// A "Path" is essentially Rust's notion of a name; for instance:
211 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
212 /// along with a bunch of supporting information.
213 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
216 /// A `::foo` path, is relative to the crate root rather than current
217 /// module (like paths in an import).
219 /// The segments in the path: the things separated by `::`.
220 pub segments: Vec<PathSegment>,
223 impl fmt::Debug for Path {
224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
225 write!(f, "path({})", pprust::path_to_string(self))
229 impl fmt::Display for Path {
230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
231 write!(f, "{}", pprust::path_to_string(self))
235 /// A segment of a path: an identifier, an optional lifetime, and a set of
237 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
238 pub struct PathSegment {
239 /// The identifier portion of this path segment.
240 pub identifier: Ident,
242 /// Type/lifetime parameters attached to this path. They come in
243 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
244 /// this is more than just simple syntactic sugar; the use of
245 /// parens affects the region binding rules, so we preserve the
247 pub parameters: PathParameters,
250 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
251 pub enum PathParameters {
252 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
253 AngleBracketed(AngleBracketedParameterData),
254 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
255 Parenthesized(ParenthesizedParameterData),
258 impl PathParameters {
259 pub fn none() -> PathParameters {
260 PathParameters::AngleBracketed(AngleBracketedParameterData {
261 lifetimes: Vec::new(),
263 bindings: P::empty(),
267 pub fn is_empty(&self) -> bool {
269 PathParameters::AngleBracketed(ref data) => data.is_empty(),
271 // Even if the user supplied no types, something like
272 // `X()` is equivalent to `X<(),()>`.
273 PathParameters::Parenthesized(..) => false,
277 pub fn has_lifetimes(&self) -> bool {
279 PathParameters::AngleBracketed(ref data) => !data.lifetimes.is_empty(),
280 PathParameters::Parenthesized(_) => false,
284 pub fn has_types(&self) -> bool {
286 PathParameters::AngleBracketed(ref data) => !data.types.is_empty(),
287 PathParameters::Parenthesized(..) => true,
291 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
292 /// parameters in the parenthesized case.
293 pub fn types(&self) -> Vec<&P<Ty>> {
295 PathParameters::AngleBracketed(ref data) => {
296 data.types.iter().collect()
298 PathParameters::Parenthesized(ref data) => {
300 .chain(data.output.iter())
306 pub fn lifetimes(&self) -> Vec<&Lifetime> {
308 PathParameters::AngleBracketed(ref data) => {
309 data.lifetimes.iter().collect()
311 PathParameters::Parenthesized(_) => {
317 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
319 PathParameters::AngleBracketed(ref data) => {
320 data.bindings.iter().collect()
322 PathParameters::Parenthesized(_) => {
329 /// A path like `Foo<'a, T>`
330 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
331 pub struct AngleBracketedParameterData {
332 /// The lifetime parameters for this path segment.
333 pub lifetimes: Vec<Lifetime>,
334 /// The type parameters for this path segment, if present.
335 pub types: P<[P<Ty>]>,
336 /// Bindings (equality constraints) on associated types, if present.
337 /// e.g., `Foo<A=Bar>`.
338 pub bindings: P<[P<TypeBinding>]>,
341 impl AngleBracketedParameterData {
342 fn is_empty(&self) -> bool {
343 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
347 /// A path like `Foo(A,B) -> C`
348 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
349 pub struct ParenthesizedParameterData {
354 pub inputs: Vec<P<Ty>>,
357 pub output: Option<P<Ty>>,
360 pub type CrateNum = u32;
362 pub type NodeId = u32;
364 /// Node id used to represent the root of the crate.
365 pub const CRATE_NODE_ID: NodeId = 0;
367 /// When parsing and doing expansions, we initially give all AST nodes this AST
368 /// node value. Then later, in the renumber pass, we renumber them to have
369 /// small, positive ids.
370 pub const DUMMY_NODE_ID: NodeId = !0;
372 pub trait NodeIdAssigner {
373 fn next_node_id(&self) -> NodeId;
374 fn peek_node_id(&self) -> NodeId;
377 /// The AST represents all type param bounds as types.
378 /// typeck::collect::compute_bounds matches these against
379 /// the "special" built-in traits (see middle::lang_items) and
380 /// detects Copy, Send and Sync.
381 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
382 pub enum TyParamBound {
383 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
384 RegionTyParamBound(Lifetime)
387 /// A modifier on a bound, currently this is only used for `?Sized`, where the
388 /// modifier is `Maybe`. Negative bounds should also be handled here.
389 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
390 pub enum TraitBoundModifier {
395 pub type TyParamBounds = P<[TyParamBound]>;
397 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
401 pub bounds: TyParamBounds,
402 pub default: Option<P<Ty>>,
406 /// Represents lifetimes and type parameters attached to a declaration
407 /// of a function, enum, trait, etc.
408 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
409 pub struct Generics {
410 pub lifetimes: Vec<LifetimeDef>,
411 pub ty_params: P<[TyParam]>,
412 pub where_clause: WhereClause,
416 pub fn is_lt_parameterized(&self) -> bool {
417 !self.lifetimes.is_empty()
419 pub fn is_type_parameterized(&self) -> bool {
420 !self.ty_params.is_empty()
422 pub fn is_parameterized(&self) -> bool {
423 self.is_lt_parameterized() || self.is_type_parameterized()
427 impl Default for Generics {
428 fn default() -> Generics {
430 lifetimes: Vec::new(),
431 ty_params: P::empty(),
432 where_clause: WhereClause {
434 predicates: Vec::new(),
440 /// A `where` clause in a definition
441 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
442 pub struct WhereClause {
444 pub predicates: Vec<WherePredicate>,
447 /// A single predicate in a `where` clause
448 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
449 pub enum WherePredicate {
450 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
451 BoundPredicate(WhereBoundPredicate),
452 /// A lifetime predicate, e.g. `'a: 'b+'c`
453 RegionPredicate(WhereRegionPredicate),
454 /// An equality predicate (unsupported)
455 EqPredicate(WhereEqPredicate),
458 /// A type bound, e.g. `for<'c> Foo: Send+Clone+'c`
459 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
460 pub struct WhereBoundPredicate {
462 /// Any lifetimes from a `for` binding
463 pub bound_lifetimes: Vec<LifetimeDef>,
464 /// The type being bounded
465 pub bounded_ty: P<Ty>,
466 /// Trait and lifetime bounds (`Clone+Send+'static`)
467 pub bounds: TyParamBounds,
470 /// A lifetime predicate, e.g. `'a: 'b+'c`
471 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
472 pub struct WhereRegionPredicate {
474 pub lifetime: Lifetime,
475 pub bounds: Vec<Lifetime>,
478 /// An equality predicate (unsupported), e.g. `T=int`
479 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
480 pub struct WhereEqPredicate {
487 /// The set of MetaItems that define the compilation environment of the crate,
488 /// used to drive conditional compilation
489 pub type CrateConfig = Vec<P<MetaItem>> ;
491 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
494 pub attrs: Vec<Attribute>,
495 pub config: CrateConfig,
497 pub exported_macros: Vec<MacroDef>,
500 pub type MetaItem = Spanned<MetaItem_>;
502 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
504 MetaWord(InternedString),
505 MetaList(InternedString, Vec<P<MetaItem>>),
506 MetaNameValue(InternedString, Lit),
509 // can't be derived because the MetaList requires an unordered comparison
510 impl PartialEq for MetaItem_ {
511 fn eq(&self, other: &MetaItem_) -> bool {
513 MetaWord(ref ns) => match *other {
514 MetaWord(ref no) => (*ns) == (*no),
517 MetaNameValue(ref ns, ref vs) => match *other {
518 MetaNameValue(ref no, ref vo) => {
519 (*ns) == (*no) && vs.node == vo.node
523 MetaList(ref ns, ref miss) => match *other {
524 MetaList(ref no, ref miso) => {
526 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
534 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
536 /// Statements in a block
537 pub stmts: Vec<P<Stmt>>,
538 /// An expression at the end of the block
539 /// without a semicolon, if any
540 pub expr: Option<P<Expr>>,
542 /// Distinguishes between `unsafe { ... }` and `{ ... }`
543 pub rules: BlockCheckMode,
547 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
554 impl fmt::Debug for Pat {
555 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
556 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
560 /// A single field in a struct pattern
562 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
563 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
564 /// except is_shorthand is true
565 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
566 pub struct FieldPat {
567 /// The identifier for the field
569 /// The pattern the field is destructured to
571 pub is_shorthand: bool,
574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
575 pub enum BindingMode {
580 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
582 /// Represents a wildcard pattern (`_`)
585 /// A PatIdent may either be a new bound variable,
586 /// or a nullary enum (in which case the third field
589 /// In the nullary enum case, the parser can't determine
590 /// which it is. The resolver determines this, and
591 /// records this pattern's NodeId in an auxiliary
592 /// set (of "PatIdents that refer to nullary enums")
593 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
595 /// "None" means a `Variant(..)` pattern where we don't bind the fields to names.
596 PatEnum(Path, Option<Vec<P<Pat>>>),
598 /// An associated const named using the qualified path `<T>::CONST` or
599 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
600 /// referred to as simply `T::CONST`, in which case they will end up as
601 /// PatEnum, and the resolver will have to sort that out.
602 PatQPath(QSelf, Path),
604 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
605 /// The `bool` is `true` in the presence of a `..`
606 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
607 /// A tuple pattern `(a, b)`
611 /// A reference pattern, e.g. `&mut (a, b)`
612 PatRegion(P<Pat>, Mutability),
615 /// A range pattern, e.g. `1...2`
616 PatRange(P<Expr>, P<Expr>),
617 /// `[a, b, ..i, y, z]` is represented as:
618 /// `PatVec(box [a, b], Some(i), box [y, z])`
619 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
620 /// A macro pattern; pre-expansion
624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
625 pub enum Mutability {
630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
632 /// The `+` operator (addition)
634 /// The `-` operator (subtraction)
636 /// The `*` operator (multiplication)
638 /// The `/` operator (division)
640 /// The `%` operator (modulus)
642 /// The `&&` operator (logical and)
644 /// The `||` operator (logical or)
646 /// The `^` operator (bitwise xor)
648 /// The `&` operator (bitwise and)
650 /// The `|` operator (bitwise or)
652 /// The `<<` operator (shift left)
654 /// The `>>` operator (shift right)
656 /// The `==` operator (equality)
658 /// The `<` operator (less than)
660 /// The `<=` operator (less than or equal to)
662 /// The `!=` operator (not equal to)
664 /// The `>=` operator (greater than or equal to)
666 /// The `>` operator (greater than)
671 pub fn to_string(&self) -> &'static str {
693 pub fn lazy(&self) -> bool {
695 BiAnd | BiOr => true,
700 pub fn is_shift(&self) -> bool {
702 BiShl | BiShr => true,
706 pub fn is_comparison(&self) -> bool {
708 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
710 BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
711 BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
715 /// Returns `true` if the binary operator takes its arguments by value
716 pub fn is_by_value(&self) -> bool {
717 !BinOp_::is_comparison(self)
721 pub type BinOp = Spanned<BinOp_>;
723 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
725 /// The `*` operator for dereferencing
727 /// The `!` operator for logical inversion
729 /// The `-` operator for negation
734 /// Returns `true` if the unary operator takes its argument by value
735 pub fn is_by_value(u: UnOp) -> bool {
737 UnNeg | UnNot => true,
742 pub fn to_string(op: UnOp) -> &'static str {
752 pub type Stmt = Spanned<Stmt_>;
754 impl fmt::Debug for Stmt {
755 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
756 write!(f, "stmt({}: {})",
758 .map_or(Cow::Borrowed("<macro>"),|id|Cow::Owned(id.to_string())),
759 pprust::stmt_to_string(self))
764 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
766 /// Could be an item or a local (let) binding:
767 StmtDecl(P<Decl>, NodeId),
769 /// Expr without trailing semi-colon (must have unit type):
770 StmtExpr(P<Expr>, NodeId),
772 /// Expr with trailing semi-colon (may have any type):
773 StmtSemi(P<Expr>, NodeId),
775 StmtMac(P<Mac>, MacStmtStyle, ThinAttributes),
779 pub fn id(&self) -> Option<NodeId> {
781 StmtDecl(_, id) => Some(id),
782 StmtExpr(_, id) => Some(id),
783 StmtSemi(_, id) => Some(id),
788 pub fn attrs(&self) -> &[Attribute] {
790 StmtDecl(ref d, _) => d.attrs(),
792 StmtSemi(ref e, _) => e.attrs(),
793 StmtMac(_, _, Some(ref b)) => b,
794 StmtMac(_, _, None) => &[],
799 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
800 pub enum MacStmtStyle {
801 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
802 /// `foo!(...);`, `foo![...];`
803 MacStmtWithSemicolon,
804 /// The macro statement had braces; e.g. foo! { ... }
806 /// The macro statement had parentheses or brackets and no semicolon; e.g.
807 /// `foo!(...)`. All of these will end up being converted into macro
809 MacStmtWithoutBraces,
812 // FIXME (pending discussion of #1697, #2178...): local should really be
813 // a refinement on pat.
814 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
818 pub ty: Option<P<Ty>>,
819 /// Initializer expression to set the value, if any
820 pub init: Option<P<Expr>>,
823 pub attrs: ThinAttributes,
827 pub fn attrs(&self) -> &[Attribute] {
835 pub type Decl = Spanned<Decl_>;
837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
839 /// A local (let) binding:
846 pub fn attrs(&self) -> &[Attribute] {
848 DeclLocal(ref l) => l.attrs(),
849 DeclItem(ref i) => i.attrs(),
854 /// represents one arm of a 'match'
855 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
857 pub attrs: Vec<Attribute>,
858 pub pats: Vec<P<Pat>>,
859 pub guard: Option<P<Expr>>,
863 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
865 pub ident: SpannedIdent,
870 pub type SpannedIdent = Spanned<Ident>;
872 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
873 pub enum BlockCheckMode {
875 UnsafeBlock(UnsafeSource),
878 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
879 pub enum UnsafeSource {
885 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
890 pub attrs: ThinAttributes
894 pub fn attrs(&self) -> &[Attribute] {
902 impl fmt::Debug for Expr {
903 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
904 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
908 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
910 /// A `box x` expression.
912 /// First expr is the place; second expr is the value.
913 ExprInPlace(P<Expr>, P<Expr>),
914 /// An array (`[a, b, c, d]`)
915 ExprVec(Vec<P<Expr>>),
918 /// The first field resolves to the function itself,
919 /// and the second field is the list of arguments
920 ExprCall(P<Expr>, Vec<P<Expr>>),
921 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
923 /// The `SpannedIdent` is the identifier for the method name.
924 /// The vector of `Ty`s are the ascripted type parameters for the method
925 /// (within the angle brackets).
927 /// The first element of the vector of `Expr`s is the expression that evaluates
928 /// to the object on which the method is being called on (the receiver),
929 /// and the remaining elements are the rest of the arguments.
931 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
932 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
933 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
934 /// A tuple (`(a, b, c ,d)`)
935 ExprTup(Vec<P<Expr>>),
936 /// A binary operation (For example: `a + b`, `a * b`)
937 ExprBinary(BinOp, P<Expr>, P<Expr>),
938 /// A unary operation (For example: `!x`, `*x`)
939 ExprUnary(UnOp, P<Expr>),
940 /// A literal (For example: `1u8`, `"foo"`)
942 /// A cast (`foo as f64`)
943 ExprCast(P<Expr>, P<Ty>),
944 ExprType(P<Expr>, P<Ty>),
945 /// An `if` block, with an optional else block
947 /// `if expr { block } else { expr }`
948 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
949 /// An `if let` expression with an optional else block
951 /// `if let pat = expr { block } else { expr }`
953 /// This is desugared to a `match` expression.
954 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
955 /// A while loop, with an optional label
957 /// `'label: while expr { block }`
958 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
959 /// A while-let loop, with an optional label
961 /// `'label: while let pat = expr { block }`
963 /// This is desugared to a combination of `loop` and `match` expressions.
964 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
965 /// A for loop, with an optional label
967 /// `'label: for pat in expr { block }`
969 /// This is desugared to a combination of `loop` and `match` expressions.
970 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
971 /// Conditionless loop (can be exited with break, continue, or return)
973 /// `'label: loop { block }`
974 ExprLoop(P<Block>, Option<Ident>),
976 ExprMatch(P<Expr>, Vec<Arm>),
977 /// A closure (for example, `move |a, b, c| {a + b + c}`)
978 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
979 /// A block (`{ ... }`)
982 /// An assignment (`a = foo()`)
983 ExprAssign(P<Expr>, P<Expr>),
984 /// An assignment with an operator
986 /// For example, `a += 1`.
987 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
988 /// Access of a named struct field (`obj.foo`)
989 ExprField(P<Expr>, SpannedIdent),
990 /// Access of an unnamed field of a struct or tuple-struct
992 /// For example, `foo.0`.
993 ExprTupField(P<Expr>, Spanned<usize>),
994 /// An indexing operation (`foo[2]`)
995 ExprIndex(P<Expr>, P<Expr>),
996 /// A range (`1..2`, `1..`, or `..2`)
997 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
999 /// Variable reference, possibly containing `::` and/or type
1000 /// parameters, e.g. foo::bar::<baz>.
1002 /// Optionally "qualified",
1003 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
1004 ExprPath(Option<QSelf>, Path),
1006 /// A referencing operation (`&a` or `&mut a`)
1007 ExprAddrOf(Mutability, P<Expr>),
1008 /// A `break`, with an optional label to break
1009 ExprBreak(Option<SpannedIdent>),
1010 /// A `continue`, with an optional label
1011 ExprAgain(Option<SpannedIdent>),
1012 /// A `return`, with an optional value to be returned
1013 ExprRet(Option<P<Expr>>),
1015 /// Output of the `asm!()` macro
1016 ExprInlineAsm(InlineAsm),
1018 /// A macro invocation; pre-expansion
1021 /// A struct literal expression.
1023 /// For example, `Foo {x: 1, y: 2}`, or
1024 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1025 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
1027 /// An array literal constructed from one repeated element.
1029 /// For example, `[1u8; 5]`. The first expression is the element
1030 /// to be repeated; the second is the number of times to repeat it.
1031 ExprRepeat(P<Expr>, P<Expr>),
1033 /// No-op: used solely so we can pretty-print faithfully
1037 /// The explicit Self type in a "qualified path". The actual
1038 /// path, including the trait and the associated item, is stored
1039 /// separately. `position` represents the index of the associated
1040 /// item qualified with this Self type.
1043 /// <Vec<T> as a::b::Trait>::AssociatedItem
1044 /// ^~~~~ ~~~~~~~~~~~~~~^
1047 /// <Vec<T>>::AssociatedItem
1051 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1057 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1058 pub enum CaptureClause {
1063 /// A delimited sequence of token trees
1064 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1065 pub struct Delimited {
1066 /// The type of delimiter
1067 pub delim: token::DelimToken,
1068 /// The span covering the opening delimiter
1069 pub open_span: Span,
1070 /// The delimited sequence of token trees
1071 pub tts: Vec<TokenTree>,
1072 /// The span covering the closing delimiter
1073 pub close_span: Span,
1077 /// Returns the opening delimiter as a token.
1078 pub fn open_token(&self) -> token::Token {
1079 token::OpenDelim(self.delim)
1082 /// Returns the closing delimiter as a token.
1083 pub fn close_token(&self) -> token::Token {
1084 token::CloseDelim(self.delim)
1087 /// Returns the opening delimiter as a token tree.
1088 pub fn open_tt(&self) -> TokenTree {
1089 TokenTree::Token(self.open_span, self.open_token())
1092 /// Returns the closing delimiter as a token tree.
1093 pub fn close_tt(&self) -> TokenTree {
1094 TokenTree::Token(self.close_span, self.close_token())
1098 /// A sequence of token trees
1099 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1100 pub struct SequenceRepetition {
1101 /// The sequence of token trees
1102 pub tts: Vec<TokenTree>,
1103 /// The optional separator
1104 pub separator: Option<token::Token>,
1105 /// Whether the sequence can be repeated zero (*), or one or more times (+)
1107 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
1108 pub num_captures: usize,
1111 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
1112 /// for token sequences.
1113 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1119 /// When the main rust parser encounters a syntax-extension invocation, it
1120 /// parses the arguments to the invocation as a token-tree. This is a very
1121 /// loose structure, such that all sorts of different AST-fragments can
1122 /// be passed to syntax extensions using a uniform type.
1124 /// If the syntax extension is an MBE macro, it will attempt to match its
1125 /// LHS token tree against the provided token tree, and if it finds a
1126 /// match, will transcribe the RHS token tree, splicing in any captured
1127 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1129 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1130 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1131 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1132 pub enum TokenTree {
1134 Token(Span, token::Token),
1135 /// A delimited sequence of token trees
1136 Delimited(Span, Rc<Delimited>),
1138 // This only makes sense in MBE macros.
1140 /// A kleene-style repetition sequence with a span
1141 // FIXME(eddyb) #12938 Use DST.
1142 Sequence(Span, Rc<SequenceRepetition>),
1146 pub fn len(&self) -> usize {
1148 TokenTree::Token(_, token::DocComment(name)) => {
1149 match doc_comment_style(&name.as_str()) {
1150 AttrStyle::Outer => 2,
1151 AttrStyle::Inner => 3
1154 TokenTree::Token(_, token::SpecialVarNt(..)) => 2,
1155 TokenTree::Token(_, token::MatchNt(..)) => 3,
1156 TokenTree::Delimited(_, ref delimed) => {
1157 delimed.tts.len() + 2
1159 TokenTree::Sequence(_, ref seq) => {
1162 TokenTree::Token(..) => 0
1166 pub fn get_tt(&self, index: usize) -> TokenTree {
1167 match (self, index) {
1168 (&TokenTree::Token(sp, token::DocComment(_)), 0) => {
1169 TokenTree::Token(sp, token::Pound)
1171 (&TokenTree::Token(sp, token::DocComment(name)), 1)
1172 if doc_comment_style(&name.as_str()) == AttrStyle::Inner => {
1173 TokenTree::Token(sp, token::Not)
1175 (&TokenTree::Token(sp, token::DocComment(name)), _) => {
1176 let stripped = strip_doc_comment_decoration(&name.as_str());
1177 TokenTree::Delimited(sp, Rc::new(Delimited {
1178 delim: token::Bracket,
1180 tts: vec![TokenTree::Token(sp, token::Ident(token::str_to_ident("doc"),
1182 TokenTree::Token(sp, token::Eq),
1183 TokenTree::Token(sp, token::Literal(
1184 token::StrRaw(token::intern(&stripped), 0), None))],
1188 (&TokenTree::Delimited(_, ref delimed), _) => {
1190 return delimed.open_tt();
1192 if index == delimed.tts.len() + 1 {
1193 return delimed.close_tt();
1195 delimed.tts[index - 1].clone()
1197 (&TokenTree::Token(sp, token::SpecialVarNt(var)), _) => {
1198 let v = [TokenTree::Token(sp, token::Dollar),
1199 TokenTree::Token(sp, token::Ident(token::str_to_ident(var.as_str()),
1203 (&TokenTree::Token(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1204 let v = [TokenTree::Token(sp, token::SubstNt(name, name_st)),
1205 TokenTree::Token(sp, token::Colon),
1206 TokenTree::Token(sp, token::Ident(kind, kind_st))];
1209 (&TokenTree::Sequence(_, ref seq), _) => {
1210 seq.tts[index].clone()
1212 _ => panic!("Cannot expand a token tree")
1216 /// Returns the `Span` corresponding to this token tree.
1217 pub fn get_span(&self) -> Span {
1219 TokenTree::Token(span, _) => span,
1220 TokenTree::Delimited(span, _) => span,
1221 TokenTree::Sequence(span, _) => span,
1225 /// Use this token tree as a matcher to parse given tts.
1226 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1227 -> macro_parser::NamedParseResult {
1228 // `None` is because we're not interpolating
1229 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1232 tts.iter().cloned().collect(),
1234 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1238 pub type Mac = Spanned<Mac_>;
1240 /// Represents a macro invocation. The Path indicates which macro
1241 /// is being invoked, and the vector of token-trees contains the source
1242 /// of the macro invocation.
1244 /// NB: the additional ident for a macro_rules-style macro is actually
1245 /// stored in the enclosing item. Oog.
1246 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1249 pub tts: Vec<TokenTree>,
1250 pub ctxt: SyntaxContext,
1253 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1255 /// A regular string, like `"foo"`
1257 /// A raw string, like `r##"foo"##`
1259 /// The uint is the number of `#` symbols used
1264 pub type Lit = Spanned<Lit_>;
1266 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1273 pub fn new<T: IntSign>(n: T) -> Sign {
1279 fn sign(&self) -> Sign;
1282 ($($t:ident)*) => ($(impl IntSign for $t {
1283 #[allow(unused_comparisons)]
1284 fn sign(&self) -> Sign {
1285 if *self < 0 {Minus} else {Plus}
1289 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1291 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1292 pub enum LitIntType {
1293 SignedIntLit(IntTy, Sign),
1294 UnsignedIntLit(UintTy),
1295 UnsuffixedIntLit(Sign)
1298 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1300 /// A string literal (`"foo"`)
1301 LitStr(InternedString, StrStyle),
1302 /// A byte string (`b"foo"`)
1303 LitByteStr(Rc<Vec<u8>>),
1304 /// A byte char (`b'f'`)
1306 /// A character literal (`'a'`)
1308 /// An integer literal (`1u8`)
1309 LitInt(u64, LitIntType),
1310 /// A float literal (`1f64` or `1E10f64`)
1311 LitFloat(InternedString, FloatTy),
1312 /// A float literal without a suffix (`1.0 or 1.0E10`)
1313 LitFloatUnsuffixed(InternedString),
1314 /// A boolean literal
1319 /// Returns true if this literal is a string and false otherwise.
1320 pub fn is_str(&self) -> bool {
1328 // NB: If you change this, you'll probably want to change the corresponding
1329 // type structure in middle/ty.rs as well.
1330 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1333 pub mutbl: Mutability,
1336 /// Represents a method's signature in a trait declaration,
1337 /// or in an implementation.
1338 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1339 pub struct MethodSig {
1340 pub unsafety: Unsafety,
1341 pub constness: Constness,
1343 pub decl: P<FnDecl>,
1344 pub generics: Generics,
1345 pub explicit_self: ExplicitSelf,
1348 /// Represents a method declaration in a trait declaration, possibly including
1349 /// a default implementation. A trait method is either required (meaning it
1350 /// doesn't have an implementation, just a signature) or provided (meaning it
1351 /// has a default implementation).
1352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1353 pub struct TraitItem {
1356 pub attrs: Vec<Attribute>,
1357 pub node: TraitItem_,
1361 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1362 pub enum TraitItem_ {
1363 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1364 MethodTraitItem(MethodSig, Option<P<Block>>),
1365 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1368 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1369 pub struct ImplItem {
1372 pub vis: Visibility,
1373 pub attrs: Vec<Attribute>,
1374 pub node: ImplItemKind,
1378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1379 pub enum ImplItemKind {
1380 Const(P<Ty>, P<Expr>),
1381 Method(MethodSig, P<Block>),
1386 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1395 impl fmt::Debug for IntTy {
1396 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1397 fmt::Display::fmt(self, f)
1401 impl fmt::Display for IntTy {
1402 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1403 write!(f, "{}", self.ty_to_string())
1408 pub fn ty_to_string(&self) -> &'static str {
1418 pub fn val_to_string(&self, val: i64) -> String {
1419 // cast to a u64 so we can correctly print INT64_MIN. All integral types
1420 // are parsed as u64, so we wouldn't want to print an extra negative
1422 format!("{}{}", val as u64, self.ty_to_string())
1425 pub fn ty_max(&self) -> u64 {
1429 TyIs | TyI32 => 0x80000000, // actually ni about TyIs
1430 TyI64 => 0x8000000000000000
1434 pub fn bit_width(&self) -> Option<usize> {
1436 TyIs => return None,
1445 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1455 pub fn ty_to_string(&self) -> &'static str {
1465 pub fn val_to_string(&self, val: u64) -> String {
1466 format!("{}{}", val, self.ty_to_string())
1469 pub fn ty_max(&self) -> u64 {
1473 TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
1474 TyU64 => 0xffffffffffffffff
1478 pub fn bit_width(&self) -> Option<usize> {
1480 TyUs => return None,
1489 impl fmt::Debug for UintTy {
1490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1491 fmt::Display::fmt(self, f)
1495 impl fmt::Display for UintTy {
1496 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497 write!(f, "{}", self.ty_to_string())
1501 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1507 impl fmt::Debug for FloatTy {
1508 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1509 fmt::Display::fmt(self, f)
1513 impl fmt::Display for FloatTy {
1514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1515 write!(f, "{}", self.ty_to_string())
1520 pub fn ty_to_string(&self) -> &'static str {
1527 pub fn bit_width(&self) -> usize {
1535 // Bind a type to an associated type: `A=Foo`.
1536 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1537 pub struct TypeBinding {
1544 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1551 impl fmt::Debug for Ty {
1552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1553 write!(f, "type({})", pprust::ty_to_string(self))
1557 /// Not represented directly in the AST, referred to by name through a ty_path.
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1569 pub struct BareFnTy {
1570 pub unsafety: Unsafety,
1572 pub lifetimes: Vec<LifetimeDef>,
1576 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1577 /// The different kinds of types recognized by the compiler
1580 /// A fixed length array (`[T; n]`)
1581 TyFixedLengthVec(P<Ty>, P<Expr>),
1582 /// A raw pointer (`*const T` or `*mut T`)
1584 /// A reference (`&'a T` or `&'a mut T`)
1585 TyRptr(Option<Lifetime>, MutTy),
1586 /// A bare function (e.g. `fn(usize) -> bool`)
1587 TyBareFn(P<BareFnTy>),
1588 /// A tuple (`(A, B, C, D,...)`)
1590 /// A path (`module::module::...::Type`), optionally
1591 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1593 /// Type parameters are stored in the Path itself
1594 TyPath(Option<QSelf>, Path),
1595 /// Something like `A+B`. Note that `B` must always be a path.
1596 TyObjectSum(P<Ty>, TyParamBounds),
1597 /// A type like `for<'a> Foo<&'a Bar>`
1598 TyPolyTraitRef(TyParamBounds),
1599 /// No-op; kept solely so that we can pretty-print faithfully
1603 /// TyInfer means the type should be inferred instead of it having been
1604 /// specified. This can appear anywhere in a type.
1606 // A macro in the type position.
1610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1611 pub enum AsmDialect {
1616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1617 pub struct InlineAsmOutput {
1618 pub constraint: InternedString,
1621 pub is_indirect: bool,
1624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1625 pub struct InlineAsm {
1626 pub asm: InternedString,
1627 pub asm_str_style: StrStyle,
1628 pub outputs: Vec<InlineAsmOutput>,
1629 pub inputs: Vec<(InternedString, P<Expr>)>,
1630 pub clobbers: Vec<InternedString>,
1632 pub alignstack: bool,
1633 pub dialect: AsmDialect,
1634 pub expn_id: ExpnId,
1637 /// represents an argument in a function header
1638 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1646 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1647 let path = Spanned{span:span,node:self_ident};
1649 // HACK(eddyb) fake type for the self argument.
1657 node: PatIdent(BindingMode::ByValue(mutability), path, None),
1665 /// Represents the header (not the body) of a function declaration
1666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1668 pub inputs: Vec<Arg>,
1669 pub output: FunctionRetTy,
1673 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1679 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1680 pub enum Constness {
1685 impl fmt::Display for Unsafety {
1686 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1687 fmt::Display::fmt(match *self {
1688 Unsafety::Normal => "normal",
1689 Unsafety::Unsafe => "unsafe",
1694 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1695 pub enum ImplPolarity {
1696 /// `impl Trait for Type`
1698 /// `impl !Trait for Type`
1702 impl fmt::Debug for ImplPolarity {
1703 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1705 ImplPolarity::Positive => "positive".fmt(f),
1706 ImplPolarity::Negative => "negative".fmt(f),
1712 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1713 pub enum FunctionRetTy {
1714 /// Functions with return type `!`that always
1715 /// raise an error or exit (i.e. never return to the caller)
1717 /// Return type is not specified.
1719 /// Functions default to `()` and
1720 /// closures default to inference. Span points to where return
1721 /// type would be inserted.
1722 DefaultReturn(Span),
1727 impl FunctionRetTy {
1728 pub fn span(&self) -> Span {
1730 NoReturn(span) => span,
1731 DefaultReturn(span) => span,
1732 Return(ref ty) => ty.span
1737 /// Represents the kind of 'self' associated with a method
1738 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1739 pub enum ExplicitSelf_ {
1744 /// `&'lt self`, `&'lt mut self`
1745 SelfRegion(Option<Lifetime>, Mutability, Ident),
1747 SelfExplicit(P<Ty>, Ident),
1750 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1754 /// A span from the first token past `{` to the last token until `}`.
1755 /// For `mod foo;`, the inner span ranges from the first token
1756 /// to the last token in the external file.
1758 pub items: Vec<P<Item>>,
1761 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1762 pub struct ForeignMod {
1764 pub items: Vec<P<ForeignItem>>,
1767 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1768 pub struct EnumDef {
1769 pub variants: Vec<P<Variant>>,
1772 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1773 pub struct Variant_ {
1775 pub attrs: Vec<Attribute>,
1776 pub data: VariantData,
1777 /// Explicit discriminant, eg `Foo = 1`
1778 pub disr_expr: Option<P<Expr>>,
1781 pub type Variant = Spanned<Variant_>;
1783 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1784 pub enum PathListItem_ {
1787 /// renamed in list, eg `use foo::{bar as baz};`
1788 rename: Option<Ident>,
1792 /// renamed in list, eg `use foo::{self as baz};`
1793 rename: Option<Ident>,
1798 impl PathListItem_ {
1799 pub fn id(&self) -> NodeId {
1801 PathListIdent { id, .. } | PathListMod { id, .. } => id
1805 pub fn name(&self) -> Option<Ident> {
1807 PathListIdent { name, .. } => Some(name),
1808 PathListMod { .. } => None,
1812 pub fn rename(&self) -> Option<Ident> {
1814 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1819 pub type PathListItem = Spanned<PathListItem_>;
1821 pub type ViewPath = Spanned<ViewPath_>;
1823 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1824 pub enum ViewPath_ {
1826 /// `foo::bar::baz as quux`
1830 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1831 ViewPathSimple(Ident, Path),
1836 /// `foo::bar::{a,b,c}`
1837 ViewPathList(Path, Vec<PathListItem>)
1840 /// Meta-data associated with an item
1841 pub type Attribute = Spanned<Attribute_>;
1843 /// Distinguishes between Attributes that decorate items and Attributes that
1844 /// are contained as statements within items. These two cases need to be
1845 /// distinguished for pretty-printing.
1846 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1847 pub enum AttrStyle {
1852 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1853 pub struct AttrId(pub usize);
1855 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1856 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1857 pub struct Attribute_ {
1859 pub style: AttrStyle,
1860 pub value: P<MetaItem>,
1861 pub is_sugared_doc: bool,
1864 /// TraitRef's appear in impls.
1866 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1867 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1868 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1869 /// same as the impl's node id).
1870 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1871 pub struct TraitRef {
1876 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1877 pub struct PolyTraitRef {
1878 /// The `'a` in `<'a> Foo<&'a T>`
1879 pub bound_lifetimes: Vec<LifetimeDef>,
1881 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1882 pub trait_ref: TraitRef,
1887 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1888 pub enum Visibility {
1894 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1896 Inherited => parent_visibility,
1902 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1903 pub struct StructField_ {
1904 pub kind: StructFieldKind,
1907 pub attrs: Vec<Attribute>,
1911 pub fn ident(&self) -> Option<Ident> {
1913 NamedField(ref ident, _) => Some(ident.clone()),
1914 UnnamedField(_) => None
1919 pub type StructField = Spanned<StructField_>;
1921 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1922 pub enum StructFieldKind {
1923 NamedField(Ident, Visibility),
1924 /// Element of a tuple-like struct
1925 UnnamedField(Visibility),
1928 impl StructFieldKind {
1929 pub fn is_unnamed(&self) -> bool {
1931 UnnamedField(..) => true,
1932 NamedField(..) => false,
1936 pub fn visibility(&self) -> Visibility {
1938 NamedField(_, vis) | UnnamedField(vis) => vis
1943 /// Fields and Ids of enum variants and structs
1945 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1946 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1947 /// One shared Id can be successfully used for these two purposes.
1948 /// Id of the whole enum lives in `Item`.
1950 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1951 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1952 /// the variant itself" from enum variants.
1953 /// Id of the whole struct lives in `Item`.
1954 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1955 pub enum VariantData {
1956 Struct(Vec<StructField>, NodeId),
1957 Tuple(Vec<StructField>, NodeId),
1962 pub fn fields(&self) -> &[StructField] {
1964 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1968 pub fn id(&self) -> NodeId {
1970 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1973 pub fn is_struct(&self) -> bool {
1974 if let VariantData::Struct(..) = *self { true } else { false }
1976 pub fn is_tuple(&self) -> bool {
1977 if let VariantData::Tuple(..) = *self { true } else { false }
1979 pub fn is_unit(&self) -> bool {
1980 if let VariantData::Unit(..) = *self { true } else { false }
1985 FIXME (#3300): Should allow items to be anonymous. Right now
1986 we just use dummy names for anon items.
1990 /// The name might be a dummy name in case of anonymous items
1991 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1994 pub attrs: Vec<Attribute>,
1997 pub vis: Visibility,
2002 pub fn attrs(&self) -> &[Attribute] {
2007 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2009 /// An`extern crate` item, with optional original crate name,
2011 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
2012 ItemExternCrate(Option<Name>),
2013 /// A `use` or `pub use` item
2014 ItemUse(P<ViewPath>),
2017 ItemStatic(P<Ty>, Mutability, P<Expr>),
2019 ItemConst(P<Ty>, P<Expr>),
2020 /// A function declaration
2021 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
2024 /// An external module
2025 ItemForeignMod(ForeignMod),
2026 /// A type alias, e.g. `type Foo = Bar<u8>`
2027 ItemTy(P<Ty>, Generics),
2028 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2029 ItemEnum(EnumDef, Generics),
2030 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2031 ItemStruct(VariantData, Generics),
2032 /// Represents a Trait Declaration
2038 // Default trait implementations
2040 // `impl Trait for .. {}`
2041 ItemDefaultImpl(Unsafety, TraitRef),
2042 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2046 Option<TraitRef>, // (optional) trait this impl implements
2049 /// A macro invocation (which includes macro definition)
2054 pub fn descriptive_variant(&self) -> &str {
2056 ItemExternCrate(..) => "extern crate",
2057 ItemUse(..) => "use",
2058 ItemStatic(..) => "static item",
2059 ItemConst(..) => "constant item",
2060 ItemFn(..) => "function",
2061 ItemMod(..) => "module",
2062 ItemForeignMod(..) => "foreign module",
2063 ItemTy(..) => "type alias",
2064 ItemEnum(..) => "enum",
2065 ItemStruct(..) => "struct",
2066 ItemTrait(..) => "trait",
2069 ItemDefaultImpl(..) => "item"
2074 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2075 pub struct ForeignItem {
2077 pub attrs: Vec<Attribute>,
2078 pub node: ForeignItem_,
2081 pub vis: Visibility,
2084 /// An item within an `extern` block
2085 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2086 pub enum ForeignItem_ {
2087 /// A foreign function
2088 ForeignItemFn(P<FnDecl>, Generics),
2089 /// A foreign static item (`static ext: u8`), with optional mutability
2090 /// (the boolean is true when mutable)
2091 ForeignItemStatic(P<Ty>, bool),
2095 pub fn descriptive_variant(&self) -> &str {
2097 ForeignItemFn(..) => "foreign function",
2098 ForeignItemStatic(..) => "foreign static item"
2103 /// A macro definition, in this crate or imported from another.
2105 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
2106 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2107 pub struct MacroDef {
2109 pub attrs: Vec<Attribute>,
2112 pub imported_from: Option<Ident>,
2114 pub use_locally: bool,
2115 pub allow_internal_unstable: bool,
2116 pub body: Vec<TokenTree>,
2124 // are ASTs encodable?
2126 fn check_asts_encodable() {
2127 fn assert_encodable<T: serialize::Encodable>() {}
2128 assert_encodable::<Crate>();