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 {
94 impl fmt
::Debug
for Ident
{
95 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
96 write
!(f
, "{}#{}", self.name
, self.ctxt
)
100 impl fmt
::Display
for Ident
{
101 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
102 fmt
::Display
::fmt(&self.name
, f
)
106 impl fmt
::Debug
for Name
{
107 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
108 let Name(nm
) = *self;
109 write
!(f
, "{:?}({})", token
::get_name(*self), nm
)
113 impl fmt
::Display
for Name
{
114 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
115 fmt
::Display
::fmt(&token
::get_name(*self), f
)
119 impl PartialEq
for Ident
{
120 fn eq(&self, other
: &Ident
) -> bool
{
121 if self.ctxt
== other
.ctxt
{
122 self.name
== other
.name
124 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
125 // idents that have different contexts. You can't fix this without
126 // knowing whether the comparison should be hygienic or non-hygienic.
127 // if it should be non-hygienic (most things are), just compare the
128 // 'name' fields of the idents. Or, even better, replace the idents
131 // On the other hand, if the comparison does need to be hygienic,
132 // one example and its non-hygienic counterpart would be:
133 // syntax::parse::token::Token::mtwt_eq
134 // syntax::ext::tt::macro_parser::token_name_eq
135 panic
!("not allowed to compare these idents: {}, {}. \
136 Probably related to issue \\#6993", self, other
);
139 fn ne(&self, other
: &Ident
) -> bool
{
144 /// A SyntaxContext represents a chain of macro-expandings
145 /// and renamings. Each macro expansion corresponds to
148 // I'm representing this syntax context as an index into
149 // a table, in order to work around a compiler bug
150 // that's causing unreleased memory to cause core dumps
151 // and also perhaps to save some work in destructor checks.
152 // the special uint '0' will be used to indicate an empty
155 // this uint is a reference to a table stored in thread-local
157 pub type SyntaxContext
= u32;
158 pub const EMPTY_CTXT
: SyntaxContext
= 0;
159 pub const ILLEGAL_CTXT
: SyntaxContext
= 1;
161 /// A name is a part of an identifier, representing a string or gensym. It's
162 /// the result of interning.
163 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
164 RustcEncodable
, RustcDecodable
, Clone
, Copy
)]
165 pub struct Name(pub u32);
168 pub fn as_str
<'a
>(&'a
self) -> &'a
str {
170 // FIXME #12938: can't use copy_lifetime since &str isn't a &T
171 ::std
::mem
::transmute
::<&str,&str>(&token
::get_name(*self))
175 pub fn usize(&self) -> usize {
176 let Name(nm
) = *self;
180 pub fn ident(&self) -> Ident
{
181 Ident { name: *self, ctxt: 0 }
185 /// A mark represents a unique id associated with a macro expansion
188 impl Encodable
for Ident
{
189 fn encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
190 s
.emit_str(&token
::get_ident(*self))
194 impl Decodable
for Ident
{
195 fn decode
<D
: Decoder
>(d
: &mut D
) -> Result
<Ident
, D
::Error
> {
196 Ok(str_to_ident(&try
!(d
.read_str())[..]))
200 /// Function name (not all functions have names)
201 pub type FnIdent
= Option
<Ident
>;
203 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,
205 pub struct Lifetime
{
211 /// A lifetime definition, eg `'a: 'b+'c+'d`
212 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
213 pub struct LifetimeDef
{
214 pub lifetime
: Lifetime
,
215 pub bounds
: Vec
<Lifetime
>
218 /// A "Path" is essentially Rust's notion of a name; for instance:
219 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
220 /// along with a bunch of supporting information.
221 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
224 /// A `::foo` path, is relative to the crate root rather than current
225 /// module (like paths in an import).
227 /// The segments in the path: the things separated by `::`.
228 pub segments
: Vec
<PathSegment
>,
231 /// A segment of a path: an identifier, an optional lifetime, and a set of
233 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
234 pub struct PathSegment
{
235 /// The identifier portion of this path segment.
236 pub identifier
: Ident
,
238 /// Type/lifetime parameters attached to this path. They come in
239 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
240 /// this is more than just simple syntactic sugar; the use of
241 /// parens affects the region binding rules, so we preserve the
243 pub parameters
: PathParameters
,
246 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
247 pub enum PathParameters
{
248 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
249 AngleBracketedParameters(AngleBracketedParameterData
),
250 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
251 ParenthesizedParameters(ParenthesizedParameterData
),
254 impl PathParameters
{
255 pub fn none() -> PathParameters
{
256 AngleBracketedParameters(AngleBracketedParameterData
{
257 lifetimes
: Vec
::new(),
258 types
: OwnedSlice
::empty(),
259 bindings
: OwnedSlice
::empty(),
263 pub fn is_empty(&self) -> bool
{
265 AngleBracketedParameters(ref data
) => data
.is_empty(),
267 // Even if the user supplied no types, something like
268 // `X()` is equivalent to `X<(),()>`.
269 ParenthesizedParameters(..) => false,
273 pub fn has_lifetimes(&self) -> bool
{
275 AngleBracketedParameters(ref data
) => !data
.lifetimes
.is_empty(),
276 ParenthesizedParameters(_
) => false,
280 pub fn has_types(&self) -> bool
{
282 AngleBracketedParameters(ref data
) => !data
.types
.is_empty(),
283 ParenthesizedParameters(..) => true,
287 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
288 /// parameters in the parenthesized case.
289 pub fn types(&self) -> Vec
<&P
<Ty
>> {
291 AngleBracketedParameters(ref data
) => {
292 data
.types
.iter().collect()
294 ParenthesizedParameters(ref data
) => {
296 .chain(data
.output
.iter())
302 pub fn lifetimes(&self) -> Vec
<&Lifetime
> {
304 AngleBracketedParameters(ref data
) => {
305 data
.lifetimes
.iter().collect()
307 ParenthesizedParameters(_
) => {
313 pub fn bindings(&self) -> Vec
<&P
<TypeBinding
>> {
315 AngleBracketedParameters(ref data
) => {
316 data
.bindings
.iter().collect()
318 ParenthesizedParameters(_
) => {
325 /// A path like `Foo<'a, T>`
326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
327 pub struct AngleBracketedParameterData
{
328 /// The lifetime parameters for this path segment.
329 pub lifetimes
: Vec
<Lifetime
>,
330 /// The type parameters for this path segment, if present.
331 pub types
: OwnedSlice
<P
<Ty
>>,
332 /// Bindings (equality constraints) on associated types, if present.
333 /// E.g., `Foo<A=Bar>`.
334 pub bindings
: OwnedSlice
<P
<TypeBinding
>>,
337 impl AngleBracketedParameterData
{
338 fn is_empty(&self) -> bool
{
339 self.lifetimes
.is_empty() && self.types
.is_empty() && self.bindings
.is_empty()
343 /// A path like `Foo(A,B) -> C`
344 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
345 pub struct ParenthesizedParameterData
{
350 pub inputs
: Vec
<P
<Ty
>>,
353 pub output
: Option
<P
<Ty
>>,
356 pub type CrateNum
= u32;
358 pub type NodeId
= u32;
360 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
361 RustcDecodable
, Hash
, Debug
, Copy
)]
368 /// Read the node id, asserting that this def-id is krate-local.
369 pub fn local_id(&self) -> NodeId
{
370 assert_eq
!(self.krate
, LOCAL_CRATE
);
375 /// Item definitions in the currently-compiled crate would have the CrateNum
376 /// LOCAL_CRATE in their DefId.
377 pub const LOCAL_CRATE
: CrateNum
= 0;
378 pub const CRATE_NODE_ID
: NodeId
= 0;
380 /// When parsing and doing expansions, we initially give all AST nodes this AST
381 /// node value. Then later, in the renumber pass, we renumber them to have
382 /// small, positive ids.
383 pub const DUMMY_NODE_ID
: NodeId
= !0;
385 /// The AST represents all type param bounds as types.
386 /// typeck::collect::compute_bounds matches these against
387 /// the "special" built-in traits (see middle::lang_items) and
388 /// detects Copy, Send and Sync.
389 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
390 pub enum TyParamBound
{
391 TraitTyParamBound(PolyTraitRef
, TraitBoundModifier
),
392 RegionTyParamBound(Lifetime
)
395 /// A modifier on a bound, currently this is only used for `?Sized`, where the
396 /// modifier is `Maybe`. Negative bounds should also be handled here.
397 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
398 pub enum TraitBoundModifier
{
403 pub type TyParamBounds
= OwnedSlice
<TyParamBound
>;
405 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
409 pub bounds
: TyParamBounds
,
410 pub default: Option
<P
<Ty
>>,
414 /// Represents lifetimes and type parameters attached to a declaration
415 /// of a function, enum, trait, etc.
416 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
417 pub struct Generics
{
418 pub lifetimes
: Vec
<LifetimeDef
>,
419 pub ty_params
: OwnedSlice
<TyParam
>,
420 pub where_clause
: WhereClause
,
424 pub fn is_lt_parameterized(&self) -> bool
{
425 !self.lifetimes
.is_empty()
427 pub fn is_type_parameterized(&self) -> bool
{
428 !self.ty_params
.is_empty()
430 pub fn is_parameterized(&self) -> bool
{
431 self.is_lt_parameterized() || self.is_type_parameterized()
435 /// A `where` clause in a definition
436 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
437 pub struct WhereClause
{
439 pub predicates
: Vec
<WherePredicate
>,
442 /// A single predicate in a `where` clause
443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
444 pub enum WherePredicate
{
445 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
446 BoundPredicate(WhereBoundPredicate
),
447 /// A lifetime predicate, e.g. `'a: 'b+'c`
448 RegionPredicate(WhereRegionPredicate
),
449 /// An equality predicate (unsupported)
450 EqPredicate(WhereEqPredicate
)
453 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
454 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
455 pub struct WhereBoundPredicate
{
457 /// Any lifetimes from a `for` binding
458 pub bound_lifetimes
: Vec
<LifetimeDef
>,
459 /// The type being bounded
460 pub bounded_ty
: P
<Ty
>,
461 /// Trait and lifetime bounds (`Clone+Send+'static`)
462 pub bounds
: OwnedSlice
<TyParamBound
>,
465 /// A lifetime predicate, e.g. `'a: 'b+'c`
466 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
467 pub struct WhereRegionPredicate
{
469 pub lifetime
: Lifetime
,
470 pub bounds
: Vec
<Lifetime
>,
473 /// An equality predicate (unsupported), e.g. `T=int`
474 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
475 pub struct WhereEqPredicate
{
482 /// The set of MetaItems that define the compilation environment of the crate,
483 /// used to drive conditional compilation
484 pub type CrateConfig
= Vec
<P
<MetaItem
>> ;
486 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
489 pub attrs
: Vec
<Attribute
>,
490 pub config
: CrateConfig
,
492 pub exported_macros
: Vec
<MacroDef
>,
495 pub type MetaItem
= Spanned
<MetaItem_
>;
497 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
499 MetaWord(InternedString
),
500 MetaList(InternedString
, Vec
<P
<MetaItem
>>),
501 MetaNameValue(InternedString
, Lit
),
504 // can't be derived because the MetaList requires an unordered comparison
505 impl PartialEq
for MetaItem_
{
506 fn eq(&self, other
: &MetaItem_
) -> bool
{
508 MetaWord(ref ns
) => match *other
{
509 MetaWord(ref no
) => (*ns
) == (*no
),
512 MetaNameValue(ref ns
, ref vs
) => match *other
{
513 MetaNameValue(ref no
, ref vo
) => {
514 (*ns
) == (*no
) && vs
.node
== vo
.node
518 MetaList(ref ns
, ref miss
) => match *other
{
519 MetaList(ref no
, ref miso
) => {
521 miss
.iter().all(|mi
| miso
.iter().any(|x
| x
.node
== mi
.node
))
529 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
531 /// Statements in a block
532 pub stmts
: Vec
<P
<Stmt
>>,
533 /// An expression at the end of the block
534 /// without a semicolon, if any
535 pub expr
: Option
<P
<Expr
>>,
537 /// Distinguishes between `unsafe { ... }` and `{ ... }`
538 pub rules
: BlockCheckMode
,
542 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
549 /// A single field in a struct pattern
551 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
552 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
553 /// except is_shorthand is true
554 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
555 pub struct FieldPat
{
556 /// The identifier for the field
558 /// The pattern the field is destructured to
560 pub is_shorthand
: bool
,
563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
564 pub enum BindingMode
{
565 BindByRef(Mutability
),
566 BindByValue(Mutability
),
569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
570 pub enum PatWildKind
{
571 /// Represents the wildcard pattern `_`
574 /// Represents the wildcard pattern `..`
578 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
580 /// Represents a wildcard pattern (either `_` or `..`)
581 PatWild(PatWildKind
),
583 /// A PatIdent may either be a new bound variable,
584 /// or a nullary enum (in which case the third field
587 /// In the nullary enum case, the parser can't determine
588 /// which it is. The resolver determines this, and
589 /// records this pattern's NodeId in an auxiliary
590 /// set (of "PatIdents that refer to nullary enums")
591 PatIdent(BindingMode
, SpannedIdent
, Option
<P
<Pat
>>),
593 /// "None" means a * pattern where we don't bind the fields to names.
594 PatEnum(Path
, Option
<Vec
<P
<Pat
>>>),
596 /// An associated const named using the qualified path `<T>::CONST` or
597 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
598 /// referred to as simply `T::CONST`, in which case they will end up as
599 /// PatEnum, and the resolver will have to sort that out.
600 PatQPath(QSelf
, Path
),
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 ConstTraitItem(P
<Ty
>, Option
<P
<Expr
>>),
1240 MethodTraitItem(MethodSig
, Option
<P
<Block
>>),
1241 TypeTraitItem(TyParamBounds
, Option
<P
<Ty
>>),
1244 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1245 pub struct ImplItem
{
1248 pub vis
: Visibility
,
1249 pub attrs
: Vec
<Attribute
>,
1250 pub node
: ImplItem_
,
1254 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1255 pub enum ImplItem_
{
1256 ConstImplItem(P
<Ty
>, P
<Expr
>),
1257 MethodImplItem(MethodSig
, P
<Block
>),
1258 TypeImplItem(P
<Ty
>),
1262 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1271 impl fmt
::Debug
for IntTy
{
1272 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1273 fmt
::Display
::fmt(self, f
)
1277 impl fmt
::Display
for IntTy
{
1278 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1279 write
!(f
, "{}", ast_util
::int_ty_to_string(*self, None
))
1284 pub fn suffix_len(&self) -> usize {
1287 TyI16
| TyI32
| TyI64
=> 3,
1292 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1302 pub fn suffix_len(&self) -> usize {
1305 TyU16
| TyU32
| TyU64
=> 3,
1310 impl fmt
::Debug
for UintTy
{
1311 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1312 fmt
::Display
::fmt(self, f
)
1316 impl fmt
::Display
for UintTy
{
1317 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1318 write
!(f
, "{}", ast_util
::uint_ty_to_string(*self, None
))
1322 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1328 impl fmt
::Debug
for FloatTy
{
1329 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1330 fmt
::Display
::fmt(self, f
)
1334 impl fmt
::Display
for FloatTy
{
1335 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1336 write
!(f
, "{}", ast_util
::float_ty_to_string(*self))
1341 pub fn suffix_len(&self) -> usize {
1343 TyF32
| TyF64
=> 3, // add F128 handling here
1348 // Bind a type to an associated type: `A=Foo`.
1349 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1350 pub struct TypeBinding
{
1358 // NB PartialEq method appears below.
1359 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1366 /// Not represented directly in the AST, referred to by name through a ty_path.
1367 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1378 pub struct BareFnTy
{
1379 pub unsafety
: Unsafety
,
1381 pub lifetimes
: Vec
<LifetimeDef
>,
1385 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1386 /// The different kinds of types recognized by the compiler
1389 /// A fixed length array (`[T; n]`)
1390 TyFixedLengthVec(P
<Ty
>, P
<Expr
>),
1391 /// A raw pointer (`*const T` or `*mut T`)
1393 /// A reference (`&'a T` or `&'a mut T`)
1394 TyRptr(Option
<Lifetime
>, MutTy
),
1395 /// A bare function (e.g. `fn(usize) -> bool`)
1396 TyBareFn(P
<BareFnTy
>),
1397 /// A tuple (`(A, B, C, D,...)`)
1399 /// A path (`module::module::...::Type`), optionally
1400 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1402 /// Type parameters are stored in the Path itself
1403 TyPath(Option
<QSelf
>, Path
),
1404 /// Something like `A+B`. Note that `B` must always be a path.
1405 TyObjectSum(P
<Ty
>, TyParamBounds
),
1406 /// A type like `for<'a> Foo<&'a Bar>`
1407 TyPolyTraitRef(TyParamBounds
),
1408 /// No-op; kept solely so that we can pretty-print faithfully
1412 /// TyInfer means the type should be inferred instead of it having been
1413 /// specified. This can appear anywhere in a type.
1417 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1418 pub enum AsmDialect
{
1423 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1424 pub struct InlineAsm
{
1425 pub asm
: InternedString
,
1426 pub asm_str_style
: StrStyle
,
1427 pub outputs
: Vec
<(InternedString
, P
<Expr
>, bool
)>,
1428 pub inputs
: Vec
<(InternedString
, P
<Expr
>)>,
1429 pub clobbers
: Vec
<InternedString
>,
1431 pub alignstack
: bool
,
1432 pub dialect
: AsmDialect
,
1433 pub expn_id
: ExpnId
,
1436 /// represents an argument in a function header
1437 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1445 pub fn new_self(span
: Span
, mutability
: Mutability
, self_ident
: Ident
) -> Arg
{
1446 let path
= Spanned{span:span,node:self_ident}
;
1448 // HACK(eddyb) fake type for the self argument.
1456 node
: PatIdent(BindByValue(mutability
), path
, None
),
1464 /// Represents the header (not the body) of a function declaration
1465 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1467 pub inputs
: Vec
<Arg
>,
1468 pub output
: FunctionRetTy
,
1472 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1478 impl fmt
::Display
for Unsafety
{
1479 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1480 fmt
::Display
::fmt(match *self {
1481 Unsafety
::Normal
=> "normal",
1482 Unsafety
::Unsafe
=> "unsafe",
1487 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1488 pub enum ImplPolarity
{
1489 /// `impl Trait for Type`
1491 /// `impl !Trait for Type`
1495 impl fmt
::Debug
for ImplPolarity
{
1496 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1498 ImplPolarity
::Positive
=> "positive".fmt(f
),
1499 ImplPolarity
::Negative
=> "negative".fmt(f
),
1505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1506 pub enum FunctionRetTy
{
1507 /// Functions with return type `!`that always
1508 /// raise an error or exit (i.e. never return to the caller)
1510 /// Return type is not specified.
1512 /// Functions default to `()` and
1513 /// closures default to inference. Span points to where return
1514 /// type would be inserted.
1515 DefaultReturn(Span
),
1520 impl FunctionRetTy
{
1521 pub fn span(&self) -> Span
{
1523 NoReturn(span
) => span
,
1524 DefaultReturn(span
) => span
,
1525 Return(ref ty
) => ty
.span
1530 /// Represents the kind of 'self' associated with a method
1531 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1532 pub enum ExplicitSelf_
{
1537 /// `&'lt self`, `&'lt mut self`
1538 SelfRegion(Option
<Lifetime
>, Mutability
, Ident
),
1540 SelfExplicit(P
<Ty
>, Ident
),
1543 pub type ExplicitSelf
= Spanned
<ExplicitSelf_
>;
1545 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1547 /// A span from the first token past `{` to the last token until `}`.
1548 /// For `mod foo;`, the inner span ranges from the first token
1549 /// to the last token in the external file.
1551 pub items
: Vec
<P
<Item
>>,
1554 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1555 pub struct ForeignMod
{
1557 pub items
: Vec
<P
<ForeignItem
>>,
1560 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1561 pub struct VariantArg
{
1566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1567 pub enum VariantKind
{
1568 /// Tuple variant, e.g. `Foo(A, B)`
1569 TupleVariantKind(Vec
<VariantArg
>),
1570 /// Struct variant, e.g. `Foo {x: A, y: B}`
1571 StructVariantKind(P
<StructDef
>),
1574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1575 pub struct EnumDef
{
1576 pub variants
: Vec
<P
<Variant
>>,
1579 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1580 pub struct Variant_
{
1582 pub attrs
: Vec
<Attribute
>,
1583 pub kind
: VariantKind
,
1585 /// Explicit discriminant, eg `Foo = 1`
1586 pub disr_expr
: Option
<P
<Expr
>>,
1587 pub vis
: Visibility
,
1590 pub type Variant
= Spanned
<Variant_
>;
1592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1593 pub enum PathListItem_
{
1594 PathListIdent { name: Ident, id: NodeId }
,
1595 PathListMod { id: NodeId }
1598 impl PathListItem_
{
1599 pub fn id(&self) -> NodeId
{
1601 PathListIdent { id, .. }
| PathListMod { id }
=> id
1606 pub type PathListItem
= Spanned
<PathListItem_
>;
1608 pub type ViewPath
= Spanned
<ViewPath_
>;
1610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1611 pub enum ViewPath_
{
1613 /// `foo::bar::baz as quux`
1617 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1618 ViewPathSimple(Ident
, Path
),
1623 /// `foo::bar::{a,b,c}`
1624 ViewPathList(Path
, Vec
<PathListItem
>)
1627 /// Meta-data associated with an item
1628 pub type Attribute
= Spanned
<Attribute_
>;
1630 /// Distinguishes between Attributes that decorate items and Attributes that
1631 /// are contained as statements within items. These two cases need to be
1632 /// distinguished for pretty-printing.
1633 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1634 pub enum AttrStyle
{
1639 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1640 pub struct AttrId(pub usize);
1642 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1643 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1644 pub struct Attribute_
{
1646 pub style
: AttrStyle
,
1647 pub value
: P
<MetaItem
>,
1648 pub is_sugared_doc
: bool
,
1651 /// TraitRef's appear in impls.
1653 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1654 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1655 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1656 /// same as the impl's node id).
1657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1658 pub struct TraitRef
{
1663 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1664 pub struct PolyTraitRef
{
1665 /// The `'a` in `<'a> Foo<&'a T>`
1666 pub bound_lifetimes
: Vec
<LifetimeDef
>,
1668 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1669 pub trait_ref
: TraitRef
,
1674 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1675 pub enum Visibility
{
1681 pub fn inherit_from(&self, parent_visibility
: Visibility
) -> Visibility
{
1683 &Inherited
=> parent_visibility
,
1689 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1690 pub struct StructField_
{
1691 pub kind
: StructFieldKind
,
1694 pub attrs
: Vec
<Attribute
>,
1698 pub fn ident(&self) -> Option
<Ident
> {
1700 NamedField(ref ident
, _
) => Some(ident
.clone()),
1701 UnnamedField(_
) => None
1706 pub type StructField
= Spanned
<StructField_
>;
1708 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1709 pub enum StructFieldKind
{
1710 NamedField(Ident
, Visibility
),
1711 /// Element of a tuple-like struct
1712 UnnamedField(Visibility
),
1715 impl StructFieldKind
{
1716 pub fn is_unnamed(&self) -> bool
{
1718 UnnamedField(..) => true,
1719 NamedField(..) => false,
1724 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1725 pub struct StructDef
{
1726 /// Fields, not including ctor
1727 pub fields
: Vec
<StructField
>,
1728 /// ID of the constructor. This is only used for tuple- or enum-like
1730 pub ctor_id
: Option
<NodeId
>,
1734 FIXME (#3300): Should allow items to be anonymous. Right now
1735 we just use dummy names for anon items.
1739 /// The name might be a dummy name in case of anonymous items
1740 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1743 pub attrs
: Vec
<Attribute
>,
1746 pub vis
: Visibility
,
1750 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1752 /// An`extern crate` item, with optional original crate name,
1754 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1755 ItemExternCrate(Option
<Name
>),
1756 /// A `use` or `pub use` item
1757 ItemUse(P
<ViewPath
>),
1760 ItemStatic(P
<Ty
>, Mutability
, P
<Expr
>),
1762 ItemConst(P
<Ty
>, P
<Expr
>),
1763 /// A function declaration
1764 ItemFn(P
<FnDecl
>, Unsafety
, Abi
, Generics
, P
<Block
>),
1767 /// An external module
1768 ItemForeignMod(ForeignMod
),
1769 /// A type alias, e.g. `type Foo = Bar<u8>`
1770 ItemTy(P
<Ty
>, Generics
),
1771 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1772 ItemEnum(EnumDef
, Generics
),
1773 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1774 ItemStruct(P
<StructDef
>, Generics
),
1775 /// Represents a Trait Declaration
1781 // Default trait implementations
1783 // `impl Trait for .. {}`
1784 ItemDefaultImpl(Unsafety
, TraitRef
),
1785 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1789 Option
<TraitRef
>, // (optional) trait this impl implements
1792 /// A macro invocation (which includes macro definition)
1797 pub fn descriptive_variant(&self) -> &str {
1799 ItemExternCrate(..) => "extern crate",
1800 ItemUse(..) => "use",
1801 ItemStatic(..) => "static item",
1802 ItemConst(..) => "constant item",
1803 ItemFn(..) => "function",
1804 ItemMod(..) => "module",
1805 ItemForeignMod(..) => "foreign module",
1806 ItemTy(..) => "type alias",
1807 ItemEnum(..) => "enum",
1808 ItemStruct(..) => "struct",
1809 ItemTrait(..) => "trait",
1812 ItemDefaultImpl(..) => "item"
1817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1818 pub struct ForeignItem
{
1820 pub attrs
: Vec
<Attribute
>,
1821 pub node
: ForeignItem_
,
1824 pub vis
: Visibility
,
1827 /// An item within an `extern` block
1828 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1829 pub enum ForeignItem_
{
1830 /// A foreign function
1831 ForeignItemFn(P
<FnDecl
>, Generics
),
1832 /// A foreign static item (`static ext: u8`), with optional mutability
1833 /// (the boolean is true when mutable)
1834 ForeignItemStatic(P
<Ty
>, bool
),
1838 pub fn descriptive_variant(&self) -> &str {
1840 ForeignItemFn(..) => "foreign function",
1841 ForeignItemStatic(..) => "foreign static item"
1846 /// The data we save and restore about an inlined item or method. This is not
1847 /// part of the AST that we parse from a file, but it becomes part of the tree
1849 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1850 pub enum InlinedItem
{
1852 IITraitItem(DefId
/* impl id */, P
<TraitItem
>),
1853 IIImplItem(DefId
/* impl id */, P
<ImplItem
>),
1854 IIForeign(P
<ForeignItem
>),
1857 /// A macro definition, in this crate or imported from another.
1859 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1860 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1861 pub struct MacroDef
{
1863 pub attrs
: Vec
<Attribute
>,
1866 pub imported_from
: Option
<Ident
>,
1868 pub use_locally
: bool
,
1869 pub allow_internal_unstable
: bool
,
1870 pub body
: Vec
<TokenTree
>,
1878 // are ASTs encodable?
1880 fn check_asts_encodable() {
1881 fn assert_encodable
<T
: serialize
::Encodable
>() {}
1882 assert_encodable
::<Crate
>();