1 // Copyright 2015 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.
13 pub use self::BindingMode::*;
14 pub use self::BinOp_::*;
15 pub use self::BlockCheckMode::*;
16 pub use self::CaptureClause::*;
17 pub use self::Decl_::*;
18 pub use self::ExplicitSelf_::*;
19 pub use self::Expr_::*;
20 pub use self::FunctionRetTy::*;
21 pub use self::ForeignItem_::*;
22 pub use self::ImplItem_::*;
23 pub use self::Item_::*;
24 pub use self::Mutability::*;
25 pub use self::Pat_::*;
26 pub use self::PathListItem_::*;
27 pub use self::PatWildKind::*;
28 pub use self::PrimTy::*;
29 pub use self::Stmt_::*;
30 pub use self::StructFieldKind::*;
31 pub use self::TraitItem_::*;
33 pub use self::TyParamBound::*;
34 pub use self::UnOp::*;
35 pub use self::UnsafeSource::*;
36 pub use self::VariantKind::*;
37 pub use self::ViewPath_::*;
38 pub use self::Visibility::*;
39 pub use self::PathParameters::*;
41 use syntax::codemap::{self, Span, Spanned, DUMMY_SP, ExpnId};
43 use syntax::ast::{Name, Ident, NodeId, DUMMY_NODE_ID, TokenTree, AsmDialect};
44 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, CrateConfig};
45 use syntax::owned_slice::OwnedSlice;
46 use syntax::parse::token::InternedString;
53 use serialize::{Encodable, Encoder, Decoder};
55 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
62 impl fmt::Debug for Lifetime {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
68 /// A lifetime definition, eg `'a: 'b+'c+'d`
69 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
70 pub struct LifetimeDef {
71 pub lifetime: Lifetime,
72 pub bounds: Vec<Lifetime>
75 /// A "Path" is essentially Rust's notion of a name; for instance:
76 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
77 /// along with a bunch of supporting information.
78 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
81 /// A `::foo` path, is relative to the crate root rather than current
82 /// module (like paths in an import).
84 /// The segments in the path: the things separated by `::`.
85 pub segments: Vec<PathSegment>,
88 impl fmt::Debug for Path {
89 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90 write!(f, "path({})", pprust::path_to_string(self))
94 impl fmt::Display for Path {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 write!(f, "{}", pprust::path_to_string(self))
100 /// A segment of a path: an identifier, an optional lifetime, and a set of
102 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
103 pub struct PathSegment {
104 /// The identifier portion of this path segment.
105 pub identifier: Ident,
107 /// Type/lifetime parameters attached to this path. They come in
108 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
109 /// this is more than just simple syntactic sugar; the use of
110 /// parens affects the region binding rules, so we preserve the
112 pub parameters: PathParameters,
115 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
116 pub enum PathParameters {
117 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
118 AngleBracketedParameters(AngleBracketedParameterData),
119 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
120 ParenthesizedParameters(ParenthesizedParameterData),
123 impl PathParameters {
124 pub fn none() -> PathParameters {
125 AngleBracketedParameters(AngleBracketedParameterData {
126 lifetimes: Vec::new(),
127 types: OwnedSlice::empty(),
128 bindings: OwnedSlice::empty(),
132 pub fn is_empty(&self) -> bool {
134 AngleBracketedParameters(ref data) => data.is_empty(),
136 // Even if the user supplied no types, something like
137 // `X()` is equivalent to `X<(),()>`.
138 ParenthesizedParameters(..) => false,
142 pub fn has_lifetimes(&self) -> bool {
144 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
145 ParenthesizedParameters(_) => false,
149 pub fn has_types(&self) -> bool {
151 AngleBracketedParameters(ref data) => !data.types.is_empty(),
152 ParenthesizedParameters(..) => true,
156 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
157 /// parameters in the parenthesized case.
158 pub fn types(&self) -> Vec<&P<Ty>> {
160 AngleBracketedParameters(ref data) => {
161 data.types.iter().collect()
163 ParenthesizedParameters(ref data) => {
165 .chain(data.output.iter())
171 pub fn lifetimes(&self) -> Vec<&Lifetime> {
173 AngleBracketedParameters(ref data) => {
174 data.lifetimes.iter().collect()
176 ParenthesizedParameters(_) => {
182 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
184 AngleBracketedParameters(ref data) => {
185 data.bindings.iter().collect()
187 ParenthesizedParameters(_) => {
194 /// A path like `Foo<'a, T>`
195 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
196 pub struct AngleBracketedParameterData {
197 /// The lifetime parameters for this path segment.
198 pub lifetimes: Vec<Lifetime>,
199 /// The type parameters for this path segment, if present.
200 pub types: OwnedSlice<P<Ty>>,
201 /// Bindings (equality constraints) on associated types, if present.
202 /// E.g., `Foo<A=Bar>`.
203 pub bindings: OwnedSlice<P<TypeBinding>>,
206 impl AngleBracketedParameterData {
207 fn is_empty(&self) -> bool {
208 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
212 /// A path like `Foo(A,B) -> C`
213 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
214 pub struct ParenthesizedParameterData {
219 pub inputs: Vec<P<Ty>>,
222 pub output: Option<P<Ty>>,
225 /// The AST represents all type param bounds as types.
226 /// typeck::collect::compute_bounds matches these against
227 /// the "special" built-in traits (see middle::lang_items) and
228 /// detects Copy, Send and Sync.
229 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
230 pub enum TyParamBound {
231 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
232 RegionTyParamBound(Lifetime)
235 /// A modifier on a bound, currently this is only used for `?Sized`, where the
236 /// modifier is `Maybe`. Negative bounds should also be handled here.
237 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
238 pub enum TraitBoundModifier {
243 pub type TyParamBounds = OwnedSlice<TyParamBound>;
245 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
249 pub bounds: TyParamBounds,
250 pub default: Option<P<Ty>>,
254 /// Represents lifetimes and type parameters attached to a declaration
255 /// of a function, enum, trait, etc.
256 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
257 pub struct Generics {
258 pub lifetimes: Vec<LifetimeDef>,
259 pub ty_params: OwnedSlice<TyParam>,
260 pub where_clause: WhereClause,
264 pub fn is_lt_parameterized(&self) -> bool {
265 !self.lifetimes.is_empty()
267 pub fn is_type_parameterized(&self) -> bool {
268 !self.ty_params.is_empty()
270 pub fn is_parameterized(&self) -> bool {
271 self.is_lt_parameterized() || self.is_type_parameterized()
275 /// A `where` clause in a definition
276 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
277 pub struct WhereClause {
279 pub predicates: Vec<WherePredicate>,
282 /// A single predicate in a `where` clause
283 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
284 pub enum WherePredicate {
285 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
286 BoundPredicate(WhereBoundPredicate),
287 /// A lifetime predicate, e.g. `'a: 'b+'c`
288 RegionPredicate(WhereRegionPredicate),
289 /// An equality predicate (unsupported)
290 EqPredicate(WhereEqPredicate)
293 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
294 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
295 pub struct WhereBoundPredicate {
297 /// Any lifetimes from a `for` binding
298 pub bound_lifetimes: Vec<LifetimeDef>,
299 /// The type being bounded
300 pub bounded_ty: P<Ty>,
301 /// Trait and lifetime bounds (`Clone+Send+'static`)
302 pub bounds: OwnedSlice<TyParamBound>,
305 /// A lifetime predicate, e.g. `'a: 'b+'c`
306 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
307 pub struct WhereRegionPredicate {
309 pub lifetime: Lifetime,
310 pub bounds: Vec<Lifetime>,
313 /// An equality predicate (unsupported), e.g. `T=int`
314 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
315 pub struct WhereEqPredicate {
322 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
325 pub attrs: Vec<Attribute>,
326 pub config: CrateConfig,
328 pub exported_macros: Vec<MacroDef>,
331 /// A macro definition, in this crate or imported from another.
333 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
334 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
335 pub struct MacroDef {
337 pub attrs: Vec<Attribute>,
340 pub imported_from: Option<Name>,
342 pub use_locally: bool,
343 pub allow_internal_unstable: bool,
344 pub body: Vec<TokenTree>,
347 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
349 /// Statements in a block
350 pub stmts: Vec<P<Stmt>>,
351 /// An expression at the end of the block
352 /// without a semicolon, if any
353 pub expr: Option<P<Expr>>,
355 /// Distinguishes between `unsafe { ... }` and `{ ... }`
356 pub rules: BlockCheckMode,
360 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
367 impl fmt::Debug for Pat {
368 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
369 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
373 /// A single field in a struct pattern
375 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
376 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
377 /// except is_shorthand is true
378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
379 pub struct FieldPat {
380 /// The identifier for the field
382 /// The pattern the field is destructured to
384 pub is_shorthand: bool,
387 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
388 pub enum BindingMode {
389 BindByRef(Mutability),
390 BindByValue(Mutability),
393 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
394 pub enum PatWildKind {
395 /// Represents the wildcard pattern `_`
398 /// Represents the wildcard pattern `..`
402 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
404 /// Represents a wildcard pattern (either `_` or `..`)
405 PatWild(PatWildKind),
407 /// A PatIdent may either be a new bound variable,
408 /// or a nullary enum (in which case the third field
411 /// In the nullary enum case, the parser can't determine
412 /// which it is. The resolver determines this, and
413 /// records this pattern's NodeId in an auxiliary
414 /// set (of "PatIdents that refer to nullary enums")
415 PatIdent(BindingMode, Spanned<Ident>, Option<P<Pat>>),
417 /// "None" means a * pattern where we don't bind the fields to names.
418 PatEnum(Path, Option<Vec<P<Pat>>>),
420 /// An associated const named using the qualified path `<T>::CONST` or
421 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
422 /// referred to as simply `T::CONST`, in which case they will end up as
423 /// PatEnum, and the resolver will have to sort that out.
424 PatQPath(QSelf, Path),
426 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
427 /// The `bool` is `true` in the presence of a `..`
428 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
429 /// A tuple pattern `(a, b)`
433 /// A reference pattern, e.g. `&mut (a, b)`
434 PatRegion(P<Pat>, Mutability),
437 /// A range pattern, e.g. `1...2`
438 PatRange(P<Expr>, P<Expr>),
439 /// [a, b, ..i, y, z] is represented as:
440 /// PatVec(box [a, b], Some(i), box [y, z])
441 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
445 pub enum Mutability {
450 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
452 /// The `+` operator (addition)
454 /// The `-` operator (subtraction)
456 /// The `*` operator (multiplication)
458 /// The `/` operator (division)
460 /// The `%` operator (modulus)
462 /// The `&&` operator (logical and)
464 /// The `||` operator (logical or)
466 /// The `^` operator (bitwise xor)
468 /// The `&` operator (bitwise and)
470 /// The `|` operator (bitwise or)
472 /// The `<<` operator (shift left)
474 /// The `>>` operator (shift right)
476 /// The `==` operator (equality)
478 /// The `<` operator (less than)
480 /// The `<=` operator (less than or equal to)
482 /// The `!=` operator (not equal to)
484 /// The `>=` operator (greater than or equal to)
486 /// The `>` operator (greater than)
490 pub type BinOp = Spanned<BinOp_>;
492 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
494 /// The `box` operator
496 /// The `*` operator for dereferencing
498 /// The `!` operator for logical inversion
500 /// The `-` operator for negation
505 pub type Stmt = Spanned<Stmt_>;
507 impl fmt::Debug for Stmt_ {
508 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
510 let spanned = codemap::dummy_spanned(self.clone());
511 write!(f, "stmt({}: {})",
512 util::stmt_id(&spanned),
513 pprust::stmt_to_string(&spanned))
517 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
519 /// Could be an item or a local (let) binding:
520 StmtDecl(P<Decl>, NodeId),
522 /// Expr without trailing semi-colon (must have unit type):
523 StmtExpr(P<Expr>, NodeId),
525 /// Expr with trailing semi-colon (may have any type):
526 StmtSemi(P<Expr>, NodeId),
529 // FIXME (pending discussion of #1697, #2178...): local should really be
530 // a refinement on pat.
531 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
532 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
535 pub ty: Option<P<Ty>>,
536 /// Initializer expression to set the value, if any
537 pub init: Option<P<Expr>>,
542 pub type Decl = Spanned<Decl_>;
544 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
546 /// A local (let) binding:
552 /// represents one arm of a 'match'
553 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
555 pub attrs: Vec<Attribute>,
556 pub pats: Vec<P<Pat>>,
557 pub guard: Option<P<Expr>>,
561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
563 pub name: Spanned<Name>,
568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
569 pub enum BlockCheckMode {
571 UnsafeBlock(UnsafeSource),
572 PushUnsafeBlock(UnsafeSource),
573 PopUnsafeBlock(UnsafeSource),
576 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
577 pub enum UnsafeSource {
583 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
590 impl fmt::Debug for Expr {
591 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
592 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
598 /// First expr is the place; second expr is the value.
599 ExprBox(Option<P<Expr>>, P<Expr>),
600 /// An array (`[a, b, c, d]`)
601 ExprVec(Vec<P<Expr>>),
604 /// The first field resolves to the function itself,
605 /// and the second field is the list of arguments
606 ExprCall(P<Expr>, Vec<P<Expr>>),
607 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
609 /// The `Spanned<Name>` is the identifier for the method name.
610 /// The vector of `Ty`s are the ascripted type parameters for the method
611 /// (within the angle brackets).
613 /// The first element of the vector of `Expr`s is the expression that evaluates
614 /// to the object on which the method is being called on (the receiver),
615 /// and the remaining elements are the rest of the arguments.
617 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
618 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
619 ExprMethodCall(Spanned<Name>, Vec<P<Ty>>, Vec<P<Expr>>),
620 /// A tuple (`(a, b, c ,d)`)
621 ExprTup(Vec<P<Expr>>),
622 /// A binary operation (For example: `a + b`, `a * b`)
623 ExprBinary(BinOp, P<Expr>, P<Expr>),
624 /// A unary operation (For example: `!x`, `*x`)
625 ExprUnary(UnOp, P<Expr>),
626 /// A literal (For example: `1u8`, `"foo"`)
628 /// A cast (`foo as f64`)
629 ExprCast(P<Expr>, P<Ty>),
630 /// An `if` block, with an optional else block
632 /// `if expr { block } else { expr }`
633 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
634 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
635 /// A while loop, with an optional label
637 /// `'label: while expr { block }`
638 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
639 /// Conditionless loop (can be exited with break, continue, or return)
641 /// `'label: loop { block }`
642 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
643 ExprLoop(P<Block>, Option<Ident>),
644 /// A `match` block, with a source that indicates whether or not it is
645 /// the result of a desugaring, and if so, which kind.
646 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
647 /// A closure (for example, `move |a, b, c| {a + b + c}`)
648 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
649 /// A block (`{ ... }`)
652 /// An assignment (`a = foo()`)
653 ExprAssign(P<Expr>, P<Expr>),
654 /// An assignment with an operator
656 /// For example, `a += 1`.
657 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
658 /// Access of a named struct field (`obj.foo`)
659 ExprField(P<Expr>, Spanned<Name>),
660 /// Access of an unnamed field of a struct or tuple-struct
662 /// For example, `foo.0`.
663 ExprTupField(P<Expr>, Spanned<usize>),
664 /// An indexing operation (`foo[2]`)
665 ExprIndex(P<Expr>, P<Expr>),
666 /// A range (`1..2`, `1..`, or `..2`)
667 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
669 /// Variable reference, possibly containing `::` and/or type
670 /// parameters, e.g. foo::bar::<baz>.
672 /// Optionally "qualified",
673 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
674 ExprPath(Option<QSelf>, Path),
676 /// A referencing operation (`&a` or `&mut a`)
677 ExprAddrOf(Mutability, P<Expr>),
678 /// A `break`, with an optional label to break
679 ExprBreak(Option<Spanned<Ident>>),
680 /// A `continue`, with an optional label
681 ExprAgain(Option<Spanned<Ident>>),
682 /// A `return`, with an optional value to be returned
683 ExprRet(Option<P<Expr>>),
685 /// Output of the `asm!()` macro
686 ExprInlineAsm(InlineAsm),
688 /// A struct literal expression.
690 /// For example, `Foo {x: 1, y: 2}`, or
691 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
692 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
694 /// A vector literal constructed from one repeated element.
696 /// For example, `[1u8; 5]`. The first expression is the element
697 /// to be repeated; the second is the number of times to repeat it.
698 ExprRepeat(P<Expr>, P<Expr>),
701 /// The explicit Self type in a "qualified path". The actual
702 /// path, including the trait and the associated item, is stored
703 /// separately. `position` represents the index of the associated
704 /// item qualified with this Self type.
706 /// <Vec<T> as a::b::Trait>::AssociatedItem
707 /// ^~~~~ ~~~~~~~~~~~~~~^
710 /// <Vec<T>>::AssociatedItem
713 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
719 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
720 pub enum MatchSource {
722 IfLetDesugar { contains_else_clause: bool },
727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
728 pub enum CaptureClause {
733 // NB: If you change this, you'll probably want to change the corresponding
734 // type structure in middle/ty.rs as well.
735 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
738 pub mutbl: Mutability,
741 /// Represents a method's signature in a trait declaration,
742 /// or in an implementation.
743 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
744 pub struct MethodSig {
745 pub unsafety: Unsafety,
746 pub constness: Constness,
749 pub generics: Generics,
750 pub explicit_self: ExplicitSelf,
753 /// Represents a method declaration in a trait declaration, possibly including
754 /// a default implementation A trait method is either required (meaning it
755 /// doesn't have an implementation, just a signature) or provided (meaning it
756 /// has a default implementation).
757 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
758 pub struct TraitItem {
761 pub attrs: Vec<Attribute>,
762 pub node: TraitItem_,
766 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
767 pub enum TraitItem_ {
768 ConstTraitItem(P<Ty>, Option<P<Expr>>),
769 MethodTraitItem(MethodSig, Option<P<Block>>),
770 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
773 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
774 pub struct ImplItem {
778 pub attrs: Vec<Attribute>,
783 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
785 ConstImplItem(P<Ty>, P<Expr>),
786 MethodImplItem(MethodSig, P<Block>),
790 // Bind a type to an associated type: `A=Foo`.
791 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
792 pub struct TypeBinding {
800 // NB PartialEq method appears below.
801 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
808 impl fmt::Debug for Ty {
809 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
810 write!(f, "type({})", pprust::ty_to_string(self))
814 /// Not represented directly in the AST, referred to by name through a ty_path.
815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
825 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
826 pub struct BareFnTy {
827 pub unsafety: Unsafety,
829 pub lifetimes: Vec<LifetimeDef>,
833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
834 /// The different kinds of types recognized by the compiler
837 /// A fixed length array (`[T; n]`)
838 TyFixedLengthVec(P<Ty>, P<Expr>),
839 /// A raw pointer (`*const T` or `*mut T`)
841 /// A reference (`&'a T` or `&'a mut T`)
842 TyRptr(Option<Lifetime>, MutTy),
843 /// A bare function (e.g. `fn(usize) -> bool`)
844 TyBareFn(P<BareFnTy>),
845 /// A tuple (`(A, B, C, D,...)`)
847 /// A path (`module::module::...::Type`), optionally
848 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
850 /// Type parameters are stored in the Path itself
851 TyPath(Option<QSelf>, Path),
852 /// Something like `A+B`. Note that `B` must always be a path.
853 TyObjectSum(P<Ty>, TyParamBounds),
854 /// A type like `for<'a> Foo<&'a Bar>`
855 TyPolyTraitRef(TyParamBounds),
856 /// No-op; kept solely so that we can pretty-print faithfully
860 /// TyInfer means the type should be inferred instead of it having been
861 /// specified. This can appear anywhere in a type.
865 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
866 pub struct InlineAsm {
867 pub asm: InternedString,
868 pub asm_str_style: StrStyle,
869 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
870 pub inputs: Vec<(InternedString, P<Expr>)>,
871 pub clobbers: Vec<InternedString>,
873 pub alignstack: bool,
874 pub dialect: AsmDialect,
878 /// represents an argument in a function header
879 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
887 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
888 let path = Spanned{span:span,node:self_ident};
890 // HACK(eddyb) fake type for the self argument.
898 node: PatIdent(BindByValue(mutability), path, None),
906 /// Represents the header (not the body) of a function declaration
907 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
909 pub inputs: Vec<Arg>,
910 pub output: FunctionRetTy,
914 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
920 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
926 impl fmt::Display for Unsafety {
927 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
928 fmt::Display::fmt(match *self {
929 Unsafety::Normal => "normal",
930 Unsafety::Unsafe => "unsafe",
935 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
936 pub enum ImplPolarity {
937 /// `impl Trait for Type`
939 /// `impl !Trait for Type`
943 impl fmt::Debug for ImplPolarity {
944 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
946 ImplPolarity::Positive => "positive".fmt(f),
947 ImplPolarity::Negative => "negative".fmt(f),
953 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
954 pub enum FunctionRetTy {
955 /// Functions with return type `!`that always
956 /// raise an error or exit (i.e. never return to the caller)
958 /// Return type is not specified.
960 /// Functions default to `()` and
961 /// closures default to inference. Span points to where return
962 /// type would be inserted.
969 pub fn span(&self) -> Span {
971 NoReturn(span) => span,
972 DefaultReturn(span) => span,
973 Return(ref ty) => ty.span
978 /// Represents the kind of 'self' associated with a method
979 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
980 pub enum ExplicitSelf_ {
985 /// `&'lt self`, `&'lt mut self`
986 SelfRegion(Option<Lifetime>, Mutability, Ident),
988 SelfExplicit(P<Ty>, Ident),
991 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
993 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
995 /// A span from the first token past `{` to the last token until `}`.
996 /// For `mod foo;`, the inner span ranges from the first token
997 /// to the last token in the external file.
999 pub items: Vec<P<Item>>,
1002 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1003 pub struct ForeignMod {
1005 pub items: Vec<P<ForeignItem>>,
1008 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1009 pub struct VariantArg {
1014 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1015 pub enum VariantKind {
1016 /// Tuple variant, e.g. `Foo(A, B)`
1017 TupleVariantKind(Vec<VariantArg>),
1018 /// Struct variant, e.g. `Foo {x: A, y: B}`
1019 StructVariantKind(P<StructDef>),
1022 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1023 pub struct EnumDef {
1024 pub variants: Vec<P<Variant>>,
1027 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1028 pub struct Variant_ {
1030 pub attrs: Vec<Attribute>,
1031 pub kind: VariantKind,
1033 /// Explicit discriminant, eg `Foo = 1`
1034 pub disr_expr: Option<P<Expr>>,
1037 pub type Variant = Spanned<Variant_>;
1039 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1040 pub enum PathListItem_ {
1043 /// renamed in list, eg `use foo::{bar as baz};`
1044 rename: Option<Name>,
1048 /// renamed in list, eg `use foo::{self as baz};`
1049 rename: Option<Name>,
1054 impl PathListItem_ {
1055 pub fn id(&self) -> NodeId {
1057 PathListIdent { id, .. } | PathListMod { id, .. } => id
1061 pub fn rename(&self) -> Option<Name> {
1063 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1068 pub type PathListItem = Spanned<PathListItem_>;
1070 pub type ViewPath = Spanned<ViewPath_>;
1072 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1073 pub enum ViewPath_ {
1075 /// `foo::bar::baz as quux`
1079 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1080 ViewPathSimple(Name, Path),
1085 /// `foo::bar::{a,b,c}`
1086 ViewPathList(Path, Vec<PathListItem>)
1089 /// TraitRef's appear in impls.
1091 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1092 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1093 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1094 /// same as the impl's node id).
1095 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1096 pub struct TraitRef {
1101 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1102 pub struct PolyTraitRef {
1103 /// The `'a` in `<'a> Foo<&'a T>`
1104 pub bound_lifetimes: Vec<LifetimeDef>,
1106 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1107 pub trait_ref: TraitRef,
1112 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1113 pub enum Visibility {
1119 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1121 &Inherited => parent_visibility,
1127 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1128 pub struct StructField_ {
1129 pub kind: StructFieldKind,
1132 pub attrs: Vec<Attribute>,
1136 pub fn ident(&self) -> Option<Ident> {
1138 NamedField(ref ident, _) => Some(ident.clone()),
1139 UnnamedField(_) => None
1144 pub type StructField = Spanned<StructField_>;
1146 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1147 pub enum StructFieldKind {
1148 NamedField(Ident, Visibility),
1149 /// Element of a tuple-like struct
1150 UnnamedField(Visibility),
1153 impl StructFieldKind {
1154 pub fn is_unnamed(&self) -> bool {
1156 UnnamedField(..) => true,
1157 NamedField(..) => false,
1162 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1163 pub struct StructDef {
1164 /// Fields, not including ctor
1165 pub fields: Vec<StructField>,
1166 /// ID of the constructor. This is only used for tuple- or enum-like
1168 pub ctor_id: Option<NodeId>,
1172 FIXME (#3300): Should allow items to be anonymous. Right now
1173 we just use dummy names for anon items.
1177 /// The name might be a dummy name in case of anonymous items
1178 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1181 pub attrs: Vec<Attribute>,
1184 pub vis: Visibility,
1188 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1190 /// An`extern crate` item, with optional original crate name,
1192 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1193 ItemExternCrate(Option<Name>),
1194 /// A `use` or `pub use` item
1195 ItemUse(P<ViewPath>),
1198 ItemStatic(P<Ty>, Mutability, P<Expr>),
1200 ItemConst(P<Ty>, P<Expr>),
1201 /// A function declaration
1202 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1205 /// An external module
1206 ItemForeignMod(ForeignMod),
1207 /// A type alias, e.g. `type Foo = Bar<u8>`
1208 ItemTy(P<Ty>, Generics),
1209 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1210 ItemEnum(EnumDef, Generics),
1211 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1212 ItemStruct(P<StructDef>, Generics),
1213 /// Represents a Trait Declaration
1219 // Default trait implementations
1221 // `impl Trait for .. {}`
1222 ItemDefaultImpl(Unsafety, TraitRef),
1223 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1227 Option<TraitRef>, // (optional) trait this impl implements
1233 pub fn descriptive_variant(&self) -> &str {
1235 ItemExternCrate(..) => "extern crate",
1236 ItemUse(..) => "use",
1237 ItemStatic(..) => "static item",
1238 ItemConst(..) => "constant item",
1239 ItemFn(..) => "function",
1240 ItemMod(..) => "module",
1241 ItemForeignMod(..) => "foreign module",
1242 ItemTy(..) => "type alias",
1243 ItemEnum(..) => "enum",
1244 ItemStruct(..) => "struct",
1245 ItemTrait(..) => "trait",
1247 ItemDefaultImpl(..) => "item"
1252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1253 pub struct ForeignItem {
1255 pub attrs: Vec<Attribute>,
1256 pub node: ForeignItem_,
1259 pub vis: Visibility,
1262 /// An item within an `extern` block
1263 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1264 pub enum ForeignItem_ {
1265 /// A foreign function
1266 ForeignItemFn(P<FnDecl>, Generics),
1267 /// A foreign static item (`static ext: u8`), with optional mutability
1268 /// (the boolean is true when mutable)
1269 ForeignItemStatic(P<Ty>, bool),
1273 pub fn descriptive_variant(&self) -> &str {
1275 ForeignItemFn(..) => "foreign function",
1276 ForeignItemStatic(..) => "foreign static item"