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::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::IntTy::*;
27 pub use self::Item_::*;
28 pub use self::Lit_::*;
29 pub use self::LitIntType::*;
30 pub use self::MetaItem_::*;
31 pub use self::Mutability::*;
32 pub use self::Pat_::*;
33 pub use self::PathListItem_::*;
34 pub use self::PatWildKind::*;
35 pub use self::PrimTy::*;
36 pub use self::Sign::*;
37 pub use self::Stmt_::*;
38 pub use self::StrStyle::*;
39 pub use self::StructFieldKind::*;
40 pub use self::TraitItem_::*;
42 pub use self::TyParamBound::*;
43 pub use self::UintTy::*;
44 pub use self::UnOp::*;
45 pub use self::UnsafeSource::*;
46 pub use self::VariantKind::*;
47 pub use self::ViewPath_::*;
48 pub use self::Visibility::*;
49 pub use self::PathParameters::*;
51 use syntax::codemap::{self, Span, Spanned, DUMMY_SP, ExpnId};
53 use syntax::ast::{Name, Ident, NodeId, DUMMY_NODE_ID, TokenTree};
54 use syntax::owned_slice::OwnedSlice;
55 use syntax::parse::token::InternedString;
63 use serialize::{Encodable, Encoder, Decoder};
66 /// Function name (not all functions have names)
67 pub type FnIdent = Option<Ident>;
69 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
76 impl fmt::Debug for Lifetime {
77 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
82 /// A lifetime definition, eg `'a: 'b+'c+'d`
83 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
84 pub struct LifetimeDef {
85 pub lifetime: Lifetime,
86 pub bounds: Vec<Lifetime>
89 /// A "Path" is essentially Rust's notion of a name; for instance:
90 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
91 /// along with a bunch of supporting information.
92 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
95 /// A `::foo` path, is relative to the crate root rather than current
96 /// module (like paths in an import).
98 /// The segments in the path: the things separated by `::`.
99 pub segments: Vec<PathSegment>,
102 impl fmt::Debug for Path {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104 write!(f, "path({})", pprust::path_to_string(self))
108 impl fmt::Display for Path {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110 write!(f, "{}", pprust::path_to_string(self))
114 /// A segment of a path: an identifier, an optional lifetime, and a set of
116 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
117 pub struct PathSegment {
118 /// The identifier portion of this path segment.
119 pub identifier: Ident,
121 /// Type/lifetime parameters attached to this path. They come in
122 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
123 /// this is more than just simple syntactic sugar; the use of
124 /// parens affects the region binding rules, so we preserve the
126 pub parameters: PathParameters,
129 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
130 pub enum PathParameters {
131 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
132 AngleBracketedParameters(AngleBracketedParameterData),
133 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
134 ParenthesizedParameters(ParenthesizedParameterData),
137 impl PathParameters {
138 pub fn none() -> PathParameters {
139 AngleBracketedParameters(AngleBracketedParameterData {
140 lifetimes: Vec::new(),
141 types: OwnedSlice::empty(),
142 bindings: OwnedSlice::empty(),
146 pub fn is_empty(&self) -> bool {
148 AngleBracketedParameters(ref data) => data.is_empty(),
150 // Even if the user supplied no types, something like
151 // `X()` is equivalent to `X<(),()>`.
152 ParenthesizedParameters(..) => false,
156 pub fn has_lifetimes(&self) -> bool {
158 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
159 ParenthesizedParameters(_) => false,
163 pub fn has_types(&self) -> bool {
165 AngleBracketedParameters(ref data) => !data.types.is_empty(),
166 ParenthesizedParameters(..) => true,
170 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
171 /// parameters in the parenthesized case.
172 pub fn types(&self) -> Vec<&P<Ty>> {
174 AngleBracketedParameters(ref data) => {
175 data.types.iter().collect()
177 ParenthesizedParameters(ref data) => {
179 .chain(data.output.iter())
185 pub fn lifetimes(&self) -> Vec<&Lifetime> {
187 AngleBracketedParameters(ref data) => {
188 data.lifetimes.iter().collect()
190 ParenthesizedParameters(_) => {
196 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
198 AngleBracketedParameters(ref data) => {
199 data.bindings.iter().collect()
201 ParenthesizedParameters(_) => {
208 /// A path like `Foo<'a, T>`
209 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
210 pub struct AngleBracketedParameterData {
211 /// The lifetime parameters for this path segment.
212 pub lifetimes: Vec<Lifetime>,
213 /// The type parameters for this path segment, if present.
214 pub types: OwnedSlice<P<Ty>>,
215 /// Bindings (equality constraints) on associated types, if present.
216 /// E.g., `Foo<A=Bar>`.
217 pub bindings: OwnedSlice<P<TypeBinding>>,
220 impl AngleBracketedParameterData {
221 fn is_empty(&self) -> bool {
222 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
226 /// A path like `Foo(A,B) -> C`
227 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
228 pub struct ParenthesizedParameterData {
233 pub inputs: Vec<P<Ty>>,
236 pub output: Option<P<Ty>>,
239 /// The AST represents all type param bounds as types.
240 /// typeck::collect::compute_bounds matches these against
241 /// the "special" built-in traits (see middle::lang_items) and
242 /// detects Copy, Send and Sync.
243 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
244 pub enum TyParamBound {
245 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
246 RegionTyParamBound(Lifetime)
249 /// A modifier on a bound, currently this is only used for `?Sized`, where the
250 /// modifier is `Maybe`. Negative bounds should also be handled here.
251 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
252 pub enum TraitBoundModifier {
257 pub type TyParamBounds = OwnedSlice<TyParamBound>;
259 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
263 pub bounds: TyParamBounds,
264 pub default: Option<P<Ty>>,
268 /// Represents lifetimes and type parameters attached to a declaration
269 /// of a function, enum, trait, etc.
270 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
271 pub struct Generics {
272 pub lifetimes: Vec<LifetimeDef>,
273 pub ty_params: OwnedSlice<TyParam>,
274 pub where_clause: WhereClause,
278 pub fn is_lt_parameterized(&self) -> bool {
279 !self.lifetimes.is_empty()
281 pub fn is_type_parameterized(&self) -> bool {
282 !self.ty_params.is_empty()
284 pub fn is_parameterized(&self) -> bool {
285 self.is_lt_parameterized() || self.is_type_parameterized()
289 /// A `where` clause in a definition
290 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
291 pub struct WhereClause {
293 pub predicates: Vec<WherePredicate>,
296 /// A single predicate in a `where` clause
297 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
298 pub enum WherePredicate {
299 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
300 BoundPredicate(WhereBoundPredicate),
301 /// A lifetime predicate, e.g. `'a: 'b+'c`
302 RegionPredicate(WhereRegionPredicate),
303 /// An equality predicate (unsupported)
304 EqPredicate(WhereEqPredicate)
307 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
308 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
309 pub struct WhereBoundPredicate {
311 /// Any lifetimes from a `for` binding
312 pub bound_lifetimes: Vec<LifetimeDef>,
313 /// The type being bounded
314 pub bounded_ty: P<Ty>,
315 /// Trait and lifetime bounds (`Clone+Send+'static`)
316 pub bounds: OwnedSlice<TyParamBound>,
319 /// A lifetime predicate, e.g. `'a: 'b+'c`
320 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
321 pub struct WhereRegionPredicate {
323 pub lifetime: Lifetime,
324 pub bounds: Vec<Lifetime>,
327 /// An equality predicate (unsupported), e.g. `T=int`
328 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
329 pub struct WhereEqPredicate {
336 /// The set of MetaItems that define the compilation environment of the crate,
337 /// used to drive conditional compilation
338 pub type CrateConfig = Vec<P<MetaItem>> ;
340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
343 pub attrs: Vec<Attribute>,
344 pub config: CrateConfig,
346 pub exported_macros: Vec<MacroDef>,
349 /// A macro definition, in this crate or imported from another.
351 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
353 pub struct MacroDef {
355 pub attrs: Vec<Attribute>,
358 pub imported_from: Option<Ident>,
360 pub use_locally: bool,
361 pub allow_internal_unstable: bool,
362 pub body: Vec<TokenTree>,
365 pub type MetaItem = Spanned<MetaItem_>;
367 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
369 MetaWord(InternedString),
370 MetaList(InternedString, Vec<P<MetaItem>>),
371 MetaNameValue(InternedString, Lit),
374 // can't be derived because the MetaList requires an unordered comparison
375 impl PartialEq for MetaItem_ {
376 fn eq(&self, other: &MetaItem_) -> bool {
378 MetaWord(ref ns) => match *other {
379 MetaWord(ref no) => (*ns) == (*no),
382 MetaNameValue(ref ns, ref vs) => match *other {
383 MetaNameValue(ref no, ref vo) => {
384 (*ns) == (*no) && vs.node == vo.node
388 MetaList(ref ns, ref miss) => match *other {
389 MetaList(ref no, ref miso) => {
391 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
401 /// Statements in a block
402 pub stmts: Vec<P<Stmt>>,
403 /// An expression at the end of the block
404 /// without a semicolon, if any
405 pub expr: Option<P<Expr>>,
407 /// Distinguishes between `unsafe { ... }` and `{ ... }`
408 pub rules: BlockCheckMode,
412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
419 impl fmt::Debug for Pat {
420 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
421 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
425 /// A single field in a struct pattern
427 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
428 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
429 /// except is_shorthand is true
430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
431 pub struct FieldPat {
432 /// The identifier for the field
434 /// The pattern the field is destructured to
436 pub is_shorthand: bool,
439 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
440 pub enum BindingMode {
441 BindByRef(Mutability),
442 BindByValue(Mutability),
445 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
446 pub enum PatWildKind {
447 /// Represents the wildcard pattern `_`
450 /// Represents the wildcard pattern `..`
454 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
456 /// Represents a wildcard pattern (either `_` or `..`)
457 PatWild(PatWildKind),
459 /// A PatIdent may either be a new bound variable,
460 /// or a nullary enum (in which case the third field
463 /// In the nullary enum case, the parser can't determine
464 /// which it is. The resolver determines this, and
465 /// records this pattern's NodeId in an auxiliary
466 /// set (of "PatIdents that refer to nullary enums")
467 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
469 /// "None" means a * pattern where we don't bind the fields to names.
470 PatEnum(Path, Option<Vec<P<Pat>>>),
472 /// An associated const named using the qualified path `<T>::CONST` or
473 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
474 /// referred to as simply `T::CONST`, in which case they will end up as
475 /// PatEnum, and the resolver will have to sort that out.
476 PatQPath(QSelf, Path),
478 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
479 /// The `bool` is `true` in the presence of a `..`
480 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
481 /// A tuple pattern `(a, b)`
485 /// A reference pattern, e.g. `&mut (a, b)`
486 PatRegion(P<Pat>, Mutability),
489 /// A range pattern, e.g. `1...2`
490 PatRange(P<Expr>, P<Expr>),
491 /// [a, b, ..i, y, z] is represented as:
492 /// PatVec(box [a, b], Some(i), box [y, z])
493 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
496 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
497 pub enum Mutability {
502 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
504 /// The `+` operator (addition)
506 /// The `-` operator (subtraction)
508 /// The `*` operator (multiplication)
510 /// The `/` operator (division)
512 /// The `%` operator (modulus)
514 /// The `&&` operator (logical and)
516 /// The `||` operator (logical or)
518 /// The `^` operator (bitwise xor)
520 /// The `&` operator (bitwise and)
522 /// The `|` operator (bitwise or)
524 /// The `<<` operator (shift left)
526 /// The `>>` operator (shift right)
528 /// The `==` operator (equality)
530 /// The `<` operator (less than)
532 /// The `<=` operator (less than or equal to)
534 /// The `!=` operator (not equal to)
536 /// The `>=` operator (greater than or equal to)
538 /// The `>` operator (greater than)
542 pub type BinOp = Spanned<BinOp_>;
544 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
546 /// The `box` operator
548 /// The `*` operator for dereferencing
550 /// The `!` operator for logical inversion
552 /// The `-` operator for negation
557 pub type Stmt = Spanned<Stmt_>;
559 impl fmt::Debug for Stmt_ {
560 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
562 let spanned = codemap::dummy_spanned(self.clone());
563 write!(f, "stmt({}: {})",
564 util::stmt_id(&spanned),
565 pprust::stmt_to_string(&spanned))
569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
571 /// Could be an item or a local (let) binding:
572 StmtDecl(P<Decl>, NodeId),
574 /// Expr without trailing semi-colon (must have unit type):
575 StmtExpr(P<Expr>, NodeId),
577 /// Expr with trailing semi-colon (may have any type):
578 StmtSemi(P<Expr>, NodeId),
581 // FIXME (pending discussion of #1697, #2178...): local should really be
582 // a refinement on pat.
583 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
584 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
587 pub ty: Option<P<Ty>>,
588 /// Initializer expression to set the value, if any
589 pub init: Option<P<Expr>>,
594 pub type Decl = Spanned<Decl_>;
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
598 /// A local (let) binding:
604 /// represents one arm of a 'match'
605 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
607 pub attrs: Vec<Attribute>,
608 pub pats: Vec<P<Pat>>,
609 pub guard: Option<P<Expr>>,
613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
615 pub ident: SpannedIdent,
620 pub type SpannedIdent = Spanned<Ident>;
622 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
623 pub enum BlockCheckMode {
625 UnsafeBlock(UnsafeSource),
626 PushUnsafeBlock(UnsafeSource),
627 PopUnsafeBlock(UnsafeSource),
630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
631 pub enum UnsafeSource {
637 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
644 impl fmt::Debug for Expr {
645 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
652 /// First expr is the place; second expr is the value.
653 ExprBox(Option<P<Expr>>, P<Expr>),
654 /// An array (`[a, b, c, d]`)
655 ExprVec(Vec<P<Expr>>),
658 /// The first field resolves to the function itself,
659 /// and the second field is the list of arguments
660 ExprCall(P<Expr>, Vec<P<Expr>>),
661 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
663 /// The `SpannedIdent` is the identifier for the method name.
664 /// The vector of `Ty`s are the ascripted type parameters for the method
665 /// (within the angle brackets).
667 /// The first element of the vector of `Expr`s is the expression that evaluates
668 /// to the object on which the method is being called on (the receiver),
669 /// and the remaining elements are the rest of the arguments.
671 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
672 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
673 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
674 /// A tuple (`(a, b, c ,d)`)
675 ExprTup(Vec<P<Expr>>),
676 /// A binary operation (For example: `a + b`, `a * b`)
677 ExprBinary(BinOp, P<Expr>, P<Expr>),
678 /// A unary operation (For example: `!x`, `*x`)
679 ExprUnary(UnOp, P<Expr>),
680 /// A literal (For example: `1u8`, `"foo"`)
682 /// A cast (`foo as f64`)
683 ExprCast(P<Expr>, P<Ty>),
684 /// An `if` block, with an optional else block
686 /// `if expr { block } else { expr }`
687 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
688 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
689 /// A while loop, with an optional label
691 /// `'label: while expr { block }`
692 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
693 /// Conditionless loop (can be exited with break, continue, or return)
695 /// `'label: loop { block }`
696 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
697 ExprLoop(P<Block>, Option<Ident>),
698 /// A `match` block, with a source that indicates whether or not it is
699 /// the result of a desugaring, and if so, which kind.
700 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
701 /// A closure (for example, `move |a, b, c| {a + b + c}`)
702 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
703 /// A block (`{ ... }`)
706 /// An assignment (`a = foo()`)
707 ExprAssign(P<Expr>, P<Expr>),
708 /// An assignment with an operator
710 /// For example, `a += 1`.
711 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
712 /// Access of a named struct field (`obj.foo`)
713 ExprField(P<Expr>, SpannedIdent),
714 /// Access of an unnamed field of a struct or tuple-struct
716 /// For example, `foo.0`.
717 ExprTupField(P<Expr>, Spanned<usize>),
718 /// An indexing operation (`foo[2]`)
719 ExprIndex(P<Expr>, P<Expr>),
720 /// A range (`1..2`, `1..`, or `..2`)
721 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
723 /// Variable reference, possibly containing `::` and/or type
724 /// parameters, e.g. foo::bar::<baz>.
726 /// Optionally "qualified",
727 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
728 ExprPath(Option<QSelf>, Path),
730 /// A referencing operation (`&a` or `&mut a`)
731 ExprAddrOf(Mutability, P<Expr>),
732 /// A `break`, with an optional label to break
733 ExprBreak(Option<SpannedIdent>),
734 /// A `continue`, with an optional label
735 ExprAgain(Option<SpannedIdent>),
736 /// A `return`, with an optional value to be returned
737 ExprRet(Option<P<Expr>>),
739 /// Output of the `asm!()` macro
740 ExprInlineAsm(InlineAsm),
742 /// A struct literal expression.
744 /// For example, `Foo {x: 1, y: 2}`, or
745 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
746 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
748 /// A vector literal constructed from one repeated element.
750 /// For example, `[1u8; 5]`. The first expression is the element
751 /// to be repeated; the second is the number of times to repeat it.
752 ExprRepeat(P<Expr>, P<Expr>),
754 /// No-op: used solely so we can pretty-print faithfully
758 /// The explicit Self type in a "qualified path". The actual
759 /// path, including the trait and the associated item, is stored
760 /// separately. `position` represents the index of the associated
761 /// item qualified with this Self type.
763 /// <Vec<T> as a::b::Trait>::AssociatedItem
764 /// ^~~~~ ~~~~~~~~~~~~~~^
767 /// <Vec<T>>::AssociatedItem
770 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
776 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
777 pub enum MatchSource {
779 IfLetDesugar { contains_else_clause: bool },
784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
785 pub enum CaptureClause {
791 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
793 /// A regular string, like `"foo"`
795 /// A raw string, like `r##"foo"##`
797 /// The uint is the number of `#` symbols used
802 pub type Lit = Spanned<Lit_>;
804 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
811 pub fn new<T: IntSign>(n: T) -> Sign {
817 fn sign(&self) -> Sign;
820 ($($t:ident)*) => ($(impl IntSign for $t {
821 #[allow(unused_comparisons)]
822 fn sign(&self) -> Sign {
823 if *self < 0 {Minus} else {Plus}
827 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
829 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
830 pub enum LitIntType {
831 SignedIntLit(IntTy, Sign),
832 UnsignedIntLit(UintTy),
833 UnsuffixedIntLit(Sign)
836 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
838 /// A string literal (`"foo"`)
839 LitStr(InternedString, StrStyle),
840 /// A byte string (`b"foo"`)
841 LitByteStr(Rc<Vec<u8>>),
842 /// A byte char (`b'f'`)
844 /// A character literal (`'a'`)
846 /// An integer literal (`1u8`)
847 LitInt(u64, LitIntType),
848 /// A float literal (`1f64` or `1E10f64`)
849 LitFloat(InternedString, FloatTy),
850 /// A float literal without a suffix (`1.0 or 1.0E10`)
851 LitFloatUnsuffixed(InternedString),
852 /// A boolean literal
856 // NB: If you change this, you'll probably want to change the corresponding
857 // type structure in middle/ty.rs as well.
858 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
861 pub mutbl: Mutability,
864 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
865 pub struct TypeField {
871 /// Represents a method's signature in a trait declaration,
872 /// or in an implementation.
873 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
874 pub struct MethodSig {
875 pub unsafety: Unsafety,
876 pub constness: Constness,
879 pub generics: Generics,
880 pub explicit_self: ExplicitSelf,
883 /// Represents a method declaration in a trait declaration, possibly including
884 /// a default implementation A trait method is either required (meaning it
885 /// doesn't have an implementation, just a signature) or provided (meaning it
886 /// has a default implementation).
887 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
888 pub struct TraitItem {
891 pub attrs: Vec<Attribute>,
892 pub node: TraitItem_,
896 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
897 pub enum TraitItem_ {
898 ConstTraitItem(P<Ty>, Option<P<Expr>>),
899 MethodTraitItem(MethodSig, Option<P<Block>>),
900 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
903 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
904 pub struct ImplItem {
908 pub attrs: Vec<Attribute>,
913 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
915 ConstImplItem(P<Ty>, P<Expr>),
916 MethodImplItem(MethodSig, P<Block>),
920 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
929 impl fmt::Debug for IntTy {
930 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
931 fmt::Display::fmt(self, f)
935 impl fmt::Display for IntTy {
936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
937 write!(f, "{}", util::int_ty_to_string(*self, None))
942 pub fn bit_width(&self) -> Option<usize> {
953 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
963 pub fn bit_width(&self) -> Option<usize> {
974 impl fmt::Debug for UintTy {
975 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
976 fmt::Display::fmt(self, f)
980 impl fmt::Display for UintTy {
981 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
982 write!(f, "{}", util::uint_ty_to_string(*self, None))
986 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
992 impl fmt::Debug for FloatTy {
993 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
994 fmt::Display::fmt(self, f)
998 impl fmt::Display for FloatTy {
999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1000 write!(f, "{}", util::float_ty_to_string(*self))
1005 pub fn bit_width(&self) -> usize {
1013 // Bind a type to an associated type: `A=Foo`.
1014 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1015 pub struct TypeBinding {
1023 // NB PartialEq method appears below.
1024 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1031 impl fmt::Debug for Ty {
1032 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1033 write!(f, "type({})", pprust::ty_to_string(self))
1037 /// Not represented directly in the AST, referred to by name through a ty_path.
1038 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1048 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1049 pub struct BareFnTy {
1050 pub unsafety: Unsafety,
1052 pub lifetimes: Vec<LifetimeDef>,
1056 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1057 /// The different kinds of types recognized by the compiler
1060 /// A fixed length array (`[T; n]`)
1061 TyFixedLengthVec(P<Ty>, P<Expr>),
1062 /// A raw pointer (`*const T` or `*mut T`)
1064 /// A reference (`&'a T` or `&'a mut T`)
1065 TyRptr(Option<Lifetime>, MutTy),
1066 /// A bare function (e.g. `fn(usize) -> bool`)
1067 TyBareFn(P<BareFnTy>),
1068 /// A tuple (`(A, B, C, D,...)`)
1070 /// A path (`module::module::...::Type`), optionally
1071 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1073 /// Type parameters are stored in the Path itself
1074 TyPath(Option<QSelf>, Path),
1075 /// Something like `A+B`. Note that `B` must always be a path.
1076 TyObjectSum(P<Ty>, TyParamBounds),
1077 /// A type like `for<'a> Foo<&'a Bar>`
1078 TyPolyTraitRef(TyParamBounds),
1079 /// No-op; kept solely so that we can pretty-print faithfully
1083 /// TyInfer means the type should be inferred instead of it having been
1084 /// specified. This can appear anywhere in a type.
1088 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1089 pub enum AsmDialect {
1094 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1095 pub struct InlineAsm {
1096 pub asm: InternedString,
1097 pub asm_str_style: StrStyle,
1098 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1099 pub inputs: Vec<(InternedString, P<Expr>)>,
1100 pub clobbers: Vec<InternedString>,
1102 pub alignstack: bool,
1103 pub dialect: AsmDialect,
1104 pub expn_id: ExpnId,
1107 /// represents an argument in a function header
1108 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1116 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1117 let path = Spanned{span:span,node:self_ident};
1119 // HACK(eddyb) fake type for the self argument.
1127 node: PatIdent(BindByValue(mutability), path, None),
1135 /// Represents the header (not the body) of a function declaration
1136 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1138 pub inputs: Vec<Arg>,
1139 pub output: FunctionRetTy,
1143 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1149 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1150 pub enum Constness {
1155 impl fmt::Display for Unsafety {
1156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1157 fmt::Display::fmt(match *self {
1158 Unsafety::Normal => "normal",
1159 Unsafety::Unsafe => "unsafe",
1164 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1165 pub enum ImplPolarity {
1166 /// `impl Trait for Type`
1168 /// `impl !Trait for Type`
1172 impl fmt::Debug for ImplPolarity {
1173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1175 ImplPolarity::Positive => "positive".fmt(f),
1176 ImplPolarity::Negative => "negative".fmt(f),
1182 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1183 pub enum FunctionRetTy {
1184 /// Functions with return type `!`that always
1185 /// raise an error or exit (i.e. never return to the caller)
1187 /// Return type is not specified.
1189 /// Functions default to `()` and
1190 /// closures default to inference. Span points to where return
1191 /// type would be inserted.
1192 DefaultReturn(Span),
1197 impl FunctionRetTy {
1198 pub fn span(&self) -> Span {
1200 NoReturn(span) => span,
1201 DefaultReturn(span) => span,
1202 Return(ref ty) => ty.span
1207 /// Represents the kind of 'self' associated with a method
1208 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1209 pub enum ExplicitSelf_ {
1214 /// `&'lt self`, `&'lt mut self`
1215 SelfRegion(Option<Lifetime>, Mutability, Ident),
1217 SelfExplicit(P<Ty>, Ident),
1220 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1224 /// A span from the first token past `{` to the last token until `}`.
1225 /// For `mod foo;`, the inner span ranges from the first token
1226 /// to the last token in the external file.
1228 pub items: Vec<P<Item>>,
1231 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1232 pub struct ForeignMod {
1234 pub items: Vec<P<ForeignItem>>,
1237 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1238 pub struct VariantArg {
1243 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1244 pub enum VariantKind {
1245 /// Tuple variant, e.g. `Foo(A, B)`
1246 TupleVariantKind(Vec<VariantArg>),
1247 /// Struct variant, e.g. `Foo {x: A, y: B}`
1248 StructVariantKind(P<StructDef>),
1251 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1252 pub struct EnumDef {
1253 pub variants: Vec<P<Variant>>,
1256 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1257 pub struct Variant_ {
1259 pub attrs: Vec<Attribute>,
1260 pub kind: VariantKind,
1262 /// Explicit discriminant, eg `Foo = 1`
1263 pub disr_expr: Option<P<Expr>>,
1264 pub vis: Visibility,
1267 pub type Variant = Spanned<Variant_>;
1269 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1270 pub enum PathListItem_ {
1273 /// renamed in list, eg `use foo::{bar as baz};`
1274 rename: Option<Ident>,
1278 /// renamed in list, eg `use foo::{self as baz};`
1279 rename: Option<Ident>,
1284 impl PathListItem_ {
1285 pub fn id(&self) -> NodeId {
1287 PathListIdent { id, .. } | PathListMod { id, .. } => id
1291 pub fn rename(&self) -> Option<Ident> {
1293 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1298 pub type PathListItem = Spanned<PathListItem_>;
1300 pub type ViewPath = Spanned<ViewPath_>;
1302 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1303 pub enum ViewPath_ {
1305 /// `foo::bar::baz as quux`
1309 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1310 ViewPathSimple(Ident, Path),
1315 /// `foo::bar::{a,b,c}`
1316 ViewPathList(Path, Vec<PathListItem>)
1319 /// Meta-data associated with an item
1320 pub type Attribute = Spanned<Attribute_>;
1322 /// Distinguishes between Attributes that decorate items and Attributes that
1323 /// are contained as statements within items. These two cases need to be
1324 /// distinguished for pretty-printing.
1325 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1326 pub enum AttrStyle {
1331 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1332 pub struct AttrId(pub usize);
1334 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1335 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1336 pub struct Attribute_ {
1338 pub style: AttrStyle,
1339 pub value: P<MetaItem>,
1340 pub is_sugared_doc: bool,
1343 /// TraitRef's appear in impls.
1345 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1346 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1347 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1348 /// same as the impl's node id).
1349 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1350 pub struct TraitRef {
1355 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1356 pub struct PolyTraitRef {
1357 /// The `'a` in `<'a> Foo<&'a T>`
1358 pub bound_lifetimes: Vec<LifetimeDef>,
1360 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1361 pub trait_ref: TraitRef,
1366 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1367 pub enum Visibility {
1373 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1375 &Inherited => parent_visibility,
1381 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1382 pub struct StructField_ {
1383 pub kind: StructFieldKind,
1386 pub attrs: Vec<Attribute>,
1390 pub fn ident(&self) -> Option<Ident> {
1392 NamedField(ref ident, _) => Some(ident.clone()),
1393 UnnamedField(_) => None
1398 pub type StructField = Spanned<StructField_>;
1400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1401 pub enum StructFieldKind {
1402 NamedField(Ident, Visibility),
1403 /// Element of a tuple-like struct
1404 UnnamedField(Visibility),
1407 impl StructFieldKind {
1408 pub fn is_unnamed(&self) -> bool {
1410 UnnamedField(..) => true,
1411 NamedField(..) => false,
1416 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1417 pub struct StructDef {
1418 /// Fields, not including ctor
1419 pub fields: Vec<StructField>,
1420 /// ID of the constructor. This is only used for tuple- or enum-like
1422 pub ctor_id: Option<NodeId>,
1426 FIXME (#3300): Should allow items to be anonymous. Right now
1427 we just use dummy names for anon items.
1431 /// The name might be a dummy name in case of anonymous items
1432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1435 pub attrs: Vec<Attribute>,
1438 pub vis: Visibility,
1442 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1444 /// An`extern crate` item, with optional original crate name,
1446 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1447 ItemExternCrate(Option<Name>),
1448 /// A `use` or `pub use` item
1449 ItemUse(P<ViewPath>),
1452 ItemStatic(P<Ty>, Mutability, P<Expr>),
1454 ItemConst(P<Ty>, P<Expr>),
1455 /// A function declaration
1456 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1459 /// An external module
1460 ItemForeignMod(ForeignMod),
1461 /// A type alias, e.g. `type Foo = Bar<u8>`
1462 ItemTy(P<Ty>, Generics),
1463 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1464 ItemEnum(EnumDef, Generics),
1465 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1466 ItemStruct(P<StructDef>, Generics),
1467 /// Represents a Trait Declaration
1473 // Default trait implementations
1475 // `impl Trait for .. {}`
1476 ItemDefaultImpl(Unsafety, TraitRef),
1477 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1481 Option<TraitRef>, // (optional) trait this impl implements
1487 pub fn descriptive_variant(&self) -> &str {
1489 ItemExternCrate(..) => "extern crate",
1490 ItemUse(..) => "use",
1491 ItemStatic(..) => "static item",
1492 ItemConst(..) => "constant item",
1493 ItemFn(..) => "function",
1494 ItemMod(..) => "module",
1495 ItemForeignMod(..) => "foreign module",
1496 ItemTy(..) => "type alias",
1497 ItemEnum(..) => "enum",
1498 ItemStruct(..) => "struct",
1499 ItemTrait(..) => "trait",
1501 ItemDefaultImpl(..) => "item"
1506 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1507 pub struct ForeignItem {
1509 pub attrs: Vec<Attribute>,
1510 pub node: ForeignItem_,
1513 pub vis: Visibility,
1516 /// An item within an `extern` block
1517 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1518 pub enum ForeignItem_ {
1519 /// A foreign function
1520 ForeignItemFn(P<FnDecl>, Generics),
1521 /// A foreign static item (`static ext: u8`), with optional mutability
1522 /// (the boolean is true when mutable)
1523 ForeignItemStatic(P<Ty>, bool),
1527 pub fn descriptive_variant(&self) -> &str {
1529 ForeignItemFn(..) => "foreign function",
1530 ForeignItemStatic(..) => "foreign static item"