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 symbol::{Ident, Symbol as Name};
18 pub use util::ThinVec;
20 use syntax_pos::{Span, DUMMY_SP};
21 use codemap::{respan, Spanned};
23 use ext::hygiene::{Mark, SyntaxContext};
26 use rustc_data_structures::indexed_vec;
27 use symbol::{Symbol, keywords};
28 use tokenstream::{ThinTokenStream, TokenStream};
30 use serialize::{self, Encoder, Decoder};
31 use std::collections::HashSet;
36 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
43 impl fmt::Debug for Lifetime {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
49 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
50 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
51 pub struct LifetimeDef {
52 pub attrs: ThinVec<Attribute>,
53 pub lifetime: Lifetime,
54 pub bounds: Vec<Lifetime>
57 /// A "Path" is essentially Rust's notion of a name.
59 /// It's represented as a sequence of identifiers,
60 /// along with a bunch of supporting information.
62 /// E.g. `std::cmp::PartialEq`
63 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
66 /// The segments in the path: the things separated by `::`.
67 /// Global paths begin with `keywords::CrateRoot`.
68 pub segments: Vec<PathSegment>,
71 impl<'a> PartialEq<&'a str> for Path {
72 fn eq(&self, string: &&'a str) -> bool {
73 self.segments.len() == 1 && self.segments[0].identifier.name == *string
77 impl fmt::Debug for Path {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 write!(f, "path({})", pprust::path_to_string(self))
83 impl fmt::Display for Path {
84 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85 write!(f, "{}", pprust::path_to_string(self))
90 // convert a span and an identifier to the corresponding
92 pub fn from_ident(s: Span, identifier: Ident) -> Path {
95 segments: vec![PathSegment::from_ident(identifier, s)],
99 pub fn default_to_global(mut self) -> Path {
100 if !self.is_global() &&
101 !::parse::token::Ident(self.segments[0].identifier).is_path_segment_keyword() {
102 self.segments.insert(0, PathSegment::crate_root(self.span));
107 pub fn is_global(&self) -> bool {
108 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
112 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
114 /// E.g. `std`, `String` or `Box<T>`
115 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
116 pub struct PathSegment {
117 /// The identifier portion of this path segment.
118 pub identifier: Ident,
119 /// Span of the segment identifier.
122 /// Type/lifetime parameters attached to this path. They come in
123 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
124 /// `None` means that no parameter list is supplied (`Path`),
125 /// `Some` means that parameter list is supplied (`Path<X, Y>`)
126 /// but it can be empty (`Path<>`).
127 /// `P` is used as a size optimization for the common case with no parameters.
128 pub parameters: Option<P<PathParameters>>,
132 pub fn from_ident(ident: Ident, span: Span) -> Self {
133 PathSegment { identifier: ident, span: span, parameters: None }
135 pub fn crate_root(span: Span) -> Self {
137 identifier: Ident { ctxt: span.ctxt, ..keywords::CrateRoot.ident() },
144 /// Parameters of a path segment.
146 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
147 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
148 pub enum PathParameters {
149 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
150 AngleBracketed(AngleBracketedParameterData),
151 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
152 Parenthesized(ParenthesizedParameterData),
155 impl PathParameters {
156 pub fn span(&self) -> Span {
158 AngleBracketed(ref data) => data.span,
159 Parenthesized(ref data) => data.span,
164 /// A path like `Foo<'a, T>`
165 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
166 pub struct AngleBracketedParameterData {
169 /// The lifetime parameters for this path segment.
170 pub lifetimes: Vec<Lifetime>,
171 /// The type parameters for this path segment, if present.
172 pub types: Vec<P<Ty>>,
173 /// Bindings (equality constraints) on associated types, if present.
175 /// E.g., `Foo<A=Bar>`.
176 pub bindings: Vec<TypeBinding>,
179 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
180 fn into(self) -> Option<P<PathParameters>> {
181 Some(P(PathParameters::AngleBracketed(self)))
185 impl Into<Option<P<PathParameters>>> for ParenthesizedParameterData {
186 fn into(self) -> Option<P<PathParameters>> {
187 Some(P(PathParameters::Parenthesized(self)))
191 /// A path like `Foo(A,B) -> C`
192 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
193 pub struct ParenthesizedParameterData {
198 pub inputs: Vec<P<Ty>>,
201 pub output: Option<P<Ty>>,
204 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
205 pub struct NodeId(u32);
208 pub fn new(x: usize) -> NodeId {
209 assert!(x < (u32::MAX as usize));
213 pub fn from_u32(x: u32) -> NodeId {
217 pub fn as_usize(&self) -> usize {
221 pub fn as_u32(&self) -> u32 {
225 pub fn placeholder_from_mark(mark: Mark) -> Self {
226 NodeId(mark.as_u32())
229 pub fn placeholder_to_mark(self) -> Mark {
230 Mark::from_u32(self.0)
234 impl fmt::Display for NodeId {
235 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
236 fmt::Display::fmt(&self.0, f)
240 impl serialize::UseSpecializedEncodable for NodeId {
241 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
246 impl serialize::UseSpecializedDecodable for NodeId {
247 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
248 d.read_u32().map(NodeId)
252 impl indexed_vec::Idx for NodeId {
253 fn new(idx: usize) -> Self {
257 fn index(self) -> usize {
262 /// Node id used to represent the root of the crate.
263 pub const CRATE_NODE_ID: NodeId = NodeId(0);
265 /// When parsing and doing expansions, we initially give all AST nodes this AST
266 /// node value. Then later, in the renumber pass, we renumber them to have
267 /// small, positive ids.
268 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
270 /// The AST represents all type param bounds as types.
271 /// typeck::collect::compute_bounds matches these against
272 /// the "special" built-in traits (see middle::lang_items) and
273 /// detects Copy, Send and Sync.
274 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
275 pub enum TyParamBound {
276 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
277 RegionTyParamBound(Lifetime)
280 /// A modifier on a bound, currently this is only used for `?Sized`, where the
281 /// modifier is `Maybe`. Negative bounds should also be handled here.
282 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
283 pub enum TraitBoundModifier {
288 pub type TyParamBounds = Vec<TyParamBound>;
290 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
292 pub attrs: ThinVec<Attribute>,
295 pub bounds: TyParamBounds,
296 pub default: Option<P<Ty>>,
300 /// Represents lifetimes and type parameters attached to a declaration
301 /// of a function, enum, trait, etc.
302 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
303 pub struct Generics {
304 pub lifetimes: Vec<LifetimeDef>,
305 pub ty_params: Vec<TyParam>,
306 pub where_clause: WhereClause,
311 pub fn is_lt_parameterized(&self) -> bool {
312 !self.lifetimes.is_empty()
314 pub fn is_type_parameterized(&self) -> bool {
315 !self.ty_params.is_empty()
317 pub fn is_parameterized(&self) -> bool {
318 self.is_lt_parameterized() || self.is_type_parameterized()
320 pub fn span_for_name(&self, name: &str) -> Option<Span> {
321 for t in &self.ty_params {
322 if t.ident.name == name {
330 impl Default for Generics {
331 /// Creates an instance of `Generics`.
332 fn default() -> Generics {
334 lifetimes: Vec::new(),
335 ty_params: Vec::new(),
336 where_clause: WhereClause {
338 predicates: Vec::new(),
345 /// A `where` clause in a definition
346 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
347 pub struct WhereClause {
349 pub predicates: Vec<WherePredicate>,
352 /// A single predicate in a `where` clause
353 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
354 pub enum WherePredicate {
355 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
356 BoundPredicate(WhereBoundPredicate),
357 /// A lifetime predicate, e.g. `'a: 'b+'c`
358 RegionPredicate(WhereRegionPredicate),
359 /// An equality predicate (unsupported)
360 EqPredicate(WhereEqPredicate),
365 /// E.g. `for<'c> Foo: Send+Clone+'c`
366 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
367 pub struct WhereBoundPredicate {
369 /// Any lifetimes from a `for` binding
370 pub bound_lifetimes: Vec<LifetimeDef>,
371 /// The type being bounded
372 pub bounded_ty: P<Ty>,
373 /// Trait and lifetime bounds (`Clone+Send+'static`)
374 pub bounds: TyParamBounds,
377 /// A lifetime predicate.
380 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
381 pub struct WhereRegionPredicate {
383 pub lifetime: Lifetime,
384 pub bounds: Vec<Lifetime>,
387 /// An equality predicate (unsupported).
390 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
391 pub struct WhereEqPredicate {
398 /// The set of MetaItems that define the compilation environment of the crate,
399 /// used to drive conditional compilation
400 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
402 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
405 pub attrs: Vec<Attribute>,
409 /// A spanned compile-time attribute list item.
410 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
412 /// Possible values inside of compile-time attribute lists.
414 /// E.g. the '..' in `#[name(..)]`.
415 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
416 pub enum NestedMetaItemKind {
417 /// A full MetaItem, for recursive meta items.
421 /// E.g. "foo", 64, true
425 /// A spanned compile-time attribute item.
427 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
428 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
429 pub struct MetaItem {
431 pub node: MetaItemKind,
435 /// A compile-time attribute item.
437 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub enum MetaItemKind {
442 /// E.g. `test` as in `#[test]`
446 /// E.g. `derive(..)` as in `#[derive(..)]`
447 List(Vec<NestedMetaItem>),
448 /// Name value meta item.
450 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
454 /// A Block (`{ .. }`).
456 /// E.g. `{ .. }` as in `fn foo() { .. }`
457 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
459 /// Statements in a block
460 pub stmts: Vec<Stmt>,
462 /// Distinguishes between `unsafe { ... }` and `{ ... }`
463 pub rules: BlockCheckMode,
467 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
474 impl fmt::Debug for Pat {
475 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
476 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
481 pub fn walk<F>(&self, it: &mut F) -> bool
482 where F: FnMut(&Pat) -> bool
489 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
490 PatKind::Struct(_, ref fields, _) => {
491 fields.iter().all(|field| field.node.pat.walk(it))
493 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
494 s.iter().all(|p| p.walk(it))
496 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
499 PatKind::Slice(ref before, ref slice, ref after) => {
500 before.iter().all(|p| p.walk(it)) &&
501 slice.iter().all(|p| p.walk(it)) &&
502 after.iter().all(|p| p.walk(it))
516 /// A single field in a struct pattern
518 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
519 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
520 /// except is_shorthand is true
521 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
522 pub struct FieldPat {
523 /// The identifier for the field
525 /// The pattern the field is destructured to
527 pub is_shorthand: bool,
528 pub attrs: ThinVec<Attribute>,
531 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
532 pub enum BindingMode {
537 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
543 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
545 /// Represents a wildcard pattern (`_`)
548 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
549 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
550 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
551 /// during name resolution.
552 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
554 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
555 /// The `bool` is `true` in the presence of a `..`.
556 Struct(Path, Vec<Spanned<FieldPat>>, bool),
558 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
559 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
560 /// 0 <= position <= subpats.len()
561 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
563 /// A possibly qualified path pattern.
564 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
565 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
566 /// only legally refer to associated constants.
567 Path(Option<QSelf>, Path),
569 /// A tuple pattern `(a, b)`.
570 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
571 /// 0 <= position <= subpats.len()
572 Tuple(Vec<P<Pat>>, Option<usize>),
575 /// A reference pattern, e.g. `&mut (a, b)`
576 Ref(P<Pat>, Mutability),
579 /// A range pattern, e.g. `1...2` or `1..2`
580 Range(P<Expr>, P<Expr>, RangeEnd),
581 /// `[a, b, ..i, y, z]` is represented as:
582 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
583 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
584 /// A macro pattern; pre-expansion
588 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
589 pub enum Mutability {
594 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
596 /// The `+` operator (addition)
598 /// The `-` operator (subtraction)
600 /// The `*` operator (multiplication)
602 /// The `/` operator (division)
604 /// The `%` operator (modulus)
606 /// The `&&` operator (logical and)
608 /// The `||` operator (logical or)
610 /// The `^` operator (bitwise xor)
612 /// The `&` operator (bitwise and)
614 /// The `|` operator (bitwise or)
616 /// The `<<` operator (shift left)
618 /// The `>>` operator (shift right)
620 /// The `==` operator (equality)
622 /// The `<` operator (less than)
624 /// The `<=` operator (less than or equal to)
626 /// The `!=` operator (not equal to)
628 /// The `>=` operator (greater than or equal to)
630 /// The `>` operator (greater than)
635 pub fn to_string(&self) -> &'static str {
636 use self::BinOpKind::*;
658 pub fn lazy(&self) -> bool {
660 BinOpKind::And | BinOpKind::Or => true,
665 pub fn is_shift(&self) -> bool {
667 BinOpKind::Shl | BinOpKind::Shr => true,
671 pub fn is_comparison(&self) -> bool {
672 use self::BinOpKind::*;
674 Eq | Lt | Le | Ne | Gt | Ge =>
676 And | Or | Add | Sub | Mul | Div | Rem |
677 BitXor | BitAnd | BitOr | Shl | Shr =>
681 /// Returns `true` if the binary operator takes its arguments by value
682 pub fn is_by_value(&self) -> bool {
683 !self.is_comparison()
687 pub type BinOp = Spanned<BinOpKind>;
689 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
691 /// The `*` operator for dereferencing
693 /// The `!` operator for logical inversion
695 /// The `-` operator for negation
700 /// Returns `true` if the unary operator takes its argument by value
701 pub fn is_by_value(u: UnOp) -> bool {
703 UnOp::Neg | UnOp::Not => true,
708 pub fn to_string(op: UnOp) -> &'static str {
718 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
726 pub fn add_trailing_semicolon(mut self) -> Self {
727 self.node = match self.node {
728 StmtKind::Expr(expr) => StmtKind::Semi(expr),
729 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
730 (mac, MacStmtStyle::Semicolon, attrs)
738 impl fmt::Debug for Stmt {
739 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
740 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
745 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
747 /// A local (let) binding.
750 /// An item definition.
753 /// Expr without trailing semi-colon.
758 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
761 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
762 pub enum MacStmtStyle {
763 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
764 /// `foo!(...);`, `foo![...];`
766 /// The macro statement had braces; e.g. foo! { ... }
768 /// The macro statement had parentheses or brackets and no semicolon; e.g.
769 /// `foo!(...)`. All of these will end up being converted into macro
774 // FIXME (pending discussion of #1697, #2178...): local should really be
775 // a refinement on pat.
776 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
777 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
780 pub ty: Option<P<Ty>>,
781 /// Initializer expression to set the value, if any
782 pub init: Option<P<Expr>>,
785 pub attrs: ThinVec<Attribute>,
788 /// An arm of a 'match'.
790 /// E.g. `0...10 => { println!("match!") }` as in
794 /// 0...10 => { println!("match!") },
795 /// _ => { println!("no match!") },
798 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
800 pub attrs: Vec<Attribute>,
801 pub pats: Vec<P<Pat>>,
802 pub guard: Option<P<Expr>>,
806 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
808 pub ident: SpannedIdent,
811 pub is_shorthand: bool,
812 pub attrs: ThinVec<Attribute>,
815 pub type SpannedIdent = Spanned<Ident>;
817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
818 pub enum BlockCheckMode {
820 Unsafe(UnsafeSource),
823 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
824 pub enum UnsafeSource {
830 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
835 pub attrs: ThinVec<Attribute>
838 impl fmt::Debug for Expr {
839 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
840 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
844 /// Limit types of a range (inclusive or exclusive)
845 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
846 pub enum RangeLimits {
847 /// Inclusive at the beginning, exclusive at the end
849 /// Inclusive at the beginning and end
853 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
855 /// A `box x` expression.
857 /// First expr is the place; second expr is the value.
858 InPlace(P<Expr>, P<Expr>),
859 /// An array (`[a, b, c, d]`)
863 /// The first field resolves to the function itself,
864 /// and the second field is the list of arguments
865 Call(P<Expr>, Vec<P<Expr>>),
866 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
868 /// The `PathSegment` represents the method name and its generic arguments
869 /// (within the angle brackets).
870 /// The first element of the vector of `Expr`s is the expression that evaluates
871 /// to the object on which the method is being called on (the receiver),
872 /// and the remaining elements are the rest of the arguments.
873 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
874 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
875 MethodCall(PathSegment, Vec<P<Expr>>),
876 /// A tuple (`(a, b, c ,d)`)
878 /// A binary operation (For example: `a + b`, `a * b`)
879 Binary(BinOp, P<Expr>, P<Expr>),
880 /// A unary operation (For example: `!x`, `*x`)
881 Unary(UnOp, P<Expr>),
882 /// A literal (For example: `1`, `"foo"`)
884 /// A cast (`foo as f64`)
885 Cast(P<Expr>, P<Ty>),
886 Type(P<Expr>, P<Ty>),
887 /// An `if` block, with an optional else block
889 /// `if expr { block } else { expr }`
890 If(P<Expr>, P<Block>, Option<P<Expr>>),
891 /// An `if let` expression with an optional else block
893 /// `if let pat = expr { block } else { expr }`
895 /// This is desugared to a `match` expression.
896 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
897 /// A while loop, with an optional label
899 /// `'label: while expr { block }`
900 While(P<Expr>, P<Block>, Option<SpannedIdent>),
901 /// A while-let loop, with an optional label
903 /// `'label: while let pat = expr { block }`
905 /// This is desugared to a combination of `loop` and `match` expressions.
906 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
907 /// A for loop, with an optional label
909 /// `'label: for pat in expr { block }`
911 /// This is desugared to a combination of `loop` and `match` expressions.
912 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
913 /// Conditionless loop (can be exited with break, continue, or return)
915 /// `'label: loop { block }`
916 Loop(P<Block>, Option<SpannedIdent>),
918 Match(P<Expr>, Vec<Arm>),
919 /// A closure (for example, `move |a, b, c| a + b + c`)
921 /// The final span is the span of the argument block `|...|`
922 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
923 /// A block (`{ ... }`)
925 /// A catch block (`catch { ... }`)
928 /// An assignment (`a = foo()`)
929 Assign(P<Expr>, P<Expr>),
930 /// An assignment with an operator
932 /// For example, `a += 1`.
933 AssignOp(BinOp, P<Expr>, P<Expr>),
934 /// Access of a named struct field (`obj.foo`)
935 Field(P<Expr>, SpannedIdent),
936 /// Access of an unnamed field of a struct or tuple-struct
938 /// For example, `foo.0`.
939 TupField(P<Expr>, Spanned<usize>),
940 /// An indexing operation (`foo[2]`)
941 Index(P<Expr>, P<Expr>),
942 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
943 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
945 /// Variable reference, possibly containing `::` and/or type
946 /// parameters, e.g. foo::bar::<baz>.
948 /// Optionally "qualified",
949 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
950 Path(Option<QSelf>, Path),
952 /// A referencing operation (`&a` or `&mut a`)
953 AddrOf(Mutability, P<Expr>),
954 /// A `break`, with an optional label to break, and an optional expression
955 Break(Option<SpannedIdent>, Option<P<Expr>>),
956 /// A `continue`, with an optional label
957 Continue(Option<SpannedIdent>),
958 /// A `return`, with an optional value to be returned
959 Ret(Option<P<Expr>>),
961 /// Output of the `asm!()` macro
962 InlineAsm(P<InlineAsm>),
964 /// A macro invocation; pre-expansion
967 /// A struct literal expression.
969 /// For example, `Foo {x: 1, y: 2}`, or
970 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
971 Struct(Path, Vec<Field>, Option<P<Expr>>),
973 /// An array literal constructed from one repeated element.
975 /// For example, `[1; 5]`. The first expression is the element
976 /// to be repeated; the second is the number of times to repeat it.
977 Repeat(P<Expr>, P<Expr>),
979 /// No-op: used solely so we can pretty-print faithfully
986 /// The explicit Self type in a "qualified path". The actual
987 /// path, including the trait and the associated item, is stored
988 /// separately. `position` represents the index of the associated
989 /// item qualified with this Self type.
991 /// ```ignore (only-for-syntax-highlight)
992 /// <Vec<T> as a::b::Trait>::AssociatedItem
993 /// ^~~~~ ~~~~~~~~~~~~~~^
996 /// <Vec<T>>::AssociatedItem
1000 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1006 /// A capture clause
1007 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1008 pub enum CaptureBy {
1013 pub type Mac = Spanned<Mac_>;
1015 /// Represents a macro invocation. The Path indicates which macro
1016 /// is being invoked, and the vector of token-trees contains the source
1017 /// of the macro invocation.
1019 /// NB: the additional ident for a macro_rules-style macro is actually
1020 /// stored in the enclosing item. Oog.
1021 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1024 pub tts: ThinTokenStream,
1028 pub fn stream(&self) -> TokenStream {
1029 self.tts.clone().into()
1033 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1034 pub struct MacroDef {
1035 pub tokens: ThinTokenStream,
1040 pub fn stream(&self) -> TokenStream {
1041 self.tokens.clone().into()
1045 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1047 /// A regular string, like `"foo"`
1049 /// A raw string, like `r##"foo"##`
1051 /// The uint is the number of `#` symbols used
1056 pub type Lit = Spanned<LitKind>;
1058 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1059 pub enum LitIntType {
1067 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1068 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1070 /// A string literal (`"foo"`)
1071 Str(Symbol, StrStyle),
1072 /// A byte string (`b"foo"`)
1073 ByteStr(Rc<Vec<u8>>),
1074 /// A byte char (`b'f'`)
1076 /// A character literal (`'a'`)
1078 /// An integer literal (`1`)
1079 Int(u128, LitIntType),
1080 /// A float literal (`1f64` or `1E10f64`)
1081 Float(Symbol, FloatTy),
1082 /// A float literal without a suffix (`1.0 or 1.0E10`)
1083 FloatUnsuffixed(Symbol),
1084 /// A boolean literal
1089 /// Returns true if this literal is a string and false otherwise.
1090 pub fn is_str(&self) -> bool {
1092 LitKind::Str(..) => true,
1097 /// Returns true if this literal has no suffix. Note: this will return true
1098 /// for literals with prefixes such as raw strings and byte strings.
1099 pub fn is_unsuffixed(&self) -> bool {
1101 // unsuffixed variants
1103 LitKind::ByteStr(..) |
1106 LitKind::Int(_, LitIntType::Unsuffixed) |
1107 LitKind::FloatUnsuffixed(..) |
1108 LitKind::Bool(..) => true,
1109 // suffixed variants
1110 LitKind::Int(_, LitIntType::Signed(..)) |
1111 LitKind::Int(_, LitIntType::Unsigned(..)) |
1112 LitKind::Float(..) => false,
1116 /// Returns true if this literal has a suffix.
1117 pub fn is_suffixed(&self) -> bool {
1118 !self.is_unsuffixed()
1122 // NB: If you change this, you'll probably want to change the corresponding
1123 // type structure in middle/ty.rs as well.
1124 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1127 pub mutbl: Mutability,
1130 /// Represents a method's signature in a trait declaration,
1131 /// or in an implementation.
1132 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1133 pub struct MethodSig {
1134 pub unsafety: Unsafety,
1135 pub constness: Spanned<Constness>,
1137 pub decl: P<FnDecl>,
1138 pub generics: Generics,
1141 /// Represents an item declaration within a trait declaration,
1142 /// possibly including a default implementation. A trait item is
1143 /// either required (meaning it doesn't have an implementation, just a
1144 /// signature) or provided (meaning it has a default implementation).
1145 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1146 pub struct TraitItem {
1149 pub attrs: Vec<Attribute>,
1150 pub node: TraitItemKind,
1154 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1155 pub enum TraitItemKind {
1156 Const(P<Ty>, Option<P<Expr>>),
1157 Method(MethodSig, Option<P<Block>>),
1158 Type(TyParamBounds, Option<P<Ty>>),
1162 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1163 pub struct ImplItem {
1166 pub vis: Visibility,
1167 pub defaultness: Defaultness,
1168 pub attrs: Vec<Attribute>,
1169 pub node: ImplItemKind,
1173 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1174 pub enum ImplItemKind {
1175 Const(P<Ty>, P<Expr>),
1176 Method(MethodSig, P<Block>),
1181 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1191 impl fmt::Debug for IntTy {
1192 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1193 fmt::Display::fmt(self, f)
1197 impl fmt::Display for IntTy {
1198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1199 write!(f, "{}", self.ty_to_string())
1204 pub fn ty_to_string(&self) -> &'static str {
1206 IntTy::Is => "isize",
1208 IntTy::I16 => "i16",
1209 IntTy::I32 => "i32",
1210 IntTy::I64 => "i64",
1211 IntTy::I128 => "i128",
1215 pub fn val_to_string(&self, val: i128) -> String {
1216 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1217 // are parsed as u128, so we wouldn't want to print an extra negative
1219 format!("{}{}", val as u128, self.ty_to_string())
1222 pub fn bit_width(&self) -> Option<usize> {
1224 IntTy::Is => return None,
1234 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1245 pub fn ty_to_string(&self) -> &'static str {
1247 UintTy::Us => "usize",
1249 UintTy::U16 => "u16",
1250 UintTy::U32 => "u32",
1251 UintTy::U64 => "u64",
1252 UintTy::U128 => "u128",
1256 pub fn val_to_string(&self, val: u128) -> String {
1257 format!("{}{}", val, self.ty_to_string())
1260 pub fn bit_width(&self) -> Option<usize> {
1262 UintTy::Us => return None,
1267 UintTy::U128 => 128,
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 slice (`[T]`)
1353 /// A fixed length array (`[T; n]`)
1354 Array(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 /// A trait object type `Bound1 + Bound2 + Bound3`
1371 /// where `Bound` is a trait or a lifetime.
1372 TraitObject(TyParamBounds),
1373 /// An `impl Bound1 + Bound2 + Bound3` type
1374 /// where `Bound` is a trait or a lifetime.
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.
1387 /// Placeholder for a kind that has failed to be defined.
1391 /// Inline assembly dialect.
1393 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1394 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1395 pub enum AsmDialect {
1400 /// Inline assembly.
1402 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1403 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1404 pub struct InlineAsmOutput {
1405 pub constraint: Symbol,
1408 pub is_indirect: bool,
1411 /// Inline assembly.
1413 /// E.g. `asm!("NOP");`
1414 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1415 pub struct InlineAsm {
1417 pub asm_str_style: StrStyle,
1418 pub outputs: Vec<InlineAsmOutput>,
1419 pub inputs: Vec<(Symbol, P<Expr>)>,
1420 pub clobbers: Vec<Symbol>,
1422 pub alignstack: bool,
1423 pub dialect: AsmDialect,
1424 pub ctxt: SyntaxContext,
1427 /// An argument in a function header.
1429 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1437 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1439 /// E.g. `&mut self` as in `fn foo(&mut self)`
1440 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1442 /// `self`, `mut self`
1444 /// `&'lt self`, `&'lt mut self`
1445 Region(Option<Lifetime>, Mutability),
1446 /// `self: TYPE`, `mut self: TYPE`
1447 Explicit(P<Ty>, Mutability),
1450 pub type ExplicitSelf = Spanned<SelfKind>;
1453 pub fn to_self(&self) -> Option<ExplicitSelf> {
1454 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1455 if ident.node.name == keywords::SelfValue.name() {
1456 return match self.ty.node {
1457 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1458 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1459 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1461 _ => Some(respan(self.pat.span.to(self.ty.span),
1462 SelfKind::Explicit(self.ty.clone(), mutbl))),
1469 pub fn is_self(&self) -> bool {
1470 if let PatKind::Ident(_, ident, _) = self.pat.node {
1471 ident.node.name == keywords::SelfValue.name()
1477 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1478 let span = eself.span.to(eself_ident.span);
1479 let infer_ty = P(Ty {
1481 node: TyKind::ImplicitSelf,
1484 let arg = |mutbl, ty| Arg {
1487 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1494 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1495 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1496 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1498 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1505 /// Header (not the body) of a function declaration.
1507 /// E.g. `fn foo(bar: baz)`
1508 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1510 pub inputs: Vec<Arg>,
1511 pub output: FunctionRetTy,
1516 pub fn get_self(&self) -> Option<ExplicitSelf> {
1517 self.inputs.get(0).and_then(Arg::to_self)
1519 pub fn has_self(&self) -> bool {
1520 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1524 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1530 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1531 pub enum Constness {
1536 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1537 pub enum Defaultness {
1542 impl fmt::Display for Unsafety {
1543 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1544 fmt::Display::fmt(match *self {
1545 Unsafety::Normal => "normal",
1546 Unsafety::Unsafe => "unsafe",
1551 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1552 pub enum ImplPolarity {
1553 /// `impl Trait for Type`
1555 /// `impl !Trait for Type`
1559 impl fmt::Debug for ImplPolarity {
1560 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1562 ImplPolarity::Positive => "positive".fmt(f),
1563 ImplPolarity::Negative => "negative".fmt(f),
1569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1570 pub enum FunctionRetTy {
1571 /// Return type is not specified.
1573 /// Functions default to `()` and
1574 /// closures default to inference. Span points to where return
1575 /// type would be inserted.
1581 impl FunctionRetTy {
1582 pub fn span(&self) -> Span {
1584 FunctionRetTy::Default(span) => span,
1585 FunctionRetTy::Ty(ref ty) => ty.span,
1590 /// Module declaration.
1592 /// E.g. `mod foo;` or `mod foo { .. }`
1593 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1595 /// A span from the first token past `{` to the last token until `}`.
1596 /// For `mod foo;`, the inner span ranges from the first token
1597 /// to the last token in the external file.
1599 pub items: Vec<P<Item>>,
1602 /// Foreign module declaration.
1604 /// E.g. `extern { .. }` or `extern C { .. }`
1605 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1606 pub struct ForeignMod {
1608 pub items: Vec<ForeignItem>,
1611 /// Global inline assembly
1613 /// aka module-level assembly or file-scoped assembly
1614 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1615 pub struct GlobalAsm {
1617 pub ctxt: SyntaxContext,
1620 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1621 pub struct EnumDef {
1622 pub variants: Vec<Variant>,
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1626 pub struct Variant_ {
1628 pub attrs: Vec<Attribute>,
1629 pub data: VariantData,
1630 /// Explicit discriminant, e.g. `Foo = 1`
1631 pub disr_expr: Option<P<Expr>>,
1634 pub type Variant = Spanned<Variant_>;
1636 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1637 pub struct PathListItem_ {
1639 /// renamed in list, e.g. `use foo::{bar as baz};`
1640 pub rename: Option<Ident>,
1644 pub type PathListItem = Spanned<PathListItem_>;
1646 pub type ViewPath = Spanned<ViewPath_>;
1648 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1649 pub enum ViewPath_ {
1651 /// `foo::bar::baz as quux`
1655 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1656 ViewPathSimple(Ident, Path),
1661 /// `foo::bar::{a,b,c}`
1662 ViewPathList(Path, Vec<PathListItem>)
1666 pub fn path(&self) -> &Path {
1668 ViewPathSimple(_, ref path) |
1669 ViewPathGlob (ref path) |
1670 ViewPathList(ref path, _) => path
1676 /// Distinguishes between Attributes that decorate items and Attributes that
1677 /// are contained as statements within items. These two cases need to be
1678 /// distinguished for pretty-printing.
1679 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1680 pub enum AttrStyle {
1685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1686 pub struct AttrId(pub usize);
1688 /// Meta-data associated with an item
1689 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1690 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1691 pub struct Attribute {
1693 pub style: AttrStyle,
1695 pub tokens: TokenStream,
1696 pub is_sugared_doc: bool,
1700 /// TraitRef's appear in impls.
1702 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1703 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1704 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1705 /// same as the impl's node id).
1706 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1707 pub struct TraitRef {
1712 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1713 pub struct PolyTraitRef {
1714 /// The `'a` in `<'a> Foo<&'a T>`
1715 pub bound_lifetimes: Vec<LifetimeDef>,
1717 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1718 pub trait_ref: TraitRef,
1724 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1726 bound_lifetimes: lifetimes,
1727 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1733 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1734 pub enum Visibility {
1737 Restricted { path: P<Path>, id: NodeId },
1741 /// Field of a struct.
1743 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1744 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1745 pub struct StructField {
1747 pub ident: Option<Ident>,
1748 pub vis: Visibility,
1751 pub attrs: Vec<Attribute>,
1754 /// Fields and Ids of enum variants and structs
1756 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1757 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1758 /// One shared Id can be successfully used for these two purposes.
1759 /// Id of the whole enum lives in `Item`.
1761 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1762 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1763 /// the variant itself" from enum variants.
1764 /// Id of the whole struct lives in `Item`.
1765 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1766 pub enum VariantData {
1769 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1770 Struct(Vec<StructField>, NodeId),
1773 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1774 Tuple(Vec<StructField>, NodeId),
1777 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1782 pub fn fields(&self) -> &[StructField] {
1784 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1788 pub fn id(&self) -> NodeId {
1790 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1793 pub fn is_struct(&self) -> bool {
1794 if let VariantData::Struct(..) = *self { true } else { false }
1796 pub fn is_tuple(&self) -> bool {
1797 if let VariantData::Tuple(..) = *self { true } else { false }
1799 pub fn is_unit(&self) -> bool {
1800 if let VariantData::Unit(..) = *self { true } else { false }
1806 /// The name might be a dummy name in case of anonymous items
1807 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1810 pub attrs: Vec<Attribute>,
1813 pub vis: Visibility,
1817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1819 /// An`extern crate` item, with optional original crate name.
1821 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1822 ExternCrate(Option<Name>),
1823 /// A use declaration (`use` or `pub use`) item.
1825 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1827 /// A static item (`static` or `pub static`).
1829 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1830 Static(P<Ty>, Mutability, P<Expr>),
1831 /// A constant item (`const` or `pub const`).
1833 /// E.g. `const FOO: i32 = 42;`
1834 Const(P<Ty>, P<Expr>),
1835 /// A function declaration (`fn` or `pub fn`).
1837 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1838 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1839 /// A module declaration (`mod` or `pub mod`).
1841 /// E.g. `mod foo;` or `mod foo { .. }`
1843 /// An external module (`extern` or `pub extern`).
1845 /// E.g. `extern {}` or `extern "C" {}`
1846 ForeignMod(ForeignMod),
1847 /// Module-level inline assembly (from `global_asm!()`)
1848 GlobalAsm(P<GlobalAsm>),
1849 /// A type alias (`type` or `pub type`).
1851 /// E.g. `type Foo = Bar<u8>;`
1852 Ty(P<Ty>, Generics),
1853 /// An enum definition (`enum` or `pub enum`).
1855 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1856 Enum(EnumDef, Generics),
1857 /// A struct definition (`struct` or `pub struct`).
1859 /// E.g. `struct Foo<A> { x: A }`
1860 Struct(VariantData, Generics),
1861 /// A union definition (`union` or `pub union`).
1863 /// E.g. `union Foo<A, B> { x: A, y: B }`
1864 Union(VariantData, Generics),
1865 /// A Trait declaration (`trait` or `pub trait`).
1867 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1868 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1869 // Default trait implementation.
1871 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1872 DefaultImpl(Unsafety, TraitRef),
1873 /// An implementation.
1875 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1880 Option<TraitRef>, // (optional) trait this impl implements
1883 /// A macro invocation.
1885 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1888 /// A macro definition.
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::GlobalAsm(..) => "global asm",
1903 ItemKind::Ty(..) => "type alias",
1904 ItemKind::Enum(..) => "enum",
1905 ItemKind::Struct(..) => "struct",
1906 ItemKind::Union(..) => "union",
1907 ItemKind::Trait(..) => "trait",
1909 ItemKind::MacroDef(..) |
1910 ItemKind::Impl(..) |
1911 ItemKind::DefaultImpl(..) => "item"
1916 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1917 pub struct ForeignItem {
1919 pub attrs: Vec<Attribute>,
1920 pub node: ForeignItemKind,
1923 pub vis: Visibility,
1926 /// An item within an `extern` block
1927 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1928 pub enum ForeignItemKind {
1929 /// A foreign function
1930 Fn(P<FnDecl>, Generics),
1931 /// A foreign static item (`static ext: u8`), with optional mutability
1932 /// (the boolean is true when mutable)
1933 Static(P<Ty>, bool),
1936 impl ForeignItemKind {
1937 pub fn descriptive_variant(&self) -> &str {
1939 ForeignItemKind::Fn(..) => "foreign function",
1940 ForeignItemKind::Static(..) => "foreign static item"
1950 // are ASTs encodable?
1952 fn check_asts_encodable() {
1953 fn assert_encodable<T: serialize::Encodable>() {}
1954 assert_encodable::<Crate>();