1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // The Rust abstract syntax tree.
13 pub use self::TyParamBound::*;
14 pub use self::UnsafeSource::*;
15 pub use self::ViewPath_::*;
16 pub use self::PathParameters::*;
17 pub use util::ThinVec;
19 use syntax_pos::{mk_sp, Span, DUMMY_SP, ExpnId};
20 use codemap::{respan, Spanned};
23 use parse::token::{self, keywords, InternedString};
26 use tokenstream::{TokenTree};
30 use std::hash::{Hash, Hasher};
31 use serialize::{Encodable, Decodable, Encoder, Decoder};
33 /// A name is a part of an identifier, representing a string or gensym. It's
34 /// the result of interning.
35 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
36 pub struct Name(pub u32);
38 /// A SyntaxContext represents a chain of macro-expandings
39 /// and renamings. Each macro expansion corresponds to
40 /// a fresh u32. This u32 is a reference to a table stored
41 /// in thread-local storage.
42 /// The special value EMPTY_CTXT is used to indicate an empty
44 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
45 pub struct SyntaxContext(pub u32);
47 /// An identifier contains a Name (index into the interner
48 /// table) and a SyntaxContext to track renaming and
49 /// macro expansion per Flatt et al., "Macros That Work Together"
50 #[derive(Clone, Copy, Eq)]
53 pub ctxt: SyntaxContext
57 pub fn as_str(self) -> token::InternedString {
58 token::InternedString::new_from_name(self)
62 impl fmt::Debug for Name {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 write!(f, "{}({})", self, self.0)
68 impl fmt::Display for Name {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 fmt::Display::fmt(&self.as_str(), f)
74 impl Encodable for Name {
75 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
76 s.emit_str(&self.as_str())
80 impl Decodable for Name {
81 fn decode<D: Decoder>(d: &mut D) -> Result<Name, D::Error> {
82 Ok(token::intern(&d.read_str()?[..]))
86 pub const EMPTY_CTXT : SyntaxContext = SyntaxContext(0);
89 pub fn new(name: Name, ctxt: SyntaxContext) -> Ident {
90 Ident {name: name, ctxt: ctxt}
92 pub const fn with_empty_ctxt(name: Name) -> Ident {
93 Ident {name: name, ctxt: EMPTY_CTXT}
97 impl PartialEq for Ident {
98 fn eq(&self, other: &Ident) -> bool {
99 if self.ctxt != other.ctxt {
100 // There's no one true way to compare Idents. They can be compared
101 // non-hygienically `id1.name == id2.name`, hygienically
102 // `mtwt::resolve(id1) == mtwt::resolve(id2)`, or even member-wise
103 // `(id1.name, id1.ctxt) == (id2.name, id2.ctxt)` depending on the situation.
104 // Ideally, PartialEq should not be implemented for Ident at all, but that
105 // would be too impractical, because many larger structures (Token, in particular)
106 // including Idents as their parts derive PartialEq and use it for non-hygienic
107 // comparisons. That's why PartialEq is implemented and defaults to non-hygienic
108 // comparison. Hash is implemented too and is consistent with PartialEq, i.e. only
109 // the name of Ident is hashed. Still try to avoid comparing idents in your code
110 // (especially as keys in hash maps), use one of the three methods listed above
113 // If you see this panic, then some idents from different contexts were compared
114 // non-hygienically. It's likely a bug. Use one of the three comparison methods
115 // listed above explicitly.
117 panic!("idents with different contexts are compared with operator `==`: \
118 {:?}, {:?}.", self, other);
121 self.name == other.name
125 impl Hash for Ident {
126 fn hash<H: Hasher>(&self, state: &mut H) {
127 self.name.hash(state)
131 impl fmt::Debug for Ident {
132 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133 write!(f, "{}#{}", self.name, self.ctxt.0)
137 impl fmt::Display for Ident {
138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139 fmt::Display::fmt(&self.name, f)
143 impl Encodable for Ident {
144 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
149 impl Decodable for Ident {
150 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
151 Ok(Ident::with_empty_ctxt(Name::decode(d)?))
155 /// A mark represents a unique id associated with a macro expansion
158 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
159 pub struct Lifetime {
165 impl fmt::Debug for Lifetime {
166 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
167 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
171 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
172 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
173 pub struct LifetimeDef {
174 pub lifetime: Lifetime,
175 pub bounds: Vec<Lifetime>
178 /// A "Path" is essentially Rust's notion of a name.
180 /// It's represented as a sequence of identifiers,
181 /// along with a bunch of supporting information.
183 /// E.g. `std::cmp::PartialEq`
184 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
187 /// A `::foo` path, is relative to the crate root rather than current
188 /// module (like paths in an import).
190 /// The segments in the path: the things separated by `::`.
191 pub segments: Vec<PathSegment>,
194 impl fmt::Debug for Path {
195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
196 write!(f, "path({})", pprust::path_to_string(self))
200 impl fmt::Display for Path {
201 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
202 write!(f, "{}", pprust::path_to_string(self))
207 // convert a span and an identifier to the corresponding
209 pub fn from_ident(s: Span, identifier: Ident) -> Path {
215 identifier: identifier,
216 parameters: PathParameters::none()
223 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
225 /// E.g. `std`, `String` or `Box<T>`
226 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
227 pub struct PathSegment {
228 /// The identifier portion of this path segment.
229 pub identifier: Ident,
231 /// Type/lifetime parameters attached to this path. They come in
232 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
233 /// this is more than just simple syntactic sugar; the use of
234 /// parens affects the region binding rules, so we preserve the
236 pub parameters: PathParameters,
239 /// Parameters of a path segment.
241 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
242 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
243 pub enum PathParameters {
244 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
245 AngleBracketed(AngleBracketedParameterData),
246 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
247 Parenthesized(ParenthesizedParameterData),
250 impl PathParameters {
251 pub fn none() -> PathParameters {
252 PathParameters::AngleBracketed(AngleBracketedParameterData {
253 lifetimes: Vec::new(),
259 pub fn is_empty(&self) -> bool {
261 PathParameters::AngleBracketed(ref data) => data.is_empty(),
263 // Even if the user supplied no types, something like
264 // `X()` is equivalent to `X<(),()>`.
265 PathParameters::Parenthesized(..) => false,
269 pub fn has_lifetimes(&self) -> bool {
271 PathParameters::AngleBracketed(ref data) => !data.lifetimes.is_empty(),
272 PathParameters::Parenthesized(_) => false,
276 pub fn has_types(&self) -> bool {
278 PathParameters::AngleBracketed(ref data) => !data.types.is_empty(),
279 PathParameters::Parenthesized(..) => true,
283 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
284 /// parameters in the parenthesized case.
285 pub fn types(&self) -> Vec<&P<Ty>> {
287 PathParameters::AngleBracketed(ref data) => {
288 data.types.iter().collect()
290 PathParameters::Parenthesized(ref data) => {
292 .chain(data.output.iter())
298 pub fn lifetimes(&self) -> Vec<&Lifetime> {
300 PathParameters::AngleBracketed(ref data) => {
301 data.lifetimes.iter().collect()
303 PathParameters::Parenthesized(_) => {
309 pub fn bindings(&self) -> Vec<&TypeBinding> {
311 PathParameters::AngleBracketed(ref data) => {
312 data.bindings.iter().collect()
314 PathParameters::Parenthesized(_) => {
321 /// A path like `Foo<'a, T>`
322 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
323 pub struct AngleBracketedParameterData {
324 /// The lifetime parameters for this path segment.
325 pub lifetimes: Vec<Lifetime>,
326 /// The type parameters for this path segment, if present.
327 pub types: P<[P<Ty>]>,
328 /// Bindings (equality constraints) on associated types, if present.
330 /// E.g., `Foo<A=Bar>`.
331 pub bindings: P<[TypeBinding]>,
334 impl AngleBracketedParameterData {
335 fn is_empty(&self) -> bool {
336 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
340 /// A path like `Foo(A,B) -> C`
341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
342 pub struct ParenthesizedParameterData {
347 pub inputs: Vec<P<Ty>>,
350 pub output: Option<P<Ty>>,
353 pub type CrateNum = u32;
355 pub type NodeId = u32;
357 /// Node id used to represent the root of the crate.
358 pub const CRATE_NODE_ID: NodeId = 0;
360 /// When parsing and doing expansions, we initially give all AST nodes this AST
361 /// node value. Then later, in the renumber pass, we renumber them to have
362 /// small, positive ids.
363 pub const DUMMY_NODE_ID: NodeId = !0;
365 pub trait NodeIdAssigner {
366 fn next_node_id(&self) -> NodeId;
367 fn peek_node_id(&self) -> NodeId;
369 fn diagnostic(&self) -> &errors::Handler {
370 panic!("this ID assigner cannot emit diagnostics")
374 /// The AST represents all type param bounds as types.
375 /// typeck::collect::compute_bounds matches these against
376 /// the "special" built-in traits (see middle::lang_items) and
377 /// detects Copy, Send and Sync.
378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
379 pub enum TyParamBound {
380 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
381 RegionTyParamBound(Lifetime)
384 /// A modifier on a bound, currently this is only used for `?Sized`, where the
385 /// modifier is `Maybe`. Negative bounds should also be handled here.
386 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
387 pub enum TraitBoundModifier {
392 pub type TyParamBounds = P<[TyParamBound]>;
394 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
398 pub bounds: TyParamBounds,
399 pub default: Option<P<Ty>>,
403 /// Represents lifetimes and type parameters attached to a declaration
404 /// of a function, enum, trait, etc.
405 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
406 pub struct Generics {
407 pub lifetimes: Vec<LifetimeDef>,
408 pub ty_params: P<[TyParam]>,
409 pub where_clause: WhereClause,
413 pub fn is_lt_parameterized(&self) -> bool {
414 !self.lifetimes.is_empty()
416 pub fn is_type_parameterized(&self) -> bool {
417 !self.ty_params.is_empty()
419 pub fn is_parameterized(&self) -> bool {
420 self.is_lt_parameterized() || self.is_type_parameterized()
424 impl Default for Generics {
425 fn default() -> Generics {
427 lifetimes: Vec::new(),
429 where_clause: WhereClause {
431 predicates: Vec::new(),
437 /// A `where` clause in a definition
438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub struct WhereClause {
441 pub predicates: Vec<WherePredicate>,
444 /// A single predicate in a `where` clause
445 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
446 pub enum WherePredicate {
447 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
448 BoundPredicate(WhereBoundPredicate),
449 /// A lifetime predicate, e.g. `'a: 'b+'c`
450 RegionPredicate(WhereRegionPredicate),
451 /// An equality predicate (unsupported)
452 EqPredicate(WhereEqPredicate),
457 /// E.g. `for<'c> Foo: Send+Clone+'c`
458 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
459 pub struct WhereBoundPredicate {
461 /// Any lifetimes from a `for` binding
462 pub bound_lifetimes: Vec<LifetimeDef>,
463 /// The type being bounded
464 pub bounded_ty: P<Ty>,
465 /// Trait and lifetime bounds (`Clone+Send+'static`)
466 pub bounds: TyParamBounds,
469 /// A lifetime predicate.
472 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
473 pub struct WhereRegionPredicate {
475 pub lifetime: Lifetime,
476 pub bounds: Vec<Lifetime>,
479 /// An equality predicate (unsupported).
482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
483 pub struct WhereEqPredicate {
490 /// The set of MetaItems that define the compilation environment of the crate,
491 /// used to drive conditional compilation
492 pub type CrateConfig = Vec<P<MetaItem>>;
494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
497 pub attrs: Vec<Attribute>,
498 pub config: CrateConfig,
500 pub exported_macros: Vec<MacroDef>,
503 /// A spanned compile-time attribute item.
505 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
506 pub type MetaItem = Spanned<MetaItemKind>;
508 /// A compile-time attribute item.
510 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
511 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
512 pub enum MetaItemKind {
515 /// E.g. `test` as in `#[test]`
516 Word(InternedString),
519 /// E.g. `derive(..)` as in `#[derive(..)]`
520 List(InternedString, Vec<P<MetaItem>>),
521 /// Name value meta item.
523 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
524 NameValue(InternedString, Lit),
527 // can't be derived because the MetaItemKind::List requires an unordered comparison
528 impl PartialEq for MetaItemKind {
529 fn eq(&self, other: &MetaItemKind) -> bool {
530 use self::MetaItemKind::*;
532 Word(ref ns) => match *other {
533 Word(ref no) => (*ns) == (*no),
536 NameValue(ref ns, ref vs) => match *other {
537 NameValue(ref no, ref vo) => {
538 (*ns) == (*no) && vs.node == vo.node
542 List(ref ns, ref miss) => match *other {
543 List(ref no, ref miso) => {
545 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
553 /// A Block (`{ .. }`).
555 /// E.g. `{ .. }` as in `fn foo() { .. }`
556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
558 /// Statements in a block
559 pub stmts: Vec<Stmt>,
561 /// Distinguishes between `unsafe { ... }` and `{ ... }`
562 pub rules: BlockCheckMode,
566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
573 impl fmt::Debug for Pat {
574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
575 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
580 pub fn walk<F>(&self, it: &mut F) -> bool
581 where F: FnMut(&Pat) -> bool
588 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
589 PatKind::Struct(_, ref fields, _) => {
590 fields.iter().all(|field| field.node.pat.walk(it))
592 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
593 s.iter().all(|p| p.walk(it))
595 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
598 PatKind::Vec(ref before, ref slice, ref after) => {
599 before.iter().all(|p| p.walk(it)) &&
600 slice.iter().all(|p| p.walk(it)) &&
601 after.iter().all(|p| p.walk(it))
605 PatKind::Range(_, _) |
606 PatKind::Ident(_, _, _) |
615 /// A single field in a struct pattern
617 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
618 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
619 /// except is_shorthand is true
620 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
621 pub struct FieldPat {
622 /// The identifier for the field
624 /// The pattern the field is destructured to
626 pub is_shorthand: bool,
629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
630 pub enum BindingMode {
635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
637 /// Represents a wildcard pattern (`_`)
640 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
641 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
642 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
643 /// during name resolution.
644 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
646 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
647 /// The `bool` is `true` in the presence of a `..`.
648 Struct(Path, Vec<Spanned<FieldPat>>, bool),
650 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
651 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
652 /// 0 <= position <= subpats.len()
653 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
655 /// A possibly qualified path pattern.
656 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
657 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
658 /// only legally refer to associated constants.
659 Path(Option<QSelf>, Path),
661 /// A tuple pattern `(a, b)`.
662 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
663 /// 0 <= position <= subpats.len()
664 Tuple(Vec<P<Pat>>, Option<usize>),
667 /// A reference pattern, e.g. `&mut (a, b)`
668 Ref(P<Pat>, Mutability),
671 /// A range pattern, e.g. `1...2`
672 Range(P<Expr>, P<Expr>),
673 /// `[a, b, ..i, y, z]` is represented as:
674 /// `PatKind::Vec(box [a, b], Some(i), box [y, z])`
675 Vec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
676 /// A macro pattern; pre-expansion
680 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
681 pub enum Mutability {
686 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
688 /// The `+` operator (addition)
690 /// The `-` operator (subtraction)
692 /// The `*` operator (multiplication)
694 /// The `/` operator (division)
696 /// The `%` operator (modulus)
698 /// The `&&` operator (logical and)
700 /// The `||` operator (logical or)
702 /// The `^` operator (bitwise xor)
704 /// The `&` operator (bitwise and)
706 /// The `|` operator (bitwise or)
708 /// The `<<` operator (shift left)
710 /// The `>>` operator (shift right)
712 /// The `==` operator (equality)
714 /// The `<` operator (less than)
716 /// The `<=` operator (less than or equal to)
718 /// The `!=` operator (not equal to)
720 /// The `>=` operator (greater than or equal to)
722 /// The `>` operator (greater than)
727 pub fn to_string(&self) -> &'static str {
728 use self::BinOpKind::*;
750 pub fn lazy(&self) -> bool {
752 BinOpKind::And | BinOpKind::Or => true,
757 pub fn is_shift(&self) -> bool {
759 BinOpKind::Shl | BinOpKind::Shr => true,
763 pub fn is_comparison(&self) -> bool {
764 use self::BinOpKind::*;
766 Eq | Lt | Le | Ne | Gt | Ge =>
768 And | Or | Add | Sub | Mul | Div | Rem |
769 BitXor | BitAnd | BitOr | Shl | Shr =>
773 /// Returns `true` if the binary operator takes its arguments by value
774 pub fn is_by_value(&self) -> bool {
775 !self.is_comparison()
779 pub type BinOp = Spanned<BinOpKind>;
781 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
783 /// The `*` operator for dereferencing
785 /// The `!` operator for logical inversion
787 /// The `-` operator for negation
792 /// Returns `true` if the unary operator takes its argument by value
793 pub fn is_by_value(u: UnOp) -> bool {
795 UnOp::Neg | UnOp::Not => true,
800 pub fn to_string(op: UnOp) -> &'static str {
810 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
817 impl fmt::Debug for Stmt {
818 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
819 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
824 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
826 /// A local (let) binding.
829 /// An item definition.
832 /// Expr without trailing semi-colon.
837 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
840 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
841 pub enum MacStmtStyle {
842 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
843 /// `foo!(...);`, `foo![...];`
845 /// The macro statement had braces; e.g. foo! { ... }
847 /// The macro statement had parentheses or brackets and no semicolon; e.g.
848 /// `foo!(...)`. All of these will end up being converted into macro
853 // FIXME (pending discussion of #1697, #2178...): local should really be
854 // a refinement on pat.
855 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
856 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
859 pub ty: Option<P<Ty>>,
860 /// Initializer expression to set the value, if any
861 pub init: Option<P<Expr>>,
864 pub attrs: ThinVec<Attribute>,
867 /// An arm of a 'match'.
869 /// E.g. `0...10 => { println!("match!") }` as in
873 /// 0...10 => { println!("match!") },
877 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
879 pub attrs: Vec<Attribute>,
880 pub pats: Vec<P<Pat>>,
881 pub guard: Option<P<Expr>>,
885 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
887 pub ident: SpannedIdent,
892 pub type SpannedIdent = Spanned<Ident>;
894 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
895 pub enum BlockCheckMode {
897 Unsafe(UnsafeSource),
900 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
901 pub enum UnsafeSource {
907 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
912 pub attrs: ThinVec<Attribute>
915 impl fmt::Debug for Expr {
916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
917 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
921 /// Limit types of a range (inclusive or exclusive)
922 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
923 pub enum RangeLimits {
924 /// Inclusive at the beginning, exclusive at the end
926 /// Inclusive at the beginning and end
930 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
932 /// A `box x` expression.
934 /// First expr is the place; second expr is the value.
935 InPlace(P<Expr>, P<Expr>),
936 /// An array (`[a, b, c, d]`)
940 /// The first field resolves to the function itself,
941 /// and the second field is the list of arguments
942 Call(P<Expr>, Vec<P<Expr>>),
943 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
945 /// The `SpannedIdent` is the identifier for the method name.
946 /// The vector of `Ty`s are the ascripted type parameters for the method
947 /// (within the angle brackets).
949 /// The first element of the vector of `Expr`s is the expression that evaluates
950 /// to the object on which the method is being called on (the receiver),
951 /// and the remaining elements are the rest of the arguments.
953 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
954 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
955 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
956 /// A tuple (`(a, b, c ,d)`)
958 /// A binary operation (For example: `a + b`, `a * b`)
959 Binary(BinOp, P<Expr>, P<Expr>),
960 /// A unary operation (For example: `!x`, `*x`)
961 Unary(UnOp, P<Expr>),
962 /// A literal (For example: `1`, `"foo"`)
964 /// A cast (`foo as f64`)
965 Cast(P<Expr>, P<Ty>),
966 Type(P<Expr>, P<Ty>),
967 /// An `if` block, with an optional else block
969 /// `if expr { block } else { expr }`
970 If(P<Expr>, P<Block>, Option<P<Expr>>),
971 /// An `if let` expression with an optional else block
973 /// `if let pat = expr { block } else { expr }`
975 /// This is desugared to a `match` expression.
976 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
977 /// A while loop, with an optional label
979 /// `'label: while expr { block }`
980 While(P<Expr>, P<Block>, Option<SpannedIdent>),
981 /// A while-let loop, with an optional label
983 /// `'label: while let pat = expr { block }`
985 /// This is desugared to a combination of `loop` and `match` expressions.
986 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
987 /// A for loop, with an optional label
989 /// `'label: for pat in expr { block }`
991 /// This is desugared to a combination of `loop` and `match` expressions.
992 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
993 /// Conditionless loop (can be exited with break, continue, or return)
995 /// `'label: loop { block }`
996 Loop(P<Block>, Option<SpannedIdent>),
998 Match(P<Expr>, Vec<Arm>),
999 /// A closure (for example, `move |a, b, c| {a + b + c}`)
1001 /// The final span is the span of the argument block `|...|`
1002 Closure(CaptureBy, P<FnDecl>, P<Block>, Span),
1003 /// A block (`{ ... }`)
1006 /// An assignment (`a = foo()`)
1007 Assign(P<Expr>, P<Expr>),
1008 /// An assignment with an operator
1010 /// For example, `a += 1`.
1011 AssignOp(BinOp, P<Expr>, P<Expr>),
1012 /// Access of a named struct field (`obj.foo`)
1013 Field(P<Expr>, SpannedIdent),
1014 /// Access of an unnamed field of a struct or tuple-struct
1016 /// For example, `foo.0`.
1017 TupField(P<Expr>, Spanned<usize>),
1018 /// An indexing operation (`foo[2]`)
1019 Index(P<Expr>, P<Expr>),
1020 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
1021 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1023 /// Variable reference, possibly containing `::` and/or type
1024 /// parameters, e.g. foo::bar::<baz>.
1026 /// Optionally "qualified",
1027 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
1028 Path(Option<QSelf>, Path),
1030 /// A referencing operation (`&a` or `&mut a`)
1031 AddrOf(Mutability, P<Expr>),
1032 /// A `break`, with an optional label to break
1033 Break(Option<SpannedIdent>),
1034 /// A `continue`, with an optional label
1035 Continue(Option<SpannedIdent>),
1036 /// A `return`, with an optional value to be returned
1037 Ret(Option<P<Expr>>),
1039 /// Output of the `asm!()` macro
1040 InlineAsm(InlineAsm),
1042 /// A macro invocation; pre-expansion
1045 /// A struct literal expression.
1047 /// For example, `Foo {x: 1, y: 2}`, or
1048 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1049 Struct(Path, Vec<Field>, Option<P<Expr>>),
1051 /// An array literal constructed from one repeated element.
1053 /// For example, `[1; 5]`. The first expression is the element
1054 /// to be repeated; the second is the number of times to repeat it.
1055 Repeat(P<Expr>, P<Expr>),
1057 /// No-op: used solely so we can pretty-print faithfully
1064 /// The explicit Self type in a "qualified path". The actual
1065 /// path, including the trait and the associated item, is stored
1066 /// separately. `position` represents the index of the associated
1067 /// item qualified with this Self type.
1070 /// <Vec<T> as a::b::Trait>::AssociatedItem
1071 /// ^~~~~ ~~~~~~~~~~~~~~^
1074 /// <Vec<T>>::AssociatedItem
1078 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1084 /// A capture clause
1085 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1086 pub enum CaptureBy {
1091 pub type Mac = Spanned<Mac_>;
1093 /// Represents a macro invocation. The Path indicates which macro
1094 /// is being invoked, and the vector of token-trees contains the source
1095 /// of the macro invocation.
1097 /// NB: the additional ident for a macro_rules-style macro is actually
1098 /// stored in the enclosing item. Oog.
1099 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1102 pub tts: Vec<TokenTree>,
1105 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1107 /// A regular string, like `"foo"`
1109 /// A raw string, like `r##"foo"##`
1111 /// The uint is the number of `#` symbols used
1116 pub type Lit = Spanned<LitKind>;
1118 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1119 pub enum LitIntType {
1127 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1128 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1130 /// A string literal (`"foo"`)
1131 Str(InternedString, StrStyle),
1132 /// A byte string (`b"foo"`)
1133 ByteStr(Rc<Vec<u8>>),
1134 /// A byte char (`b'f'`)
1136 /// A character literal (`'a'`)
1138 /// An integer literal (`1`)
1139 Int(u64, LitIntType),
1140 /// A float literal (`1f64` or `1E10f64`)
1141 Float(InternedString, FloatTy),
1142 /// A float literal without a suffix (`1.0 or 1.0E10`)
1143 FloatUnsuffixed(InternedString),
1144 /// A boolean literal
1149 /// Returns true if this literal is a string and false otherwise.
1150 pub fn is_str(&self) -> bool {
1152 LitKind::Str(..) => true,
1158 // NB: If you change this, you'll probably want to change the corresponding
1159 // type structure in middle/ty.rs as well.
1160 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1163 pub mutbl: Mutability,
1166 /// Represents a method's signature in a trait declaration,
1167 /// or in an implementation.
1168 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1169 pub struct MethodSig {
1170 pub unsafety: Unsafety,
1171 pub constness: Constness,
1173 pub decl: P<FnDecl>,
1174 pub generics: Generics,
1177 /// Represents an item declaration within a trait declaration,
1178 /// possibly including a default implementation. A trait item is
1179 /// either required (meaning it doesn't have an implementation, just a
1180 /// signature) or provided (meaning it has a default implementation).
1181 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1182 pub struct TraitItem {
1185 pub attrs: Vec<Attribute>,
1186 pub node: TraitItemKind,
1190 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1191 pub enum TraitItemKind {
1192 Const(P<Ty>, Option<P<Expr>>),
1193 Method(MethodSig, Option<P<Block>>),
1194 Type(TyParamBounds, Option<P<Ty>>),
1198 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1199 pub struct ImplItem {
1202 pub vis: Visibility,
1203 pub defaultness: Defaultness,
1204 pub attrs: Vec<Attribute>,
1205 pub node: ImplItemKind,
1209 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1210 pub enum ImplItemKind {
1211 Const(P<Ty>, P<Expr>),
1212 Method(MethodSig, P<Block>),
1217 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1226 impl fmt::Debug for IntTy {
1227 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1228 fmt::Display::fmt(self, f)
1232 impl fmt::Display for IntTy {
1233 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1234 write!(f, "{}", self.ty_to_string())
1239 pub fn ty_to_string(&self) -> &'static str {
1241 IntTy::Is => "isize",
1243 IntTy::I16 => "i16",
1244 IntTy::I32 => "i32",
1249 pub fn val_to_string(&self, val: i64) -> String {
1250 // cast to a u64 so we can correctly print INT64_MIN. All integral types
1251 // are parsed as u64, so we wouldn't want to print an extra negative
1253 format!("{}{}", val as u64, self.ty_to_string())
1256 pub fn ty_max(&self) -> u64 {
1259 IntTy::I16 => 0x8000,
1260 IntTy::Is | IntTy::I32 => 0x80000000, // FIXME: actually ni about Is
1261 IntTy::I64 => 0x8000000000000000
1265 pub fn bit_width(&self) -> Option<usize> {
1267 IntTy::Is => return None,
1276 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1286 pub fn ty_to_string(&self) -> &'static str {
1288 UintTy::Us => "usize",
1290 UintTy::U16 => "u16",
1291 UintTy::U32 => "u32",
1292 UintTy::U64 => "u64"
1296 pub fn val_to_string(&self, val: u64) -> String {
1297 format!("{}{}", val, self.ty_to_string())
1300 pub fn ty_max(&self) -> u64 {
1303 UintTy::U16 => 0xffff,
1304 UintTy::Us | UintTy::U32 => 0xffffffff, // FIXME: actually ni about Us
1305 UintTy::U64 => 0xffffffffffffffff
1309 pub fn bit_width(&self) -> Option<usize> {
1311 UintTy::Us => return None,
1320 impl fmt::Debug for UintTy {
1321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1322 fmt::Display::fmt(self, f)
1326 impl fmt::Display for UintTy {
1327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1328 write!(f, "{}", self.ty_to_string())
1332 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1338 impl fmt::Debug for FloatTy {
1339 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1340 fmt::Display::fmt(self, f)
1344 impl fmt::Display for FloatTy {
1345 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1346 write!(f, "{}", self.ty_to_string())
1351 pub fn ty_to_string(&self) -> &'static str {
1353 FloatTy::F32 => "f32",
1354 FloatTy::F64 => "f64",
1358 pub fn bit_width(&self) -> usize {
1366 // Bind a type to an associated type: `A=Foo`.
1367 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1368 pub struct TypeBinding {
1375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1382 impl fmt::Debug for Ty {
1383 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1384 write!(f, "type({})", pprust::ty_to_string(self))
1388 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1389 pub struct BareFnTy {
1390 pub unsafety: Unsafety,
1392 pub lifetimes: Vec<LifetimeDef>,
1396 /// The different kinds of types recognized by the compiler
1397 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1400 /// A fixed length array (`[T; n]`)
1401 FixedLengthVec(P<Ty>, P<Expr>),
1402 /// A raw pointer (`*const T` or `*mut T`)
1404 /// A reference (`&'a T` or `&'a mut T`)
1405 Rptr(Option<Lifetime>, MutTy),
1406 /// A bare function (e.g. `fn(usize) -> bool`)
1407 BareFn(P<BareFnTy>),
1408 /// A tuple (`(A, B, C, D,...)`)
1410 /// A path (`module::module::...::Type`), optionally
1411 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1413 /// Type parameters are stored in the Path itself
1414 Path(Option<QSelf>, Path),
1415 /// Something like `A+B`. Note that `B` must always be a path.
1416 ObjectSum(P<Ty>, TyParamBounds),
1417 /// A type like `for<'a> Foo<&'a Bar>`
1418 PolyTraitRef(TyParamBounds),
1419 /// No-op; kept solely so that we can pretty-print faithfully
1423 /// TyKind::Infer means the type should be inferred instead of it having been
1424 /// specified. This can appear anywhere in a type.
1426 /// Inferred type of a `self` or `&self` argument in a method.
1428 // A macro in the type position.
1432 /// Inline assembly dialect.
1434 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1435 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1436 pub enum AsmDialect {
1441 /// Inline assembly.
1443 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1445 pub struct InlineAsmOutput {
1446 pub constraint: InternedString,
1449 pub is_indirect: bool,
1452 /// Inline assembly.
1454 /// E.g. `asm!("NOP");`
1455 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1456 pub struct InlineAsm {
1457 pub asm: InternedString,
1458 pub asm_str_style: StrStyle,
1459 pub outputs: Vec<InlineAsmOutput>,
1460 pub inputs: Vec<(InternedString, P<Expr>)>,
1461 pub clobbers: Vec<InternedString>,
1463 pub alignstack: bool,
1464 pub dialect: AsmDialect,
1465 pub expn_id: ExpnId,
1468 /// An argument in a function header.
1470 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1471 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1478 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1480 /// E.g. `&mut self` as in `fn foo(&mut self)`
1481 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1483 /// `self`, `mut self`
1485 /// `&'lt self`, `&'lt mut self`
1486 Region(Option<Lifetime>, Mutability),
1487 /// `self: TYPE`, `mut self: TYPE`
1488 Explicit(P<Ty>, Mutability),
1491 pub type ExplicitSelf = Spanned<SelfKind>;
1494 pub fn to_self(&self) -> Option<ExplicitSelf> {
1495 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1496 if ident.node.name == keywords::SelfValue.name() {
1497 return match self.ty.node {
1498 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1499 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1500 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1502 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1503 SelfKind::Explicit(self.ty.clone(), mutbl))),
1510 pub fn is_self(&self) -> bool {
1511 if let PatKind::Ident(_, ident, _) = self.pat.node {
1512 ident.node.name == keywords::SelfValue.name()
1518 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1519 let infer_ty = P(Ty {
1521 node: TyKind::ImplicitSelf,
1524 let arg = |mutbl, ty, span| Arg {
1527 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1534 SelfKind::Explicit(ty, mutbl) => {
1535 arg(mutbl, ty, mk_sp(eself.span.lo, eself_ident.span.hi))
1537 SelfKind::Value(mutbl) => arg(mutbl, infer_ty, eself.span),
1538 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1540 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1547 /// Header (not the body) of a function declaration.
1549 /// E.g. `fn foo(bar: baz)`
1550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1552 pub inputs: Vec<Arg>,
1553 pub output: FunctionRetTy,
1558 pub fn get_self(&self) -> Option<ExplicitSelf> {
1559 self.inputs.get(0).and_then(Arg::to_self)
1561 pub fn has_self(&self) -> bool {
1562 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1566 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1572 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1573 pub enum Constness {
1578 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1579 pub enum Defaultness {
1584 impl fmt::Display for Unsafety {
1585 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1586 fmt::Display::fmt(match *self {
1587 Unsafety::Normal => "normal",
1588 Unsafety::Unsafe => "unsafe",
1593 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1594 pub enum ImplPolarity {
1595 /// `impl Trait for Type`
1597 /// `impl !Trait for Type`
1601 impl fmt::Debug for ImplPolarity {
1602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1604 ImplPolarity::Positive => "positive".fmt(f),
1605 ImplPolarity::Negative => "negative".fmt(f),
1611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1612 pub enum FunctionRetTy {
1613 /// Functions with return type `!`that always
1614 /// raise an error or exit (i.e. never return to the caller)
1616 /// Return type is not specified.
1618 /// Functions default to `()` and
1619 /// closures default to inference. Span points to where return
1620 /// type would be inserted.
1626 impl FunctionRetTy {
1627 pub fn span(&self) -> Span {
1629 FunctionRetTy::None(span) => span,
1630 FunctionRetTy::Default(span) => span,
1631 FunctionRetTy::Ty(ref ty) => ty.span,
1636 /// Module declaration.
1638 /// E.g. `mod foo;` or `mod foo { .. }`
1639 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1641 /// A span from the first token past `{` to the last token until `}`.
1642 /// For `mod foo;`, the inner span ranges from the first token
1643 /// to the last token in the external file.
1645 pub items: Vec<P<Item>>,
1648 /// Foreign module declaration.
1650 /// E.g. `extern { .. }` or `extern C { .. }`
1651 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1652 pub struct ForeignMod {
1654 pub items: Vec<ForeignItem>,
1657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1658 pub struct EnumDef {
1659 pub variants: Vec<Variant>,
1662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1663 pub struct Variant_ {
1665 pub attrs: Vec<Attribute>,
1666 pub data: VariantData,
1667 /// Explicit discriminant, e.g. `Foo = 1`
1668 pub disr_expr: Option<P<Expr>>,
1671 pub type Variant = Spanned<Variant_>;
1673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1674 pub enum PathListItemKind {
1677 /// renamed in list, e.g. `use foo::{bar as baz};`
1678 rename: Option<Ident>,
1682 /// renamed in list, e.g. `use foo::{self as baz};`
1683 rename: Option<Ident>,
1688 impl PathListItemKind {
1689 pub fn id(&self) -> NodeId {
1691 PathListItemKind::Ident { id, .. } | PathListItemKind::Mod { id, .. } => id
1695 pub fn name(&self) -> Option<Ident> {
1697 PathListItemKind::Ident { name, .. } => Some(name),
1698 PathListItemKind::Mod { .. } => None,
1702 pub fn rename(&self) -> Option<Ident> {
1704 PathListItemKind::Ident { rename, .. } | PathListItemKind::Mod { rename, .. } => rename
1709 pub type PathListItem = Spanned<PathListItemKind>;
1711 pub type ViewPath = Spanned<ViewPath_>;
1713 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1714 pub enum ViewPath_ {
1716 /// `foo::bar::baz as quux`
1720 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1721 ViewPathSimple(Ident, Path),
1726 /// `foo::bar::{a,b,c}`
1727 ViewPathList(Path, Vec<PathListItem>)
1731 pub fn path(&self) -> &Path {
1733 ViewPathSimple(_, ref path) |
1734 ViewPathGlob (ref path) |
1735 ViewPathList(ref path, _) => path
1740 /// Meta-data associated with an item
1741 pub type Attribute = Spanned<Attribute_>;
1743 /// Distinguishes between Attributes that decorate items and Attributes that
1744 /// are contained as statements within items. These two cases need to be
1745 /// distinguished for pretty-printing.
1746 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1747 pub enum AttrStyle {
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1753 pub struct AttrId(pub usize);
1755 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1756 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1757 pub struct Attribute_ {
1759 pub style: AttrStyle,
1760 pub value: P<MetaItem>,
1761 pub is_sugared_doc: bool,
1764 /// TraitRef's appear in impls.
1766 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1767 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1768 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1769 /// same as the impl's node id).
1770 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1771 pub struct TraitRef {
1776 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1777 pub struct PolyTraitRef {
1778 /// The `'a` in `<'a> Foo<&'a T>`
1779 pub bound_lifetimes: Vec<LifetimeDef>,
1781 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1782 pub trait_ref: TraitRef,
1787 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1788 pub enum Visibility {
1791 Restricted { path: P<Path>, id: NodeId },
1795 /// Field of a struct.
1797 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1798 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1799 pub struct StructField {
1801 pub ident: Option<Ident>,
1802 pub vis: Visibility,
1805 pub attrs: Vec<Attribute>,
1808 /// Fields and Ids of enum variants and structs
1810 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1811 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1812 /// One shared Id can be successfully used for these two purposes.
1813 /// Id of the whole enum lives in `Item`.
1815 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1816 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1817 /// the variant itself" from enum variants.
1818 /// Id of the whole struct lives in `Item`.
1819 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1820 pub enum VariantData {
1823 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1824 Struct(Vec<StructField>, NodeId),
1827 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1828 Tuple(Vec<StructField>, NodeId),
1831 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1836 pub fn fields(&self) -> &[StructField] {
1838 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1842 pub fn id(&self) -> NodeId {
1844 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1847 pub fn is_struct(&self) -> bool {
1848 if let VariantData::Struct(..) = *self { true } else { false }
1850 pub fn is_tuple(&self) -> bool {
1851 if let VariantData::Tuple(..) = *self { true } else { false }
1853 pub fn is_unit(&self) -> bool {
1854 if let VariantData::Unit(..) = *self { true } else { false }
1859 FIXME (#3300): Should allow items to be anonymous. Right now
1860 we just use dummy names for anon items.
1864 /// The name might be a dummy name in case of anonymous items
1865 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1868 pub attrs: Vec<Attribute>,
1871 pub vis: Visibility,
1875 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1877 /// An`extern crate` item, with optional original crate name.
1879 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1880 ExternCrate(Option<Name>),
1881 /// A use declaration (`use` or `pub use`) item.
1883 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1885 /// A static item (`static` or `pub static`).
1887 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1888 Static(P<Ty>, Mutability, P<Expr>),
1889 /// A constant item (`const` or `pub const`).
1891 /// E.g. `const FOO: i32 = 42;`
1892 Const(P<Ty>, P<Expr>),
1893 /// A function declaration (`fn` or `pub fn`).
1895 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1896 Fn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1897 /// A module declaration (`mod` or `pub mod`).
1899 /// E.g. `mod foo;` or `mod foo { .. }`
1901 /// An external module (`extern` or `pub extern`).
1903 /// E.g. `extern {}` or `extern "C" {}`
1904 ForeignMod(ForeignMod),
1905 /// A type alias (`type` or `pub type`).
1907 /// E.g. `type Foo = Bar<u8>;`
1908 Ty(P<Ty>, Generics),
1909 /// An enum definition (`enum` or `pub enum`).
1911 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1912 Enum(EnumDef, Generics),
1913 /// A struct definition (`struct` or `pub struct`).
1915 /// E.g. `struct Foo<A> { x: A }`
1916 Struct(VariantData, Generics),
1917 /// A Trait declaration (`trait` or `pub trait`).
1919 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1920 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1921 // Default trait implementation.
1923 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1924 DefaultImpl(Unsafety, TraitRef),
1925 /// An implementation.
1927 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1931 Option<TraitRef>, // (optional) trait this impl implements
1934 /// A macro invocation (which includes macro definition).
1936 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1941 pub fn descriptive_variant(&self) -> &str {
1943 ItemKind::ExternCrate(..) => "extern crate",
1944 ItemKind::Use(..) => "use",
1945 ItemKind::Static(..) => "static item",
1946 ItemKind::Const(..) => "constant item",
1947 ItemKind::Fn(..) => "function",
1948 ItemKind::Mod(..) => "module",
1949 ItemKind::ForeignMod(..) => "foreign module",
1950 ItemKind::Ty(..) => "type alias",
1951 ItemKind::Enum(..) => "enum",
1952 ItemKind::Struct(..) => "struct",
1953 ItemKind::Trait(..) => "trait",
1955 ItemKind::Impl(..) |
1956 ItemKind::DefaultImpl(..) => "item"
1961 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1962 pub struct ForeignItem {
1964 pub attrs: Vec<Attribute>,
1965 pub node: ForeignItemKind,
1968 pub vis: Visibility,
1971 /// An item within an `extern` block
1972 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1973 pub enum ForeignItemKind {
1974 /// A foreign function
1975 Fn(P<FnDecl>, Generics),
1976 /// A foreign static item (`static ext: u8`), with optional mutability
1977 /// (the boolean is true when mutable)
1978 Static(P<Ty>, bool),
1981 impl ForeignItemKind {
1982 pub fn descriptive_variant(&self) -> &str {
1984 ForeignItemKind::Fn(..) => "foreign function",
1985 ForeignItemKind::Static(..) => "foreign static item"
1990 /// A macro definition, in this crate or imported from another.
1992 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1993 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1994 pub struct MacroDef {
1996 pub attrs: Vec<Attribute>,
1999 pub imported_from: Option<Ident>,
2001 pub use_locally: bool,
2002 pub allow_internal_unstable: bool,
2003 pub body: Vec<TokenTree>,
2011 // are ASTs encodable?
2013 fn check_asts_encodable() {
2014 fn assert_encodable<T: serialize::Encodable>() {}
2015 assert_encodable::<Crate>();