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::TyParamBound
::*;
14 pub use self::UnsafeSource
::*;
15 pub use self::ViewPath_
::*;
16 pub use self::PathParameters
::*;
17 pub use symbol
::Symbol
as Name
;
18 pub use util
::ThinVec
;
20 use syntax_pos
::{mk_sp, Span, DUMMY_SP, ExpnId}
;
21 use codemap
::{respan, Spanned}
;
23 use ext
::hygiene
::SyntaxContext
;
26 use symbol
::{Symbol, keywords}
;
27 use tokenstream
::{ThinTokenStream, TokenStream}
;
29 use std
::collections
::HashSet
;
34 use serialize
::{self, Encodable, Decodable, Encoder, Decoder}
;
36 /// An identifier contains a Name (index into the interner
37 /// table) and a SyntaxContext to track renaming and
38 /// macro expansion per Flatt et al., "Macros That Work Together"
39 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
42 pub ctxt
: SyntaxContext
46 pub const fn with_empty_ctxt(name
: Name
) -> Ident
{
47 Ident { name: name, ctxt: SyntaxContext::empty() }
50 /// Maps a string to an identifier with an empty syntax context.
51 pub fn from_str(s
: &str) -> Ident
{
52 Ident
::with_empty_ctxt(Symbol
::intern(s
))
55 pub fn unhygienize(&self) -> Ident
{
56 Ident { name: self.name, ctxt: SyntaxContext::empty() }
60 impl fmt
::Debug
for Ident
{
61 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
62 write
!(f
, "{}{:?}", self.name
, self.ctxt
)
66 impl fmt
::Display
for Ident
{
67 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
68 fmt
::Display
::fmt(&self.name
, f
)
72 impl Encodable
for Ident
{
73 fn encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
78 impl Decodable
for Ident
{
79 fn decode
<D
: Decoder
>(d
: &mut D
) -> Result
<Ident
, D
::Error
> {
80 Ok(Ident
::with_empty_ctxt(Name
::decode(d
)?
))
84 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
91 impl fmt
::Debug
for Lifetime
{
92 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
93 write
!(f
, "lifetime({}: {})", self.id
, pprust
::lifetime_to_string(self))
97 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
98 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
99 pub struct LifetimeDef
{
100 pub attrs
: ThinVec
<Attribute
>,
101 pub lifetime
: Lifetime
,
102 pub bounds
: Vec
<Lifetime
>
105 /// A "Path" is essentially Rust's notion of a name.
107 /// It's represented as a sequence of identifiers,
108 /// along with a bunch of supporting information.
110 /// E.g. `std::cmp::PartialEq`
111 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
114 /// The segments in the path: the things separated by `::`.
115 /// Global paths begin with `keywords::CrateRoot`.
116 pub segments
: Vec
<PathSegment
>,
119 impl fmt
::Debug
for Path
{
120 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
121 write
!(f
, "path({})", pprust
::path_to_string(self))
125 impl fmt
::Display
for Path
{
126 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
127 write
!(f
, "{}", pprust
::path_to_string(self))
132 // convert a span and an identifier to the corresponding
134 pub fn from_ident(s
: Span
, identifier
: Ident
) -> Path
{
137 segments
: vec
![PathSegment
::from_ident(identifier
, s
)],
141 pub fn default_to_global(mut self) -> Path
{
142 let name
= self.segments
[0].identifier
.name
;
143 if !self.is_global() && name
!= "$crate" &&
144 name
!= keywords
::SelfValue
.name() && name
!= keywords
::Super
.name() {
145 self.segments
.insert(0, PathSegment
::crate_root());
150 pub fn is_global(&self) -> bool
{
151 !self.segments
.is_empty() && self.segments
[0].identifier
.name
== keywords
::CrateRoot
.name()
155 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
157 /// E.g. `std`, `String` or `Box<T>`
158 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
159 pub struct PathSegment
{
160 /// The identifier portion of this path segment.
161 pub identifier
: Ident
,
162 /// Span of the segment identifier.
165 /// Type/lifetime parameters attached to this path. They come in
166 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
167 /// this is more than just simple syntactic sugar; the use of
168 /// parens affects the region binding rules, so we preserve the
170 /// The `Option<P<..>>` wrapper is purely a size optimization;
171 /// `None` is used to represent both `Path` and `Path<>`.
172 pub parameters
: Option
<P
<PathParameters
>>,
176 pub fn from_ident(ident
: Ident
, span
: Span
) -> Self {
177 PathSegment { identifier: ident, span: span, parameters: None }
179 pub fn crate_root() -> Self {
181 identifier
: keywords
::CrateRoot
.ident(),
188 /// Parameters of a path segment.
190 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
192 pub enum PathParameters
{
193 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
194 AngleBracketed(AngleBracketedParameterData
),
195 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
196 Parenthesized(ParenthesizedParameterData
),
199 /// A path like `Foo<'a, T>`
200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
201 pub struct AngleBracketedParameterData
{
202 /// The lifetime parameters for this path segment.
203 pub lifetimes
: Vec
<Lifetime
>,
204 /// The type parameters for this path segment, if present.
205 pub types
: Vec
<P
<Ty
>>,
206 /// Bindings (equality constraints) on associated types, if present.
208 /// E.g., `Foo<A=Bar>`.
209 pub bindings
: Vec
<TypeBinding
>,
212 impl Into
<Option
<P
<PathParameters
>>> for AngleBracketedParameterData
{
213 fn into(self) -> Option
<P
<PathParameters
>> {
214 let empty
= self.lifetimes
.is_empty() && self.types
.is_empty() && self.bindings
.is_empty();
215 if empty { None }
else { Some(P(PathParameters::AngleBracketed(self))) }
219 /// A path like `Foo(A,B) -> C`
220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
221 pub struct ParenthesizedParameterData
{
226 pub inputs
: Vec
<P
<Ty
>>,
229 pub output
: Option
<P
<Ty
>>,
232 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
233 pub struct NodeId(u32);
236 pub fn new(x
: usize) -> NodeId
{
237 assert
!(x
< (u32::MAX
as usize));
241 pub fn from_u32(x
: u32) -> NodeId
{
245 pub fn as_usize(&self) -> usize {
249 pub fn as_u32(&self) -> u32 {
254 impl fmt
::Display
for NodeId
{
255 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
256 fmt
::Display
::fmt(&self.0, f
)
260 impl serialize
::UseSpecializedEncodable
for NodeId
{
261 fn default_encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
266 impl serialize
::UseSpecializedDecodable
for NodeId
{
267 fn default_decode
<D
: Decoder
>(d
: &mut D
) -> Result
<NodeId
, D
::Error
> {
268 d
.read_u32().map(NodeId
)
272 /// Node id used to represent the root of the crate.
273 pub const CRATE_NODE_ID
: NodeId
= NodeId(0);
275 /// When parsing and doing expansions, we initially give all AST nodes this AST
276 /// node value. Then later, in the renumber pass, we renumber them to have
277 /// small, positive ids.
278 pub const DUMMY_NODE_ID
: NodeId
= NodeId(!0);
280 /// The AST represents all type param bounds as types.
281 /// typeck::collect::compute_bounds matches these against
282 /// the "special" built-in traits (see middle::lang_items) and
283 /// detects Copy, Send and Sync.
284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
285 pub enum TyParamBound
{
286 TraitTyParamBound(PolyTraitRef
, TraitBoundModifier
),
287 RegionTyParamBound(Lifetime
)
290 /// A modifier on a bound, currently this is only used for `?Sized`, where the
291 /// modifier is `Maybe`. Negative bounds should also be handled here.
292 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
293 pub enum TraitBoundModifier
{
298 pub type TyParamBounds
= Vec
<TyParamBound
>;
300 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
302 pub attrs
: ThinVec
<Attribute
>,
305 pub bounds
: TyParamBounds
,
306 pub default: Option
<P
<Ty
>>,
310 /// Represents lifetimes and type parameters attached to a declaration
311 /// of a function, enum, trait, etc.
312 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
313 pub struct Generics
{
314 pub lifetimes
: Vec
<LifetimeDef
>,
315 pub ty_params
: Vec
<TyParam
>,
316 pub where_clause
: WhereClause
,
321 pub fn is_lt_parameterized(&self) -> bool
{
322 !self.lifetimes
.is_empty()
324 pub fn is_type_parameterized(&self) -> bool
{
325 !self.ty_params
.is_empty()
327 pub fn is_parameterized(&self) -> bool
{
328 self.is_lt_parameterized() || self.is_type_parameterized()
330 pub fn span_for_name(&self, name
: &str) -> Option
<Span
> {
331 for t
in &self.ty_params
{
332 if t
.ident
.name
== name
{
340 impl Default
for Generics
{
341 /// Creates an instance of `Generics`.
342 fn default() -> Generics
{
344 lifetimes
: Vec
::new(),
345 ty_params
: Vec
::new(),
346 where_clause
: WhereClause
{
348 predicates
: Vec
::new(),
355 /// A `where` clause in a definition
356 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
357 pub struct WhereClause
{
359 pub predicates
: Vec
<WherePredicate
>,
362 /// A single predicate in a `where` clause
363 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
364 pub enum WherePredicate
{
365 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
366 BoundPredicate(WhereBoundPredicate
),
367 /// A lifetime predicate, e.g. `'a: 'b+'c`
368 RegionPredicate(WhereRegionPredicate
),
369 /// An equality predicate (unsupported)
370 EqPredicate(WhereEqPredicate
),
375 /// E.g. `for<'c> Foo: Send+Clone+'c`
376 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
377 pub struct WhereBoundPredicate
{
379 /// Any lifetimes from a `for` binding
380 pub bound_lifetimes
: Vec
<LifetimeDef
>,
381 /// The type being bounded
382 pub bounded_ty
: P
<Ty
>,
383 /// Trait and lifetime bounds (`Clone+Send+'static`)
384 pub bounds
: TyParamBounds
,
387 /// A lifetime predicate.
390 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
391 pub struct WhereRegionPredicate
{
393 pub lifetime
: Lifetime
,
394 pub bounds
: Vec
<Lifetime
>,
397 /// An equality predicate (unsupported).
400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
401 pub struct WhereEqPredicate
{
408 /// The set of MetaItems that define the compilation environment of the crate,
409 /// used to drive conditional compilation
410 pub type CrateConfig
= HashSet
<(Name
, Option
<Symbol
>)>;
412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
415 pub attrs
: Vec
<Attribute
>,
419 /// A spanned compile-time attribute list item.
420 pub type NestedMetaItem
= Spanned
<NestedMetaItemKind
>;
422 /// Possible values inside of compile-time attribute lists.
424 /// E.g. the '..' in `#[name(..)]`.
425 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
426 pub enum NestedMetaItemKind
{
427 /// A full MetaItem, for recursive meta items.
431 /// E.g. "foo", 64, true
435 /// A spanned compile-time attribute item.
437 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub struct MetaItem
{
441 pub node
: MetaItemKind
,
445 /// A compile-time attribute item.
447 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
448 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
449 pub enum MetaItemKind
{
452 /// E.g. `test` as in `#[test]`
456 /// E.g. `derive(..)` as in `#[derive(..)]`
457 List(Vec
<NestedMetaItem
>),
458 /// Name value meta item.
460 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
464 /// A Block (`{ .. }`).
466 /// E.g. `{ .. }` as in `fn foo() { .. }`
467 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
469 /// Statements in a block
470 pub stmts
: Vec
<Stmt
>,
472 /// Distinguishes between `unsafe { ... }` and `{ ... }`
473 pub rules
: BlockCheckMode
,
477 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
484 impl fmt
::Debug
for Pat
{
485 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
486 write
!(f
, "pat({}: {})", self.id
, pprust
::pat_to_string(self))
491 pub fn walk
<F
>(&self, it
: &mut F
) -> bool
492 where F
: FnMut(&Pat
) -> bool
499 PatKind
::Ident(_
, _
, Some(ref p
)) => p
.walk(it
),
500 PatKind
::Struct(_
, ref fields
, _
) => {
501 fields
.iter().all(|field
| field
.node
.pat
.walk(it
))
503 PatKind
::TupleStruct(_
, ref s
, _
) | PatKind
::Tuple(ref s
, _
) => {
504 s
.iter().all(|p
| p
.walk(it
))
506 PatKind
::Box(ref s
) | PatKind
::Ref(ref s
, _
) => {
509 PatKind
::Slice(ref before
, ref slice
, ref after
) => {
510 before
.iter().all(|p
| p
.walk(it
)) &&
511 slice
.iter().all(|p
| p
.walk(it
)) &&
512 after
.iter().all(|p
| p
.walk(it
))
526 /// A single field in a struct pattern
528 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
529 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
530 /// except is_shorthand is true
531 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
532 pub struct FieldPat
{
533 /// The identifier for the field
535 /// The pattern the field is destructured to
537 pub is_shorthand
: bool
,
538 pub attrs
: ThinVec
<Attribute
>,
541 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
542 pub enum BindingMode
{
547 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
553 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
555 /// Represents a wildcard pattern (`_`)
558 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
559 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
560 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
561 /// during name resolution.
562 Ident(BindingMode
, SpannedIdent
, Option
<P
<Pat
>>),
564 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
565 /// The `bool` is `true` in the presence of a `..`.
566 Struct(Path
, Vec
<Spanned
<FieldPat
>>, bool
),
568 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
569 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
570 /// 0 <= position <= subpats.len()
571 TupleStruct(Path
, Vec
<P
<Pat
>>, Option
<usize>),
573 /// A possibly qualified path pattern.
574 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
575 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
576 /// only legally refer to associated constants.
577 Path(Option
<QSelf
>, Path
),
579 /// A tuple pattern `(a, b)`.
580 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
581 /// 0 <= position <= subpats.len()
582 Tuple(Vec
<P
<Pat
>>, Option
<usize>),
585 /// A reference pattern, e.g. `&mut (a, b)`
586 Ref(P
<Pat
>, Mutability
),
589 /// A range pattern, e.g. `1...2` or `1..2`
590 Range(P
<Expr
>, P
<Expr
>, RangeEnd
),
591 /// `[a, b, ..i, y, z]` is represented as:
592 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
593 Slice(Vec
<P
<Pat
>>, Option
<P
<Pat
>>, Vec
<P
<Pat
>>),
594 /// A macro pattern; pre-expansion
598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
599 pub enum Mutability
{
604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
606 /// The `+` operator (addition)
608 /// The `-` operator (subtraction)
610 /// The `*` operator (multiplication)
612 /// The `/` operator (division)
614 /// The `%` operator (modulus)
616 /// The `&&` operator (logical and)
618 /// The `||` operator (logical or)
620 /// The `^` operator (bitwise xor)
622 /// The `&` operator (bitwise and)
624 /// The `|` operator (bitwise or)
626 /// The `<<` operator (shift left)
628 /// The `>>` operator (shift right)
630 /// The `==` operator (equality)
632 /// The `<` operator (less than)
634 /// The `<=` operator (less than or equal to)
636 /// The `!=` operator (not equal to)
638 /// The `>=` operator (greater than or equal to)
640 /// The `>` operator (greater than)
645 pub fn to_string(&self) -> &'
static str {
646 use self::BinOpKind
::*;
668 pub fn lazy(&self) -> bool
{
670 BinOpKind
::And
| BinOpKind
::Or
=> true,
675 pub fn is_shift(&self) -> bool
{
677 BinOpKind
::Shl
| BinOpKind
::Shr
=> true,
681 pub fn is_comparison(&self) -> bool
{
682 use self::BinOpKind
::*;
684 Eq
| Lt
| Le
| Ne
| Gt
| Ge
=>
686 And
| Or
| Add
| Sub
| Mul
| Div
| Rem
|
687 BitXor
| BitAnd
| BitOr
| Shl
| Shr
=>
691 /// Returns `true` if the binary operator takes its arguments by value
692 pub fn is_by_value(&self) -> bool
{
693 !self.is_comparison()
697 pub type BinOp
= Spanned
<BinOpKind
>;
699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
701 /// The `*` operator for dereferencing
703 /// The `!` operator for logical inversion
705 /// The `-` operator for negation
710 /// Returns `true` if the unary operator takes its argument by value
711 pub fn is_by_value(u
: UnOp
) -> bool
{
713 UnOp
::Neg
| UnOp
::Not
=> true,
718 pub fn to_string(op
: UnOp
) -> &'
static str {
728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
736 pub fn add_trailing_semicolon(mut self) -> Self {
737 self.node
= match self.node
{
738 StmtKind
::Expr(expr
) => StmtKind
::Semi(expr
),
739 StmtKind
::Mac(mac
) => StmtKind
::Mac(mac
.map(|(mac
, _style
, attrs
)| {
740 (mac
, MacStmtStyle
::Semicolon
, attrs
)
748 impl fmt
::Debug
for Stmt
{
749 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
750 write
!(f
, "stmt({}: {})", self.id
.to_string(), pprust
::stmt_to_string(self))
755 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
757 /// A local (let) binding.
760 /// An item definition.
763 /// Expr without trailing semi-colon.
768 Mac(P
<(Mac
, MacStmtStyle
, ThinVec
<Attribute
>)>),
771 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
772 pub enum MacStmtStyle
{
773 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
774 /// `foo!(...);`, `foo![...];`
776 /// The macro statement had braces; e.g. foo! { ... }
778 /// The macro statement had parentheses or brackets and no semicolon; e.g.
779 /// `foo!(...)`. All of these will end up being converted into macro
784 // FIXME (pending discussion of #1697, #2178...): local should really be
785 // a refinement on pat.
786 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
787 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
790 pub ty
: Option
<P
<Ty
>>,
791 /// Initializer expression to set the value, if any
792 pub init
: Option
<P
<Expr
>>,
795 pub attrs
: ThinVec
<Attribute
>,
798 /// An arm of a 'match'.
800 /// E.g. `0...10 => { println!("match!") }` as in
804 /// 0...10 => { println!("match!") },
808 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
810 pub attrs
: Vec
<Attribute
>,
811 pub pats
: Vec
<P
<Pat
>>,
812 pub guard
: Option
<P
<Expr
>>,
816 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
818 pub ident
: SpannedIdent
,
821 pub is_shorthand
: bool
,
822 pub attrs
: ThinVec
<Attribute
>,
825 pub type SpannedIdent
= Spanned
<Ident
>;
827 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
828 pub enum BlockCheckMode
{
830 Unsafe(UnsafeSource
),
833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
834 pub enum UnsafeSource
{
840 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
845 pub attrs
: ThinVec
<Attribute
>
848 impl fmt
::Debug
for Expr
{
849 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
850 write
!(f
, "expr({}: {})", self.id
, pprust
::expr_to_string(self))
854 /// Limit types of a range (inclusive or exclusive)
855 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
856 pub enum RangeLimits
{
857 /// Inclusive at the beginning, exclusive at the end
859 /// Inclusive at the beginning and end
863 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
865 /// A `box x` expression.
867 /// First expr is the place; second expr is the value.
868 InPlace(P
<Expr
>, P
<Expr
>),
869 /// An array (`[a, b, c, d]`)
873 /// The first field resolves to the function itself,
874 /// and the second field is the list of arguments
875 Call(P
<Expr
>, Vec
<P
<Expr
>>),
876 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
878 /// The `SpannedIdent` is the identifier for the method name.
879 /// The vector of `Ty`s are the ascripted type parameters for the method
880 /// (within the angle brackets).
882 /// The first element of the vector of `Expr`s is the expression that evaluates
883 /// to the object on which the method is being called on (the receiver),
884 /// and the remaining elements are the rest of the arguments.
886 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
887 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
888 MethodCall(SpannedIdent
, Vec
<P
<Ty
>>, Vec
<P
<Expr
>>),
889 /// A tuple (`(a, b, c ,d)`)
891 /// A binary operation (For example: `a + b`, `a * b`)
892 Binary(BinOp
, P
<Expr
>, P
<Expr
>),
893 /// A unary operation (For example: `!x`, `*x`)
894 Unary(UnOp
, P
<Expr
>),
895 /// A literal (For example: `1`, `"foo"`)
897 /// A cast (`foo as f64`)
898 Cast(P
<Expr
>, P
<Ty
>),
899 Type(P
<Expr
>, P
<Ty
>),
900 /// An `if` block, with an optional else block
902 /// `if expr { block } else { expr }`
903 If(P
<Expr
>, P
<Block
>, Option
<P
<Expr
>>),
904 /// An `if let` expression with an optional else block
906 /// `if let pat = expr { block } else { expr }`
908 /// This is desugared to a `match` expression.
909 IfLet(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<P
<Expr
>>),
910 /// A while loop, with an optional label
912 /// `'label: while expr { block }`
913 While(P
<Expr
>, P
<Block
>, Option
<SpannedIdent
>),
914 /// A while-let loop, with an optional label
916 /// `'label: while let pat = expr { block }`
918 /// This is desugared to a combination of `loop` and `match` expressions.
919 WhileLet(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<SpannedIdent
>),
920 /// A for loop, with an optional label
922 /// `'label: for pat in expr { block }`
924 /// This is desugared to a combination of `loop` and `match` expressions.
925 ForLoop(P
<Pat
>, P
<Expr
>, P
<Block
>, Option
<SpannedIdent
>),
926 /// Conditionless loop (can be exited with break, continue, or return)
928 /// `'label: loop { block }`
929 Loop(P
<Block
>, Option
<SpannedIdent
>),
931 Match(P
<Expr
>, Vec
<Arm
>),
932 /// A closure (for example, `move |a, b, c| a + b + c`)
934 /// The final span is the span of the argument block `|...|`
935 Closure(CaptureBy
, P
<FnDecl
>, P
<Expr
>, Span
),
936 /// A block (`{ ... }`)
939 /// An assignment (`a = foo()`)
940 Assign(P
<Expr
>, P
<Expr
>),
941 /// An assignment with an operator
943 /// For example, `a += 1`.
944 AssignOp(BinOp
, P
<Expr
>, P
<Expr
>),
945 /// Access of a named struct field (`obj.foo`)
946 Field(P
<Expr
>, SpannedIdent
),
947 /// Access of an unnamed field of a struct or tuple-struct
949 /// For example, `foo.0`.
950 TupField(P
<Expr
>, Spanned
<usize>),
951 /// An indexing operation (`foo[2]`)
952 Index(P
<Expr
>, P
<Expr
>),
953 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
954 Range(Option
<P
<Expr
>>, Option
<P
<Expr
>>, RangeLimits
),
956 /// Variable reference, possibly containing `::` and/or type
957 /// parameters, e.g. foo::bar::<baz>.
959 /// Optionally "qualified",
960 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
961 Path(Option
<QSelf
>, Path
),
963 /// A referencing operation (`&a` or `&mut a`)
964 AddrOf(Mutability
, P
<Expr
>),
965 /// A `break`, with an optional label to break, and an optional expression
966 Break(Option
<SpannedIdent
>, Option
<P
<Expr
>>),
967 /// A `continue`, with an optional label
968 Continue(Option
<SpannedIdent
>),
969 /// A `return`, with an optional value to be returned
970 Ret(Option
<P
<Expr
>>),
972 /// Output of the `asm!()` macro
973 InlineAsm(P
<InlineAsm
>),
975 /// A macro invocation; pre-expansion
978 /// A struct literal expression.
980 /// For example, `Foo {x: 1, y: 2}`, or
981 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
982 Struct(Path
, Vec
<Field
>, Option
<P
<Expr
>>),
984 /// An array literal constructed from one repeated element.
986 /// For example, `[1; 5]`. The first expression is the element
987 /// to be repeated; the second is the number of times to repeat it.
988 Repeat(P
<Expr
>, P
<Expr
>),
990 /// No-op: used solely so we can pretty-print faithfully
997 /// The explicit Self type in a "qualified path". The actual
998 /// path, including the trait and the associated item, is stored
999 /// separately. `position` represents the index of the associated
1000 /// item qualified with this Self type.
1003 /// <Vec<T> as a::b::Trait>::AssociatedItem
1004 /// ^~~~~ ~~~~~~~~~~~~~~^
1007 /// <Vec<T>>::AssociatedItem
1011 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1017 /// A capture clause
1018 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1019 pub enum CaptureBy
{
1024 pub type Mac
= Spanned
<Mac_
>;
1026 /// Represents a macro invocation. The Path indicates which macro
1027 /// is being invoked, and the vector of token-trees contains the source
1028 /// of the macro invocation.
1030 /// NB: the additional ident for a macro_rules-style macro is actually
1031 /// stored in the enclosing item. Oog.
1032 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1035 pub tts
: ThinTokenStream
,
1039 pub fn stream(&self) -> TokenStream
{
1040 self.tts
.clone().into()
1044 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1046 /// A regular string, like `"foo"`
1048 /// A raw string, like `r##"foo"##`
1050 /// The uint is the number of `#` symbols used
1055 pub type Lit
= Spanned
<LitKind
>;
1057 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1058 pub enum LitIntType
{
1066 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1067 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1069 /// A string literal (`"foo"`)
1070 Str(Symbol
, StrStyle
),
1071 /// A byte string (`b"foo"`)
1072 ByteStr(Rc
<Vec
<u8>>),
1073 /// A byte char (`b'f'`)
1075 /// A character literal (`'a'`)
1077 /// An integer literal (`1`)
1078 Int(u128
, LitIntType
),
1079 /// A float literal (`1f64` or `1E10f64`)
1080 Float(Symbol
, FloatTy
),
1081 /// A float literal without a suffix (`1.0 or 1.0E10`)
1082 FloatUnsuffixed(Symbol
),
1083 /// A boolean literal
1088 /// Returns true if this literal is a string and false otherwise.
1089 pub fn is_str(&self) -> bool
{
1091 LitKind
::Str(..) => true,
1096 /// Returns true if this literal has no suffix. Note: this will return true
1097 /// for literals with prefixes such as raw strings and byte strings.
1098 pub fn is_unsuffixed(&self) -> bool
{
1100 // unsuffixed variants
1101 LitKind
::Str(..) => true,
1102 LitKind
::ByteStr(..) => true,
1103 LitKind
::Byte(..) => true,
1104 LitKind
::Char(..) => true,
1105 LitKind
::Int(_
, LitIntType
::Unsuffixed
) => true,
1106 LitKind
::FloatUnsuffixed(..) => true,
1107 LitKind
::Bool(..) => true,
1108 // suffixed variants
1109 LitKind
::Int(_
, LitIntType
::Signed(..)) => false,
1110 LitKind
::Int(_
, LitIntType
::Unsigned(..)) => false,
1111 LitKind
::Float(..) => false,
1115 /// Returns true if this literal has a suffix.
1116 pub fn is_suffixed(&self) -> bool
{
1117 !self.is_unsuffixed()
1121 // NB: If you change this, you'll probably want to change the corresponding
1122 // type structure in middle/ty.rs as well.
1123 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1126 pub mutbl
: Mutability
,
1129 /// Represents a method's signature in a trait declaration,
1130 /// or in an implementation.
1131 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1132 pub struct MethodSig
{
1133 pub unsafety
: Unsafety
,
1134 pub constness
: Spanned
<Constness
>,
1136 pub decl
: P
<FnDecl
>,
1137 pub generics
: Generics
,
1140 /// Represents an item declaration within a trait declaration,
1141 /// possibly including a default implementation. A trait item is
1142 /// either required (meaning it doesn't have an implementation, just a
1143 /// signature) or provided (meaning it has a default implementation).
1144 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1145 pub struct TraitItem
{
1148 pub attrs
: Vec
<Attribute
>,
1149 pub node
: TraitItemKind
,
1153 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1154 pub enum TraitItemKind
{
1155 Const(P
<Ty
>, Option
<P
<Expr
>>),
1156 Method(MethodSig
, Option
<P
<Block
>>),
1157 Type(TyParamBounds
, Option
<P
<Ty
>>),
1161 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1162 pub struct ImplItem
{
1165 pub vis
: Visibility
,
1166 pub defaultness
: Defaultness
,
1167 pub attrs
: Vec
<Attribute
>,
1168 pub node
: ImplItemKind
,
1172 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1173 pub enum ImplItemKind
{
1174 Const(P
<Ty
>, P
<Expr
>),
1175 Method(MethodSig
, P
<Block
>),
1180 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1190 impl fmt
::Debug
for IntTy
{
1191 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1192 fmt
::Display
::fmt(self, f
)
1196 impl fmt
::Display
for IntTy
{
1197 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1198 write
!(f
, "{}", self.ty_to_string())
1203 pub fn ty_to_string(&self) -> &'
static str {
1205 IntTy
::Is
=> "isize",
1207 IntTy
::I16
=> "i16",
1208 IntTy
::I32
=> "i32",
1209 IntTy
::I64
=> "i64",
1210 IntTy
::I128
=> "i128",
1214 pub fn val_to_string(&self, val
: i128
) -> String
{
1215 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1216 // are parsed as u128, so we wouldn't want to print an extra negative
1218 format
!("{}{}", val
as u128
, self.ty_to_string())
1221 pub fn bit_width(&self) -> Option
<usize> {
1223 IntTy
::Is
=> return None
,
1233 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1244 pub fn ty_to_string(&self) -> &'
static str {
1246 UintTy
::Us
=> "usize",
1248 UintTy
::U16
=> "u16",
1249 UintTy
::U32
=> "u32",
1250 UintTy
::U64
=> "u64",
1251 UintTy
::U128
=> "u128",
1255 pub fn val_to_string(&self, val
: u128
) -> String
{
1256 format
!("{}{}", val
, self.ty_to_string())
1259 pub fn bit_width(&self) -> Option
<usize> {
1261 UintTy
::Us
=> return None
,
1266 UintTy
::U128
=> 128,
1271 impl fmt
::Debug
for UintTy
{
1272 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1273 fmt
::Display
::fmt(self, f
)
1277 impl fmt
::Display
for UintTy
{
1278 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1279 write
!(f
, "{}", self.ty_to_string())
1283 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1289 impl fmt
::Debug
for FloatTy
{
1290 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1291 fmt
::Display
::fmt(self, f
)
1295 impl fmt
::Display
for FloatTy
{
1296 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1297 write
!(f
, "{}", self.ty_to_string())
1302 pub fn ty_to_string(&self) -> &'
static str {
1304 FloatTy
::F32
=> "f32",
1305 FloatTy
::F64
=> "f64",
1309 pub fn bit_width(&self) -> usize {
1317 // Bind a type to an associated type: `A=Foo`.
1318 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1319 pub struct TypeBinding
{
1326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1333 impl fmt
::Debug
for Ty
{
1334 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1335 write
!(f
, "type({})", pprust
::ty_to_string(self))
1339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1340 pub struct BareFnTy
{
1341 pub unsafety
: Unsafety
,
1343 pub lifetimes
: Vec
<LifetimeDef
>,
1347 /// The different kinds of types recognized by the compiler
1348 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1350 /// A variable-length slice (`[T]`)
1352 /// A fixed length array (`[T; n]`)
1353 Array(P
<Ty
>, P
<Expr
>),
1354 /// A raw pointer (`*const T` or `*mut T`)
1356 /// A reference (`&'a T` or `&'a mut T`)
1357 Rptr(Option
<Lifetime
>, MutTy
),
1358 /// A bare function (e.g. `fn(usize) -> bool`)
1359 BareFn(P
<BareFnTy
>),
1360 /// The never type (`!`)
1362 /// A tuple (`(A, B, C, D,...)`)
1364 /// A path (`module::module::...::Type`), optionally
1365 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1367 /// Type parameters are stored in the Path itself
1368 Path(Option
<QSelf
>, Path
),
1369 /// A trait object type `Bound1 + Bound2 + Bound3`
1370 /// where `Bound` is a trait or a lifetime.
1371 TraitObject(TyParamBounds
),
1372 /// An `impl Bound1 + Bound2 + Bound3` type
1373 /// where `Bound` is a trait or a lifetime.
1374 ImplTrait(TyParamBounds
),
1375 /// No-op; kept solely so that we can pretty-print faithfully
1379 /// TyKind::Infer means the type should be inferred instead of it having been
1380 /// specified. This can appear anywhere in a type.
1382 /// Inferred type of a `self` or `&self` argument in a method.
1384 // A macro in the type position.
1388 /// Inline assembly dialect.
1390 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1392 pub enum AsmDialect
{
1397 /// Inline assembly.
1399 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1401 pub struct InlineAsmOutput
{
1402 pub constraint
: Symbol
,
1405 pub is_indirect
: bool
,
1408 /// Inline assembly.
1410 /// E.g. `asm!("NOP");`
1411 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1412 pub struct InlineAsm
{
1414 pub asm_str_style
: StrStyle
,
1415 pub outputs
: Vec
<InlineAsmOutput
>,
1416 pub inputs
: Vec
<(Symbol
, P
<Expr
>)>,
1417 pub clobbers
: Vec
<Symbol
>,
1419 pub alignstack
: bool
,
1420 pub dialect
: AsmDialect
,
1421 pub expn_id
: ExpnId
,
1424 /// An argument in a function header.
1426 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1427 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1434 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1436 /// E.g. `&mut self` as in `fn foo(&mut self)`
1437 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1439 /// `self`, `mut self`
1441 /// `&'lt self`, `&'lt mut self`
1442 Region(Option
<Lifetime
>, Mutability
),
1443 /// `self: TYPE`, `mut self: TYPE`
1444 Explicit(P
<Ty
>, Mutability
),
1447 pub type ExplicitSelf
= Spanned
<SelfKind
>;
1450 pub fn to_self(&self) -> Option
<ExplicitSelf
> {
1451 if let PatKind
::Ident(BindingMode
::ByValue(mutbl
), ident
, _
) = self.pat
.node
{
1452 if ident
.node
.name
== keywords
::SelfValue
.name() {
1453 return match self.ty
.node
{
1454 TyKind
::ImplicitSelf
=> Some(respan(self.pat
.span
, SelfKind
::Value(mutbl
))),
1455 TyKind
::Rptr(lt
, MutTy{ref ty, mutbl}
) if ty
.node
== TyKind
::ImplicitSelf
=> {
1456 Some(respan(self.pat
.span
, SelfKind
::Region(lt
, mutbl
)))
1458 _
=> Some(respan(mk_sp(self.pat
.span
.lo
, self.ty
.span
.hi
),
1459 SelfKind
::Explicit(self.ty
.clone(), mutbl
))),
1466 pub fn is_self(&self) -> bool
{
1467 if let PatKind
::Ident(_
, ident
, _
) = self.pat
.node
{
1468 ident
.node
.name
== keywords
::SelfValue
.name()
1474 pub fn from_self(eself
: ExplicitSelf
, eself_ident
: SpannedIdent
) -> Arg
{
1475 let span
= mk_sp(eself
.span
.lo
, eself_ident
.span
.hi
);
1476 let infer_ty
= P(Ty
{
1478 node
: TyKind
::ImplicitSelf
,
1481 let arg
= |mutbl
, ty
| Arg
{
1484 node
: PatKind
::Ident(BindingMode
::ByValue(mutbl
), eself_ident
, None
),
1491 SelfKind
::Explicit(ty
, mutbl
) => arg(mutbl
, ty
),
1492 SelfKind
::Value(mutbl
) => arg(mutbl
, infer_ty
),
1493 SelfKind
::Region(lt
, mutbl
) => arg(Mutability
::Immutable
, P(Ty
{
1495 node
: TyKind
::Rptr(lt
, MutTy { ty: infer_ty, mutbl: mutbl }
),
1502 /// Header (not the body) of a function declaration.
1504 /// E.g. `fn foo(bar: baz)`
1505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1507 pub inputs
: Vec
<Arg
>,
1508 pub output
: FunctionRetTy
,
1513 pub fn get_self(&self) -> Option
<ExplicitSelf
> {
1514 self.inputs
.get(0).and_then(Arg
::to_self
)
1516 pub fn has_self(&self) -> bool
{
1517 self.inputs
.get(0).map(Arg
::is_self
).unwrap_or(false)
1521 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1527 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1528 pub enum Constness
{
1533 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1534 pub enum Defaultness
{
1539 impl fmt
::Display
for Unsafety
{
1540 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1541 fmt
::Display
::fmt(match *self {
1542 Unsafety
::Normal
=> "normal",
1543 Unsafety
::Unsafe
=> "unsafe",
1548 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1549 pub enum ImplPolarity
{
1550 /// `impl Trait for Type`
1552 /// `impl !Trait for Type`
1556 impl fmt
::Debug
for ImplPolarity
{
1557 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1559 ImplPolarity
::Positive
=> "positive".fmt(f
),
1560 ImplPolarity
::Negative
=> "negative".fmt(f
),
1566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1567 pub enum FunctionRetTy
{
1568 /// Return type is not specified.
1570 /// Functions default to `()` and
1571 /// closures default to inference. Span points to where return
1572 /// type would be inserted.
1578 impl FunctionRetTy
{
1579 pub fn span(&self) -> Span
{
1581 FunctionRetTy
::Default(span
) => span
,
1582 FunctionRetTy
::Ty(ref ty
) => ty
.span
,
1587 /// Module declaration.
1589 /// E.g. `mod foo;` or `mod foo { .. }`
1590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1592 /// A span from the first token past `{` to the last token until `}`.
1593 /// For `mod foo;`, the inner span ranges from the first token
1594 /// to the last token in the external file.
1596 pub items
: Vec
<P
<Item
>>,
1599 /// Foreign module declaration.
1601 /// E.g. `extern { .. }` or `extern C { .. }`
1602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1603 pub struct ForeignMod
{
1605 pub items
: Vec
<ForeignItem
>,
1608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1609 pub struct EnumDef
{
1610 pub variants
: Vec
<Variant
>,
1613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1614 pub struct Variant_
{
1616 pub attrs
: Vec
<Attribute
>,
1617 pub data
: VariantData
,
1618 /// Explicit discriminant, e.g. `Foo = 1`
1619 pub disr_expr
: Option
<P
<Expr
>>,
1622 pub type Variant
= Spanned
<Variant_
>;
1624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1625 pub struct PathListItem_
{
1627 /// renamed in list, e.g. `use foo::{bar as baz};`
1628 pub rename
: Option
<Ident
>,
1632 pub type PathListItem
= Spanned
<PathListItem_
>;
1634 pub type ViewPath
= Spanned
<ViewPath_
>;
1636 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1637 pub enum ViewPath_
{
1639 /// `foo::bar::baz as quux`
1643 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1644 ViewPathSimple(Ident
, Path
),
1649 /// `foo::bar::{a,b,c}`
1650 ViewPathList(Path
, Vec
<PathListItem
>)
1654 pub fn path(&self) -> &Path
{
1656 ViewPathSimple(_
, ref path
) |
1657 ViewPathGlob (ref path
) |
1658 ViewPathList(ref path
, _
) => path
1664 /// Distinguishes between Attributes that decorate items and Attributes that
1665 /// are contained as statements within items. These two cases need to be
1666 /// distinguished for pretty-printing.
1667 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1668 pub enum AttrStyle
{
1673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1674 pub struct AttrId(pub usize);
1676 /// Meta-data associated with an item
1677 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1678 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1679 pub struct Attribute
{
1681 pub style
: AttrStyle
,
1682 pub value
: MetaItem
,
1683 pub is_sugared_doc
: bool
,
1687 /// TraitRef's appear in impls.
1689 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1690 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1691 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1692 /// same as the impl's node id).
1693 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1694 pub struct TraitRef
{
1699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1700 pub struct PolyTraitRef
{
1701 /// The `'a` in `<'a> Foo<&'a T>`
1702 pub bound_lifetimes
: Vec
<LifetimeDef
>,
1704 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1705 pub trait_ref
: TraitRef
,
1710 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1711 pub enum Visibility
{
1714 Restricted { path: P<Path>, id: NodeId }
,
1718 /// Field of a struct.
1720 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1722 pub struct StructField
{
1724 pub ident
: Option
<Ident
>,
1725 pub vis
: Visibility
,
1728 pub attrs
: Vec
<Attribute
>,
1731 /// Fields and Ids of enum variants and structs
1733 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1734 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1735 /// One shared Id can be successfully used for these two purposes.
1736 /// Id of the whole enum lives in `Item`.
1738 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1739 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1740 /// the variant itself" from enum variants.
1741 /// Id of the whole struct lives in `Item`.
1742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1743 pub enum VariantData
{
1746 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1747 Struct(Vec
<StructField
>, NodeId
),
1750 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1751 Tuple(Vec
<StructField
>, NodeId
),
1754 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1759 pub fn fields(&self) -> &[StructField
] {
1761 VariantData
::Struct(ref fields
, _
) | VariantData
::Tuple(ref fields
, _
) => fields
,
1765 pub fn id(&self) -> NodeId
{
1767 VariantData
::Struct(_
, id
) | VariantData
::Tuple(_
, id
) | VariantData
::Unit(id
) => id
1770 pub fn is_struct(&self) -> bool
{
1771 if let VariantData
::Struct(..) = *self { true }
else { false }
1773 pub fn is_tuple(&self) -> bool
{
1774 if let VariantData
::Tuple(..) = *self { true }
else { false }
1776 pub fn is_unit(&self) -> bool
{
1777 if let VariantData
::Unit(..) = *self { true }
else { false }
1783 /// The name might be a dummy name in case of anonymous items
1784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1787 pub attrs
: Vec
<Attribute
>,
1790 pub vis
: Visibility
,
1794 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1796 /// An`extern crate` item, with optional original crate name.
1798 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1799 ExternCrate(Option
<Name
>),
1800 /// A use declaration (`use` or `pub use`) item.
1802 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1804 /// A static item (`static` or `pub static`).
1806 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1807 Static(P
<Ty
>, Mutability
, P
<Expr
>),
1808 /// A constant item (`const` or `pub const`).
1810 /// E.g. `const FOO: i32 = 42;`
1811 Const(P
<Ty
>, P
<Expr
>),
1812 /// A function declaration (`fn` or `pub fn`).
1814 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1815 Fn(P
<FnDecl
>, Unsafety
, Spanned
<Constness
>, Abi
, Generics
, P
<Block
>),
1816 /// A module declaration (`mod` or `pub mod`).
1818 /// E.g. `mod foo;` or `mod foo { .. }`
1820 /// An external module (`extern` or `pub extern`).
1822 /// E.g. `extern {}` or `extern "C" {}`
1823 ForeignMod(ForeignMod
),
1824 /// A type alias (`type` or `pub type`).
1826 /// E.g. `type Foo = Bar<u8>;`
1827 Ty(P
<Ty
>, Generics
),
1828 /// An enum definition (`enum` or `pub enum`).
1830 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1831 Enum(EnumDef
, Generics
),
1832 /// A struct definition (`struct` or `pub struct`).
1834 /// E.g. `struct Foo<A> { x: A }`
1835 Struct(VariantData
, Generics
),
1836 /// A union definition (`union` or `pub union`).
1838 /// E.g. `union Foo<A, B> { x: A, y: B }`
1839 Union(VariantData
, Generics
),
1840 /// A Trait declaration (`trait` or `pub trait`).
1842 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1843 Trait(Unsafety
, Generics
, TyParamBounds
, Vec
<TraitItem
>),
1844 // Default trait implementation.
1846 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1847 DefaultImpl(Unsafety
, TraitRef
),
1848 /// An implementation.
1850 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1854 Option
<TraitRef
>, // (optional) trait this impl implements
1857 /// A macro invocation.
1859 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1862 /// A macro definition.
1863 MacroDef(ThinTokenStream
),
1867 pub fn descriptive_variant(&self) -> &str {
1869 ItemKind
::ExternCrate(..) => "extern crate",
1870 ItemKind
::Use(..) => "use",
1871 ItemKind
::Static(..) => "static item",
1872 ItemKind
::Const(..) => "constant item",
1873 ItemKind
::Fn(..) => "function",
1874 ItemKind
::Mod(..) => "module",
1875 ItemKind
::ForeignMod(..) => "foreign module",
1876 ItemKind
::Ty(..) => "type alias",
1877 ItemKind
::Enum(..) => "enum",
1878 ItemKind
::Struct(..) => "struct",
1879 ItemKind
::Union(..) => "union",
1880 ItemKind
::Trait(..) => "trait",
1882 ItemKind
::MacroDef(..) |
1883 ItemKind
::Impl(..) |
1884 ItemKind
::DefaultImpl(..) => "item"
1889 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1890 pub struct ForeignItem
{
1892 pub attrs
: Vec
<Attribute
>,
1893 pub node
: ForeignItemKind
,
1896 pub vis
: Visibility
,
1899 /// An item within an `extern` block
1900 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1901 pub enum ForeignItemKind
{
1902 /// A foreign function
1903 Fn(P
<FnDecl
>, Generics
),
1904 /// A foreign static item (`static ext: u8`), with optional mutability
1905 /// (the boolean is true when mutable)
1906 Static(P
<Ty
>, bool
),
1909 impl ForeignItemKind
{
1910 pub fn descriptive_variant(&self) -> &str {
1912 ForeignItemKind
::Fn(..) => "foreign function",
1913 ForeignItemKind
::Static(..) => "foreign static item"
1923 // are ASTs encodable?
1925 fn check_asts_encodable() {
1926 fn assert_encodable
<T
: serialize
::Encodable
>() {}
1927 assert_encodable
::<Crate
>();