1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // The Rust abstract syntax tree.
13 pub use self::AsmDialect
::*;
14 pub use self::AttrStyle
::*;
15 pub use self::BindingMode
::*;
16 pub use self::BinOp_
::*;
17 pub use self::BlockCheckMode
::*;
18 pub use self::CaptureClause
::*;
19 pub use self::Decl_
::*;
20 pub use self::ExplicitSelf_
::*;
21 pub use self::Expr_
::*;
22 pub use self::FloatTy
::*;
23 pub use self::FunctionRetTy
::*;
24 pub use self::ForeignItem_
::*;
25 pub use self::ImplItem_
::*;
26 pub use self::InlinedItem
::*;
27 pub use self::IntTy
::*;
28 pub use self::Item_
::*;
29 pub use self::KleeneOp
::*;
30 pub use self::Lit_
::*;
31 pub use self::LitIntType
::*;
32 pub use self::LocalSource
::*;
33 pub use self::Mac_
::*;
34 pub use self::MacStmtStyle
::*;
35 pub use self::MetaItem_
::*;
36 pub use self::Mutability
::*;
37 pub use self::Pat_
::*;
38 pub use self::PathListItem_
::*;
39 pub use self::PatWildKind
::*;
40 pub use self::PrimTy
::*;
41 pub use self::Sign
::*;
42 pub use self::Stmt_
::*;
43 pub use self::StrStyle
::*;
44 pub use self::StructFieldKind
::*;
45 pub use self::TokenTree
::*;
46 pub use self::TraitItem_
::*;
48 pub use self::TyParamBound
::*;
49 pub use self::UintTy
::*;
50 pub use self::UnOp
::*;
51 pub use self::UnsafeSource
::*;
52 pub use self::VariantKind
::*;
53 pub use self::ViewPath_
::*;
54 pub use self::Visibility
::*;
55 pub use self::PathParameters
::*;
57 use codemap
::{Span, Spanned, DUMMY_SP, ExpnId}
;
61 use ext
::tt
::macro_parser
;
62 use owned_slice
::OwnedSlice
;
63 use parse
::token
::{InternedString, str_to_ident}
;
70 use serialize
::{Encodable, Decodable, Encoder, Decoder}
;
72 // FIXME #6993: in librustc, uses of "ident" should be replaced
75 /// An identifier contains a Name (index into the interner
76 /// table) and a SyntaxContext to track renaming and
77 /// macro expansion per Flatt et al., "Macros
78 /// That Work Together"
79 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
82 pub ctxt
: SyntaxContext
86 /// Construct an identifier with the given name and an empty context:
87 pub fn new(name
: Name
) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}
}
89 pub fn as_str
<'a
>(&'a
self) -> &'a
str {
93 pub fn encode_with_hygiene(&self) -> String
{
94 format
!("\x00name_{},ctxt_{}\x00",
100 impl fmt
::Debug
for Ident
{
101 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
102 write
!(f
, "{}#{}", self.name
, self.ctxt
)
106 impl fmt
::Display
for Ident
{
107 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
108 fmt
::Display
::fmt(&self.name
, f
)
112 impl fmt
::Debug
for Name
{
113 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
114 let Name(nm
) = *self;
115 write
!(f
, "{:?}({})", token
::get_name(*self), nm
)
119 impl fmt
::Display
for Name
{
120 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
121 fmt
::Display
::fmt(&token
::get_name(*self), f
)
125 impl PartialEq
for Ident
{
126 fn eq(&self, other
: &Ident
) -> bool
{
127 if self.ctxt
== other
.ctxt
{
128 self.name
== other
.name
130 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
131 // idents that have different contexts. You can't fix this without
132 // knowing whether the comparison should be hygienic or non-hygienic.
133 // if it should be non-hygienic (most things are), just compare the
134 // 'name' fields of the idents. Or, even better, replace the idents
137 // On the other hand, if the comparison does need to be hygienic,
138 // one example and its non-hygienic counterpart would be:
139 // syntax::parse::token::Token::mtwt_eq
140 // syntax::ext::tt::macro_parser::token_name_eq
141 panic
!("not allowed to compare these idents: {}, {}. \
142 Probably related to issue \\#6993", self, other
);
145 fn ne(&self, other
: &Ident
) -> bool
{
150 /// A SyntaxContext represents a chain of macro-expandings
151 /// and renamings. Each macro expansion corresponds to
154 // I'm representing this syntax context as an index into
155 // a table, in order to work around a compiler bug
156 // that's causing unreleased memory to cause core dumps
157 // and also perhaps to save some work in destructor checks.
158 // the special uint '0' will be used to indicate an empty
161 // this uint is a reference to a table stored in thread-local
163 pub type SyntaxContext
= u32;
164 pub const EMPTY_CTXT
: SyntaxContext
= 0;
165 pub const ILLEGAL_CTXT
: SyntaxContext
= 1;
167 /// A name is a part of an identifier, representing a string or gensym. It's
168 /// the result of interning.
169 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
170 RustcEncodable
, RustcDecodable
, Clone
, Copy
)]
171 pub struct Name(pub u32);
174 pub fn as_str
<'a
>(&'a
self) -> &'a
str {
176 // FIXME #12938: can't use copy_lifetime since &str isn't a &T
177 ::std
::mem
::transmute
::<&str,&str>(&token
::get_name(*self))
181 pub fn usize(&self) -> usize {
182 let Name(nm
) = *self;
186 pub fn ident(&self) -> Ident
{
187 Ident { name: *self, ctxt: 0 }
191 /// A mark represents a unique id associated with a macro expansion
194 impl Encodable
for Ident
{
195 fn encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
196 s
.emit_str(&token
::get_ident(*self))
200 impl Decodable
for Ident
{
201 fn decode
<D
: Decoder
>(d
: &mut D
) -> Result
<Ident
, D
::Error
> {
202 Ok(str_to_ident(&try
!(d
.read_str())[..]))
206 /// Function name (not all functions have names)
207 pub type FnIdent
= Option
<Ident
>;
209 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,
211 pub struct Lifetime
{
217 /// A lifetime definition, eg `'a: 'b+'c+'d`
218 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
219 pub struct LifetimeDef
{
220 pub lifetime
: Lifetime
,
221 pub bounds
: Vec
<Lifetime
>
224 /// A "Path" is essentially Rust's notion of a name; for instance:
225 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
226 /// along with a bunch of supporting information.
227 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
230 /// A `::foo` path, is relative to the crate root rather than current
231 /// module (like paths in an import).
233 /// The segments in the path: the things separated by `::`.
234 pub segments
: Vec
<PathSegment
>,
237 /// A segment of a path: an identifier, an optional lifetime, and a set of
239 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
240 pub struct PathSegment
{
241 /// The identifier portion of this path segment.
242 pub identifier
: Ident
,
244 /// Type/lifetime parameters attached to this path. They come in
245 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
246 /// this is more than just simple syntactic sugar; the use of
247 /// parens affects the region binding rules, so we preserve the
249 pub parameters
: PathParameters
,
252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
253 pub enum PathParameters
{
254 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
255 AngleBracketedParameters(AngleBracketedParameterData
),
256 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
257 ParenthesizedParameters(ParenthesizedParameterData
),
260 impl PathParameters
{
261 pub fn none() -> PathParameters
{
262 AngleBracketedParameters(AngleBracketedParameterData
{
263 lifetimes
: Vec
::new(),
264 types
: OwnedSlice
::empty(),
265 bindings
: OwnedSlice
::empty(),
269 pub fn is_empty(&self) -> bool
{
271 AngleBracketedParameters(ref data
) => data
.is_empty(),
273 // Even if the user supplied no types, something like
274 // `X()` is equivalent to `X<(),()>`.
275 ParenthesizedParameters(..) => false,
279 pub fn has_lifetimes(&self) -> bool
{
281 AngleBracketedParameters(ref data
) => !data
.lifetimes
.is_empty(),
282 ParenthesizedParameters(_
) => false,
286 pub fn has_types(&self) -> bool
{
288 AngleBracketedParameters(ref data
) => !data
.types
.is_empty(),
289 ParenthesizedParameters(..) => true,
293 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
294 /// parameters in the parenthesized case.
295 pub fn types(&self) -> Vec
<&P
<Ty
>> {
297 AngleBracketedParameters(ref data
) => {
298 data
.types
.iter().collect()
300 ParenthesizedParameters(ref data
) => {
302 .chain(data
.output
.iter())
308 pub fn lifetimes(&self) -> Vec
<&Lifetime
> {
310 AngleBracketedParameters(ref data
) => {
311 data
.lifetimes
.iter().collect()
313 ParenthesizedParameters(_
) => {
319 pub fn bindings(&self) -> Vec
<&P
<TypeBinding
>> {
321 AngleBracketedParameters(ref data
) => {
322 data
.bindings
.iter().collect()
324 ParenthesizedParameters(_
) => {
331 /// A path like `Foo<'a, T>`
332 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
333 pub struct AngleBracketedParameterData
{
334 /// The lifetime parameters for this path segment.
335 pub lifetimes
: Vec
<Lifetime
>,
336 /// The type parameters for this path segment, if present.
337 pub types
: OwnedSlice
<P
<Ty
>>,
338 /// Bindings (equality constraints) on associated types, if present.
339 /// E.g., `Foo<A=Bar>`.
340 pub bindings
: OwnedSlice
<P
<TypeBinding
>>,
343 impl AngleBracketedParameterData
{
344 fn is_empty(&self) -> bool
{
345 self.lifetimes
.is_empty() && self.types
.is_empty() && self.bindings
.is_empty()
349 /// A path like `Foo(A,B) -> C`
350 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
351 pub struct ParenthesizedParameterData
{
356 pub inputs
: Vec
<P
<Ty
>>,
359 pub output
: Option
<P
<Ty
>>,
362 pub type CrateNum
= u32;
364 pub type NodeId
= u32;
366 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
367 RustcDecodable
, Hash
, Debug
, Copy
)]
374 /// Read the node id, asserting that this def-id is krate-local.
375 pub fn local_id(&self) -> NodeId
{
376 assert_eq
!(self.krate
, LOCAL_CRATE
);
381 /// Item definitions in the currently-compiled crate would have the CrateNum
382 /// LOCAL_CRATE in their DefId.
383 pub const LOCAL_CRATE
: CrateNum
= 0;
384 pub const CRATE_NODE_ID
: NodeId
= 0;
386 /// When parsing and doing expansions, we initially give all AST nodes this AST
387 /// node value. Then later, in the renumber pass, we renumber them to have
388 /// small, positive ids.
389 pub const DUMMY_NODE_ID
: NodeId
= !0;
391 /// The AST represents all type param bounds as types.
392 /// typeck::collect::compute_bounds matches these against
393 /// the "special" built-in traits (see middle::lang_items) and
394 /// detects Copy, Send and Sync.
395 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
396 pub enum TyParamBound
{
397 TraitTyParamBound(PolyTraitRef
, TraitBoundModifier
),
398 RegionTyParamBound(Lifetime
)
401 /// A modifier on a bound, currently this is only used for `?Sized`, where the
402 /// modifier is `Maybe`. Negative bounds should also be handled here.
403 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
404 pub enum TraitBoundModifier
{
409 pub type TyParamBounds
= OwnedSlice
<TyParamBound
>;
411 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
415 pub bounds
: TyParamBounds
,
416 pub default: Option
<P
<Ty
>>,
420 /// Represents lifetimes and type parameters attached to a declaration
421 /// of a function, enum, trait, etc.
422 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
423 pub struct Generics
{
424 pub lifetimes
: Vec
<LifetimeDef
>,
425 pub ty_params
: OwnedSlice
<TyParam
>,
426 pub where_clause
: WhereClause
,
430 pub fn is_lt_parameterized(&self) -> bool
{
431 !self.lifetimes
.is_empty()
433 pub fn is_type_parameterized(&self) -> bool
{
434 !self.ty_params
.is_empty()
436 pub fn is_parameterized(&self) -> bool
{
437 self.is_lt_parameterized() || self.is_type_parameterized()
441 /// A `where` clause in a definition
442 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
443 pub struct WhereClause
{
445 pub predicates
: Vec
<WherePredicate
>,
448 /// A single predicate in a `where` clause
449 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
450 pub enum WherePredicate
{
451 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
452 BoundPredicate(WhereBoundPredicate
),
453 /// A lifetime predicate, e.g. `'a: 'b+'c`
454 RegionPredicate(WhereRegionPredicate
),
455 /// An equality predicate (unsupported)
456 EqPredicate(WhereEqPredicate
)
459 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
460 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
461 pub struct WhereBoundPredicate
{
463 /// Any lifetimes from a `for` binding
464 pub bound_lifetimes
: Vec
<LifetimeDef
>,
465 /// The type being bounded
466 pub bounded_ty
: P
<Ty
>,
467 /// Trait and lifetime bounds (`Clone+Send+'static`)
468 pub bounds
: OwnedSlice
<TyParamBound
>,
471 /// A lifetime predicate, e.g. `'a: 'b+'c`
472 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
473 pub struct WhereRegionPredicate
{
475 pub lifetime
: Lifetime
,
476 pub bounds
: Vec
<Lifetime
>,
479 /// An equality predicate (unsupported), e.g. `T=int`
480 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
481 pub struct WhereEqPredicate
{
488 /// The set of MetaItems that define the compilation environment of the crate,
489 /// used to drive conditional compilation
490 pub type CrateConfig
= Vec
<P
<MetaItem
>> ;
492 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
495 pub attrs
: Vec
<Attribute
>,
496 pub config
: CrateConfig
,
498 pub exported_macros
: Vec
<MacroDef
>,
501 pub type MetaItem
= Spanned
<MetaItem_
>;
503 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
505 MetaWord(InternedString
),
506 MetaList(InternedString
, Vec
<P
<MetaItem
>>),
507 MetaNameValue(InternedString
, Lit
),
510 // can't be derived because the MetaList requires an unordered comparison
511 impl PartialEq
for MetaItem_
{
512 fn eq(&self, other
: &MetaItem_
) -> bool
{
514 MetaWord(ref ns
) => match *other
{
515 MetaWord(ref no
) => (*ns
) == (*no
),
518 MetaNameValue(ref ns
, ref vs
) => match *other
{
519 MetaNameValue(ref no
, ref vo
) => {
520 (*ns
) == (*no
) && vs
.node
== vo
.node
524 MetaList(ref ns
, ref miss
) => match *other
{
525 MetaList(ref no
, ref miso
) => {
527 miss
.iter().all(|mi
| miso
.iter().any(|x
| x
.node
== mi
.node
))
535 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
537 /// Statements in a block
538 pub stmts
: Vec
<P
<Stmt
>>,
539 /// An expression at the end of the block
540 /// without a semicolon, if any
541 pub expr
: Option
<P
<Expr
>>,
543 /// Distinguishes between `unsafe { ... }` and `{ ... }`
544 pub rules
: BlockCheckMode
,
548 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
555 /// A single field in a struct pattern
557 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
558 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
559 /// except is_shorthand is true
560 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
561 pub struct FieldPat
{
562 /// The identifier for the field
564 /// The pattern the field is destructured to
566 pub is_shorthand
: bool
,
569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
570 pub enum BindingMode
{
571 BindByRef(Mutability
),
572 BindByValue(Mutability
),
575 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
576 pub enum PatWildKind
{
577 /// Represents the wildcard pattern `_`
580 /// Represents the wildcard pattern `..`
584 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
586 /// Represents a wildcard pattern (either `_` or `..`)
587 PatWild(PatWildKind
),
589 /// A PatIdent may either be a new bound variable,
590 /// or a nullary enum (in which case the third field
593 /// In the nullary enum case, the parser can't determine
594 /// which it is. The resolver determines this, and
595 /// records this pattern's NodeId in an auxiliary
596 /// set (of "PatIdents that refer to nullary enums")
597 PatIdent(BindingMode
, SpannedIdent
, Option
<P
<Pat
>>),
599 /// "None" means a * pattern where we don't bind the fields to names.
600 PatEnum(Path
, Option
<Vec
<P
<Pat
>>>),
602 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
603 /// The `bool` is `true` in the presence of a `..`
604 PatStruct(Path
, Vec
<Spanned
<FieldPat
>>, bool
),
605 /// A tuple pattern `(a, b)`
609 /// A reference pattern, e.g. `&mut (a, b)`
610 PatRegion(P
<Pat
>, Mutability
),
613 /// A range pattern, e.g. `1...2`
614 PatRange(P
<Expr
>, P
<Expr
>),
615 /// [a, b, ..i, y, z] is represented as:
616 /// PatVec(box [a, b], Some(i), box [y, z])
617 PatVec(Vec
<P
<Pat
>>, Option
<P
<Pat
>>, Vec
<P
<Pat
>>),
618 /// A macro pattern; pre-expansion
622 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
623 pub enum Mutability
{
628 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
630 /// The `+` operator (addition)
632 /// The `-` operator (subtraction)
634 /// The `*` operator (multiplication)
636 /// The `/` operator (division)
638 /// The `%` operator (modulus)
640 /// The `&&` operator (logical and)
642 /// The `||` operator (logical or)
644 /// The `^` operator (bitwise xor)
646 /// The `&` operator (bitwise and)
648 /// The `|` operator (bitwise or)
650 /// The `<<` operator (shift left)
652 /// The `>>` operator (shift right)
654 /// The `==` operator (equality)
656 /// The `<` operator (less than)
658 /// The `<=` operator (less than or equal to)
660 /// The `!=` operator (not equal to)
662 /// The `>=` operator (greater than or equal to)
664 /// The `>` operator (greater than)
668 pub type BinOp
= Spanned
<BinOp_
>;
670 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
672 /// The `box` operator
674 /// The `*` operator for dereferencing
676 /// The `!` operator for logical inversion
678 /// The `-` operator for negation
683 pub type Stmt
= Spanned
<Stmt_
>;
685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
687 /// Could be an item or a local (let) binding:
688 StmtDecl(P
<Decl
>, NodeId
),
690 /// Expr without trailing semi-colon (must have unit type):
691 StmtExpr(P
<Expr
>, NodeId
),
693 /// Expr with trailing semi-colon (may have any type):
694 StmtSemi(P
<Expr
>, NodeId
),
696 StmtMac(P
<Mac
>, MacStmtStyle
),
699 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
700 pub enum MacStmtStyle
{
701 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
702 /// `foo!(...);`, `foo![...];`
703 MacStmtWithSemicolon
,
704 /// The macro statement had braces; e.g. foo! { ... }
706 /// The macro statement had parentheses or brackets and no semicolon; e.g.
707 /// `foo!(...)`. All of these will end up being converted into macro
709 MacStmtWithoutBraces
,
712 /// Where a local declaration came from: either a true `let ... =
713 /// ...;`, or one desugared from the pattern of a for loop.
714 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
715 pub enum LocalSource
{
720 // FIXME (pending discussion of #1697, #2178...): local should really be
721 // a refinement on pat.
722 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
723 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
726 pub ty
: Option
<P
<Ty
>>,
727 /// Initializer expression to set the value, if any
728 pub init
: Option
<P
<Expr
>>,
731 pub source
: LocalSource
,
734 pub type Decl
= Spanned
<Decl_
>;
736 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
738 /// A local (let) binding:
744 /// represents one arm of a 'match'
745 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
747 pub attrs
: Vec
<Attribute
>,
748 pub pats
: Vec
<P
<Pat
>>,
749 pub guard
: Option
<P
<Expr
>>,
753 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
755 pub ident
: SpannedIdent
,
760 pub type SpannedIdent
= Spanned
<Ident
>;
762 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
763 pub enum BlockCheckMode
{
765 UnsafeBlock(UnsafeSource
),
768 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
769 pub enum UnsafeSource
{
775 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
782 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
784 /// First expr is the place; second expr is the value.
785 ExprBox(Option
<P
<Expr
>>, P
<Expr
>),
786 /// An array (`[a, b, c, d]`)
787 ExprVec(Vec
<P
<Expr
>>),
790 /// The first field resolves to the function itself,
791 /// and the second field is the list of arguments
792 ExprCall(P
<Expr
>, Vec
<P
<Expr
>>),
793 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
795 /// The `SpannedIdent` is the identifier for the method name.
796 /// The vector of `Ty`s are the ascripted type parameters for the method
797 /// (within the angle brackets).
799 /// The first element of the vector of `Expr`s is the expression that evaluates
800 /// to the object on which the method is being called on (the receiver),
801 /// and the remaining elements are the rest of the arguments.
803 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
804 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
805 ExprMethodCall(SpannedIdent
, Vec
<P
<Ty
>>, Vec
<P
<Expr
>>),
806 /// A tuple (`(a, b, c ,d)`)
807 ExprTup(Vec
<P
<Expr
>>),
808 /// A binary operation (For example: `a + b`, `a * b`)
809 ExprBinary(BinOp
, P
<Expr
>, P
<Expr
>),
810 /// A unary operation (For example: `!x`, `*x`)
811 ExprUnary(UnOp
, P
<Expr
>),
812 /// A literal (For example: `1u8`, `"foo"`)
814 /// A cast (`foo as f64`)
815 ExprCast(P
<Expr
>, P
<Ty
>),
816 /// An `if` block, with an optional else block
818 /// `if expr { block } else { expr }`
819 ExprIf(P
<Expr
>, P
<Block
>, Option
<P
<Expr
>>),
820 /// An `if let` expression with an optional else block
822 /// `if let pat = expr { block } else { expr }`
824 /// This is desugared to a `match` expression.
825 ExprIfLet(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<P
<Expr
>>),
826 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
827 /// A while loop, with an optional label
829 /// `'label: while expr { block }`
830 ExprWhile(P
<Expr
>, P
<Block
>, Option
<Ident
>),
831 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
832 /// A while-let loop, with an optional label
834 /// `'label: while let pat = expr { block }`
836 /// This is desugared to a combination of `loop` and `match` expressions.
837 ExprWhileLet(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<Ident
>),
838 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
839 /// A for loop, with an optional label
841 /// `'label: for pat in expr { block }`
843 /// This is desugared to a combination of `loop` and `match` expressions.
844 ExprForLoop(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<Ident
>),
845 /// Conditionless loop (can be exited with break, continue, or return)
847 /// `'label: loop { block }`
848 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
849 ExprLoop(P
<Block
>, Option
<Ident
>),
850 /// A `match` block, with a source that indicates whether or not it is
851 /// the result of a desugaring, and if so, which kind.
852 ExprMatch(P
<Expr
>, Vec
<Arm
>, MatchSource
),
853 /// A closure (for example, `move |a, b, c| {a + b + c}`)
854 ExprClosure(CaptureClause
, P
<FnDecl
>, P
<Block
>),
855 /// A block (`{ ... }`)
858 /// An assignment (`a = foo()`)
859 ExprAssign(P
<Expr
>, P
<Expr
>),
860 /// An assignment with an operator
862 /// For example, `a += 1`.
863 ExprAssignOp(BinOp
, P
<Expr
>, P
<Expr
>),
864 /// Access of a named struct field (`obj.foo`)
865 ExprField(P
<Expr
>, SpannedIdent
),
866 /// Access of an unnamed field of a struct or tuple-struct
868 /// For example, `foo.0`.
869 ExprTupField(P
<Expr
>, Spanned
<usize>),
870 /// An indexing operation (`foo[2]`)
871 ExprIndex(P
<Expr
>, P
<Expr
>),
872 /// A range (`1..2`, `1..`, or `..2`)
873 ExprRange(Option
<P
<Expr
>>, Option
<P
<Expr
>>),
875 /// Variable reference, possibly containing `::` and/or type
876 /// parameters, e.g. foo::bar::<baz>.
878 /// Optionally "qualified",
879 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
880 ExprPath(Option
<QSelf
>, Path
),
882 /// A referencing operation (`&a` or `&mut a`)
883 ExprAddrOf(Mutability
, P
<Expr
>),
884 /// A `break`, with an optional label to break
885 ExprBreak(Option
<Ident
>),
886 /// A `continue`, with an optional label
887 ExprAgain(Option
<Ident
>),
888 /// A `return`, with an optional value to be returned
889 ExprRet(Option
<P
<Expr
>>),
891 /// Output of the `asm!()` macro
892 ExprInlineAsm(InlineAsm
),
894 /// A macro invocation; pre-expansion
897 /// A struct literal expression.
899 /// For example, `Foo {x: 1, y: 2}`, or
900 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
901 ExprStruct(Path
, Vec
<Field
>, Option
<P
<Expr
>>),
903 /// A vector literal constructed from one repeated element.
905 /// For example, `[1u8; 5]`. The first expression is the element
906 /// to be repeated; the second is the number of times to repeat it.
907 ExprRepeat(P
<Expr
>, P
<Expr
>),
909 /// No-op: used solely so we can pretty-print faithfully
913 /// The explicit Self type in a "qualified path". The actual
914 /// path, including the trait and the associated item, is stored
915 /// separately. `position` represents the index of the associated
916 /// item qualified with this Self type.
918 /// <Vec<T> as a::b::Trait>::AssociatedItem
919 /// ^~~~~ ~~~~~~~~~~~~~~^
922 /// <Vec<T>>::AssociatedItem
925 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
931 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
932 pub enum MatchSource
{
934 IfLetDesugar { contains_else_clause: bool }
,
939 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
940 pub enum CaptureClause
{
945 /// A delimited sequence of token trees
946 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
947 pub struct Delimited
{
948 /// The type of delimiter
949 pub delim
: token
::DelimToken
,
950 /// The span covering the opening delimiter
952 /// The delimited sequence of token trees
953 pub tts
: Vec
<TokenTree
>,
954 /// The span covering the closing delimiter
955 pub close_span
: Span
,
959 /// Returns the opening delimiter as a token.
960 pub fn open_token(&self) -> token
::Token
{
961 token
::OpenDelim(self.delim
)
964 /// Returns the closing delimiter as a token.
965 pub fn close_token(&self) -> token
::Token
{
966 token
::CloseDelim(self.delim
)
969 /// Returns the opening delimiter as a token tree.
970 pub fn open_tt(&self) -> TokenTree
{
971 TtToken(self.open_span
, self.open_token())
974 /// Returns the closing delimiter as a token tree.
975 pub fn close_tt(&self) -> TokenTree
{
976 TtToken(self.close_span
, self.close_token())
980 /// A sequence of token treesee
981 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
982 pub struct SequenceRepetition
{
983 /// The sequence of token trees
984 pub tts
: Vec
<TokenTree
>,
985 /// The optional separator
986 pub separator
: Option
<token
::Token
>,
987 /// Whether the sequence can be repeated zero (*), or one or more times (+)
989 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
990 pub num_captures
: usize,
993 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
994 /// for token sequences.
995 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1001 /// When the main rust parser encounters a syntax-extension invocation, it
1002 /// parses the arguments to the invocation as a token-tree. This is a very
1003 /// loose structure, such that all sorts of different AST-fragments can
1004 /// be passed to syntax extensions using a uniform type.
1006 /// If the syntax extension is an MBE macro, it will attempt to match its
1007 /// LHS token tree against the provided token tree, and if it finds a
1008 /// match, will transcribe the RHS token tree, splicing in any captured
1009 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1011 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1012 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1013 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1014 pub enum TokenTree
{
1016 TtToken(Span
, token
::Token
),
1017 /// A delimited sequence of token trees
1018 TtDelimited(Span
, Rc
<Delimited
>),
1020 // This only makes sense in MBE macros.
1022 /// A kleene-style repetition sequence with a span
1023 // FIXME(eddyb) #12938 Use DST.
1024 TtSequence(Span
, Rc
<SequenceRepetition
>),
1028 pub fn len(&self) -> usize {
1030 TtToken(_
, token
::DocComment(_
)) => 2,
1031 TtToken(_
, token
::SpecialVarNt(..)) => 2,
1032 TtToken(_
, token
::MatchNt(..)) => 3,
1033 TtDelimited(_
, ref delimed
) => {
1034 delimed
.tts
.len() + 2
1036 TtSequence(_
, ref seq
) => {
1043 pub fn get_tt(&self, index
: usize) -> TokenTree
{
1044 match (self, index
) {
1045 (&TtToken(sp
, token
::DocComment(_
)), 0) => {
1046 TtToken(sp
, token
::Pound
)
1048 (&TtToken(sp
, token
::DocComment(name
)), 1) => {
1049 TtDelimited(sp
, Rc
::new(Delimited
{
1050 delim
: token
::Bracket
,
1052 tts
: vec
![TtToken(sp
, token
::Ident(token
::str_to_ident("doc"),
1054 TtToken(sp
, token
::Eq
),
1055 TtToken(sp
, token
::Literal(token
::Str_(name
), None
))],
1059 (&TtDelimited(_
, ref delimed
), _
) => {
1061 return delimed
.open_tt();
1063 if index
== delimed
.tts
.len() + 1 {
1064 return delimed
.close_tt();
1066 delimed
.tts
[index
- 1].clone()
1068 (&TtToken(sp
, token
::SpecialVarNt(var
)), _
) => {
1069 let v
= [TtToken(sp
, token
::Dollar
),
1070 TtToken(sp
, token
::Ident(token
::str_to_ident(var
.as_str()),
1074 (&TtToken(sp
, token
::MatchNt(name
, kind
, name_st
, kind_st
)), _
) => {
1075 let v
= [TtToken(sp
, token
::SubstNt(name
, name_st
)),
1076 TtToken(sp
, token
::Colon
),
1077 TtToken(sp
, token
::Ident(kind
, kind_st
))];
1080 (&TtSequence(_
, ref seq
), _
) => {
1081 seq
.tts
[index
].clone()
1083 _
=> panic
!("Cannot expand a token tree")
1087 /// Returns the `Span` corresponding to this token tree.
1088 pub fn get_span(&self) -> Span
{
1090 TtToken(span
, _
) => span
,
1091 TtDelimited(span
, _
) => span
,
1092 TtSequence(span
, _
) => span
,
1096 /// Use this token tree as a matcher to parse given tts.
1097 pub fn parse(cx
: &base
::ExtCtxt
, mtch
: &[TokenTree
], tts
: &[TokenTree
])
1098 -> macro_parser
::NamedParseResult
{
1099 // `None` is because we're not interpolating
1100 let arg_rdr
= lexer
::new_tt_reader_with_doc_flag(&cx
.parse_sess().span_diagnostic
,
1103 tts
.iter().cloned().collect(),
1105 macro_parser
::parse(cx
.parse_sess(), cx
.cfg(), arg_rdr
, mtch
)
1109 pub type Mac
= Spanned
<Mac_
>;
1111 /// Represents a macro invocation. The Path indicates which macro
1112 /// is being invoked, and the vector of token-trees contains the source
1113 /// of the macro invocation.
1115 /// There's only one flavor, now, so this could presumably be simplified.
1116 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1118 // NB: the additional ident for a macro_rules-style macro is actually
1119 // stored in the enclosing item. Oog.
1120 MacInvocTT(Path
, Vec
<TokenTree
>, SyntaxContext
), // new macro-invocation
1123 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1125 /// A regular string, like `"foo"`
1127 /// A raw string, like `r##"foo"##`
1129 /// The uint is the number of `#` symbols used
1134 pub type Lit
= Spanned
<Lit_
>;
1136 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1143 pub fn new
<T
: IntSign
>(n
: T
) -> Sign
{
1149 fn sign(&self) -> Sign
;
1152 ($
($t
:ident
)*) => ($
(impl IntSign
for $t
{
1153 #[allow(unused_comparisons)]
1154 fn sign(&self) -> Sign
{
1155 if *self < 0 {Minus}
else {Plus}
1159 doit
! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1161 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1162 pub enum LitIntType
{
1163 SignedIntLit(IntTy
, Sign
),
1164 UnsignedIntLit(UintTy
),
1165 UnsuffixedIntLit(Sign
)
1169 pub fn suffix_len(&self) -> usize {
1171 UnsuffixedIntLit(_
) => 0,
1172 SignedIntLit(s
, _
) => s
.suffix_len(),
1173 UnsignedIntLit(u
) => u
.suffix_len()
1178 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1180 /// A string literal (`"foo"`)
1181 LitStr(InternedString
, StrStyle
),
1182 /// A byte string (`b"foo"`)
1183 LitBinary(Rc
<Vec
<u8>>),
1184 /// A byte char (`b'f'`)
1186 /// A character literal (`'a'`)
1188 /// An integer literal (`1u8`)
1189 LitInt(u64, LitIntType
),
1190 /// A float literal (`1f64` or `1E10f64`)
1191 LitFloat(InternedString
, FloatTy
),
1192 /// A float literal without a suffix (`1.0 or 1.0E10`)
1193 LitFloatUnsuffixed(InternedString
),
1194 /// A boolean literal
1198 // NB: If you change this, you'll probably want to change the corresponding
1199 // type structure in middle/ty.rs as well.
1200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1203 pub mutbl
: Mutability
,
1206 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1207 pub struct TypeField
{
1213 /// Represents a method's signature in a trait declaration,
1214 /// or in an implementation.
1215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1216 pub struct MethodSig
{
1217 pub unsafety
: Unsafety
,
1219 pub decl
: P
<FnDecl
>,
1220 pub generics
: Generics
,
1221 pub explicit_self
: ExplicitSelf
,
1224 /// Represents a method declaration in a trait declaration, possibly including
1225 /// a default implementation A trait method is either required (meaning it
1226 /// doesn't have an implementation, just a signature) or provided (meaning it
1227 /// has a default implementation).
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1229 pub struct TraitItem
{
1232 pub attrs
: Vec
<Attribute
>,
1233 pub node
: TraitItem_
,
1237 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1238 pub enum TraitItem_
{
1239 MethodTraitItem(MethodSig
, Option
<P
<Block
>>),
1240 TypeTraitItem(TyParamBounds
, Option
<P
<Ty
>>),
1243 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1244 pub struct ImplItem
{
1247 pub vis
: Visibility
,
1248 pub attrs
: Vec
<Attribute
>,
1249 pub node
: ImplItem_
,
1253 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1254 pub enum ImplItem_
{
1255 MethodImplItem(MethodSig
, P
<Block
>),
1256 TypeImplItem(P
<Ty
>),
1260 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1269 impl fmt
::Debug
for IntTy
{
1270 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1271 fmt
::Display
::fmt(self, f
)
1275 impl fmt
::Display
for IntTy
{
1276 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1277 write
!(f
, "{}", ast_util
::int_ty_to_string(*self, None
))
1282 pub fn suffix_len(&self) -> usize {
1285 TyI16
| TyI32
| TyI64
=> 3,
1290 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1300 pub fn suffix_len(&self) -> usize {
1303 TyU16
| TyU32
| TyU64
=> 3,
1308 impl fmt
::Debug
for UintTy
{
1309 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1310 fmt
::Display
::fmt(self, f
)
1314 impl fmt
::Display
for UintTy
{
1315 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1316 write
!(f
, "{}", ast_util
::uint_ty_to_string(*self, None
))
1320 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1326 impl fmt
::Debug
for FloatTy
{
1327 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1328 fmt
::Display
::fmt(self, f
)
1332 impl fmt
::Display
for FloatTy
{
1333 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1334 write
!(f
, "{}", ast_util
::float_ty_to_string(*self))
1339 pub fn suffix_len(&self) -> usize {
1341 TyF32
| TyF64
=> 3, // add F128 handling here
1346 // Bind a type to an associated type: `A=Foo`.
1347 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1348 pub struct TypeBinding
{
1356 // NB PartialEq method appears below.
1357 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1364 /// Not represented directly in the AST, referred to by name through a ty_path.
1365 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1376 pub struct BareFnTy
{
1377 pub unsafety
: Unsafety
,
1379 pub lifetimes
: Vec
<LifetimeDef
>,
1383 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1384 /// The different kinds of types recognized by the compiler
1387 /// A fixed length array (`[T; n]`)
1388 TyFixedLengthVec(P
<Ty
>, P
<Expr
>),
1389 /// A raw pointer (`*const T` or `*mut T`)
1391 /// A reference (`&'a T` or `&'a mut T`)
1392 TyRptr(Option
<Lifetime
>, MutTy
),
1393 /// A bare function (e.g. `fn(usize) -> bool`)
1394 TyBareFn(P
<BareFnTy
>),
1395 /// A tuple (`(A, B, C, D,...)`)
1397 /// A path (`module::module::...::Type`), optionally
1398 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1400 /// Type parameters are stored in the Path itself
1401 TyPath(Option
<QSelf
>, Path
),
1402 /// Something like `A+B`. Note that `B` must always be a path.
1403 TyObjectSum(P
<Ty
>, TyParamBounds
),
1404 /// A type like `for<'a> Foo<&'a Bar>`
1405 TyPolyTraitRef(TyParamBounds
),
1406 /// No-op; kept solely so that we can pretty-print faithfully
1410 /// TyInfer means the type should be inferred instead of it having been
1411 /// specified. This can appear anywhere in a type.
1415 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1416 pub enum AsmDialect
{
1421 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1422 pub struct InlineAsm
{
1423 pub asm
: InternedString
,
1424 pub asm_str_style
: StrStyle
,
1425 pub outputs
: Vec
<(InternedString
, P
<Expr
>, bool
)>,
1426 pub inputs
: Vec
<(InternedString
, P
<Expr
>)>,
1427 pub clobbers
: Vec
<InternedString
>,
1429 pub alignstack
: bool
,
1430 pub dialect
: AsmDialect
,
1431 pub expn_id
: ExpnId
,
1434 /// represents an argument in a function header
1435 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1443 pub fn new_self(span
: Span
, mutability
: Mutability
, self_ident
: Ident
) -> Arg
{
1444 let path
= Spanned{span:span,node:self_ident}
;
1446 // HACK(eddyb) fake type for the self argument.
1454 node
: PatIdent(BindByValue(mutability
), path
, None
),
1462 /// Represents the header (not the body) of a function declaration
1463 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1465 pub inputs
: Vec
<Arg
>,
1466 pub output
: FunctionRetTy
,
1470 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1476 impl fmt
::Display
for Unsafety
{
1477 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1478 fmt
::Display
::fmt(match *self {
1479 Unsafety
::Normal
=> "normal",
1480 Unsafety
::Unsafe
=> "unsafe",
1485 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1486 pub enum ImplPolarity
{
1487 /// `impl Trait for Type`
1489 /// `impl !Trait for Type`
1493 impl fmt
::Debug
for ImplPolarity
{
1494 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1496 ImplPolarity
::Positive
=> "positive".fmt(f
),
1497 ImplPolarity
::Negative
=> "negative".fmt(f
),
1503 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1504 pub enum FunctionRetTy
{
1505 /// Functions with return type `!`that always
1506 /// raise an error or exit (i.e. never return to the caller)
1508 /// Return type is not specified.
1510 /// Functions default to `()` and
1511 /// closures default to inference. Span points to where return
1512 /// type would be inserted.
1513 DefaultReturn(Span
),
1518 impl FunctionRetTy
{
1519 pub fn span(&self) -> Span
{
1521 NoReturn(span
) => span
,
1522 DefaultReturn(span
) => span
,
1523 Return(ref ty
) => ty
.span
1528 /// Represents the kind of 'self' associated with a method
1529 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1530 pub enum ExplicitSelf_
{
1535 /// `&'lt self`, `&'lt mut self`
1536 SelfRegion(Option
<Lifetime
>, Mutability
, Ident
),
1538 SelfExplicit(P
<Ty
>, Ident
),
1541 pub type ExplicitSelf
= Spanned
<ExplicitSelf_
>;
1543 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1545 /// A span from the first token past `{` to the last token until `}`.
1546 /// For `mod foo;`, the inner span ranges from the first token
1547 /// to the last token in the external file.
1549 pub items
: Vec
<P
<Item
>>,
1552 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1553 pub struct ForeignMod
{
1555 pub items
: Vec
<P
<ForeignItem
>>,
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1559 pub struct VariantArg
{
1564 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1565 pub enum VariantKind
{
1566 /// Tuple variant, e.g. `Foo(A, B)`
1567 TupleVariantKind(Vec
<VariantArg
>),
1568 /// Struct variant, e.g. `Foo {x: A, y: B}`
1569 StructVariantKind(P
<StructDef
>),
1572 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1573 pub struct EnumDef
{
1574 pub variants
: Vec
<P
<Variant
>>,
1577 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1578 pub struct Variant_
{
1580 pub attrs
: Vec
<Attribute
>,
1581 pub kind
: VariantKind
,
1583 /// Explicit discriminant, eg `Foo = 1`
1584 pub disr_expr
: Option
<P
<Expr
>>,
1585 pub vis
: Visibility
,
1588 pub type Variant
= Spanned
<Variant_
>;
1590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1591 pub enum PathListItem_
{
1592 PathListIdent { name: Ident, id: NodeId }
,
1593 PathListMod { id: NodeId }
1596 impl PathListItem_
{
1597 pub fn id(&self) -> NodeId
{
1599 PathListIdent { id, .. }
| PathListMod { id }
=> id
1604 pub type PathListItem
= Spanned
<PathListItem_
>;
1606 pub type ViewPath
= Spanned
<ViewPath_
>;
1608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1609 pub enum ViewPath_
{
1611 /// `foo::bar::baz as quux`
1615 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1616 ViewPathSimple(Ident
, Path
),
1621 /// `foo::bar::{a,b,c}`
1622 ViewPathList(Path
, Vec
<PathListItem
>)
1625 /// Meta-data associated with an item
1626 pub type Attribute
= Spanned
<Attribute_
>;
1628 /// Distinguishes between Attributes that decorate items and Attributes that
1629 /// are contained as statements within items. These two cases need to be
1630 /// distinguished for pretty-printing.
1631 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1632 pub enum AttrStyle
{
1637 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1638 pub struct AttrId(pub usize);
1640 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1641 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1642 pub struct Attribute_
{
1644 pub style
: AttrStyle
,
1645 pub value
: P
<MetaItem
>,
1646 pub is_sugared_doc
: bool
,
1649 /// TraitRef's appear in impls.
1651 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1652 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1653 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1654 /// same as the impl's node id).
1655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1656 pub struct TraitRef
{
1661 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1662 pub struct PolyTraitRef
{
1663 /// The `'a` in `<'a> Foo<&'a T>`
1664 pub bound_lifetimes
: Vec
<LifetimeDef
>,
1666 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1667 pub trait_ref
: TraitRef
,
1672 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1673 pub enum Visibility
{
1679 pub fn inherit_from(&self, parent_visibility
: Visibility
) -> Visibility
{
1681 &Inherited
=> parent_visibility
,
1687 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1688 pub struct StructField_
{
1689 pub kind
: StructFieldKind
,
1692 pub attrs
: Vec
<Attribute
>,
1696 pub fn ident(&self) -> Option
<Ident
> {
1698 NamedField(ref ident
, _
) => Some(ident
.clone()),
1699 UnnamedField(_
) => None
1704 pub type StructField
= Spanned
<StructField_
>;
1706 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1707 pub enum StructFieldKind
{
1708 NamedField(Ident
, Visibility
),
1709 /// Element of a tuple-like struct
1710 UnnamedField(Visibility
),
1713 impl StructFieldKind
{
1714 pub fn is_unnamed(&self) -> bool
{
1716 UnnamedField(..) => true,
1717 NamedField(..) => false,
1722 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1723 pub struct StructDef
{
1724 /// Fields, not including ctor
1725 pub fields
: Vec
<StructField
>,
1726 /// ID of the constructor. This is only used for tuple- or enum-like
1728 pub ctor_id
: Option
<NodeId
>,
1732 FIXME (#3300): Should allow items to be anonymous. Right now
1733 we just use dummy names for anon items.
1737 /// The name might be a dummy name in case of anonymous items
1738 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1741 pub attrs
: Vec
<Attribute
>,
1744 pub vis
: Visibility
,
1748 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1750 /// An`extern crate` item, with optional original crate name,
1752 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1753 ItemExternCrate(Option
<Name
>),
1754 /// A `use` or `pub use` item
1755 ItemUse(P
<ViewPath
>),
1758 ItemStatic(P
<Ty
>, Mutability
, P
<Expr
>),
1760 ItemConst(P
<Ty
>, P
<Expr
>),
1761 /// A function declaration
1762 ItemFn(P
<FnDecl
>, Unsafety
, Abi
, Generics
, P
<Block
>),
1765 /// An external module
1766 ItemForeignMod(ForeignMod
),
1767 /// A type alias, e.g. `type Foo = Bar<u8>`
1768 ItemTy(P
<Ty
>, Generics
),
1769 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1770 ItemEnum(EnumDef
, Generics
),
1771 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1772 ItemStruct(P
<StructDef
>, Generics
),
1773 /// Represents a Trait Declaration
1779 // Default trait implementations
1781 // `impl Trait for .. {}`
1782 ItemDefaultImpl(Unsafety
, TraitRef
),
1783 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1787 Option
<TraitRef
>, // (optional) trait this impl implements
1790 /// A macro invocation (which includes macro definition)
1795 pub fn descriptive_variant(&self) -> &str {
1797 ItemExternCrate(..) => "extern crate",
1798 ItemUse(..) => "use",
1799 ItemStatic(..) => "static item",
1800 ItemConst(..) => "constant item",
1801 ItemFn(..) => "function",
1802 ItemMod(..) => "module",
1803 ItemForeignMod(..) => "foreign module",
1804 ItemTy(..) => "type alias",
1805 ItemEnum(..) => "enum",
1806 ItemStruct(..) => "struct",
1807 ItemTrait(..) => "trait",
1810 ItemDefaultImpl(..) => "item"
1815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1816 pub struct ForeignItem
{
1818 pub attrs
: Vec
<Attribute
>,
1819 pub node
: ForeignItem_
,
1822 pub vis
: Visibility
,
1825 /// An item within an `extern` block
1826 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1827 pub enum ForeignItem_
{
1828 /// A foreign function
1829 ForeignItemFn(P
<FnDecl
>, Generics
),
1830 /// A foreign static item (`static ext: u8`), with optional mutability
1831 /// (the boolean is true when mutable)
1832 ForeignItemStatic(P
<Ty
>, bool
),
1836 pub fn descriptive_variant(&self) -> &str {
1838 ForeignItemFn(..) => "foreign function",
1839 ForeignItemStatic(..) => "foreign static item"
1844 /// The data we save and restore about an inlined item or method. This is not
1845 /// part of the AST that we parse from a file, but it becomes part of the tree
1847 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1848 pub enum InlinedItem
{
1850 IITraitItem(DefId
/* impl id */, P
<TraitItem
>),
1851 IIImplItem(DefId
/* impl id */, P
<ImplItem
>),
1852 IIForeign(P
<ForeignItem
>),
1855 /// A macro definition, in this crate or imported from another.
1857 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1858 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1859 pub struct MacroDef
{
1861 pub attrs
: Vec
<Attribute
>,
1864 pub imported_from
: Option
<Ident
>,
1866 pub use_locally
: bool
,
1867 pub allow_internal_unstable
: bool
,
1868 pub body
: Vec
<TokenTree
>,
1876 // are ASTs encodable?
1878 fn check_asts_encodable() {
1879 fn assert_encodable
<T
: serialize
::Encodable
>() {}
1880 assert_encodable
::<Crate
>();