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::Mac_
::*;
33 pub use self::MacStmtStyle
::*;
34 pub use self::MetaItem_
::*;
35 pub use self::Mutability
::*;
36 pub use self::Pat_
::*;
37 pub use self::PathListItem_
::*;
38 pub use self::PatWildKind
::*;
39 pub use self::PrimTy
::*;
40 pub use self::Sign
::*;
41 pub use self::Stmt_
::*;
42 pub use self::StrStyle
::*;
43 pub use self::StructFieldKind
::*;
44 pub use self::TokenTree
::*;
45 pub use self::TraitItem_
::*;
47 pub use self::TyParamBound
::*;
48 pub use self::UintTy
::*;
49 pub use self::UnOp
::*;
50 pub use self::UnsafeSource
::*;
51 pub use self::VariantKind
::*;
52 pub use self::ViewPath_
::*;
53 pub use self::Visibility
::*;
54 pub use self::PathParameters
::*;
56 use codemap
::{Span, Spanned, DUMMY_SP, ExpnId}
;
60 use ext
::tt
::macro_parser
;
61 use owned_slice
::OwnedSlice
;
62 use parse
::token
::{InternedString, str_to_ident}
;
65 use parse
::lexer
::comments
::{doc_comment_style, strip_doc_comment_decoration}
;
72 use serialize
::{Encodable, Decodable, Encoder, Decoder}
;
74 // FIXME #6993: in librustc, uses of "ident" should be replaced
77 /// An identifier contains a Name (index into the interner
78 /// table) and a SyntaxContext to track renaming and
79 /// macro expansion per Flatt et al., "Macros
80 /// That Work Together"
81 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
84 pub ctxt
: SyntaxContext
88 /// Construct an identifier with the given name and an empty context:
89 pub fn new(name
: Name
) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}
}
92 impl fmt
::Debug
for Ident
{
93 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
94 write
!(f
, "{}#{}", self.name
, self.ctxt
)
98 impl fmt
::Display
for Ident
{
99 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
100 fmt
::Display
::fmt(&self.name
, f
)
104 impl fmt
::Debug
for Name
{
105 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
106 let Name(nm
) = *self;
107 write
!(f
, "{}({})", self, nm
)
111 impl fmt
::Display
for Name
{
112 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
113 fmt
::Display
::fmt(&self.as_str(), f
)
117 impl PartialEq
for Ident
{
118 fn eq(&self, other
: &Ident
) -> bool
{
119 if self.ctxt
== other
.ctxt
{
120 self.name
== other
.name
122 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
123 // idents that have different contexts. You can't fix this without
124 // knowing whether the comparison should be hygienic or non-hygienic.
125 // if it should be non-hygienic (most things are), just compare the
126 // 'name' fields of the idents. Or, even better, replace the idents
129 // On the other hand, if the comparison does need to be hygienic,
130 // one example and its non-hygienic counterpart would be:
131 // syntax::parse::token::Token::mtwt_eq
132 // syntax::ext::tt::macro_parser::token_name_eq
133 panic
!("not allowed to compare these idents: {:?}, {:?}. \
134 Probably related to issue \\#6993", self, other
);
139 /// A SyntaxContext represents a chain of macro-expandings
140 /// and renamings. Each macro expansion corresponds to
143 // I'm representing this syntax context as an index into
144 // a table, in order to work around a compiler bug
145 // that's causing unreleased memory to cause core dumps
146 // and also perhaps to save some work in destructor checks.
147 // the special uint '0' will be used to indicate an empty
150 // this uint is a reference to a table stored in thread-local
152 pub type SyntaxContext
= u32;
153 pub const EMPTY_CTXT
: SyntaxContext
= 0;
154 pub const ILLEGAL_CTXT
: SyntaxContext
= 1;
156 /// A name is a part of an identifier, representing a string or gensym. It's
157 /// the result of interning.
158 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
159 RustcEncodable
, RustcDecodable
, Clone
, Copy
)]
160 pub struct Name(pub u32);
162 impl<T
: AsRef
<str>> PartialEq
<T
> for Name
{
163 fn eq(&self, other
: &T
) -> bool
{
164 self.as_str() == other
.as_ref()
169 pub fn as_str(&self) -> token
::InternedString
{
170 token
::InternedString
::new_from_name(*self)
173 pub fn usize(&self) -> usize {
174 let Name(nm
) = *self;
178 pub fn ident(&self) -> Ident
{
179 Ident { name: *self, ctxt: 0 }
183 /// A mark represents a unique id associated with a macro expansion
186 impl Encodable
for Ident
{
187 fn encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
188 s
.emit_str(&self.name
.as_str())
192 impl Decodable
for Ident
{
193 fn decode
<D
: Decoder
>(d
: &mut D
) -> Result
<Ident
, D
::Error
> {
194 Ok(str_to_ident(&try
!(d
.read_str())[..]))
198 /// Function name (not all functions have names)
199 pub type FnIdent
= Option
<Ident
>;
201 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
202 pub struct Lifetime
{
208 impl fmt
::Debug
for Lifetime
{
209 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
210 write
!(f
, "lifetime({}: {})", self.id
, pprust
::lifetime_to_string(self))
214 /// A lifetime definition, eg `'a: 'b+'c+'d`
215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
216 pub struct LifetimeDef
{
217 pub lifetime
: Lifetime
,
218 pub bounds
: Vec
<Lifetime
>
221 /// A "Path" is essentially Rust's notion of a name; for instance:
222 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
223 /// along with a bunch of supporting information.
224 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
227 /// A `::foo` path, is relative to the crate root rather than current
228 /// module (like paths in an import).
230 /// The segments in the path: the things separated by `::`.
231 pub segments
: Vec
<PathSegment
>,
234 impl fmt
::Debug
for Path
{
235 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
236 write
!(f
, "path({})", pprust
::path_to_string(self))
240 impl fmt
::Display
for Path
{
241 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
242 write
!(f
, "{}", pprust
::path_to_string(self))
246 /// A segment of a path: an identifier, an optional lifetime, and a set of
248 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
249 pub struct PathSegment
{
250 /// The identifier portion of this path segment.
251 pub identifier
: Ident
,
253 /// Type/lifetime parameters attached to this path. They come in
254 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
255 /// this is more than just simple syntactic sugar; the use of
256 /// parens affects the region binding rules, so we preserve the
258 pub parameters
: PathParameters
,
261 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
262 pub enum PathParameters
{
263 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
264 AngleBracketedParameters(AngleBracketedParameterData
),
265 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
266 ParenthesizedParameters(ParenthesizedParameterData
),
269 impl PathParameters
{
270 pub fn none() -> PathParameters
{
271 AngleBracketedParameters(AngleBracketedParameterData
{
272 lifetimes
: Vec
::new(),
273 types
: OwnedSlice
::empty(),
274 bindings
: OwnedSlice
::empty(),
278 pub fn is_empty(&self) -> bool
{
280 AngleBracketedParameters(ref data
) => data
.is_empty(),
282 // Even if the user supplied no types, something like
283 // `X()` is equivalent to `X<(),()>`.
284 ParenthesizedParameters(..) => false,
288 pub fn has_lifetimes(&self) -> bool
{
290 AngleBracketedParameters(ref data
) => !data
.lifetimes
.is_empty(),
291 ParenthesizedParameters(_
) => false,
295 pub fn has_types(&self) -> bool
{
297 AngleBracketedParameters(ref data
) => !data
.types
.is_empty(),
298 ParenthesizedParameters(..) => true,
302 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
303 /// parameters in the parenthesized case.
304 pub fn types(&self) -> Vec
<&P
<Ty
>> {
306 AngleBracketedParameters(ref data
) => {
307 data
.types
.iter().collect()
309 ParenthesizedParameters(ref data
) => {
311 .chain(data
.output
.iter())
317 pub fn lifetimes(&self) -> Vec
<&Lifetime
> {
319 AngleBracketedParameters(ref data
) => {
320 data
.lifetimes
.iter().collect()
322 ParenthesizedParameters(_
) => {
328 pub fn bindings(&self) -> Vec
<&P
<TypeBinding
>> {
330 AngleBracketedParameters(ref data
) => {
331 data
.bindings
.iter().collect()
333 ParenthesizedParameters(_
) => {
340 /// A path like `Foo<'a, T>`
341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
342 pub struct AngleBracketedParameterData
{
343 /// The lifetime parameters for this path segment.
344 pub lifetimes
: Vec
<Lifetime
>,
345 /// The type parameters for this path segment, if present.
346 pub types
: OwnedSlice
<P
<Ty
>>,
347 /// Bindings (equality constraints) on associated types, if present.
348 /// E.g., `Foo<A=Bar>`.
349 pub bindings
: OwnedSlice
<P
<TypeBinding
>>,
352 impl AngleBracketedParameterData
{
353 fn is_empty(&self) -> bool
{
354 self.lifetimes
.is_empty() && self.types
.is_empty() && self.bindings
.is_empty()
358 /// A path like `Foo(A,B) -> C`
359 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
360 pub struct ParenthesizedParameterData
{
365 pub inputs
: Vec
<P
<Ty
>>,
368 pub output
: Option
<P
<Ty
>>,
371 pub type CrateNum
= u32;
373 pub type NodeId
= u32;
375 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
376 RustcDecodable
, Hash
, Copy
)]
382 fn default_def_id_debug(_
: DefId
, _
: &mut fmt
::Formatter
) -> fmt
::Result { Ok(()) }
384 thread_local
!(pub static DEF_ID_DEBUG
: Cell
<fn(DefId
, &mut fmt
::Formatter
) -> fmt
::Result
> =
385 Cell
::new(default_def_id_debug
));
387 impl fmt
::Debug
for DefId
{
388 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
389 try
!(write
!(f
, "DefId {{ krate: {}, node: {} }}",
390 self.krate
, self.node
));
391 DEF_ID_DEBUG
.with(|def_id_debug
| def_id_debug
.get()(*self, f
))
396 /// Read the node id, asserting that this def-id is krate-local.
397 pub fn local_id(&self) -> NodeId
{
398 assert_eq
!(self.krate
, LOCAL_CRATE
);
403 /// Item definitions in the currently-compiled crate would have the CrateNum
404 /// LOCAL_CRATE in their DefId.
405 pub const LOCAL_CRATE
: CrateNum
= 0;
406 pub const CRATE_NODE_ID
: NodeId
= 0;
408 /// When parsing and doing expansions, we initially give all AST nodes this AST
409 /// node value. Then later, in the renumber pass, we renumber them to have
410 /// small, positive ids.
411 pub const DUMMY_NODE_ID
: NodeId
= !0;
413 /// The AST represents all type param bounds as types.
414 /// typeck::collect::compute_bounds matches these against
415 /// the "special" built-in traits (see middle::lang_items) and
416 /// detects Copy, Send and Sync.
417 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
418 pub enum TyParamBound
{
419 TraitTyParamBound(PolyTraitRef
, TraitBoundModifier
),
420 RegionTyParamBound(Lifetime
)
423 /// A modifier on a bound, currently this is only used for `?Sized`, where the
424 /// modifier is `Maybe`. Negative bounds should also be handled here.
425 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
426 pub enum TraitBoundModifier
{
431 pub type TyParamBounds
= OwnedSlice
<TyParamBound
>;
433 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
437 pub bounds
: TyParamBounds
,
438 pub default: Option
<P
<Ty
>>,
442 /// Represents lifetimes and type parameters attached to a declaration
443 /// of a function, enum, trait, etc.
444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
445 pub struct Generics
{
446 pub lifetimes
: Vec
<LifetimeDef
>,
447 pub ty_params
: OwnedSlice
<TyParam
>,
448 pub where_clause
: WhereClause
,
452 pub fn is_lt_parameterized(&self) -> bool
{
453 !self.lifetimes
.is_empty()
455 pub fn is_type_parameterized(&self) -> bool
{
456 !self.ty_params
.is_empty()
458 pub fn is_parameterized(&self) -> bool
{
459 self.is_lt_parameterized() || self.is_type_parameterized()
463 /// A `where` clause in a definition
464 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
465 pub struct WhereClause
{
467 pub predicates
: Vec
<WherePredicate
>,
470 /// A single predicate in a `where` clause
471 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
472 pub enum WherePredicate
{
473 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
474 BoundPredicate(WhereBoundPredicate
),
475 /// A lifetime predicate, e.g. `'a: 'b+'c`
476 RegionPredicate(WhereRegionPredicate
),
477 /// An equality predicate (unsupported)
478 EqPredicate(WhereEqPredicate
)
481 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
483 pub struct WhereBoundPredicate
{
485 /// Any lifetimes from a `for` binding
486 pub bound_lifetimes
: Vec
<LifetimeDef
>,
487 /// The type being bounded
488 pub bounded_ty
: P
<Ty
>,
489 /// Trait and lifetime bounds (`Clone+Send+'static`)
490 pub bounds
: OwnedSlice
<TyParamBound
>,
493 /// A lifetime predicate, e.g. `'a: 'b+'c`
494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
495 pub struct WhereRegionPredicate
{
497 pub lifetime
: Lifetime
,
498 pub bounds
: Vec
<Lifetime
>,
501 /// An equality predicate (unsupported), e.g. `T=int`
502 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
503 pub struct WhereEqPredicate
{
510 /// The set of MetaItems that define the compilation environment of the crate,
511 /// used to drive conditional compilation
512 pub type CrateConfig
= Vec
<P
<MetaItem
>> ;
514 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
517 pub attrs
: Vec
<Attribute
>,
518 pub config
: CrateConfig
,
520 pub exported_macros
: Vec
<MacroDef
>,
523 pub type MetaItem
= Spanned
<MetaItem_
>;
525 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
527 MetaWord(InternedString
),
528 MetaList(InternedString
, Vec
<P
<MetaItem
>>),
529 MetaNameValue(InternedString
, Lit
),
532 // can't be derived because the MetaList requires an unordered comparison
533 impl PartialEq
for MetaItem_
{
534 fn eq(&self, other
: &MetaItem_
) -> bool
{
536 MetaWord(ref ns
) => match *other
{
537 MetaWord(ref no
) => (*ns
) == (*no
),
540 MetaNameValue(ref ns
, ref vs
) => match *other
{
541 MetaNameValue(ref no
, ref vo
) => {
542 (*ns
) == (*no
) && vs
.node
== vo
.node
546 MetaList(ref ns
, ref miss
) => match *other
{
547 MetaList(ref no
, ref miso
) => {
549 miss
.iter().all(|mi
| miso
.iter().any(|x
| x
.node
== mi
.node
))
557 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
559 /// Statements in a block
560 pub stmts
: Vec
<P
<Stmt
>>,
561 /// An expression at the end of the block
562 /// without a semicolon, if any
563 pub expr
: Option
<P
<Expr
>>,
565 /// Distinguishes between `unsafe { ... }` and `{ ... }`
566 pub rules
: BlockCheckMode
,
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
577 impl fmt
::Debug
for Pat
{
578 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
579 write
!(f
, "pat({}: {})", self.id
, pprust
::pat_to_string(self))
583 /// A single field in a struct pattern
585 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
586 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
587 /// except is_shorthand is true
588 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
589 pub struct FieldPat
{
590 /// The identifier for the field
592 /// The pattern the field is destructured to
594 pub is_shorthand
: bool
,
597 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
598 pub enum BindingMode
{
599 BindByRef(Mutability
),
600 BindByValue(Mutability
),
603 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
604 pub enum PatWildKind
{
605 /// Represents the wildcard pattern `_`
608 /// Represents the wildcard pattern `..`
612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
614 /// Represents a wildcard pattern (either `_` or `..`)
615 PatWild(PatWildKind
),
617 /// A PatIdent may either be a new bound variable,
618 /// or a nullary enum (in which case the third field
621 /// In the nullary enum case, the parser can't determine
622 /// which it is. The resolver determines this, and
623 /// records this pattern's NodeId in an auxiliary
624 /// set (of "PatIdents that refer to nullary enums")
625 PatIdent(BindingMode
, SpannedIdent
, Option
<P
<Pat
>>),
627 /// "None" means a * pattern where we don't bind the fields to names.
628 PatEnum(Path
, Option
<Vec
<P
<Pat
>>>),
630 /// An associated const named using the qualified path `<T>::CONST` or
631 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
632 /// referred to as simply `T::CONST`, in which case they will end up as
633 /// PatEnum, and the resolver will have to sort that out.
634 PatQPath(QSelf
, Path
),
636 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
637 /// The `bool` is `true` in the presence of a `..`
638 PatStruct(Path
, Vec
<Spanned
<FieldPat
>>, bool
),
639 /// A tuple pattern `(a, b)`
643 /// A reference pattern, e.g. `&mut (a, b)`
644 PatRegion(P
<Pat
>, Mutability
),
647 /// A range pattern, e.g. `1...2`
648 PatRange(P
<Expr
>, P
<Expr
>),
649 /// [a, b, ..i, y, z] is represented as:
650 /// PatVec(box [a, b], Some(i), box [y, z])
651 PatVec(Vec
<P
<Pat
>>, Option
<P
<Pat
>>, Vec
<P
<Pat
>>),
652 /// A macro pattern; pre-expansion
656 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
657 pub enum Mutability
{
662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
664 /// The `+` operator (addition)
666 /// The `-` operator (subtraction)
668 /// The `*` operator (multiplication)
670 /// The `/` operator (division)
672 /// The `%` operator (modulus)
674 /// The `&&` operator (logical and)
676 /// The `||` operator (logical or)
678 /// The `^` operator (bitwise xor)
680 /// The `&` operator (bitwise and)
682 /// The `|` operator (bitwise or)
684 /// The `<<` operator (shift left)
686 /// The `>>` operator (shift right)
688 /// The `==` operator (equality)
690 /// The `<` operator (less than)
692 /// The `<=` operator (less than or equal to)
694 /// The `!=` operator (not equal to)
696 /// The `>=` operator (greater than or equal to)
698 /// The `>` operator (greater than)
702 pub type BinOp
= Spanned
<BinOp_
>;
704 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
706 /// The `box` operator
708 /// The `*` operator for dereferencing
710 /// The `!` operator for logical inversion
712 /// The `-` operator for negation
717 pub type Stmt
= Spanned
<Stmt_
>;
719 impl fmt
::Debug
for Stmt
{
720 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
721 write
!(f
, "stmt({}: {})",
722 ast_util
::stmt_id(self),
723 pprust
::stmt_to_string(self))
728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
730 /// Could be an item or a local (let) binding:
731 StmtDecl(P
<Decl
>, NodeId
),
733 /// Expr without trailing semi-colon (must have unit type):
734 StmtExpr(P
<Expr
>, NodeId
),
736 /// Expr with trailing semi-colon (may have any type):
737 StmtSemi(P
<Expr
>, NodeId
),
739 StmtMac(P
<Mac
>, MacStmtStyle
),
741 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
742 pub enum MacStmtStyle
{
743 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
744 /// `foo!(...);`, `foo![...];`
745 MacStmtWithSemicolon
,
746 /// The macro statement had braces; e.g. foo! { ... }
748 /// The macro statement had parentheses or brackets and no semicolon; e.g.
749 /// `foo!(...)`. All of these will end up being converted into macro
751 MacStmtWithoutBraces
,
754 // FIXME (pending discussion of #1697, #2178...): local should really be
755 // a refinement on pat.
756 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
757 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
760 pub ty
: Option
<P
<Ty
>>,
761 /// Initializer expression to set the value, if any
762 pub init
: Option
<P
<Expr
>>,
767 pub type Decl
= Spanned
<Decl_
>;
769 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
771 /// A local (let) binding:
777 /// represents one arm of a 'match'
778 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
780 pub attrs
: Vec
<Attribute
>,
781 pub pats
: Vec
<P
<Pat
>>,
782 pub guard
: Option
<P
<Expr
>>,
786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
788 pub ident
: SpannedIdent
,
793 pub type SpannedIdent
= Spanned
<Ident
>;
795 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
796 pub enum BlockCheckMode
{
798 UnsafeBlock(UnsafeSource
),
799 PushUnsafeBlock(UnsafeSource
),
800 PopUnsafeBlock(UnsafeSource
),
803 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
804 pub enum UnsafeSource
{
810 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
817 impl fmt
::Debug
for Expr
{
818 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
819 write
!(f
, "expr({}: {})", self.id
, pprust
::expr_to_string(self))
823 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
825 /// First expr is the place; second expr is the value.
826 ExprBox(Option
<P
<Expr
>>, P
<Expr
>),
827 /// An array (`[a, b, c, d]`)
828 ExprVec(Vec
<P
<Expr
>>),
831 /// The first field resolves to the function itself,
832 /// and the second field is the list of arguments
833 ExprCall(P
<Expr
>, Vec
<P
<Expr
>>),
834 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
836 /// The `SpannedIdent` is the identifier for the method name.
837 /// The vector of `Ty`s are the ascripted type parameters for the method
838 /// (within the angle brackets).
840 /// The first element of the vector of `Expr`s is the expression that evaluates
841 /// to the object on which the method is being called on (the receiver),
842 /// and the remaining elements are the rest of the arguments.
844 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
845 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
846 ExprMethodCall(SpannedIdent
, Vec
<P
<Ty
>>, Vec
<P
<Expr
>>),
847 /// A tuple (`(a, b, c ,d)`)
848 ExprTup(Vec
<P
<Expr
>>),
849 /// A binary operation (For example: `a + b`, `a * b`)
850 ExprBinary(BinOp
, P
<Expr
>, P
<Expr
>),
851 /// A unary operation (For example: `!x`, `*x`)
852 ExprUnary(UnOp
, P
<Expr
>),
853 /// A literal (For example: `1u8`, `"foo"`)
855 /// A cast (`foo as f64`)
856 ExprCast(P
<Expr
>, P
<Ty
>),
857 /// An `if` block, with an optional else block
859 /// `if expr { block } else { expr }`
860 ExprIf(P
<Expr
>, P
<Block
>, Option
<P
<Expr
>>),
861 /// An `if let` expression with an optional else block
863 /// `if let pat = expr { block } else { expr }`
865 /// This is desugared to a `match` expression.
866 ExprIfLet(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<P
<Expr
>>),
867 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
868 /// A while loop, with an optional label
870 /// `'label: while expr { block }`
871 ExprWhile(P
<Expr
>, P
<Block
>, Option
<Ident
>),
872 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
873 /// A while-let loop, with an optional label
875 /// `'label: while let pat = expr { block }`
877 /// This is desugared to a combination of `loop` and `match` expressions.
878 ExprWhileLet(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<Ident
>),
879 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
880 /// A for loop, with an optional label
882 /// `'label: for pat in expr { block }`
884 /// This is desugared to a combination of `loop` and `match` expressions.
885 ExprForLoop(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<Ident
>),
886 /// Conditionless loop (can be exited with break, continue, or return)
888 /// `'label: loop { block }`
889 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
890 ExprLoop(P
<Block
>, Option
<Ident
>),
891 /// A `match` block, with a source that indicates whether or not it is
892 /// the result of a desugaring, and if so, which kind.
893 ExprMatch(P
<Expr
>, Vec
<Arm
>, MatchSource
),
894 /// A closure (for example, `move |a, b, c| {a + b + c}`)
895 ExprClosure(CaptureClause
, P
<FnDecl
>, P
<Block
>),
896 /// A block (`{ ... }`)
899 /// An assignment (`a = foo()`)
900 ExprAssign(P
<Expr
>, P
<Expr
>),
901 /// An assignment with an operator
903 /// For example, `a += 1`.
904 ExprAssignOp(BinOp
, P
<Expr
>, P
<Expr
>),
905 /// Access of a named struct field (`obj.foo`)
906 ExprField(P
<Expr
>, SpannedIdent
),
907 /// Access of an unnamed field of a struct or tuple-struct
909 /// For example, `foo.0`.
910 ExprTupField(P
<Expr
>, Spanned
<usize>),
911 /// An indexing operation (`foo[2]`)
912 ExprIndex(P
<Expr
>, P
<Expr
>),
913 /// A range (`1..2`, `1..`, or `..2`)
914 ExprRange(Option
<P
<Expr
>>, Option
<P
<Expr
>>),
916 /// Variable reference, possibly containing `::` and/or type
917 /// parameters, e.g. foo::bar::<baz>.
919 /// Optionally "qualified",
920 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
921 ExprPath(Option
<QSelf
>, Path
),
923 /// A referencing operation (`&a` or `&mut a`)
924 ExprAddrOf(Mutability
, P
<Expr
>),
925 /// A `break`, with an optional label to break
926 ExprBreak(Option
<Ident
>),
927 /// A `continue`, with an optional label
928 ExprAgain(Option
<Ident
>),
929 /// A `return`, with an optional value to be returned
930 ExprRet(Option
<P
<Expr
>>),
932 /// Output of the `asm!()` macro
933 ExprInlineAsm(InlineAsm
),
935 /// A macro invocation; pre-expansion
938 /// A struct literal expression.
940 /// For example, `Foo {x: 1, y: 2}`, or
941 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
942 ExprStruct(Path
, Vec
<Field
>, Option
<P
<Expr
>>),
944 /// A vector literal constructed from one repeated element.
946 /// For example, `[1u8; 5]`. The first expression is the element
947 /// to be repeated; the second is the number of times to repeat it.
948 ExprRepeat(P
<Expr
>, P
<Expr
>),
950 /// No-op: used solely so we can pretty-print faithfully
954 /// The explicit Self type in a "qualified path". The actual
955 /// path, including the trait and the associated item, is stored
956 /// separately. `position` represents the index of the associated
957 /// item qualified with this Self type.
959 /// <Vec<T> as a::b::Trait>::AssociatedItem
960 /// ^~~~~ ~~~~~~~~~~~~~~^
963 /// <Vec<T>>::AssociatedItem
966 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
972 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
973 pub enum MatchSource
{
975 IfLetDesugar { contains_else_clause: bool }
,
980 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
981 pub enum CaptureClause
{
986 /// A delimited sequence of token trees
987 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
988 pub struct Delimited
{
989 /// The type of delimiter
990 pub delim
: token
::DelimToken
,
991 /// The span covering the opening delimiter
993 /// The delimited sequence of token trees
994 pub tts
: Vec
<TokenTree
>,
995 /// The span covering the closing delimiter
996 pub close_span
: Span
,
1000 /// Returns the opening delimiter as a token.
1001 pub fn open_token(&self) -> token
::Token
{
1002 token
::OpenDelim(self.delim
)
1005 /// Returns the closing delimiter as a token.
1006 pub fn close_token(&self) -> token
::Token
{
1007 token
::CloseDelim(self.delim
)
1010 /// Returns the opening delimiter as a token tree.
1011 pub fn open_tt(&self) -> TokenTree
{
1012 TtToken(self.open_span
, self.open_token())
1015 /// Returns the closing delimiter as a token tree.
1016 pub fn close_tt(&self) -> TokenTree
{
1017 TtToken(self.close_span
, self.close_token())
1021 /// A sequence of token treesee
1022 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1023 pub struct SequenceRepetition
{
1024 /// The sequence of token trees
1025 pub tts
: Vec
<TokenTree
>,
1026 /// The optional separator
1027 pub separator
: Option
<token
::Token
>,
1028 /// Whether the sequence can be repeated zero (*), or one or more times (+)
1030 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
1031 pub num_captures
: usize,
1034 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
1035 /// for token sequences.
1036 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1042 /// When the main rust parser encounters a syntax-extension invocation, it
1043 /// parses the arguments to the invocation as a token-tree. This is a very
1044 /// loose structure, such that all sorts of different AST-fragments can
1045 /// be passed to syntax extensions using a uniform type.
1047 /// If the syntax extension is an MBE macro, it will attempt to match its
1048 /// LHS token tree against the provided token tree, and if it finds a
1049 /// match, will transcribe the RHS token tree, splicing in any captured
1050 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1052 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1053 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1054 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1055 pub enum TokenTree
{
1057 TtToken(Span
, token
::Token
),
1058 /// A delimited sequence of token trees
1059 TtDelimited(Span
, Rc
<Delimited
>),
1061 // This only makes sense in MBE macros.
1063 /// A kleene-style repetition sequence with a span
1064 // FIXME(eddyb) #12938 Use DST.
1065 TtSequence(Span
, Rc
<SequenceRepetition
>),
1069 pub fn len(&self) -> usize {
1071 TtToken(_
, token
::DocComment(name
)) => {
1072 match doc_comment_style(&name
.as_str()) {
1077 TtToken(_
, token
::SpecialVarNt(..)) => 2,
1078 TtToken(_
, token
::MatchNt(..)) => 3,
1079 TtDelimited(_
, ref delimed
) => {
1080 delimed
.tts
.len() + 2
1082 TtSequence(_
, ref seq
) => {
1089 pub fn get_tt(&self, index
: usize) -> TokenTree
{
1090 match (self, index
) {
1091 (&TtToken(sp
, token
::DocComment(_
)), 0) => {
1092 TtToken(sp
, token
::Pound
)
1094 (&TtToken(sp
, token
::DocComment(name
)), 1)
1095 if doc_comment_style(&name
.as_str()) == AttrInner
=> {
1096 TtToken(sp
, token
::Not
)
1098 (&TtToken(sp
, token
::DocComment(name
)), _
) => {
1099 let stripped
= strip_doc_comment_decoration(&name
.as_str());
1100 TtDelimited(sp
, Rc
::new(Delimited
{
1101 delim
: token
::Bracket
,
1103 tts
: vec
![TtToken(sp
, token
::Ident(token
::str_to_ident("doc"),
1105 TtToken(sp
, token
::Eq
),
1106 TtToken(sp
, token
::Literal(
1107 token
::StrRaw(token
::intern(&stripped
), 0), None
))],
1111 (&TtDelimited(_
, ref delimed
), _
) => {
1113 return delimed
.open_tt();
1115 if index
== delimed
.tts
.len() + 1 {
1116 return delimed
.close_tt();
1118 delimed
.tts
[index
- 1].clone()
1120 (&TtToken(sp
, token
::SpecialVarNt(var
)), _
) => {
1121 let v
= [TtToken(sp
, token
::Dollar
),
1122 TtToken(sp
, token
::Ident(token
::str_to_ident(var
.as_str()),
1126 (&TtToken(sp
, token
::MatchNt(name
, kind
, name_st
, kind_st
)), _
) => {
1127 let v
= [TtToken(sp
, token
::SubstNt(name
, name_st
)),
1128 TtToken(sp
, token
::Colon
),
1129 TtToken(sp
, token
::Ident(kind
, kind_st
))];
1132 (&TtSequence(_
, ref seq
), _
) => {
1133 seq
.tts
[index
].clone()
1135 _
=> panic
!("Cannot expand a token tree")
1139 /// Returns the `Span` corresponding to this token tree.
1140 pub fn get_span(&self) -> Span
{
1142 TtToken(span
, _
) => span
,
1143 TtDelimited(span
, _
) => span
,
1144 TtSequence(span
, _
) => span
,
1148 /// Use this token tree as a matcher to parse given tts.
1149 pub fn parse(cx
: &base
::ExtCtxt
, mtch
: &[TokenTree
], tts
: &[TokenTree
])
1150 -> macro_parser
::NamedParseResult
{
1151 // `None` is because we're not interpolating
1152 let arg_rdr
= lexer
::new_tt_reader_with_doc_flag(&cx
.parse_sess().span_diagnostic
,
1155 tts
.iter().cloned().collect(),
1157 macro_parser
::parse(cx
.parse_sess(), cx
.cfg(), arg_rdr
, mtch
)
1161 pub type Mac
= Spanned
<Mac_
>;
1163 /// Represents a macro invocation. The Path indicates which macro
1164 /// is being invoked, and the vector of token-trees contains the source
1165 /// of the macro invocation.
1167 /// There's only one flavor, now, so this could presumably be simplified.
1168 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1170 // NB: the additional ident for a macro_rules-style macro is actually
1171 // stored in the enclosing item. Oog.
1172 MacInvocTT(Path
, Vec
<TokenTree
>, SyntaxContext
), // new macro-invocation
1175 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1177 /// A regular string, like `"foo"`
1179 /// A raw string, like `r##"foo"##`
1181 /// The uint is the number of `#` symbols used
1186 pub type Lit
= Spanned
<Lit_
>;
1188 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1195 pub fn new
<T
: IntSign
>(n
: T
) -> Sign
{
1201 fn sign(&self) -> Sign
;
1204 ($
($t
:ident
)*) => ($
(impl IntSign
for $t
{
1205 #[allow(unused_comparisons)]
1206 fn sign(&self) -> Sign
{
1207 if *self < 0 {Minus}
else {Plus}
1211 doit
! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1213 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1214 pub enum LitIntType
{
1215 SignedIntLit(IntTy
, Sign
),
1216 UnsignedIntLit(UintTy
),
1217 UnsuffixedIntLit(Sign
)
1221 pub fn suffix_len(&self) -> usize {
1223 UnsuffixedIntLit(_
) => 0,
1224 SignedIntLit(s
, _
) => s
.suffix_len(),
1225 UnsignedIntLit(u
) => u
.suffix_len()
1230 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1232 /// A string literal (`"foo"`)
1233 LitStr(InternedString
, StrStyle
),
1234 /// A byte string (`b"foo"`)
1235 LitBinary(Rc
<Vec
<u8>>),
1236 /// A byte char (`b'f'`)
1238 /// A character literal (`'a'`)
1240 /// An integer literal (`1u8`)
1241 LitInt(u64, LitIntType
),
1242 /// A float literal (`1f64` or `1E10f64`)
1243 LitFloat(InternedString
, FloatTy
),
1244 /// A float literal without a suffix (`1.0 or 1.0E10`)
1245 LitFloatUnsuffixed(InternedString
),
1246 /// A boolean literal
1250 // NB: If you change this, you'll probably want to change the corresponding
1251 // type structure in middle/ty.rs as well.
1252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1255 pub mutbl
: Mutability
,
1258 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1259 pub struct TypeField
{
1265 /// Represents a method's signature in a trait declaration,
1266 /// or in an implementation.
1267 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1268 pub struct MethodSig
{
1269 pub unsafety
: Unsafety
,
1270 pub constness
: Constness
,
1272 pub decl
: P
<FnDecl
>,
1273 pub generics
: Generics
,
1274 pub explicit_self
: ExplicitSelf
,
1277 /// Represents a method declaration in a trait declaration, possibly including
1278 /// a default implementation A trait method is either required (meaning it
1279 /// doesn't have an implementation, just a signature) or provided (meaning it
1280 /// has a default implementation).
1281 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1282 pub struct TraitItem
{
1285 pub attrs
: Vec
<Attribute
>,
1286 pub node
: TraitItem_
,
1290 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1291 pub enum TraitItem_
{
1292 ConstTraitItem(P
<Ty
>, Option
<P
<Expr
>>),
1293 MethodTraitItem(MethodSig
, Option
<P
<Block
>>),
1294 TypeTraitItem(TyParamBounds
, Option
<P
<Ty
>>),
1297 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1298 pub struct ImplItem
{
1301 pub vis
: Visibility
,
1302 pub attrs
: Vec
<Attribute
>,
1303 pub node
: ImplItem_
,
1307 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1308 pub enum ImplItem_
{
1309 ConstImplItem(P
<Ty
>, P
<Expr
>),
1310 MethodImplItem(MethodSig
, P
<Block
>),
1311 TypeImplItem(P
<Ty
>),
1315 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1324 impl fmt
::Debug
for IntTy
{
1325 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1326 fmt
::Display
::fmt(self, f
)
1330 impl fmt
::Display
for IntTy
{
1331 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1332 write
!(f
, "{}", ast_util
::int_ty_to_string(*self, None
))
1337 pub fn suffix_len(&self) -> usize {
1340 TyI16
| TyI32
| TyI64
=> 3,
1345 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1355 pub fn suffix_len(&self) -> usize {
1358 TyU16
| TyU32
| TyU64
=> 3,
1363 impl fmt
::Debug
for UintTy
{
1364 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1365 fmt
::Display
::fmt(self, f
)
1369 impl fmt
::Display
for UintTy
{
1370 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1371 write
!(f
, "{}", ast_util
::uint_ty_to_string(*self, None
))
1375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1381 impl fmt
::Debug
for FloatTy
{
1382 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1383 fmt
::Display
::fmt(self, f
)
1387 impl fmt
::Display
for FloatTy
{
1388 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1389 write
!(f
, "{}", ast_util
::float_ty_to_string(*self))
1394 pub fn suffix_len(&self) -> usize {
1396 TyF32
| TyF64
=> 3, // add F128 handling here
1401 // Bind a type to an associated type: `A=Foo`.
1402 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1403 pub struct TypeBinding
{
1411 // NB PartialEq method appears below.
1412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1419 impl fmt
::Debug
for Ty
{
1420 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1421 write
!(f
, "type({})", pprust
::ty_to_string(self))
1425 /// Not represented directly in the AST, referred to by name through a ty_path.
1426 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1436 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1437 pub struct BareFnTy
{
1438 pub unsafety
: Unsafety
,
1440 pub lifetimes
: Vec
<LifetimeDef
>,
1444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1445 /// The different kinds of types recognized by the compiler
1448 /// A fixed length array (`[T; n]`)
1449 TyFixedLengthVec(P
<Ty
>, P
<Expr
>),
1450 /// A raw pointer (`*const T` or `*mut T`)
1452 /// A reference (`&'a T` or `&'a mut T`)
1453 TyRptr(Option
<Lifetime
>, MutTy
),
1454 /// A bare function (e.g. `fn(usize) -> bool`)
1455 TyBareFn(P
<BareFnTy
>),
1456 /// A tuple (`(A, B, C, D,...)`)
1458 /// A path (`module::module::...::Type`), optionally
1459 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1461 /// Type parameters are stored in the Path itself
1462 TyPath(Option
<QSelf
>, Path
),
1463 /// Something like `A+B`. Note that `B` must always be a path.
1464 TyObjectSum(P
<Ty
>, TyParamBounds
),
1465 /// A type like `for<'a> Foo<&'a Bar>`
1466 TyPolyTraitRef(TyParamBounds
),
1467 /// No-op; kept solely so that we can pretty-print faithfully
1471 /// TyInfer means the type should be inferred instead of it having been
1472 /// specified. This can appear anywhere in a type.
1476 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1477 pub enum AsmDialect
{
1482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1483 pub struct InlineAsm
{
1484 pub asm
: InternedString
,
1485 pub asm_str_style
: StrStyle
,
1486 pub outputs
: Vec
<(InternedString
, P
<Expr
>, bool
)>,
1487 pub inputs
: Vec
<(InternedString
, P
<Expr
>)>,
1488 pub clobbers
: Vec
<InternedString
>,
1490 pub alignstack
: bool
,
1491 pub dialect
: AsmDialect
,
1492 pub expn_id
: ExpnId
,
1495 /// represents an argument in a function header
1496 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1504 pub fn new_self(span
: Span
, mutability
: Mutability
, self_ident
: Ident
) -> Arg
{
1505 let path
= Spanned{span:span,node:self_ident}
;
1507 // HACK(eddyb) fake type for the self argument.
1515 node
: PatIdent(BindByValue(mutability
), path
, None
),
1523 /// Represents the header (not the body) of a function declaration
1524 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1526 pub inputs
: Vec
<Arg
>,
1527 pub output
: FunctionRetTy
,
1531 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1537 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1538 pub enum Constness
{
1543 impl fmt
::Display
for Unsafety
{
1544 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1545 fmt
::Display
::fmt(match *self {
1546 Unsafety
::Normal
=> "normal",
1547 Unsafety
::Unsafe
=> "unsafe",
1552 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1553 pub enum ImplPolarity
{
1554 /// `impl Trait for Type`
1556 /// `impl !Trait for Type`
1560 impl fmt
::Debug
for ImplPolarity
{
1561 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1563 ImplPolarity
::Positive
=> "positive".fmt(f
),
1564 ImplPolarity
::Negative
=> "negative".fmt(f
),
1570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1571 pub enum FunctionRetTy
{
1572 /// Functions with return type `!`that always
1573 /// raise an error or exit (i.e. never return to the caller)
1575 /// Return type is not specified.
1577 /// Functions default to `()` and
1578 /// closures default to inference. Span points to where return
1579 /// type would be inserted.
1580 DefaultReturn(Span
),
1585 impl FunctionRetTy
{
1586 pub fn span(&self) -> Span
{
1588 NoReturn(span
) => span
,
1589 DefaultReturn(span
) => span
,
1590 Return(ref ty
) => ty
.span
1595 /// Represents the kind of 'self' associated with a method
1596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1597 pub enum ExplicitSelf_
{
1602 /// `&'lt self`, `&'lt mut self`
1603 SelfRegion(Option
<Lifetime
>, Mutability
, Ident
),
1605 SelfExplicit(P
<Ty
>, Ident
),
1608 pub type ExplicitSelf
= Spanned
<ExplicitSelf_
>;
1610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1612 /// A span from the first token past `{` to the last token until `}`.
1613 /// For `mod foo;`, the inner span ranges from the first token
1614 /// to the last token in the external file.
1616 pub items
: Vec
<P
<Item
>>,
1619 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1620 pub struct ForeignMod
{
1622 pub items
: Vec
<P
<ForeignItem
>>,
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1626 pub struct VariantArg
{
1631 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1632 pub enum VariantKind
{
1633 /// Tuple variant, e.g. `Foo(A, B)`
1634 TupleVariantKind(Vec
<VariantArg
>),
1635 /// Struct variant, e.g. `Foo {x: A, y: B}`
1636 StructVariantKind(P
<StructDef
>),
1639 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1640 pub struct EnumDef
{
1641 pub variants
: Vec
<P
<Variant
>>,
1644 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1645 pub struct Variant_
{
1647 pub attrs
: Vec
<Attribute
>,
1648 pub kind
: VariantKind
,
1650 /// Explicit discriminant, eg `Foo = 1`
1651 pub disr_expr
: Option
<P
<Expr
>>,
1652 pub vis
: Visibility
,
1655 pub type Variant
= Spanned
<Variant_
>;
1657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1658 pub enum PathListItem_
{
1659 PathListIdent { name: Ident, id: NodeId }
,
1660 PathListMod { id: NodeId }
1663 impl PathListItem_
{
1664 pub fn id(&self) -> NodeId
{
1666 PathListIdent { id, .. }
| PathListMod { id }
=> id
1671 pub type PathListItem
= Spanned
<PathListItem_
>;
1673 pub type ViewPath
= Spanned
<ViewPath_
>;
1675 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1676 pub enum ViewPath_
{
1678 /// `foo::bar::baz as quux`
1682 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1683 ViewPathSimple(Ident
, Path
),
1688 /// `foo::bar::{a,b,c}`
1689 ViewPathList(Path
, Vec
<PathListItem
>)
1692 /// Meta-data associated with an item
1693 pub type Attribute
= Spanned
<Attribute_
>;
1695 /// Distinguishes between Attributes that decorate items and Attributes that
1696 /// are contained as statements within items. These two cases need to be
1697 /// distinguished for pretty-printing.
1698 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1699 pub enum AttrStyle
{
1704 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1705 pub struct AttrId(pub usize);
1707 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1708 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1709 pub struct Attribute_
{
1711 pub style
: AttrStyle
,
1712 pub value
: P
<MetaItem
>,
1713 pub is_sugared_doc
: bool
,
1716 /// TraitRef's appear in impls.
1718 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1719 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1720 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1721 /// same as the impl's node id).
1722 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1723 pub struct TraitRef
{
1728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1729 pub struct PolyTraitRef
{
1730 /// The `'a` in `<'a> Foo<&'a T>`
1731 pub bound_lifetimes
: Vec
<LifetimeDef
>,
1733 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1734 pub trait_ref
: TraitRef
,
1739 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1740 pub enum Visibility
{
1746 pub fn inherit_from(&self, parent_visibility
: Visibility
) -> Visibility
{
1748 &Inherited
=> parent_visibility
,
1754 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1755 pub struct StructField_
{
1756 pub kind
: StructFieldKind
,
1759 pub attrs
: Vec
<Attribute
>,
1763 pub fn ident(&self) -> Option
<Ident
> {
1765 NamedField(ref ident
, _
) => Some(ident
.clone()),
1766 UnnamedField(_
) => None
1771 pub type StructField
= Spanned
<StructField_
>;
1773 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1774 pub enum StructFieldKind
{
1775 NamedField(Ident
, Visibility
),
1776 /// Element of a tuple-like struct
1777 UnnamedField(Visibility
),
1780 impl StructFieldKind
{
1781 pub fn is_unnamed(&self) -> bool
{
1783 UnnamedField(..) => true,
1784 NamedField(..) => false,
1789 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1790 pub struct StructDef
{
1791 /// Fields, not including ctor
1792 pub fields
: Vec
<StructField
>,
1793 /// ID of the constructor. This is only used for tuple- or enum-like
1795 pub ctor_id
: Option
<NodeId
>,
1799 FIXME (#3300): Should allow items to be anonymous. Right now
1800 we just use dummy names for anon items.
1804 /// The name might be a dummy name in case of anonymous items
1805 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1808 pub attrs
: Vec
<Attribute
>,
1811 pub vis
: Visibility
,
1815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1817 /// An`extern crate` item, with optional original crate name,
1819 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1820 ItemExternCrate(Option
<Name
>),
1821 /// A `use` or `pub use` item
1822 ItemUse(P
<ViewPath
>),
1825 ItemStatic(P
<Ty
>, Mutability
, P
<Expr
>),
1827 ItemConst(P
<Ty
>, P
<Expr
>),
1828 /// A function declaration
1829 ItemFn(P
<FnDecl
>, Unsafety
, Constness
, Abi
, Generics
, P
<Block
>),
1832 /// An external module
1833 ItemForeignMod(ForeignMod
),
1834 /// A type alias, e.g. `type Foo = Bar<u8>`
1835 ItemTy(P
<Ty
>, Generics
),
1836 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1837 ItemEnum(EnumDef
, Generics
),
1838 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1839 ItemStruct(P
<StructDef
>, Generics
),
1840 /// Represents a Trait Declaration
1846 // Default trait implementations
1848 // `impl Trait for .. {}`
1849 ItemDefaultImpl(Unsafety
, TraitRef
),
1850 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1854 Option
<TraitRef
>, // (optional) trait this impl implements
1857 /// A macro invocation (which includes macro definition)
1862 pub fn descriptive_variant(&self) -> &str {
1864 ItemExternCrate(..) => "extern crate",
1865 ItemUse(..) => "use",
1866 ItemStatic(..) => "static item",
1867 ItemConst(..) => "constant item",
1868 ItemFn(..) => "function",
1869 ItemMod(..) => "module",
1870 ItemForeignMod(..) => "foreign module",
1871 ItemTy(..) => "type alias",
1872 ItemEnum(..) => "enum",
1873 ItemStruct(..) => "struct",
1874 ItemTrait(..) => "trait",
1877 ItemDefaultImpl(..) => "item"
1882 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1883 pub struct ForeignItem
{
1885 pub attrs
: Vec
<Attribute
>,
1886 pub node
: ForeignItem_
,
1889 pub vis
: Visibility
,
1892 /// An item within an `extern` block
1893 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1894 pub enum ForeignItem_
{
1895 /// A foreign function
1896 ForeignItemFn(P
<FnDecl
>, Generics
),
1897 /// A foreign static item (`static ext: u8`), with optional mutability
1898 /// (the boolean is true when mutable)
1899 ForeignItemStatic(P
<Ty
>, bool
),
1903 pub fn descriptive_variant(&self) -> &str {
1905 ForeignItemFn(..) => "foreign function",
1906 ForeignItemStatic(..) => "foreign static item"
1911 /// The data we save and restore about an inlined item or method. This is not
1912 /// part of the AST that we parse from a file, but it becomes part of the tree
1914 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1915 pub enum InlinedItem
{
1917 IITraitItem(DefId
/* impl id */, P
<TraitItem
>),
1918 IIImplItem(DefId
/* impl id */, P
<ImplItem
>),
1919 IIForeign(P
<ForeignItem
>),
1922 /// A macro definition, in this crate or imported from another.
1924 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1925 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1926 pub struct MacroDef
{
1928 pub attrs
: Vec
<Attribute
>,
1931 pub imported_from
: Option
<Ident
>,
1933 pub use_locally
: bool
,
1934 pub allow_internal_unstable
: bool
,
1935 pub body
: Vec
<TokenTree
>,
1943 // are ASTs encodable?
1945 fn check_asts_encodable() {
1946 fn assert_encodable
<T
: serialize
::Encodable
>() {}
1947 assert_encodable
::<Crate
>();