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::Item_::*;
23 pub use self::Mutability::*;
24 pub use self::Pat_::*;
25 pub use self::PathListItem_::*;
26 pub use self::PrimTy::*;
27 pub use self::Stmt_::*;
28 pub use self::StructFieldKind::*;
29 pub use self::TraitItem_::*;
31 pub use self::TyParamBound::*;
32 pub use self::UnOp::*;
33 pub use self::UnsafeSource::*;
34 pub use self::ViewPath_::*;
35 pub use self::Visibility::*;
36 pub use self::PathParameters::*;
38 use intravisit::Visitor;
39 use std::collections::BTreeMap;
40 use syntax::codemap::{self, Span, Spanned, DUMMY_SP, ExpnId};
42 use syntax::ast::{Name, Ident, NodeId, DUMMY_NODE_ID, TokenTree, AsmDialect};
43 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, CrateConfig};
44 use syntax::owned_slice::OwnedSlice;
45 use syntax::parse::token::InternedString;
52 use serialize::{Encodable, Encoder, Decoder};
54 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
61 impl fmt::Debug for Lifetime {
62 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 pprust::lifetime_to_string(self))
70 /// A lifetime definition, eg `'a: 'b+'c+'d`
71 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
72 pub struct LifetimeDef {
73 pub lifetime: Lifetime,
74 pub bounds: Vec<Lifetime>,
77 /// A "Path" is essentially Rust's notion of a name; for instance:
78 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
79 /// along with a bunch of supporting information.
80 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
83 /// A `::foo` path, is relative to the crate root rather than current
84 /// module (like paths in an import).
86 /// The segments in the path: the things separated by `::`.
87 pub segments: Vec<PathSegment>,
90 impl fmt::Debug for Path {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 write!(f, "path({})", pprust::path_to_string(self))
96 impl fmt::Display for Path {
97 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98 write!(f, "{}", pprust::path_to_string(self))
102 /// A segment of a path: an identifier, an optional lifetime, and a set of
104 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
105 pub struct PathSegment {
106 /// The identifier portion of this path segment.
107 pub identifier: Ident,
109 /// Type/lifetime parameters attached to this path. They come in
110 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
111 /// this is more than just simple syntactic sugar; the use of
112 /// parens affects the region binding rules, so we preserve the
114 pub parameters: PathParameters,
117 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
118 pub enum PathParameters {
119 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
120 AngleBracketedParameters(AngleBracketedParameterData),
121 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
122 ParenthesizedParameters(ParenthesizedParameterData),
125 impl PathParameters {
126 pub fn none() -> PathParameters {
127 AngleBracketedParameters(AngleBracketedParameterData {
128 lifetimes: Vec::new(),
129 types: OwnedSlice::empty(),
130 bindings: OwnedSlice::empty(),
134 pub fn is_empty(&self) -> bool {
136 AngleBracketedParameters(ref data) => data.is_empty(),
138 // Even if the user supplied no types, something like
139 // `X()` is equivalent to `X<(),()>`.
140 ParenthesizedParameters(..) => false,
144 pub fn has_lifetimes(&self) -> bool {
146 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
147 ParenthesizedParameters(_) => false,
151 pub fn has_types(&self) -> bool {
153 AngleBracketedParameters(ref data) => !data.types.is_empty(),
154 ParenthesizedParameters(..) => true,
158 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
159 /// parameters in the parenthesized case.
160 pub fn types(&self) -> Vec<&P<Ty>> {
162 AngleBracketedParameters(ref data) => {
163 data.types.iter().collect()
165 ParenthesizedParameters(ref data) => {
168 .chain(data.output.iter())
174 pub fn lifetimes(&self) -> Vec<&Lifetime> {
176 AngleBracketedParameters(ref data) => {
177 data.lifetimes.iter().collect()
179 ParenthesizedParameters(_) => {
185 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
187 AngleBracketedParameters(ref data) => {
188 data.bindings.iter().collect()
190 ParenthesizedParameters(_) => {
197 /// A path like `Foo<'a, T>`
198 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
199 pub struct AngleBracketedParameterData {
200 /// The lifetime parameters for this path segment.
201 pub lifetimes: Vec<Lifetime>,
202 /// The type parameters for this path segment, if present.
203 pub types: OwnedSlice<P<Ty>>,
204 /// Bindings (equality constraints) on associated types, if present.
205 /// E.g., `Foo<A=Bar>`.
206 pub bindings: OwnedSlice<P<TypeBinding>>,
209 impl AngleBracketedParameterData {
210 fn is_empty(&self) -> bool {
211 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
215 /// A path like `Foo(A,B) -> C`
216 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
217 pub struct ParenthesizedParameterData {
222 pub inputs: Vec<P<Ty>>,
225 pub output: Option<P<Ty>>,
228 /// The AST represents all type param bounds as types.
229 /// typeck::collect::compute_bounds matches these against
230 /// the "special" built-in traits (see middle::lang_items) and
231 /// detects Copy, Send and Sync.
232 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
233 pub enum TyParamBound {
234 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
235 RegionTyParamBound(Lifetime),
238 /// A modifier on a bound, currently this is only used for `?Sized`, where the
239 /// modifier is `Maybe`. Negative bounds should also be handled here.
240 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
241 pub enum TraitBoundModifier {
246 pub type TyParamBounds = OwnedSlice<TyParamBound>;
248 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
252 pub bounds: TyParamBounds,
253 pub default: Option<P<Ty>>,
257 /// Represents lifetimes and type parameters attached to a declaration
258 /// of a function, enum, trait, etc.
259 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
260 pub struct Generics {
261 pub lifetimes: Vec<LifetimeDef>,
262 pub ty_params: OwnedSlice<TyParam>,
263 pub where_clause: WhereClause,
267 pub fn is_lt_parameterized(&self) -> bool {
268 !self.lifetimes.is_empty()
270 pub fn is_type_parameterized(&self) -> bool {
271 !self.ty_params.is_empty()
273 pub fn is_parameterized(&self) -> bool {
274 self.is_lt_parameterized() || self.is_type_parameterized()
278 /// A `where` clause in a definition
279 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
280 pub struct WhereClause {
282 pub predicates: Vec<WherePredicate>,
285 /// A single predicate in a `where` clause
286 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
287 pub enum WherePredicate {
288 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
289 BoundPredicate(WhereBoundPredicate),
290 /// A lifetime predicate, e.g. `'a: 'b+'c`
291 RegionPredicate(WhereRegionPredicate),
292 /// An equality predicate (unsupported)
293 EqPredicate(WhereEqPredicate),
296 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
297 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
298 pub struct WhereBoundPredicate {
300 /// Any lifetimes from a `for` binding
301 pub bound_lifetimes: Vec<LifetimeDef>,
302 /// The type being bounded
303 pub bounded_ty: P<Ty>,
304 /// Trait and lifetime bounds (`Clone+Send+'static`)
305 pub bounds: OwnedSlice<TyParamBound>,
308 /// A lifetime predicate, e.g. `'a: 'b+'c`
309 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
310 pub struct WhereRegionPredicate {
312 pub lifetime: Lifetime,
313 pub bounds: Vec<Lifetime>,
316 /// An equality predicate (unsupported), e.g. `T=int`
317 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
318 pub struct WhereEqPredicate {
325 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
328 pub attrs: Vec<Attribute>,
329 pub config: CrateConfig,
331 pub exported_macros: Vec<MacroDef>,
333 // NB: We use a BTreeMap here so that `visit_all_items` iterates
334 // over the ids in increasing order. In principle it should not
335 // matter what order we visit things in, but in *practice* it
336 // does, because it can affect the order in which errors are
337 // detected, which in turn can make compile-fail tests yield
338 // slightly different results.
339 pub items: BTreeMap<NodeId, Item>,
343 pub fn item(&self, id: NodeId) -> &Item {
347 /// Visits all items in the crate in some determinstic (but
348 /// unspecified) order. If you just need to process every item,
349 /// but don't care about nesting, this method is the best choice.
351 /// If you do care about nesting -- usually because your algorithm
352 /// follows lexical scoping rules -- then you want a different
353 /// approach. You should override `visit_nested_item` in your
354 /// visitor and then call `intravisit::walk_crate` instead.
355 pub fn visit_all_items<'hir, V:Visitor<'hir>>(&'hir self, visitor: &mut V) {
356 for (_, item) in &self.items {
357 visitor.visit_item(item);
362 /// A macro definition, in this crate or imported from another.
364 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
365 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
366 pub struct MacroDef {
368 pub attrs: Vec<Attribute>,
371 pub imported_from: Option<Name>,
373 pub use_locally: bool,
374 pub allow_internal_unstable: bool,
375 pub body: Vec<TokenTree>,
378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
380 /// Statements in a block
381 pub stmts: Vec<P<Stmt>>,
382 /// An expression at the end of the block
383 /// without a semicolon, if any
384 pub expr: Option<P<Expr>>,
386 /// Distinguishes between `unsafe { ... }` and `{ ... }`
387 pub rules: BlockCheckMode,
391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
398 impl fmt::Debug for Pat {
399 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
400 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
404 /// A single field in a struct pattern
406 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
407 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
408 /// except is_shorthand is true
409 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
410 pub struct FieldPat {
411 /// The identifier for the field
413 /// The pattern the field is destructured to
415 pub is_shorthand: bool,
418 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
419 pub enum BindingMode {
420 BindByRef(Mutability),
421 BindByValue(Mutability),
424 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
426 /// Represents a wildcard pattern (`_`)
429 /// A PatIdent may either be a new bound variable,
430 /// or a nullary enum (in which case the third field
433 /// In the nullary enum case, the parser can't determine
434 /// which it is. The resolver determines this, and
435 /// records this pattern's NodeId in an auxiliary
436 /// set (of "PatIdents that refer to nullary enums")
437 PatIdent(BindingMode, Spanned<Ident>, Option<P<Pat>>),
439 /// "None" means a `Variant(..)` pattern where we don't bind the fields to names.
440 PatEnum(Path, Option<Vec<P<Pat>>>),
442 /// An associated const named using the qualified path `<T>::CONST` or
443 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
444 /// referred to as simply `T::CONST`, in which case they will end up as
445 /// PatEnum, and the resolver will have to sort that out.
446 PatQPath(QSelf, Path),
448 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
449 /// The `bool` is `true` in the presence of a `..`
450 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
451 /// A tuple pattern `(a, b)`
455 /// A reference pattern, e.g. `&mut (a, b)`
456 PatRegion(P<Pat>, Mutability),
459 /// A range pattern, e.g. `1...2`
460 PatRange(P<Expr>, P<Expr>),
461 /// `[a, b, ..i, y, z]` is represented as:
462 /// `PatVec(box [a, b], Some(i), box [y, z])`
463 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
466 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
467 pub enum Mutability {
472 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
474 /// The `+` operator (addition)
476 /// The `-` operator (subtraction)
478 /// The `*` operator (multiplication)
480 /// The `/` operator (division)
482 /// The `%` operator (modulus)
484 /// The `&&` operator (logical and)
486 /// The `||` operator (logical or)
488 /// The `^` operator (bitwise xor)
490 /// The `&` operator (bitwise and)
492 /// The `|` operator (bitwise or)
494 /// The `<<` operator (shift left)
496 /// The `>>` operator (shift right)
498 /// The `==` operator (equality)
500 /// The `<` operator (less than)
502 /// The `<=` operator (less than or equal to)
504 /// The `!=` operator (not equal to)
506 /// The `>=` operator (greater than or equal to)
508 /// The `>` operator (greater than)
512 pub type BinOp = Spanned<BinOp_>;
514 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
516 /// The `*` operator for dereferencing
518 /// The `!` operator for logical inversion
520 /// The `-` operator for negation
525 pub type Stmt = Spanned<Stmt_>;
527 impl fmt::Debug for Stmt_ {
528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
530 let spanned = codemap::dummy_spanned(self.clone());
533 util::stmt_id(&spanned),
534 pprust::stmt_to_string(&spanned))
538 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
540 /// Could be an item or a local (let) binding:
541 StmtDecl(P<Decl>, NodeId),
543 /// Expr without trailing semi-colon (must have unit type):
544 StmtExpr(P<Expr>, NodeId),
546 /// Expr with trailing semi-colon (may have any type):
547 StmtSemi(P<Expr>, NodeId),
550 // FIXME (pending discussion of #1697, #2178...): local should really be
551 // a refinement on pat.
552 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
553 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
556 pub ty: Option<P<Ty>>,
557 /// Initializer expression to set the value, if any
558 pub init: Option<P<Expr>>,
563 pub type Decl = Spanned<Decl_>;
565 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
567 /// A local (let) binding:
573 /// represents one arm of a 'match'
574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
576 pub attrs: Vec<Attribute>,
577 pub pats: Vec<P<Pat>>,
578 pub guard: Option<P<Expr>>,
582 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
584 pub name: Spanned<Name>,
589 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
590 pub enum BlockCheckMode {
592 UnsafeBlock(UnsafeSource),
593 PushUnsafeBlock(UnsafeSource),
594 PopUnsafeBlock(UnsafeSource),
595 // Within this block (but outside a PopUnstableBlock), we suspend checking of stability.
600 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
601 pub enum UnsafeSource {
607 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
614 impl fmt::Debug for Expr {
615 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
616 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
620 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
622 /// A `box x` expression.
624 /// An array (`[a, b, c, d]`)
625 ExprVec(Vec<P<Expr>>),
628 /// The first field resolves to the function itself,
629 /// and the second field is the list of arguments
630 ExprCall(P<Expr>, Vec<P<Expr>>),
631 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
633 /// The `Spanned<Name>` is the identifier for the method name.
634 /// The vector of `Ty`s are the ascripted type parameters for the method
635 /// (within the angle brackets).
637 /// The first element of the vector of `Expr`s is the expression that evaluates
638 /// to the object on which the method is being called on (the receiver),
639 /// and the remaining elements are the rest of the arguments.
641 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
642 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
643 ExprMethodCall(Spanned<Name>, Vec<P<Ty>>, Vec<P<Expr>>),
644 /// A tuple (`(a, b, c ,d)`)
645 ExprTup(Vec<P<Expr>>),
646 /// A binary operation (For example: `a + b`, `a * b`)
647 ExprBinary(BinOp, P<Expr>, P<Expr>),
648 /// A unary operation (For example: `!x`, `*x`)
649 ExprUnary(UnOp, P<Expr>),
650 /// A literal (For example: `1u8`, `"foo"`)
652 /// A cast (`foo as f64`)
653 ExprCast(P<Expr>, P<Ty>),
654 /// An `if` block, with an optional else block
656 /// `if expr { block } else { expr }`
657 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
658 /// A while loop, with an optional label
660 /// `'label: while expr { block }`
661 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
662 /// Conditionless loop (can be exited with break, continue, or return)
664 /// `'label: loop { block }`
665 ExprLoop(P<Block>, Option<Ident>),
666 /// A `match` block, with a source that indicates whether or not it is
667 /// the result of a desugaring, and if so, which kind.
668 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
669 /// A closure (for example, `move |a, b, c| {a + b + c}`)
670 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
671 /// A block (`{ ... }`)
674 /// An assignment (`a = foo()`)
675 ExprAssign(P<Expr>, P<Expr>),
676 /// An assignment with an operator
678 /// For example, `a += 1`.
679 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
680 /// Access of a named struct field (`obj.foo`)
681 ExprField(P<Expr>, Spanned<Name>),
682 /// Access of an unnamed field of a struct or tuple-struct
684 /// For example, `foo.0`.
685 ExprTupField(P<Expr>, Spanned<usize>),
686 /// An indexing operation (`foo[2]`)
687 ExprIndex(P<Expr>, P<Expr>),
688 /// A range (`1..2`, `1..`, or `..2`)
689 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
691 /// Variable reference, possibly containing `::` and/or type
692 /// parameters, e.g. foo::bar::<baz>.
694 /// Optionally "qualified",
695 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
696 ExprPath(Option<QSelf>, Path),
698 /// A referencing operation (`&a` or `&mut a`)
699 ExprAddrOf(Mutability, P<Expr>),
700 /// A `break`, with an optional label to break
701 ExprBreak(Option<Spanned<Ident>>),
702 /// A `continue`, with an optional label
703 ExprAgain(Option<Spanned<Ident>>),
704 /// A `return`, with an optional value to be returned
705 ExprRet(Option<P<Expr>>),
707 /// Output of the `asm!()` macro
708 ExprInlineAsm(InlineAsm),
710 /// A struct literal expression.
712 /// For example, `Foo {x: 1, y: 2}`, or
713 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
714 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
716 /// A vector literal constructed from one repeated element.
718 /// For example, `[1u8; 5]`. The first expression is the element
719 /// to be repeated; the second is the number of times to repeat it.
720 ExprRepeat(P<Expr>, P<Expr>),
723 /// The explicit Self type in a "qualified path". The actual
724 /// path, including the trait and the associated item, is stored
725 /// separately. `position` represents the index of the associated
726 /// item qualified with this Self type.
728 /// <Vec<T> as a::b::Trait>::AssociatedItem
729 /// ^~~~~ ~~~~~~~~~~~~~~^
732 /// <Vec<T>>::AssociatedItem
735 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
741 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
742 pub enum MatchSource {
745 contains_else_clause: bool,
751 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
752 pub enum CaptureClause {
757 // NB: If you change this, you'll probably want to change the corresponding
758 // type structure in middle/ty.rs as well.
759 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
762 pub mutbl: Mutability,
765 /// Represents a method's signature in a trait declaration,
766 /// or in an implementation.
767 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
768 pub struct MethodSig {
769 pub unsafety: Unsafety,
770 pub constness: Constness,
773 pub generics: Generics,
774 pub explicit_self: ExplicitSelf,
777 /// Represents a method declaration in a trait declaration, possibly including
778 /// a default implementation A trait method is either required (meaning it
779 /// doesn't have an implementation, just a signature) or provided (meaning it
780 /// has a default implementation).
781 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
782 pub struct TraitItem {
785 pub attrs: Vec<Attribute>,
786 pub node: TraitItem_,
790 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
791 pub enum TraitItem_ {
792 ConstTraitItem(P<Ty>, Option<P<Expr>>),
793 MethodTraitItem(MethodSig, Option<P<Block>>),
794 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
797 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
798 pub struct ImplItem {
802 pub attrs: Vec<Attribute>,
803 pub node: ImplItemKind,
807 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
808 pub enum ImplItemKind {
809 Const(P<Ty>, P<Expr>),
810 Method(MethodSig, P<Block>),
814 // Bind a type to an associated type: `A=Foo`.
815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
816 pub struct TypeBinding {
824 // NB PartialEq method appears below.
825 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
832 impl fmt::Debug for Ty {
833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
834 write!(f, "type({})", pprust::ty_to_string(self))
838 /// Not represented directly in the AST, referred to by name through a ty_path.
839 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
849 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
850 pub struct BareFnTy {
851 pub unsafety: Unsafety,
853 pub lifetimes: Vec<LifetimeDef>,
857 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
858 /// The different kinds of types recognized by the compiler
861 /// A fixed length array (`[T; n]`)
862 TyFixedLengthVec(P<Ty>, P<Expr>),
863 /// A raw pointer (`*const T` or `*mut T`)
865 /// A reference (`&'a T` or `&'a mut T`)
866 TyRptr(Option<Lifetime>, MutTy),
867 /// A bare function (e.g. `fn(usize) -> bool`)
868 TyBareFn(P<BareFnTy>),
869 /// A tuple (`(A, B, C, D,...)`)
871 /// A path (`module::module::...::Type`), optionally
872 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
874 /// Type parameters are stored in the Path itself
875 TyPath(Option<QSelf>, Path),
876 /// Something like `A+B`. Note that `B` must always be a path.
877 TyObjectSum(P<Ty>, TyParamBounds),
878 /// A type like `for<'a> Foo<&'a Bar>`
879 TyPolyTraitRef(TyParamBounds),
882 /// TyInfer means the type should be inferred instead of it having been
883 /// specified. This can appear anywhere in a type.
887 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
888 pub struct InlineAsm {
889 pub asm: InternedString,
890 pub asm_str_style: StrStyle,
891 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
892 pub inputs: Vec<(InternedString, P<Expr>)>,
893 pub clobbers: Vec<InternedString>,
895 pub alignstack: bool,
896 pub dialect: AsmDialect,
900 /// represents an argument in a function header
901 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
909 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
915 // HACK(eddyb) fake type for the self argument.
923 node: PatIdent(BindByValue(mutability), path, None),
931 /// Represents the header (not the body) of a function declaration
932 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
934 pub inputs: Vec<Arg>,
935 pub output: FunctionRetTy,
939 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
945 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
951 impl fmt::Display for Unsafety {
952 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
953 fmt::Display::fmt(match *self {
954 Unsafety::Normal => "normal",
955 Unsafety::Unsafe => "unsafe",
961 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
962 pub enum ImplPolarity {
963 /// `impl Trait for Type`
965 /// `impl !Trait for Type`
969 impl fmt::Debug for ImplPolarity {
970 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
972 ImplPolarity::Positive => "positive".fmt(f),
973 ImplPolarity::Negative => "negative".fmt(f),
979 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
980 pub enum FunctionRetTy {
981 /// Functions with return type `!`that always
982 /// raise an error or exit (i.e. never return to the caller)
984 /// Return type is not specified.
986 /// Functions default to `()` and
987 /// closures default to inference. Span points to where return
988 /// type would be inserted.
995 pub fn span(&self) -> Span {
997 NoReturn(span) => span,
998 DefaultReturn(span) => span,
999 Return(ref ty) => ty.span,
1004 /// Represents the kind of 'self' associated with a method
1005 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1006 pub enum ExplicitSelf_ {
1011 /// `&'lt self`, `&'lt mut self`
1012 SelfRegion(Option<Lifetime>, Mutability, Name),
1014 SelfExplicit(P<Ty>, Name),
1017 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1019 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1021 /// A span from the first token past `{` to the last token until `}`.
1022 /// For `mod foo;`, the inner span ranges from the first token
1023 /// to the last token in the external file.
1025 pub item_ids: Vec<ItemId>,
1028 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1029 pub struct ForeignMod {
1031 pub items: Vec<P<ForeignItem>>,
1034 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1035 pub struct EnumDef {
1036 pub variants: Vec<P<Variant>>,
1039 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1040 pub struct Variant_ {
1042 pub attrs: Vec<Attribute>,
1043 pub data: VariantData,
1044 /// Explicit discriminant, eg `Foo = 1`
1045 pub disr_expr: Option<P<Expr>>,
1048 pub type Variant = Spanned<Variant_>;
1050 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1051 pub enum PathListItem_ {
1054 /// renamed in list, eg `use foo::{bar as baz};`
1055 rename: Option<Name>,
1059 /// renamed in list, eg `use foo::{self as baz};`
1060 rename: Option<Name>,
1065 impl PathListItem_ {
1066 pub fn id(&self) -> NodeId {
1068 PathListIdent { id, .. } | PathListMod { id, .. } => id,
1072 pub fn name(&self) -> Option<Name> {
1074 PathListIdent { name, .. } => Some(name),
1075 PathListMod { .. } => None,
1079 pub fn rename(&self) -> Option<Name> {
1081 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename,
1086 pub type PathListItem = Spanned<PathListItem_>;
1088 pub type ViewPath = Spanned<ViewPath_>;
1090 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1091 pub enum ViewPath_ {
1092 /// `foo::bar::baz as quux`
1096 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1097 ViewPathSimple(Name, Path),
1102 /// `foo::bar::{a,b,c}`
1103 ViewPathList(Path, Vec<PathListItem>),
1106 /// TraitRef's appear in impls.
1108 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1109 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1110 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1111 /// same as the impl's node id).
1112 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1113 pub struct TraitRef {
1118 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1119 pub struct PolyTraitRef {
1120 /// The `'a` in `<'a> Foo<&'a T>`
1121 pub bound_lifetimes: Vec<LifetimeDef>,
1123 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1124 pub trait_ref: TraitRef,
1129 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1130 pub enum Visibility {
1136 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1138 &Inherited => parent_visibility,
1144 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1145 pub struct StructField_ {
1146 pub kind: StructFieldKind,
1149 pub attrs: Vec<Attribute>,
1153 pub fn name(&self) -> Option<Name> {
1155 NamedField(name, _) => Some(name),
1156 UnnamedField(_) => None,
1161 pub type StructField = Spanned<StructField_>;
1163 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1164 pub enum StructFieldKind {
1165 NamedField(Name, Visibility),
1166 /// Element of a tuple-like struct
1167 UnnamedField(Visibility),
1170 impl StructFieldKind {
1171 pub fn is_unnamed(&self) -> bool {
1173 UnnamedField(..) => true,
1174 NamedField(..) => false,
1178 pub fn visibility(&self) -> Visibility {
1180 NamedField(_, vis) | UnnamedField(vis) => vis,
1185 /// Fields and Ids of enum variants and structs
1187 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1188 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1189 /// One shared Id can be successfully used for these two purposes.
1190 /// Id of the whole enum lives in `Item`.
1192 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1193 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1194 /// the variant itself" from enum variants.
1195 /// Id of the whole struct lives in `Item`.
1196 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1197 pub enum VariantData {
1198 Struct(Vec<StructField>, NodeId),
1199 Tuple(Vec<StructField>, NodeId),
1204 pub fn fields(&self) -> &[StructField] {
1206 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1210 pub fn id(&self) -> NodeId {
1212 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1215 pub fn is_struct(&self) -> bool {
1216 if let VariantData::Struct(..) = *self {
1222 pub fn is_tuple(&self) -> bool {
1223 if let VariantData::Tuple(..) = *self {
1229 pub fn is_unit(&self) -> bool {
1230 if let VariantData::Unit(..) = *self {
1238 // The bodies for items are stored "out of line", in a separate
1239 // hashmap in the `Crate`. Here we just record the node-id of the item
1240 // so it can fetched later.
1241 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1246 // FIXME (#3300): Should allow items to be anonymous. Right now
1247 // we just use dummy names for anon items.
1250 /// The name might be a dummy name in case of anonymous items
1251 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1254 pub attrs: Vec<Attribute>,
1257 pub vis: Visibility,
1261 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1263 /// An`extern crate` item, with optional original crate name,
1265 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1266 ItemExternCrate(Option<Name>),
1267 /// A `use` or `pub use` item
1268 ItemUse(P<ViewPath>),
1271 ItemStatic(P<Ty>, Mutability, P<Expr>),
1273 ItemConst(P<Ty>, P<Expr>),
1274 /// A function declaration
1275 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1278 /// An external module
1279 ItemForeignMod(ForeignMod),
1280 /// A type alias, e.g. `type Foo = Bar<u8>`
1281 ItemTy(P<Ty>, Generics),
1282 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1283 ItemEnum(EnumDef, Generics),
1284 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1285 ItemStruct(VariantData, Generics),
1286 /// Represents a Trait Declaration
1287 ItemTrait(Unsafety, Generics, TyParamBounds, Vec<P<TraitItem>>),
1289 // Default trait implementations
1291 /// `impl Trait for .. {}`
1292 ItemDefaultImpl(Unsafety, TraitRef),
1293 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1297 Option<TraitRef>, // (optional) trait this impl implements
1303 pub fn descriptive_variant(&self) -> &str {
1305 ItemExternCrate(..) => "extern crate",
1306 ItemUse(..) => "use",
1307 ItemStatic(..) => "static item",
1308 ItemConst(..) => "constant item",
1309 ItemFn(..) => "function",
1310 ItemMod(..) => "module",
1311 ItemForeignMod(..) => "foreign module",
1312 ItemTy(..) => "type alias",
1313 ItemEnum(..) => "enum",
1314 ItemStruct(..) => "struct",
1315 ItemTrait(..) => "trait",
1317 ItemDefaultImpl(..) => "item",
1322 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1323 pub struct ForeignItem {
1325 pub attrs: Vec<Attribute>,
1326 pub node: ForeignItem_,
1329 pub vis: Visibility,
1332 /// An item within an `extern` block
1333 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1334 pub enum ForeignItem_ {
1335 /// A foreign function
1336 ForeignItemFn(P<FnDecl>, Generics),
1337 /// A foreign static item (`static ext: u8`), with optional mutability
1338 /// (the boolean is true when mutable)
1339 ForeignItemStatic(P<Ty>, bool),
1343 pub fn descriptive_variant(&self) -> &str {
1345 ForeignItemFn(..) => "foreign function",
1346 ForeignItemStatic(..) => "foreign static item",