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)]
1352 /// A fixed length array (`[T; n]`)
1353 FixedLengthVec(P<Ty>, P<Expr>),
1354 /// A raw pointer (`*const T` or `*mut T`)
1356 /// A reference (`&'a T` or `&'a mut T`)
1357 Rptr(Option<Lifetime>, MutTy),
1358 /// A bare function (e.g. `fn(usize) -> bool`)
1359 BareFn(P<BareFnTy>),
1360 /// A tuple (`(A, B, C, D,...)`)
1362 /// A path (`module::module::...::Type`), optionally
1363 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1365 /// Type parameters are stored in the Path itself
1366 Path(Option<QSelf>, Path),
1367 /// Something like `A+B`. Note that `B` must always be a path.
1368 ObjectSum(P<Ty>, TyParamBounds),
1369 /// A type like `for<'a> Foo<&'a Bar>`
1370 PolyTraitRef(TyParamBounds),
1371 /// No-op; kept solely so that we can pretty-print faithfully
1375 /// TyKind::Infer means the type should be inferred instead of it having been
1376 /// specified. This can appear anywhere in a type.
1378 /// Inferred type of a `self` or `&self` argument in a method.
1380 // A macro in the type position.
1384 /// Inline assembly dialect.
1386 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1387 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1388 pub enum AsmDialect {
1393 /// Inline assembly.
1395 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1396 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1397 pub struct InlineAsmOutput {
1398 pub constraint: InternedString,
1401 pub is_indirect: bool,
1404 /// Inline assembly.
1406 /// E.g. `asm!("NOP");`
1407 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1408 pub struct InlineAsm {
1409 pub asm: InternedString,
1410 pub asm_str_style: StrStyle,
1411 pub outputs: Vec<InlineAsmOutput>,
1412 pub inputs: Vec<(InternedString, P<Expr>)>,
1413 pub clobbers: Vec<InternedString>,
1415 pub alignstack: bool,
1416 pub dialect: AsmDialect,
1417 pub expn_id: ExpnId,
1420 /// An argument in a function header.
1422 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1423 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1430 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1432 /// E.g. `&mut self` as in `fn foo(&mut self)`
1433 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1435 /// `self`, `mut self`
1437 /// `&'lt self`, `&'lt mut self`
1438 Region(Option<Lifetime>, Mutability),
1439 /// `self: TYPE`, `mut self: TYPE`
1440 Explicit(P<Ty>, Mutability),
1443 pub type ExplicitSelf = Spanned<SelfKind>;
1446 pub fn to_self(&self) -> Option<ExplicitSelf> {
1447 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1448 if ident.node.name == keywords::SelfValue.name() {
1449 return match self.ty.node {
1450 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1451 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1452 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1454 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1455 SelfKind::Explicit(self.ty.clone(), mutbl))),
1462 pub fn is_self(&self) -> bool {
1463 if let PatKind::Ident(_, ident, _) = self.pat.node {
1464 ident.node.name == keywords::SelfValue.name()
1470 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1471 let infer_ty = P(Ty {
1473 node: TyKind::ImplicitSelf,
1476 let arg = |mutbl, ty, span| Arg {
1479 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1486 SelfKind::Explicit(ty, mutbl) => {
1487 arg(mutbl, ty, mk_sp(eself.span.lo, eself_ident.span.hi))
1489 SelfKind::Value(mutbl) => arg(mutbl, infer_ty, eself.span),
1490 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1492 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1499 /// Header (not the body) of a function declaration.
1501 /// E.g. `fn foo(bar: baz)`
1502 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1504 pub inputs: Vec<Arg>,
1505 pub output: FunctionRetTy,
1510 pub fn get_self(&self) -> Option<ExplicitSelf> {
1511 self.inputs.get(0).and_then(Arg::to_self)
1513 pub fn has_self(&self) -> bool {
1514 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1518 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1524 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1525 pub enum Constness {
1530 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1531 pub enum Defaultness {
1536 impl fmt::Display for Unsafety {
1537 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1538 fmt::Display::fmt(match *self {
1539 Unsafety::Normal => "normal",
1540 Unsafety::Unsafe => "unsafe",
1545 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1546 pub enum ImplPolarity {
1547 /// `impl Trait for Type`
1549 /// `impl !Trait for Type`
1553 impl fmt::Debug for ImplPolarity {
1554 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1556 ImplPolarity::Positive => "positive".fmt(f),
1557 ImplPolarity::Negative => "negative".fmt(f),
1563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1564 pub enum FunctionRetTy {
1565 /// Functions with return type `!`that always
1566 /// raise an error or exit (i.e. never return to the caller)
1568 /// Return type is not specified.
1570 /// Functions default to `()` and
1571 /// closures default to inference. Span points to where return
1572 /// type would be inserted.
1578 impl FunctionRetTy {
1579 pub fn span(&self) -> Span {
1581 FunctionRetTy::None(span) => span,
1582 FunctionRetTy::Default(span) => span,
1583 FunctionRetTy::Ty(ref ty) => ty.span,
1588 /// Module declaration.
1590 /// E.g. `mod foo;` or `mod foo { .. }`
1591 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1593 /// A span from the first token past `{` to the last token until `}`.
1594 /// For `mod foo;`, the inner span ranges from the first token
1595 /// to the last token in the external file.
1597 pub items: Vec<P<Item>>,
1600 /// Foreign module declaration.
1602 /// E.g. `extern { .. }` or `extern C { .. }`
1603 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1604 pub struct ForeignMod {
1606 pub items: Vec<ForeignItem>,
1609 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1610 pub struct EnumDef {
1611 pub variants: Vec<Variant>,
1614 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1615 pub struct Variant_ {
1617 pub attrs: Vec<Attribute>,
1618 pub data: VariantData,
1619 /// Explicit discriminant, e.g. `Foo = 1`
1620 pub disr_expr: Option<P<Expr>>,
1623 pub type Variant = Spanned<Variant_>;
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1626 pub enum PathListItemKind {
1629 /// renamed in list, e.g. `use foo::{bar as baz};`
1630 rename: Option<Ident>,
1634 /// renamed in list, e.g. `use foo::{self as baz};`
1635 rename: Option<Ident>,
1640 impl PathListItemKind {
1641 pub fn id(&self) -> NodeId {
1643 PathListItemKind::Ident { id, .. } | PathListItemKind::Mod { id, .. } => id
1647 pub fn name(&self) -> Option<Ident> {
1649 PathListItemKind::Ident { name, .. } => Some(name),
1650 PathListItemKind::Mod { .. } => None,
1654 pub fn rename(&self) -> Option<Ident> {
1656 PathListItemKind::Ident { rename, .. } | PathListItemKind::Mod { rename, .. } => rename
1661 pub type PathListItem = Spanned<PathListItemKind>;
1663 pub type ViewPath = Spanned<ViewPath_>;
1665 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1666 pub enum ViewPath_ {
1668 /// `foo::bar::baz as quux`
1672 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1673 ViewPathSimple(Ident, Path),
1678 /// `foo::bar::{a,b,c}`
1679 ViewPathList(Path, Vec<PathListItem>)
1683 pub fn path(&self) -> &Path {
1685 ViewPathSimple(_, ref path) |
1686 ViewPathGlob (ref path) |
1687 ViewPathList(ref path, _) => path
1692 /// Meta-data associated with an item
1693 pub type Attribute = Spanned<Attribute_>;
1695 /// Distinguishes between Attributes that decorate items and Attributes that
1696 /// are contained as statements within items. These two cases need to be
1697 /// distinguished for pretty-printing.
1698 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1699 pub enum AttrStyle {
1704 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1705 pub struct AttrId(pub usize);
1707 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1708 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1709 pub struct Attribute_ {
1711 pub style: AttrStyle,
1712 pub value: P<MetaItem>,
1713 pub is_sugared_doc: bool,
1716 /// TraitRef's appear in impls.
1718 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1719 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1720 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1721 /// same as the impl's node id).
1722 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1723 pub struct TraitRef {
1728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1729 pub struct PolyTraitRef {
1730 /// The `'a` in `<'a> Foo<&'a T>`
1731 pub bound_lifetimes: Vec<LifetimeDef>,
1733 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1734 pub trait_ref: TraitRef,
1739 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1740 pub enum Visibility {
1743 Restricted { path: P<Path>, id: NodeId },
1747 /// Field of a struct.
1749 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1750 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1751 pub struct StructField {
1753 pub ident: Option<Ident>,
1754 pub vis: Visibility,
1757 pub attrs: Vec<Attribute>,
1760 /// Fields and Ids of enum variants and structs
1762 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1763 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1764 /// One shared Id can be successfully used for these two purposes.
1765 /// Id of the whole enum lives in `Item`.
1767 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1768 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1769 /// the variant itself" from enum variants.
1770 /// Id of the whole struct lives in `Item`.
1771 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1772 pub enum VariantData {
1775 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1776 Struct(Vec<StructField>, NodeId),
1779 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1780 Tuple(Vec<StructField>, NodeId),
1783 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1788 pub fn fields(&self) -> &[StructField] {
1790 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1794 pub fn id(&self) -> NodeId {
1796 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1799 pub fn is_struct(&self) -> bool {
1800 if let VariantData::Struct(..) = *self { true } else { false }
1802 pub fn is_tuple(&self) -> bool {
1803 if let VariantData::Tuple(..) = *self { true } else { false }
1805 pub fn is_unit(&self) -> bool {
1806 if let VariantData::Unit(..) = *self { true } else { false }
1811 FIXME (#3300): Should allow items to be anonymous. Right now
1812 we just use dummy names for anon items.
1816 /// The name might be a dummy name in case of anonymous items
1817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1820 pub attrs: Vec<Attribute>,
1823 pub vis: Visibility,
1827 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1829 /// An`extern crate` item, with optional original crate name.
1831 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1832 ExternCrate(Option<Name>),
1833 /// A use declaration (`use` or `pub use`) item.
1835 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1837 /// A static item (`static` or `pub static`).
1839 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1840 Static(P<Ty>, Mutability, P<Expr>),
1841 /// A constant item (`const` or `pub const`).
1843 /// E.g. `const FOO: i32 = 42;`
1844 Const(P<Ty>, P<Expr>),
1845 /// A function declaration (`fn` or `pub fn`).
1847 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1848 Fn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1849 /// A module declaration (`mod` or `pub mod`).
1851 /// E.g. `mod foo;` or `mod foo { .. }`
1853 /// An external module (`extern` or `pub extern`).
1855 /// E.g. `extern {}` or `extern "C" {}`
1856 ForeignMod(ForeignMod),
1857 /// A type alias (`type` or `pub type`).
1859 /// E.g. `type Foo = Bar<u8>;`
1860 Ty(P<Ty>, Generics),
1861 /// An enum definition (`enum` or `pub enum`).
1863 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1864 Enum(EnumDef, Generics),
1865 /// A struct definition (`struct` or `pub struct`).
1867 /// E.g. `struct Foo<A> { x: A }`
1868 Struct(VariantData, Generics),
1869 /// A Trait declaration (`trait` or `pub trait`).
1871 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1872 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1873 // Default trait implementation.
1875 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1876 DefaultImpl(Unsafety, TraitRef),
1877 /// An implementation.
1879 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1883 Option<TraitRef>, // (optional) trait this impl implements
1886 /// A macro invocation (which includes macro definition).
1888 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1893 pub fn descriptive_variant(&self) -> &str {
1895 ItemKind::ExternCrate(..) => "extern crate",
1896 ItemKind::Use(..) => "use",
1897 ItemKind::Static(..) => "static item",
1898 ItemKind::Const(..) => "constant item",
1899 ItemKind::Fn(..) => "function",
1900 ItemKind::Mod(..) => "module",
1901 ItemKind::ForeignMod(..) => "foreign module",
1902 ItemKind::Ty(..) => "type alias",
1903 ItemKind::Enum(..) => "enum",
1904 ItemKind::Struct(..) => "struct",
1905 ItemKind::Trait(..) => "trait",
1907 ItemKind::Impl(..) |
1908 ItemKind::DefaultImpl(..) => "item"
1913 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1914 pub struct ForeignItem {
1916 pub attrs: Vec<Attribute>,
1917 pub node: ForeignItemKind,
1920 pub vis: Visibility,
1923 /// An item within an `extern` block
1924 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1925 pub enum ForeignItemKind {
1926 /// A foreign function
1927 Fn(P<FnDecl>, Generics),
1928 /// A foreign static item (`static ext: u8`), with optional mutability
1929 /// (the boolean is true when mutable)
1930 Static(P<Ty>, bool),
1933 impl ForeignItemKind {
1934 pub fn descriptive_variant(&self) -> &str {
1936 ForeignItemKind::Fn(..) => "foreign function",
1937 ForeignItemKind::Static(..) => "foreign static item"
1942 /// A macro definition, in this crate or imported from another.
1944 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1945 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1946 pub struct MacroDef {
1948 pub attrs: Vec<Attribute>,
1951 pub imported_from: Option<Ident>,
1953 pub use_locally: bool,
1954 pub allow_internal_unstable: bool,
1955 pub body: Vec<TokenTree>,
1963 // are ASTs encodable?
1965 fn check_asts_encodable() {
1966 fn assert_encodable<T: serialize::Encodable>() {}
1967 assert_encodable::<Crate>();