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};
22 use ext::hygiene::SyntaxContext;
23 use parse::token::{self, keywords, InternedString};
26 use tokenstream::{TokenTree};
30 use serialize::{Encodable, Decodable, Encoder, Decoder};
32 /// A name is a part of an identifier, representing a string or gensym. It's
33 /// the result of interning.
34 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
35 pub struct Name(pub u32);
37 /// An identifier contains a Name (index into the interner
38 /// table) and a SyntaxContext to track renaming and
39 /// macro expansion per Flatt et al., "Macros That Work Together"
40 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
43 pub ctxt: SyntaxContext
47 pub fn as_str(self) -> token::InternedString {
48 token::InternedString::new_from_name(self)
52 impl fmt::Debug for Name {
53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 write!(f, "{}({})", self, self.0)
58 impl fmt::Display for Name {
59 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60 fmt::Display::fmt(&self.as_str(), f)
64 impl Encodable for Name {
65 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
66 s.emit_str(&self.as_str())
70 impl Decodable for Name {
71 fn decode<D: Decoder>(d: &mut D) -> Result<Name, D::Error> {
72 Ok(token::intern(&d.read_str()?[..]))
77 pub const fn with_empty_ctxt(name: Name) -> Ident {
78 Ident { name: name, ctxt: SyntaxContext::empty() }
82 impl fmt::Debug for Ident {
83 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 write!(f, "{}{:?}", self.name, self.ctxt)
88 impl fmt::Display for Ident {
89 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90 fmt::Display::fmt(&self.name, f)
94 impl Encodable for Ident {
95 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
100 impl Decodable for Ident {
101 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
102 Ok(Ident::with_empty_ctxt(Name::decode(d)?))
106 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
107 pub struct Lifetime {
113 impl fmt::Debug for Lifetime {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
119 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
120 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
121 pub struct LifetimeDef {
122 pub lifetime: Lifetime,
123 pub bounds: Vec<Lifetime>
126 /// A "Path" is essentially Rust's notion of a name.
128 /// It's represented as a sequence of identifiers,
129 /// along with a bunch of supporting information.
131 /// E.g. `std::cmp::PartialEq`
132 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
135 /// A `::foo` path, is relative to the crate root rather than current
136 /// module (like paths in an import).
138 /// The segments in the path: the things separated by `::`.
139 pub segments: Vec<PathSegment>,
142 impl fmt::Debug for Path {
143 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144 write!(f, "path({})", pprust::path_to_string(self))
148 impl fmt::Display for Path {
149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 write!(f, "{}", pprust::path_to_string(self))
155 // convert a span and an identifier to the corresponding
157 pub fn from_ident(s: Span, identifier: Ident) -> Path {
163 identifier: identifier,
164 parameters: PathParameters::none()
171 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
173 /// E.g. `std`, `String` or `Box<T>`
174 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
175 pub struct PathSegment {
176 /// The identifier portion of this path segment.
177 pub identifier: Ident,
179 /// Type/lifetime parameters attached to this path. They come in
180 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
181 /// this is more than just simple syntactic sugar; the use of
182 /// parens affects the region binding rules, so we preserve the
184 pub parameters: PathParameters,
187 /// Parameters of a path segment.
189 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
190 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
191 pub enum PathParameters {
192 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
193 AngleBracketed(AngleBracketedParameterData),
194 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
195 Parenthesized(ParenthesizedParameterData),
198 impl PathParameters {
199 pub fn none() -> PathParameters {
200 PathParameters::AngleBracketed(AngleBracketedParameterData {
201 lifetimes: Vec::new(),
207 pub fn is_empty(&self) -> bool {
209 PathParameters::AngleBracketed(ref data) => data.is_empty(),
211 // Even if the user supplied no types, something like
212 // `X()` is equivalent to `X<(),()>`.
213 PathParameters::Parenthesized(..) => false,
217 pub fn has_lifetimes(&self) -> bool {
219 PathParameters::AngleBracketed(ref data) => !data.lifetimes.is_empty(),
220 PathParameters::Parenthesized(_) => false,
224 pub fn has_types(&self) -> bool {
226 PathParameters::AngleBracketed(ref data) => !data.types.is_empty(),
227 PathParameters::Parenthesized(..) => true,
231 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
232 /// parameters in the parenthesized case.
233 pub fn types(&self) -> Vec<&P<Ty>> {
235 PathParameters::AngleBracketed(ref data) => {
236 data.types.iter().collect()
238 PathParameters::Parenthesized(ref data) => {
240 .chain(data.output.iter())
246 pub fn lifetimes(&self) -> Vec<&Lifetime> {
248 PathParameters::AngleBracketed(ref data) => {
249 data.lifetimes.iter().collect()
251 PathParameters::Parenthesized(_) => {
257 pub fn bindings(&self) -> Vec<&TypeBinding> {
259 PathParameters::AngleBracketed(ref data) => {
260 data.bindings.iter().collect()
262 PathParameters::Parenthesized(_) => {
269 /// A path like `Foo<'a, T>`
270 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
271 pub struct AngleBracketedParameterData {
272 /// The lifetime parameters for this path segment.
273 pub lifetimes: Vec<Lifetime>,
274 /// The type parameters for this path segment, if present.
275 pub types: P<[P<Ty>]>,
276 /// Bindings (equality constraints) on associated types, if present.
278 /// E.g., `Foo<A=Bar>`.
279 pub bindings: P<[TypeBinding]>,
282 impl AngleBracketedParameterData {
283 fn is_empty(&self) -> bool {
284 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
288 /// A path like `Foo(A,B) -> C`
289 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
290 pub struct ParenthesizedParameterData {
295 pub inputs: Vec<P<Ty>>,
298 pub output: Option<P<Ty>>,
301 pub type CrateNum = u32;
303 pub type NodeId = u32;
305 /// Node id used to represent the root of the crate.
306 pub const CRATE_NODE_ID: NodeId = 0;
308 /// When parsing and doing expansions, we initially give all AST nodes this AST
309 /// node value. Then later, in the renumber pass, we renumber them to have
310 /// small, positive ids.
311 pub const DUMMY_NODE_ID: NodeId = !0;
313 /// The AST represents all type param bounds as types.
314 /// typeck::collect::compute_bounds matches these against
315 /// the "special" built-in traits (see middle::lang_items) and
316 /// detects Copy, Send and Sync.
317 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
318 pub enum TyParamBound {
319 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
320 RegionTyParamBound(Lifetime)
323 /// A modifier on a bound, currently this is only used for `?Sized`, where the
324 /// modifier is `Maybe`. Negative bounds should also be handled here.
325 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
326 pub enum TraitBoundModifier {
331 pub type TyParamBounds = P<[TyParamBound]>;
333 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
337 pub bounds: TyParamBounds,
338 pub default: Option<P<Ty>>,
342 /// Represents lifetimes and type parameters attached to a declaration
343 /// of a function, enum, trait, etc.
344 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
345 pub struct Generics {
346 pub lifetimes: Vec<LifetimeDef>,
347 pub ty_params: P<[TyParam]>,
348 pub where_clause: WhereClause,
352 pub fn is_lt_parameterized(&self) -> bool {
353 !self.lifetimes.is_empty()
355 pub fn is_type_parameterized(&self) -> bool {
356 !self.ty_params.is_empty()
358 pub fn is_parameterized(&self) -> bool {
359 self.is_lt_parameterized() || self.is_type_parameterized()
363 impl Default for Generics {
364 fn default() -> Generics {
366 lifetimes: Vec::new(),
368 where_clause: WhereClause {
370 predicates: Vec::new(),
376 /// A `where` clause in a definition
377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
378 pub struct WhereClause {
380 pub predicates: Vec<WherePredicate>,
383 /// A single predicate in a `where` clause
384 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
385 pub enum WherePredicate {
386 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
387 BoundPredicate(WhereBoundPredicate),
388 /// A lifetime predicate, e.g. `'a: 'b+'c`
389 RegionPredicate(WhereRegionPredicate),
390 /// An equality predicate (unsupported)
391 EqPredicate(WhereEqPredicate),
396 /// E.g. `for<'c> Foo: Send+Clone+'c`
397 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
398 pub struct WhereBoundPredicate {
400 /// Any lifetimes from a `for` binding
401 pub bound_lifetimes: Vec<LifetimeDef>,
402 /// The type being bounded
403 pub bounded_ty: P<Ty>,
404 /// Trait and lifetime bounds (`Clone+Send+'static`)
405 pub bounds: TyParamBounds,
408 /// A lifetime predicate.
411 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
412 pub struct WhereRegionPredicate {
414 pub lifetime: Lifetime,
415 pub bounds: Vec<Lifetime>,
418 /// An equality predicate (unsupported).
421 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
422 pub struct WhereEqPredicate {
429 /// The set of MetaItems that define the compilation environment of the crate,
430 /// used to drive conditional compilation
431 pub type CrateConfig = Vec<P<MetaItem>>;
433 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
436 pub attrs: Vec<Attribute>,
437 pub config: CrateConfig,
439 pub exported_macros: Vec<MacroDef>,
442 /// A spanned compile-time attribute item.
444 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
445 pub type MetaItem = Spanned<MetaItemKind>;
447 /// A compile-time attribute item.
449 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
450 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
451 pub enum MetaItemKind {
454 /// E.g. `test` as in `#[test]`
455 Word(InternedString),
458 /// E.g. `derive(..)` as in `#[derive(..)]`
459 List(InternedString, Vec<P<MetaItem>>),
460 /// Name value meta item.
462 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
463 NameValue(InternedString, Lit),
466 // can't be derived because the MetaItemKind::List requires an unordered comparison
467 impl PartialEq for MetaItemKind {
468 fn eq(&self, other: &MetaItemKind) -> bool {
469 use self::MetaItemKind::*;
471 Word(ref ns) => match *other {
472 Word(ref no) => (*ns) == (*no),
475 NameValue(ref ns, ref vs) => match *other {
476 NameValue(ref no, ref vo) => {
477 (*ns) == (*no) && vs.node == vo.node
481 List(ref ns, ref miss) => match *other {
482 List(ref no, ref miso) => {
484 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
492 /// A Block (`{ .. }`).
494 /// E.g. `{ .. }` as in `fn foo() { .. }`
495 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
497 /// Statements in a block
498 pub stmts: Vec<Stmt>,
500 /// Distinguishes between `unsafe { ... }` and `{ ... }`
501 pub rules: BlockCheckMode,
505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
512 impl fmt::Debug for Pat {
513 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
514 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
519 pub fn walk<F>(&self, it: &mut F) -> bool
520 where F: FnMut(&Pat) -> bool
527 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
528 PatKind::Struct(_, ref fields, _) => {
529 fields.iter().all(|field| field.node.pat.walk(it))
531 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
532 s.iter().all(|p| p.walk(it))
534 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
537 PatKind::Vec(ref before, ref slice, ref after) => {
538 before.iter().all(|p| p.walk(it)) &&
539 slice.iter().all(|p| p.walk(it)) &&
540 after.iter().all(|p| p.walk(it))
544 PatKind::Range(_, _) |
545 PatKind::Ident(_, _, _) |
554 /// A single field in a struct pattern
556 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
557 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
558 /// except is_shorthand is true
559 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
560 pub struct FieldPat {
561 /// The identifier for the field
563 /// The pattern the field is destructured to
565 pub is_shorthand: bool,
568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
569 pub enum BindingMode {
574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
576 /// Represents a wildcard pattern (`_`)
579 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
580 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
581 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
582 /// during name resolution.
583 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
585 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
586 /// The `bool` is `true` in the presence of a `..`.
587 Struct(Path, Vec<Spanned<FieldPat>>, bool),
589 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
590 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
591 /// 0 <= position <= subpats.len()
592 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
594 /// A possibly qualified path pattern.
595 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
596 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
597 /// only legally refer to associated constants.
598 Path(Option<QSelf>, Path),
600 /// A tuple pattern `(a, b)`.
601 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
602 /// 0 <= position <= subpats.len()
603 Tuple(Vec<P<Pat>>, Option<usize>),
606 /// A reference pattern, e.g. `&mut (a, b)`
607 Ref(P<Pat>, Mutability),
610 /// A range pattern, e.g. `1...2`
611 Range(P<Expr>, P<Expr>),
612 /// `[a, b, ..i, y, z]` is represented as:
613 /// `PatKind::Vec(box [a, b], Some(i), box [y, z])`
614 Vec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
615 /// A macro pattern; pre-expansion
619 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
620 pub enum Mutability {
625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
627 /// The `+` operator (addition)
629 /// The `-` operator (subtraction)
631 /// The `*` operator (multiplication)
633 /// The `/` operator (division)
635 /// The `%` operator (modulus)
637 /// The `&&` operator (logical and)
639 /// The `||` operator (logical or)
641 /// The `^` operator (bitwise xor)
643 /// The `&` operator (bitwise and)
645 /// The `|` operator (bitwise or)
647 /// The `<<` operator (shift left)
649 /// The `>>` operator (shift right)
651 /// The `==` operator (equality)
653 /// The `<` operator (less than)
655 /// The `<=` operator (less than or equal to)
657 /// The `!=` operator (not equal to)
659 /// The `>=` operator (greater than or equal to)
661 /// The `>` operator (greater than)
666 pub fn to_string(&self) -> &'static str {
667 use self::BinOpKind::*;
689 pub fn lazy(&self) -> bool {
691 BinOpKind::And | BinOpKind::Or => true,
696 pub fn is_shift(&self) -> bool {
698 BinOpKind::Shl | BinOpKind::Shr => true,
702 pub fn is_comparison(&self) -> bool {
703 use self::BinOpKind::*;
705 Eq | Lt | Le | Ne | Gt | Ge =>
707 And | Or | Add | Sub | Mul | Div | Rem |
708 BitXor | BitAnd | BitOr | Shl | Shr =>
712 /// Returns `true` if the binary operator takes its arguments by value
713 pub fn is_by_value(&self) -> bool {
714 !self.is_comparison()
718 pub type BinOp = Spanned<BinOpKind>;
720 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
722 /// The `*` operator for dereferencing
724 /// The `!` operator for logical inversion
726 /// The `-` operator for negation
731 /// Returns `true` if the unary operator takes its argument by value
732 pub fn is_by_value(u: UnOp) -> bool {
734 UnOp::Neg | UnOp::Not => true,
739 pub fn to_string(op: UnOp) -> &'static str {
749 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
757 pub fn add_trailing_semicolon(mut self) -> Self {
758 self.node = match self.node {
759 StmtKind::Expr(expr) => StmtKind::Semi(expr),
760 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
761 (mac, MacStmtStyle::Semicolon, attrs)
769 impl fmt::Debug for Stmt {
770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
776 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
778 /// A local (let) binding.
781 /// An item definition.
784 /// Expr without trailing semi-colon.
789 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
792 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
793 pub enum MacStmtStyle {
794 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
795 /// `foo!(...);`, `foo![...];`
797 /// The macro statement had braces; e.g. foo! { ... }
799 /// The macro statement had parentheses or brackets and no semicolon; e.g.
800 /// `foo!(...)`. All of these will end up being converted into macro
805 // FIXME (pending discussion of #1697, #2178...): local should really be
806 // a refinement on pat.
807 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
808 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
811 pub ty: Option<P<Ty>>,
812 /// Initializer expression to set the value, if any
813 pub init: Option<P<Expr>>,
816 pub attrs: ThinVec<Attribute>,
819 /// An arm of a 'match'.
821 /// E.g. `0...10 => { println!("match!") }` as in
825 /// 0...10 => { println!("match!") },
829 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
831 pub attrs: Vec<Attribute>,
832 pub pats: Vec<P<Pat>>,
833 pub guard: Option<P<Expr>>,
837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
839 pub ident: SpannedIdent,
844 pub type SpannedIdent = Spanned<Ident>;
846 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
847 pub enum BlockCheckMode {
849 Unsafe(UnsafeSource),
852 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
853 pub enum UnsafeSource {
859 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
864 pub attrs: ThinVec<Attribute>
867 impl fmt::Debug for Expr {
868 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
869 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
873 /// Limit types of a range (inclusive or exclusive)
874 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
875 pub enum RangeLimits {
876 /// Inclusive at the beginning, exclusive at the end
878 /// Inclusive at the beginning and end
882 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
884 /// A `box x` expression.
886 /// First expr is the place; second expr is the value.
887 InPlace(P<Expr>, P<Expr>),
888 /// An array (`[a, b, c, d]`)
892 /// The first field resolves to the function itself,
893 /// and the second field is the list of arguments
894 Call(P<Expr>, Vec<P<Expr>>),
895 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
897 /// The `SpannedIdent` is the identifier for the method name.
898 /// The vector of `Ty`s are the ascripted type parameters for the method
899 /// (within the angle brackets).
901 /// The first element of the vector of `Expr`s is the expression that evaluates
902 /// to the object on which the method is being called on (the receiver),
903 /// and the remaining elements are the rest of the arguments.
905 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
906 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
907 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
908 /// A tuple (`(a, b, c ,d)`)
910 /// A binary operation (For example: `a + b`, `a * b`)
911 Binary(BinOp, P<Expr>, P<Expr>),
912 /// A unary operation (For example: `!x`, `*x`)
913 Unary(UnOp, P<Expr>),
914 /// A literal (For example: `1`, `"foo"`)
916 /// A cast (`foo as f64`)
917 Cast(P<Expr>, P<Ty>),
918 Type(P<Expr>, P<Ty>),
919 /// An `if` block, with an optional else block
921 /// `if expr { block } else { expr }`
922 If(P<Expr>, P<Block>, Option<P<Expr>>),
923 /// An `if let` expression with an optional else block
925 /// `if let pat = expr { block } else { expr }`
927 /// This is desugared to a `match` expression.
928 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
929 /// A while loop, with an optional label
931 /// `'label: while expr { block }`
932 While(P<Expr>, P<Block>, Option<SpannedIdent>),
933 /// A while-let loop, with an optional label
935 /// `'label: while let pat = expr { block }`
937 /// This is desugared to a combination of `loop` and `match` expressions.
938 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
939 /// A for loop, with an optional label
941 /// `'label: for pat in expr { block }`
943 /// This is desugared to a combination of `loop` and `match` expressions.
944 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
945 /// Conditionless loop (can be exited with break, continue, or return)
947 /// `'label: loop { block }`
948 Loop(P<Block>, Option<SpannedIdent>),
950 Match(P<Expr>, Vec<Arm>),
951 /// A closure (for example, `move |a, b, c| {a + b + c}`)
953 /// The final span is the span of the argument block `|...|`
954 Closure(CaptureBy, P<FnDecl>, P<Block>, Span),
955 /// A block (`{ ... }`)
958 /// An assignment (`a = foo()`)
959 Assign(P<Expr>, P<Expr>),
960 /// An assignment with an operator
962 /// For example, `a += 1`.
963 AssignOp(BinOp, P<Expr>, P<Expr>),
964 /// Access of a named struct field (`obj.foo`)
965 Field(P<Expr>, SpannedIdent),
966 /// Access of an unnamed field of a struct or tuple-struct
968 /// For example, `foo.0`.
969 TupField(P<Expr>, Spanned<usize>),
970 /// An indexing operation (`foo[2]`)
971 Index(P<Expr>, P<Expr>),
972 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
973 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
975 /// Variable reference, possibly containing `::` and/or type
976 /// parameters, e.g. foo::bar::<baz>.
978 /// Optionally "qualified",
979 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
980 Path(Option<QSelf>, Path),
982 /// A referencing operation (`&a` or `&mut a`)
983 AddrOf(Mutability, P<Expr>),
984 /// A `break`, with an optional label to break
985 Break(Option<SpannedIdent>),
986 /// A `continue`, with an optional label
987 Continue(Option<SpannedIdent>),
988 /// A `return`, with an optional value to be returned
989 Ret(Option<P<Expr>>),
991 /// Output of the `asm!()` macro
992 InlineAsm(InlineAsm),
994 /// A macro invocation; pre-expansion
997 /// A struct literal expression.
999 /// For example, `Foo {x: 1, y: 2}`, or
1000 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1001 Struct(Path, Vec<Field>, Option<P<Expr>>),
1003 /// An array literal constructed from one repeated element.
1005 /// For example, `[1; 5]`. The first expression is the element
1006 /// to be repeated; the second is the number of times to repeat it.
1007 Repeat(P<Expr>, P<Expr>),
1009 /// No-op: used solely so we can pretty-print faithfully
1016 /// The explicit Self type in a "qualified path". The actual
1017 /// path, including the trait and the associated item, is stored
1018 /// separately. `position` represents the index of the associated
1019 /// item qualified with this Self type.
1022 /// <Vec<T> as a::b::Trait>::AssociatedItem
1023 /// ^~~~~ ~~~~~~~~~~~~~~^
1026 /// <Vec<T>>::AssociatedItem
1030 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1036 /// A capture clause
1037 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1038 pub enum CaptureBy {
1043 pub type Mac = Spanned<Mac_>;
1045 /// Represents a macro invocation. The Path indicates which macro
1046 /// is being invoked, and the vector of token-trees contains the source
1047 /// of the macro invocation.
1049 /// NB: the additional ident for a macro_rules-style macro is actually
1050 /// stored in the enclosing item. Oog.
1051 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1054 pub tts: Vec<TokenTree>,
1057 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1059 /// A regular string, like `"foo"`
1061 /// A raw string, like `r##"foo"##`
1063 /// The uint is the number of `#` symbols used
1068 pub type Lit = Spanned<LitKind>;
1070 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1071 pub enum LitIntType {
1079 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1080 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1082 /// A string literal (`"foo"`)
1083 Str(InternedString, StrStyle),
1084 /// A byte string (`b"foo"`)
1085 ByteStr(Rc<Vec<u8>>),
1086 /// A byte char (`b'f'`)
1088 /// A character literal (`'a'`)
1090 /// An integer literal (`1`)
1091 Int(u64, LitIntType),
1092 /// A float literal (`1f64` or `1E10f64`)
1093 Float(InternedString, FloatTy),
1094 /// A float literal without a suffix (`1.0 or 1.0E10`)
1095 FloatUnsuffixed(InternedString),
1096 /// A boolean literal
1101 /// Returns true if this literal is a string and false otherwise.
1102 pub fn is_str(&self) -> bool {
1104 LitKind::Str(..) => true,
1110 // NB: If you change this, you'll probably want to change the corresponding
1111 // type structure in middle/ty.rs as well.
1112 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1115 pub mutbl: Mutability,
1118 /// Represents a method's signature in a trait declaration,
1119 /// or in an implementation.
1120 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1121 pub struct MethodSig {
1122 pub unsafety: Unsafety,
1123 pub constness: Constness,
1125 pub decl: P<FnDecl>,
1126 pub generics: Generics,
1129 /// Represents an item declaration within a trait declaration,
1130 /// possibly including a default implementation. A trait item is
1131 /// either required (meaning it doesn't have an implementation, just a
1132 /// signature) or provided (meaning it has a default implementation).
1133 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1134 pub struct TraitItem {
1137 pub attrs: Vec<Attribute>,
1138 pub node: TraitItemKind,
1142 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1143 pub enum TraitItemKind {
1144 Const(P<Ty>, Option<P<Expr>>),
1145 Method(MethodSig, Option<P<Block>>),
1146 Type(TyParamBounds, Option<P<Ty>>),
1150 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1151 pub struct ImplItem {
1154 pub vis: Visibility,
1155 pub defaultness: Defaultness,
1156 pub attrs: Vec<Attribute>,
1157 pub node: ImplItemKind,
1161 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1162 pub enum ImplItemKind {
1163 Const(P<Ty>, P<Expr>),
1164 Method(MethodSig, P<Block>),
1169 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1178 impl fmt::Debug for IntTy {
1179 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1180 fmt::Display::fmt(self, f)
1184 impl fmt::Display for IntTy {
1185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1186 write!(f, "{}", self.ty_to_string())
1191 pub fn ty_to_string(&self) -> &'static str {
1193 IntTy::Is => "isize",
1195 IntTy::I16 => "i16",
1196 IntTy::I32 => "i32",
1201 pub fn val_to_string(&self, val: i64) -> String {
1202 // cast to a u64 so we can correctly print INT64_MIN. All integral types
1203 // are parsed as u64, so we wouldn't want to print an extra negative
1205 format!("{}{}", val as u64, self.ty_to_string())
1208 pub fn ty_max(&self) -> u64 {
1211 IntTy::I16 => 0x8000,
1212 IntTy::Is | IntTy::I32 => 0x80000000, // FIXME: actually ni about Is
1213 IntTy::I64 => 0x8000000000000000
1217 pub fn bit_width(&self) -> Option<usize> {
1219 IntTy::Is => return None,
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1238 pub fn ty_to_string(&self) -> &'static str {
1240 UintTy::Us => "usize",
1242 UintTy::U16 => "u16",
1243 UintTy::U32 => "u32",
1244 UintTy::U64 => "u64"
1248 pub fn val_to_string(&self, val: u64) -> String {
1249 format!("{}{}", val, self.ty_to_string())
1252 pub fn ty_max(&self) -> u64 {
1255 UintTy::U16 => 0xffff,
1256 UintTy::Us | UintTy::U32 => 0xffffffff, // FIXME: actually ni about Us
1257 UintTy::U64 => 0xffffffffffffffff
1261 pub fn bit_width(&self) -> Option<usize> {
1263 UintTy::Us => return None,
1272 impl fmt::Debug for UintTy {
1273 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1274 fmt::Display::fmt(self, f)
1278 impl fmt::Display for UintTy {
1279 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1280 write!(f, "{}", self.ty_to_string())
1284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1290 impl fmt::Debug for FloatTy {
1291 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1292 fmt::Display::fmt(self, f)
1296 impl fmt::Display for FloatTy {
1297 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1298 write!(f, "{}", self.ty_to_string())
1303 pub fn ty_to_string(&self) -> &'static str {
1305 FloatTy::F32 => "f32",
1306 FloatTy::F64 => "f64",
1310 pub fn bit_width(&self) -> usize {
1318 // Bind a type to an associated type: `A=Foo`.
1319 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1320 pub struct TypeBinding {
1327 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1334 impl fmt::Debug for Ty {
1335 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1336 write!(f, "type({})", pprust::ty_to_string(self))
1340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1341 pub struct BareFnTy {
1342 pub unsafety: Unsafety,
1344 pub lifetimes: Vec<LifetimeDef>,
1348 /// The different kinds of types recognized by the compiler
1349 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1351 /// A variable-length array (`[T]`)
1353 /// A fixed length array (`[T; n]`)
1354 FixedLengthVec(P<Ty>, P<Expr>),
1355 /// A raw pointer (`*const T` or `*mut T`)
1357 /// A reference (`&'a T` or `&'a mut T`)
1358 Rptr(Option<Lifetime>, MutTy),
1359 /// A bare function (e.g. `fn(usize) -> bool`)
1360 BareFn(P<BareFnTy>),
1361 /// The never type (`!`)
1363 /// A tuple (`(A, B, C, D,...)`)
1365 /// A path (`module::module::...::Type`), optionally
1366 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1368 /// Type parameters are stored in the Path itself
1369 Path(Option<QSelf>, Path),
1370 /// Something like `A+B`. Note that `B` must always be a path.
1371 ObjectSum(P<Ty>, TyParamBounds),
1372 /// A type like `for<'a> Foo<&'a Bar>`
1373 PolyTraitRef(TyParamBounds),
1374 /// An `impl TraitA+TraitB` type.
1375 ImplTrait(TyParamBounds),
1376 /// No-op; kept solely so that we can pretty-print faithfully
1380 /// TyKind::Infer means the type should be inferred instead of it having been
1381 /// specified. This can appear anywhere in a type.
1383 /// Inferred type of a `self` or `&self` argument in a method.
1385 // A macro in the type position.
1389 /// Inline assembly dialect.
1391 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1393 pub enum AsmDialect {
1398 /// Inline assembly.
1400 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1401 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1402 pub struct InlineAsmOutput {
1403 pub constraint: InternedString,
1406 pub is_indirect: bool,
1409 /// Inline assembly.
1411 /// E.g. `asm!("NOP");`
1412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1413 pub struct InlineAsm {
1414 pub asm: InternedString,
1415 pub asm_str_style: StrStyle,
1416 pub outputs: Vec<InlineAsmOutput>,
1417 pub inputs: Vec<(InternedString, P<Expr>)>,
1418 pub clobbers: Vec<InternedString>,
1420 pub alignstack: bool,
1421 pub dialect: AsmDialect,
1422 pub expn_id: ExpnId,
1425 /// An argument in a function header.
1427 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1428 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1435 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1437 /// E.g. `&mut self` as in `fn foo(&mut self)`
1438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1440 /// `self`, `mut self`
1442 /// `&'lt self`, `&'lt mut self`
1443 Region(Option<Lifetime>, Mutability),
1444 /// `self: TYPE`, `mut self: TYPE`
1445 Explicit(P<Ty>, Mutability),
1448 pub type ExplicitSelf = Spanned<SelfKind>;
1451 pub fn to_self(&self) -> Option<ExplicitSelf> {
1452 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1453 if ident.node.name == keywords::SelfValue.name() {
1454 return match self.ty.node {
1455 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1456 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1457 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1459 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1460 SelfKind::Explicit(self.ty.clone(), mutbl))),
1467 pub fn is_self(&self) -> bool {
1468 if let PatKind::Ident(_, ident, _) = self.pat.node {
1469 ident.node.name == keywords::SelfValue.name()
1475 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1476 let infer_ty = P(Ty {
1478 node: TyKind::ImplicitSelf,
1481 let arg = |mutbl, ty, span| Arg {
1484 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1491 SelfKind::Explicit(ty, mutbl) => {
1492 arg(mutbl, ty, mk_sp(eself.span.lo, eself_ident.span.hi))
1494 SelfKind::Value(mutbl) => arg(mutbl, infer_ty, eself.span),
1495 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1497 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1504 /// Header (not the body) of a function declaration.
1506 /// E.g. `fn foo(bar: baz)`
1507 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1509 pub inputs: Vec<Arg>,
1510 pub output: FunctionRetTy,
1515 pub fn get_self(&self) -> Option<ExplicitSelf> {
1516 self.inputs.get(0).and_then(Arg::to_self)
1518 pub fn has_self(&self) -> bool {
1519 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1523 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1529 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1530 pub enum Constness {
1535 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub enum Defaultness {
1541 impl fmt::Display for Unsafety {
1542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543 fmt::Display::fmt(match *self {
1544 Unsafety::Normal => "normal",
1545 Unsafety::Unsafe => "unsafe",
1550 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1551 pub enum ImplPolarity {
1552 /// `impl Trait for Type`
1554 /// `impl !Trait for Type`
1558 impl fmt::Debug for ImplPolarity {
1559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1561 ImplPolarity::Positive => "positive".fmt(f),
1562 ImplPolarity::Negative => "negative".fmt(f),
1568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1569 pub enum FunctionRetTy {
1570 /// Return type is not specified.
1572 /// Functions default to `()` and
1573 /// closures default to inference. Span points to where return
1574 /// type would be inserted.
1580 impl FunctionRetTy {
1581 pub fn span(&self) -> Span {
1583 FunctionRetTy::Default(span) => span,
1584 FunctionRetTy::Ty(ref ty) => ty.span,
1589 /// Module declaration.
1591 /// E.g. `mod foo;` or `mod foo { .. }`
1592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1594 /// A span from the first token past `{` to the last token until `}`.
1595 /// For `mod foo;`, the inner span ranges from the first token
1596 /// to the last token in the external file.
1598 pub items: Vec<P<Item>>,
1601 /// Foreign module declaration.
1603 /// E.g. `extern { .. }` or `extern C { .. }`
1604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1605 pub struct ForeignMod {
1607 pub items: Vec<ForeignItem>,
1610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1611 pub struct EnumDef {
1612 pub variants: Vec<Variant>,
1615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1616 pub struct Variant_ {
1618 pub attrs: Vec<Attribute>,
1619 pub data: VariantData,
1620 /// Explicit discriminant, e.g. `Foo = 1`
1621 pub disr_expr: Option<P<Expr>>,
1624 pub type Variant = Spanned<Variant_>;
1626 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1627 pub enum PathListItemKind {
1630 /// renamed in list, e.g. `use foo::{bar as baz};`
1631 rename: Option<Ident>,
1635 /// renamed in list, e.g. `use foo::{self as baz};`
1636 rename: Option<Ident>,
1641 impl PathListItemKind {
1642 pub fn id(&self) -> NodeId {
1644 PathListItemKind::Ident { id, .. } | PathListItemKind::Mod { id, .. } => id
1648 pub fn name(&self) -> Option<Ident> {
1650 PathListItemKind::Ident { name, .. } => Some(name),
1651 PathListItemKind::Mod { .. } => None,
1655 pub fn rename(&self) -> Option<Ident> {
1657 PathListItemKind::Ident { rename, .. } | PathListItemKind::Mod { rename, .. } => rename
1662 pub type PathListItem = Spanned<PathListItemKind>;
1664 pub type ViewPath = Spanned<ViewPath_>;
1666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1667 pub enum ViewPath_ {
1669 /// `foo::bar::baz as quux`
1673 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1674 ViewPathSimple(Ident, Path),
1679 /// `foo::bar::{a,b,c}`
1680 ViewPathList(Path, Vec<PathListItem>)
1684 pub fn path(&self) -> &Path {
1686 ViewPathSimple(_, ref path) |
1687 ViewPathGlob (ref path) |
1688 ViewPathList(ref path, _) => path
1693 /// Meta-data associated with an item
1694 pub type Attribute = Spanned<Attribute_>;
1696 /// Distinguishes between Attributes that decorate items and Attributes that
1697 /// are contained as statements within items. These two cases need to be
1698 /// distinguished for pretty-printing.
1699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1700 pub enum AttrStyle {
1705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1706 pub struct AttrId(pub usize);
1708 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1709 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1710 pub struct Attribute_ {
1712 pub style: AttrStyle,
1713 pub value: P<MetaItem>,
1714 pub is_sugared_doc: bool,
1717 /// TraitRef's appear in impls.
1719 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1720 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1721 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1722 /// same as the impl's node id).
1723 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1724 pub struct TraitRef {
1729 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1730 pub struct PolyTraitRef {
1731 /// The `'a` in `<'a> Foo<&'a T>`
1732 pub bound_lifetimes: Vec<LifetimeDef>,
1734 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1735 pub trait_ref: TraitRef,
1740 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1741 pub enum Visibility {
1744 Restricted { path: P<Path>, id: NodeId },
1748 /// Field of a struct.
1750 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1751 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1752 pub struct StructField {
1754 pub ident: Option<Ident>,
1755 pub vis: Visibility,
1758 pub attrs: Vec<Attribute>,
1761 /// Fields and Ids of enum variants and structs
1763 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1764 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1765 /// One shared Id can be successfully used for these two purposes.
1766 /// Id of the whole enum lives in `Item`.
1768 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1769 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1770 /// the variant itself" from enum variants.
1771 /// Id of the whole struct lives in `Item`.
1772 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1773 pub enum VariantData {
1776 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1777 Struct(Vec<StructField>, NodeId),
1780 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1781 Tuple(Vec<StructField>, NodeId),
1784 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1789 pub fn fields(&self) -> &[StructField] {
1791 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1795 pub fn id(&self) -> NodeId {
1797 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1800 pub fn is_struct(&self) -> bool {
1801 if let VariantData::Struct(..) = *self { true } else { false }
1803 pub fn is_tuple(&self) -> bool {
1804 if let VariantData::Tuple(..) = *self { true } else { false }
1806 pub fn is_unit(&self) -> bool {
1807 if let VariantData::Unit(..) = *self { true } else { false }
1812 FIXME (#3300): Should allow items to be anonymous. Right now
1813 we just use dummy names for anon items.
1817 /// The name might be a dummy name in case of anonymous items
1818 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1821 pub attrs: Vec<Attribute>,
1824 pub vis: Visibility,
1828 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1830 /// An`extern crate` item, with optional original crate name.
1832 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1833 ExternCrate(Option<Name>),
1834 /// A use declaration (`use` or `pub use`) item.
1836 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1838 /// A static item (`static` or `pub static`).
1840 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1841 Static(P<Ty>, Mutability, P<Expr>),
1842 /// A constant item (`const` or `pub const`).
1844 /// E.g. `const FOO: i32 = 42;`
1845 Const(P<Ty>, P<Expr>),
1846 /// A function declaration (`fn` or `pub fn`).
1848 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1849 Fn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1850 /// A module declaration (`mod` or `pub mod`).
1852 /// E.g. `mod foo;` or `mod foo { .. }`
1854 /// An external module (`extern` or `pub extern`).
1856 /// E.g. `extern {}` or `extern "C" {}`
1857 ForeignMod(ForeignMod),
1858 /// A type alias (`type` or `pub type`).
1860 /// E.g. `type Foo = Bar<u8>;`
1861 Ty(P<Ty>, Generics),
1862 /// An enum definition (`enum` or `pub enum`).
1864 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1865 Enum(EnumDef, Generics),
1866 /// A struct definition (`struct` or `pub struct`).
1868 /// E.g. `struct Foo<A> { x: A }`
1869 Struct(VariantData, Generics),
1870 /// A Trait declaration (`trait` or `pub trait`).
1872 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1873 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1874 // Default trait implementation.
1876 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1877 DefaultImpl(Unsafety, TraitRef),
1878 /// An implementation.
1880 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1884 Option<TraitRef>, // (optional) trait this impl implements
1887 /// A macro invocation (which includes macro definition).
1889 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1894 pub fn descriptive_variant(&self) -> &str {
1896 ItemKind::ExternCrate(..) => "extern crate",
1897 ItemKind::Use(..) => "use",
1898 ItemKind::Static(..) => "static item",
1899 ItemKind::Const(..) => "constant item",
1900 ItemKind::Fn(..) => "function",
1901 ItemKind::Mod(..) => "module",
1902 ItemKind::ForeignMod(..) => "foreign module",
1903 ItemKind::Ty(..) => "type alias",
1904 ItemKind::Enum(..) => "enum",
1905 ItemKind::Struct(..) => "struct",
1906 ItemKind::Trait(..) => "trait",
1908 ItemKind::Impl(..) |
1909 ItemKind::DefaultImpl(..) => "item"
1914 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1915 pub struct ForeignItem {
1917 pub attrs: Vec<Attribute>,
1918 pub node: ForeignItemKind,
1921 pub vis: Visibility,
1924 /// An item within an `extern` block
1925 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1926 pub enum ForeignItemKind {
1927 /// A foreign function
1928 Fn(P<FnDecl>, Generics),
1929 /// A foreign static item (`static ext: u8`), with optional mutability
1930 /// (the boolean is true when mutable)
1931 Static(P<Ty>, bool),
1934 impl ForeignItemKind {
1935 pub fn descriptive_variant(&self) -> &str {
1937 ForeignItemKind::Fn(..) => "foreign function",
1938 ForeignItemKind::Static(..) => "foreign static item"
1943 /// A macro definition, in this crate or imported from another.
1945 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1946 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1947 pub struct MacroDef {
1949 pub attrs: Vec<Attribute>,
1952 pub imported_from: Option<Ident>,
1954 pub use_locally: bool,
1955 pub allow_internal_unstable: bool,
1956 pub body: Vec<TokenTree>,
1964 // are ASTs encodable?
1966 fn check_asts_encodable() {
1967 fn assert_encodable<T: serialize::Encodable>() {}
1968 assert_encodable::<Crate>();