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());
1178 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
1179 // required to wrap the text.
1180 let num_of_hashes = stripped.chars().scan(0, |cnt, x| {
1181 *cnt = if x == '"' {
1183 } else if *cnt != 0 && x == '#' {
1189 }).max().unwrap_or(0);
1191 TokenTree::Delimited(sp, Rc::new(Delimited {
1192 delim: token::Bracket,
1194 tts: vec![TokenTree::Token(sp, token::Ident(token::str_to_ident("doc"),
1196 TokenTree::Token(sp, token::Eq),
1197 TokenTree::Token(sp, token::Literal(
1198 token::StrRaw(token::intern(&stripped), num_of_hashes), None))],
1202 (&TokenTree::Delimited(_, ref delimed), _) => {
1204 return delimed.open_tt();
1206 if index == delimed.tts.len() + 1 {
1207 return delimed.close_tt();
1209 delimed.tts[index - 1].clone()
1211 (&TokenTree::Token(sp, token::SpecialVarNt(var)), _) => {
1212 let v = [TokenTree::Token(sp, token::Dollar),
1213 TokenTree::Token(sp, token::Ident(token::str_to_ident(var.as_str()),
1217 (&TokenTree::Token(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1218 let v = [TokenTree::Token(sp, token::SubstNt(name, name_st)),
1219 TokenTree::Token(sp, token::Colon),
1220 TokenTree::Token(sp, token::Ident(kind, kind_st))];
1223 (&TokenTree::Sequence(_, ref seq), _) => {
1224 seq.tts[index].clone()
1226 _ => panic!("Cannot expand a token tree")
1230 /// Returns the `Span` corresponding to this token tree.
1231 pub fn get_span(&self) -> Span {
1233 TokenTree::Token(span, _) => span,
1234 TokenTree::Delimited(span, _) => span,
1235 TokenTree::Sequence(span, _) => span,
1239 /// Use this token tree as a matcher to parse given tts.
1240 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1241 -> macro_parser::NamedParseResult {
1242 // `None` is because we're not interpolating
1243 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1246 tts.iter().cloned().collect(),
1248 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1252 pub type Mac = Spanned<Mac_>;
1254 /// Represents a macro invocation. The Path indicates which macro
1255 /// is being invoked, and the vector of token-trees contains the source
1256 /// of the macro invocation.
1258 /// NB: the additional ident for a macro_rules-style macro is actually
1259 /// stored in the enclosing item. Oog.
1260 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1263 pub tts: Vec<TokenTree>,
1264 pub ctxt: SyntaxContext,
1267 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1269 /// A regular string, like `"foo"`
1271 /// A raw string, like `r##"foo"##`
1273 /// The uint is the number of `#` symbols used
1278 pub type Lit = Spanned<Lit_>;
1280 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1287 pub fn new<T: IntSign>(n: T) -> Sign {
1293 fn sign(&self) -> Sign;
1296 ($($t:ident)*) => ($(impl IntSign for $t {
1297 #[allow(unused_comparisons)]
1298 fn sign(&self) -> Sign {
1299 if *self < 0 {Minus} else {Plus}
1303 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1305 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1306 pub enum LitIntType {
1307 SignedIntLit(IntTy, Sign),
1308 UnsignedIntLit(UintTy),
1309 UnsuffixedIntLit(Sign)
1312 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1314 /// A string literal (`"foo"`)
1315 LitStr(InternedString, StrStyle),
1316 /// A byte string (`b"foo"`)
1317 LitByteStr(Rc<Vec<u8>>),
1318 /// A byte char (`b'f'`)
1320 /// A character literal (`'a'`)
1322 /// An integer literal (`1u8`)
1323 LitInt(u64, LitIntType),
1324 /// A float literal (`1f64` or `1E10f64`)
1325 LitFloat(InternedString, FloatTy),
1326 /// A float literal without a suffix (`1.0 or 1.0E10`)
1327 LitFloatUnsuffixed(InternedString),
1328 /// A boolean literal
1333 /// Returns true if this literal is a string and false otherwise.
1334 pub fn is_str(&self) -> bool {
1342 // NB: If you change this, you'll probably want to change the corresponding
1343 // type structure in middle/ty.rs as well.
1344 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1347 pub mutbl: Mutability,
1350 /// Represents a method's signature in a trait declaration,
1351 /// or in an implementation.
1352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1353 pub struct MethodSig {
1354 pub unsafety: Unsafety,
1355 pub constness: Constness,
1357 pub decl: P<FnDecl>,
1358 pub generics: Generics,
1359 pub explicit_self: ExplicitSelf,
1362 /// Represents a method declaration in a trait declaration, possibly including
1363 /// a default implementation. A trait method is either required (meaning it
1364 /// doesn't have an implementation, just a signature) or provided (meaning it
1365 /// has a default implementation).
1366 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1367 pub struct TraitItem {
1370 pub attrs: Vec<Attribute>,
1371 pub node: TraitItem_,
1375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1376 pub enum TraitItem_ {
1377 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1378 MethodTraitItem(MethodSig, Option<P<Block>>),
1379 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1382 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1383 pub struct ImplItem {
1386 pub vis: Visibility,
1387 pub attrs: Vec<Attribute>,
1388 pub node: ImplItemKind,
1392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1393 pub enum ImplItemKind {
1394 Const(P<Ty>, P<Expr>),
1395 Method(MethodSig, P<Block>),
1400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1409 impl fmt::Debug for IntTy {
1410 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1411 fmt::Display::fmt(self, f)
1415 impl fmt::Display for IntTy {
1416 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1417 write!(f, "{}", self.ty_to_string())
1422 pub fn ty_to_string(&self) -> &'static str {
1432 pub fn val_to_string(&self, val: i64) -> String {
1433 // cast to a u64 so we can correctly print INT64_MIN. All integral types
1434 // are parsed as u64, so we wouldn't want to print an extra negative
1436 format!("{}{}", val as u64, self.ty_to_string())
1439 pub fn ty_max(&self) -> u64 {
1443 TyIs | TyI32 => 0x80000000, // actually ni about TyIs
1444 TyI64 => 0x8000000000000000
1448 pub fn bit_width(&self) -> Option<usize> {
1450 TyIs => return None,
1459 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1469 pub fn ty_to_string(&self) -> &'static str {
1479 pub fn val_to_string(&self, val: u64) -> String {
1480 format!("{}{}", val, self.ty_to_string())
1483 pub fn ty_max(&self) -> u64 {
1487 TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
1488 TyU64 => 0xffffffffffffffff
1492 pub fn bit_width(&self) -> Option<usize> {
1494 TyUs => return None,
1503 impl fmt::Debug for UintTy {
1504 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1505 fmt::Display::fmt(self, f)
1509 impl fmt::Display for UintTy {
1510 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511 write!(f, "{}", self.ty_to_string())
1515 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1521 impl fmt::Debug for FloatTy {
1522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1523 fmt::Display::fmt(self, f)
1527 impl fmt::Display for FloatTy {
1528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1529 write!(f, "{}", self.ty_to_string())
1534 pub fn ty_to_string(&self) -> &'static str {
1541 pub fn bit_width(&self) -> usize {
1549 // Bind a type to an associated type: `A=Foo`.
1550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1551 pub struct TypeBinding {
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1565 impl fmt::Debug for Ty {
1566 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1567 write!(f, "type({})", pprust::ty_to_string(self))
1571 /// Not represented directly in the AST, referred to by name through a ty_path.
1572 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1582 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1583 pub struct BareFnTy {
1584 pub unsafety: Unsafety,
1586 pub lifetimes: Vec<LifetimeDef>,
1590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1591 /// The different kinds of types recognized by the compiler
1594 /// A fixed length array (`[T; n]`)
1595 TyFixedLengthVec(P<Ty>, P<Expr>),
1596 /// A raw pointer (`*const T` or `*mut T`)
1598 /// A reference (`&'a T` or `&'a mut T`)
1599 TyRptr(Option<Lifetime>, MutTy),
1600 /// A bare function (e.g. `fn(usize) -> bool`)
1601 TyBareFn(P<BareFnTy>),
1602 /// A tuple (`(A, B, C, D,...)`)
1604 /// A path (`module::module::...::Type`), optionally
1605 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1607 /// Type parameters are stored in the Path itself
1608 TyPath(Option<QSelf>, Path),
1609 /// Something like `A+B`. Note that `B` must always be a path.
1610 TyObjectSum(P<Ty>, TyParamBounds),
1611 /// A type like `for<'a> Foo<&'a Bar>`
1612 TyPolyTraitRef(TyParamBounds),
1613 /// No-op; kept solely so that we can pretty-print faithfully
1617 /// TyInfer means the type should be inferred instead of it having been
1618 /// specified. This can appear anywhere in a type.
1620 // A macro in the type position.
1624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1625 pub enum AsmDialect {
1630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1631 pub struct InlineAsmOutput {
1632 pub constraint: InternedString,
1635 pub is_indirect: bool,
1638 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1639 pub struct InlineAsm {
1640 pub asm: InternedString,
1641 pub asm_str_style: StrStyle,
1642 pub outputs: Vec<InlineAsmOutput>,
1643 pub inputs: Vec<(InternedString, P<Expr>)>,
1644 pub clobbers: Vec<InternedString>,
1646 pub alignstack: bool,
1647 pub dialect: AsmDialect,
1648 pub expn_id: ExpnId,
1651 /// represents an argument in a function header
1652 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1660 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1661 let path = Spanned{span:span,node:self_ident};
1663 // HACK(eddyb) fake type for the self argument.
1671 node: PatIdent(BindingMode::ByValue(mutability), path, None),
1679 /// Represents the header (not the body) of a function declaration
1680 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1682 pub inputs: Vec<Arg>,
1683 pub output: FunctionRetTy,
1687 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1693 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1694 pub enum Constness {
1699 impl fmt::Display for Unsafety {
1700 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1701 fmt::Display::fmt(match *self {
1702 Unsafety::Normal => "normal",
1703 Unsafety::Unsafe => "unsafe",
1708 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1709 pub enum ImplPolarity {
1710 /// `impl Trait for Type`
1712 /// `impl !Trait for Type`
1716 impl fmt::Debug for ImplPolarity {
1717 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1719 ImplPolarity::Positive => "positive".fmt(f),
1720 ImplPolarity::Negative => "negative".fmt(f),
1726 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1727 pub enum FunctionRetTy {
1728 /// Functions with return type `!`that always
1729 /// raise an error or exit (i.e. never return to the caller)
1731 /// Return type is not specified.
1733 /// Functions default to `()` and
1734 /// closures default to inference. Span points to where return
1735 /// type would be inserted.
1736 DefaultReturn(Span),
1741 impl FunctionRetTy {
1742 pub fn span(&self) -> Span {
1744 NoReturn(span) => span,
1745 DefaultReturn(span) => span,
1746 Return(ref ty) => ty.span
1751 /// Represents the kind of 'self' associated with a method
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1753 pub enum ExplicitSelf_ {
1758 /// `&'lt self`, `&'lt mut self`
1759 SelfRegion(Option<Lifetime>, Mutability, Ident),
1761 SelfExplicit(P<Ty>, Ident),
1764 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1766 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1768 /// A span from the first token past `{` to the last token until `}`.
1769 /// For `mod foo;`, the inner span ranges from the first token
1770 /// to the last token in the external file.
1772 pub items: Vec<P<Item>>,
1775 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1776 pub struct ForeignMod {
1778 pub items: Vec<P<ForeignItem>>,
1781 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1782 pub struct EnumDef {
1783 pub variants: Vec<P<Variant>>,
1786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1787 pub struct Variant_ {
1789 pub attrs: Vec<Attribute>,
1790 pub data: VariantData,
1791 /// Explicit discriminant, eg `Foo = 1`
1792 pub disr_expr: Option<P<Expr>>,
1795 pub type Variant = Spanned<Variant_>;
1797 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1798 pub enum PathListItem_ {
1801 /// renamed in list, eg `use foo::{bar as baz};`
1802 rename: Option<Ident>,
1806 /// renamed in list, eg `use foo::{self as baz};`
1807 rename: Option<Ident>,
1812 impl PathListItem_ {
1813 pub fn id(&self) -> NodeId {
1815 PathListIdent { id, .. } | PathListMod { id, .. } => id
1819 pub fn name(&self) -> Option<Ident> {
1821 PathListIdent { name, .. } => Some(name),
1822 PathListMod { .. } => None,
1826 pub fn rename(&self) -> Option<Ident> {
1828 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1833 pub type PathListItem = Spanned<PathListItem_>;
1835 pub type ViewPath = Spanned<ViewPath_>;
1837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1838 pub enum ViewPath_ {
1840 /// `foo::bar::baz as quux`
1844 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1845 ViewPathSimple(Ident, Path),
1850 /// `foo::bar::{a,b,c}`
1851 ViewPathList(Path, Vec<PathListItem>)
1854 /// Meta-data associated with an item
1855 pub type Attribute = Spanned<Attribute_>;
1857 /// Distinguishes between Attributes that decorate items and Attributes that
1858 /// are contained as statements within items. These two cases need to be
1859 /// distinguished for pretty-printing.
1860 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1861 pub enum AttrStyle {
1866 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1867 pub struct AttrId(pub usize);
1869 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1870 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1871 pub struct Attribute_ {
1873 pub style: AttrStyle,
1874 pub value: P<MetaItem>,
1875 pub is_sugared_doc: bool,
1878 /// TraitRef's appear in impls.
1880 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1881 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1882 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1883 /// same as the impl's node id).
1884 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1885 pub struct TraitRef {
1890 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1891 pub struct PolyTraitRef {
1892 /// The `'a` in `<'a> Foo<&'a T>`
1893 pub bound_lifetimes: Vec<LifetimeDef>,
1895 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1896 pub trait_ref: TraitRef,
1901 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1902 pub enum Visibility {
1908 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1910 Inherited => parent_visibility,
1916 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1917 pub struct StructField_ {
1918 pub kind: StructFieldKind,
1921 pub attrs: Vec<Attribute>,
1925 pub fn ident(&self) -> Option<Ident> {
1927 NamedField(ref ident, _) => Some(ident.clone()),
1928 UnnamedField(_) => None
1933 pub type StructField = Spanned<StructField_>;
1935 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1936 pub enum StructFieldKind {
1937 NamedField(Ident, Visibility),
1938 /// Element of a tuple-like struct
1939 UnnamedField(Visibility),
1942 impl StructFieldKind {
1943 pub fn is_unnamed(&self) -> bool {
1945 UnnamedField(..) => true,
1946 NamedField(..) => false,
1950 pub fn visibility(&self) -> Visibility {
1952 NamedField(_, vis) | UnnamedField(vis) => vis
1957 /// Fields and Ids of enum variants and structs
1959 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1960 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1961 /// One shared Id can be successfully used for these two purposes.
1962 /// Id of the whole enum lives in `Item`.
1964 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1965 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1966 /// the variant itself" from enum variants.
1967 /// Id of the whole struct lives in `Item`.
1968 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1969 pub enum VariantData {
1970 Struct(Vec<StructField>, NodeId),
1971 Tuple(Vec<StructField>, NodeId),
1976 pub fn fields(&self) -> &[StructField] {
1978 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1982 pub fn id(&self) -> NodeId {
1984 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1987 pub fn is_struct(&self) -> bool {
1988 if let VariantData::Struct(..) = *self { true } else { false }
1990 pub fn is_tuple(&self) -> bool {
1991 if let VariantData::Tuple(..) = *self { true } else { false }
1993 pub fn is_unit(&self) -> bool {
1994 if let VariantData::Unit(..) = *self { true } else { false }
1999 FIXME (#3300): Should allow items to be anonymous. Right now
2000 we just use dummy names for anon items.
2004 /// The name might be a dummy name in case of anonymous items
2005 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2008 pub attrs: Vec<Attribute>,
2011 pub vis: Visibility,
2016 pub fn attrs(&self) -> &[Attribute] {
2021 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2023 /// An`extern crate` item, with optional original crate name,
2025 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
2026 ItemExternCrate(Option<Name>),
2027 /// A `use` or `pub use` item
2028 ItemUse(P<ViewPath>),
2031 ItemStatic(P<Ty>, Mutability, P<Expr>),
2033 ItemConst(P<Ty>, P<Expr>),
2034 /// A function declaration
2035 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
2038 /// An external module
2039 ItemForeignMod(ForeignMod),
2040 /// A type alias, e.g. `type Foo = Bar<u8>`
2041 ItemTy(P<Ty>, Generics),
2042 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2043 ItemEnum(EnumDef, Generics),
2044 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2045 ItemStruct(VariantData, Generics),
2046 /// Represents a Trait Declaration
2052 // Default trait implementations
2054 // `impl Trait for .. {}`
2055 ItemDefaultImpl(Unsafety, TraitRef),
2056 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2060 Option<TraitRef>, // (optional) trait this impl implements
2063 /// A macro invocation (which includes macro definition)
2068 pub fn descriptive_variant(&self) -> &str {
2070 ItemExternCrate(..) => "extern crate",
2071 ItemUse(..) => "use",
2072 ItemStatic(..) => "static item",
2073 ItemConst(..) => "constant item",
2074 ItemFn(..) => "function",
2075 ItemMod(..) => "module",
2076 ItemForeignMod(..) => "foreign module",
2077 ItemTy(..) => "type alias",
2078 ItemEnum(..) => "enum",
2079 ItemStruct(..) => "struct",
2080 ItemTrait(..) => "trait",
2083 ItemDefaultImpl(..) => "item"
2088 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2089 pub struct ForeignItem {
2091 pub attrs: Vec<Attribute>,
2092 pub node: ForeignItem_,
2095 pub vis: Visibility,
2098 /// An item within an `extern` block
2099 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2100 pub enum ForeignItem_ {
2101 /// A foreign function
2102 ForeignItemFn(P<FnDecl>, Generics),
2103 /// A foreign static item (`static ext: u8`), with optional mutability
2104 /// (the boolean is true when mutable)
2105 ForeignItemStatic(P<Ty>, bool),
2109 pub fn descriptive_variant(&self) -> &str {
2111 ForeignItemFn(..) => "foreign function",
2112 ForeignItemStatic(..) => "foreign static item"
2117 /// A macro definition, in this crate or imported from another.
2119 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
2120 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2121 pub struct MacroDef {
2123 pub attrs: Vec<Attribute>,
2126 pub imported_from: Option<Ident>,
2128 pub use_locally: bool,
2129 pub allow_internal_unstable: bool,
2130 pub body: Vec<TokenTree>,
2138 // are ASTs encodable?
2140 fn check_asts_encodable() {
2141 fn assert_encodable<T: serialize::Encodable>() {}
2142 assert_encodable::<Crate>();