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(),
346 /// A `where` clause in a definition
347 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
348 pub struct WhereClause {
350 pub predicates: Vec<WherePredicate>,
354 /// A single predicate in a `where` clause
355 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
356 pub enum WherePredicate {
357 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
358 BoundPredicate(WhereBoundPredicate),
359 /// A lifetime predicate, e.g. `'a: 'b+'c`
360 RegionPredicate(WhereRegionPredicate),
361 /// An equality predicate (unsupported)
362 EqPredicate(WhereEqPredicate),
367 /// E.g. `for<'c> Foo: Send+Clone+'c`
368 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
369 pub struct WhereBoundPredicate {
371 /// Any lifetimes from a `for` binding
372 pub bound_lifetimes: Vec<LifetimeDef>,
373 /// The type being bounded
374 pub bounded_ty: P<Ty>,
375 /// Trait and lifetime bounds (`Clone+Send+'static`)
376 pub bounds: TyParamBounds,
379 /// A lifetime predicate.
382 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
383 pub struct WhereRegionPredicate {
385 pub lifetime: Lifetime,
386 pub bounds: Vec<Lifetime>,
389 /// An equality predicate (unsupported).
392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
393 pub struct WhereEqPredicate {
400 /// The set of MetaItems that define the compilation environment of the crate,
401 /// used to drive conditional compilation
402 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
404 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
407 pub attrs: Vec<Attribute>,
411 /// A spanned compile-time attribute list item.
412 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
414 /// Possible values inside of compile-time attribute lists.
416 /// E.g. the '..' in `#[name(..)]`.
417 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
418 pub enum NestedMetaItemKind {
419 /// A full MetaItem, for recursive meta items.
423 /// E.g. "foo", 64, true
427 /// A spanned compile-time attribute item.
429 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
431 pub struct MetaItem {
433 pub node: MetaItemKind,
437 /// A compile-time attribute item.
439 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
440 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
441 pub enum MetaItemKind {
444 /// E.g. `test` as in `#[test]`
448 /// E.g. `derive(..)` as in `#[derive(..)]`
449 List(Vec<NestedMetaItem>),
450 /// Name value meta item.
452 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
456 /// A Block (`{ .. }`).
458 /// E.g. `{ .. }` as in `fn foo() { .. }`
459 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
461 /// Statements in a block
462 pub stmts: Vec<Stmt>,
464 /// Distinguishes between `unsafe { ... }` and `{ ... }`
465 pub rules: BlockCheckMode,
469 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
476 impl fmt::Debug for Pat {
477 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
478 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
483 pub fn walk<F>(&self, it: &mut F) -> bool
484 where F: FnMut(&Pat) -> bool
491 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
492 PatKind::Struct(_, ref fields, _) => {
493 fields.iter().all(|field| field.node.pat.walk(it))
495 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
496 s.iter().all(|p| p.walk(it))
498 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
501 PatKind::Slice(ref before, ref slice, ref after) => {
502 before.iter().all(|p| p.walk(it)) &&
503 slice.iter().all(|p| p.walk(it)) &&
504 after.iter().all(|p| p.walk(it))
518 /// A single field in a struct pattern
520 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
521 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
522 /// except is_shorthand is true
523 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
524 pub struct FieldPat {
525 /// The identifier for the field
527 /// The pattern the field is destructured to
529 pub is_shorthand: bool,
530 pub attrs: ThinVec<Attribute>,
533 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
534 pub enum BindingMode {
539 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
545 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
547 /// Represents a wildcard pattern (`_`)
550 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
551 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
552 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
553 /// during name resolution.
554 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
556 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
557 /// The `bool` is `true` in the presence of a `..`.
558 Struct(Path, Vec<Spanned<FieldPat>>, bool),
560 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
561 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
562 /// 0 <= position <= subpats.len()
563 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
565 /// A possibly qualified path pattern.
566 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
567 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
568 /// only legally refer to associated constants.
569 Path(Option<QSelf>, Path),
571 /// A tuple pattern `(a, b)`.
572 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
573 /// 0 <= position <= subpats.len()
574 Tuple(Vec<P<Pat>>, Option<usize>),
577 /// A reference pattern, e.g. `&mut (a, b)`
578 Ref(P<Pat>, Mutability),
581 /// A range pattern, e.g. `1...2` or `1..2`
582 Range(P<Expr>, P<Expr>, RangeEnd),
583 /// `[a, b, ..i, y, z]` is represented as:
584 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
585 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
586 /// A macro pattern; pre-expansion
590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
591 pub enum Mutability {
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
598 /// The `+` operator (addition)
600 /// The `-` operator (subtraction)
602 /// The `*` operator (multiplication)
604 /// The `/` operator (division)
606 /// The `%` operator (modulus)
608 /// The `&&` operator (logical and)
610 /// The `||` operator (logical or)
612 /// The `^` operator (bitwise xor)
614 /// The `&` operator (bitwise and)
616 /// The `|` operator (bitwise or)
618 /// The `<<` operator (shift left)
620 /// The `>>` operator (shift right)
622 /// The `==` operator (equality)
624 /// The `<` operator (less than)
626 /// The `<=` operator (less than or equal to)
628 /// The `!=` operator (not equal to)
630 /// The `>=` operator (greater than or equal to)
632 /// The `>` operator (greater than)
637 pub fn to_string(&self) -> &'static str {
638 use self::BinOpKind::*;
660 pub fn lazy(&self) -> bool {
662 BinOpKind::And | BinOpKind::Or => true,
667 pub fn is_shift(&self) -> bool {
669 BinOpKind::Shl | BinOpKind::Shr => true,
673 pub fn is_comparison(&self) -> bool {
674 use self::BinOpKind::*;
676 Eq | Lt | Le | Ne | Gt | Ge =>
678 And | Or | Add | Sub | Mul | Div | Rem |
679 BitXor | BitAnd | BitOr | Shl | Shr =>
683 /// Returns `true` if the binary operator takes its arguments by value
684 pub fn is_by_value(&self) -> bool {
685 !self.is_comparison()
689 pub type BinOp = Spanned<BinOpKind>;
691 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
693 /// The `*` operator for dereferencing
695 /// The `!` operator for logical inversion
697 /// The `-` operator for negation
702 /// Returns `true` if the unary operator takes its argument by value
703 pub fn is_by_value(u: UnOp) -> bool {
705 UnOp::Neg | UnOp::Not => true,
710 pub fn to_string(op: UnOp) -> &'static str {
720 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
728 pub fn add_trailing_semicolon(mut self) -> Self {
729 self.node = match self.node {
730 StmtKind::Expr(expr) => StmtKind::Semi(expr),
731 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
732 (mac, MacStmtStyle::Semicolon, attrs)
739 pub fn is_item(&self) -> bool {
741 StmtKind::Local(_) => true,
747 impl fmt::Debug for Stmt {
748 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
749 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
754 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
756 /// A local (let) binding.
759 /// An item definition.
762 /// Expr without trailing semi-colon.
767 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
770 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
771 pub enum MacStmtStyle {
772 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
773 /// `foo!(...);`, `foo![...];`
775 /// The macro statement had braces; e.g. foo! { ... }
777 /// The macro statement had parentheses or brackets and no semicolon; e.g.
778 /// `foo!(...)`. All of these will end up being converted into macro
783 // FIXME (pending discussion of #1697, #2178...): local should really be
784 // a refinement on pat.
785 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
789 pub ty: Option<P<Ty>>,
790 /// Initializer expression to set the value, if any
791 pub init: Option<P<Expr>>,
794 pub attrs: ThinVec<Attribute>,
797 /// An arm of a 'match'.
799 /// E.g. `0...10 => { println!("match!") }` as in
803 /// 0...10 => { println!("match!") },
804 /// _ => { println!("no match!") },
807 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
809 pub attrs: Vec<Attribute>,
810 pub pats: Vec<P<Pat>>,
811 pub guard: Option<P<Expr>>,
815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
817 pub ident: SpannedIdent,
820 pub is_shorthand: bool,
821 pub attrs: ThinVec<Attribute>,
824 pub type SpannedIdent = Spanned<Ident>;
826 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
827 pub enum BlockCheckMode {
829 Unsafe(UnsafeSource),
832 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
833 pub enum UnsafeSource {
839 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
844 pub attrs: ThinVec<Attribute>
848 /// Wether this expression would be valid somewhere that expects a value, for example, an `if`
850 pub fn returns(&self) -> bool {
851 if let ExprKind::Block(ref block) = self.node {
852 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
854 Some(&StmtKind::Expr(_)) => true,
855 Some(&StmtKind::Semi(ref expr)) => {
856 if let ExprKind::Ret(_) = expr.node {
857 // last statement is explicit return
863 // This is a block that doesn't end in either an implicit or explicit return
867 // This is not a block, it is a value
873 impl fmt::Debug for Expr {
874 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
875 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
879 /// Limit types of a range (inclusive or exclusive)
880 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
881 pub enum RangeLimits {
882 /// Inclusive at the beginning, exclusive at the end
884 /// Inclusive at the beginning and end
888 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
890 /// A `box x` expression.
892 /// First expr is the place; second expr is the value.
893 InPlace(P<Expr>, P<Expr>),
894 /// An array (`[a, b, c, d]`)
898 /// The first field resolves to the function itself,
899 /// and the second field is the list of arguments
900 Call(P<Expr>, Vec<P<Expr>>),
901 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
903 /// The `PathSegment` represents the method name and its generic arguments
904 /// (within the angle brackets).
905 /// The first element of the vector of `Expr`s is the expression that evaluates
906 /// to the object on which the method is being called on (the receiver),
907 /// and the remaining elements are the rest of the arguments.
908 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
909 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
910 MethodCall(PathSegment, Vec<P<Expr>>),
911 /// A tuple (`(a, b, c ,d)`)
913 /// A binary operation (For example: `a + b`, `a * b`)
914 Binary(BinOp, P<Expr>, P<Expr>),
915 /// A unary operation (For example: `!x`, `*x`)
916 Unary(UnOp, P<Expr>),
917 /// A literal (For example: `1`, `"foo"`)
919 /// A cast (`foo as f64`)
920 Cast(P<Expr>, P<Ty>),
921 Type(P<Expr>, P<Ty>),
922 /// An `if` block, with an optional else block
924 /// `if expr { block } else { expr }`
925 If(P<Expr>, P<Block>, Option<P<Expr>>),
926 /// An `if let` expression with an optional else block
928 /// `if let pat = expr { block } else { expr }`
930 /// This is desugared to a `match` expression.
931 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
932 /// A while loop, with an optional label
934 /// `'label: while expr { block }`
935 While(P<Expr>, P<Block>, Option<SpannedIdent>),
936 /// A while-let loop, with an optional label
938 /// `'label: while let pat = expr { block }`
940 /// This is desugared to a combination of `loop` and `match` expressions.
941 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
942 /// A for loop, with an optional label
944 /// `'label: for pat in expr { block }`
946 /// This is desugared to a combination of `loop` and `match` expressions.
947 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
948 /// Conditionless loop (can be exited with break, continue, or return)
950 /// `'label: loop { block }`
951 Loop(P<Block>, Option<SpannedIdent>),
953 Match(P<Expr>, Vec<Arm>),
954 /// A closure (for example, `move |a, b, c| a + b + c`)
956 /// The final span is the span of the argument block `|...|`
957 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
958 /// A block (`{ ... }`)
960 /// A catch block (`catch { ... }`)
963 /// An assignment (`a = foo()`)
964 Assign(P<Expr>, P<Expr>),
965 /// An assignment with an operator
967 /// For example, `a += 1`.
968 AssignOp(BinOp, P<Expr>, P<Expr>),
969 /// Access of a named struct field (`obj.foo`)
970 Field(P<Expr>, SpannedIdent),
971 /// Access of an unnamed field of a struct or tuple-struct
973 /// For example, `foo.0`.
974 TupField(P<Expr>, Spanned<usize>),
975 /// An indexing operation (`foo[2]`)
976 Index(P<Expr>, P<Expr>),
977 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
978 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
980 /// Variable reference, possibly containing `::` and/or type
981 /// parameters, e.g. foo::bar::<baz>.
983 /// Optionally "qualified",
984 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
985 Path(Option<QSelf>, Path),
987 /// A referencing operation (`&a` or `&mut a`)
988 AddrOf(Mutability, P<Expr>),
989 /// A `break`, with an optional label to break, and an optional expression
990 Break(Option<SpannedIdent>, Option<P<Expr>>),
991 /// A `continue`, with an optional label
992 Continue(Option<SpannedIdent>),
993 /// A `return`, with an optional value to be returned
994 Ret(Option<P<Expr>>),
996 /// Output of the `asm!()` macro
997 InlineAsm(P<InlineAsm>),
999 /// A macro invocation; pre-expansion
1002 /// A struct literal expression.
1004 /// For example, `Foo {x: 1, y: 2}`, or
1005 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1006 Struct(Path, Vec<Field>, Option<P<Expr>>),
1008 /// An array literal constructed from one repeated element.
1010 /// For example, `[1; 5]`. The first expression is the element
1011 /// to be repeated; the second is the number of times to repeat it.
1012 Repeat(P<Expr>, P<Expr>),
1014 /// No-op: used solely so we can pretty-print faithfully
1020 /// A `yield`, with an optional value to be yielded
1021 Yield(Option<P<Expr>>),
1024 /// The explicit Self type in a "qualified path". The actual
1025 /// path, including the trait and the associated item, is stored
1026 /// separately. `position` represents the index of the associated
1027 /// item qualified with this Self type.
1029 /// ```ignore (only-for-syntax-highlight)
1030 /// <Vec<T> as a::b::Trait>::AssociatedItem
1031 /// ^~~~~ ~~~~~~~~~~~~~~^
1034 /// <Vec<T>>::AssociatedItem
1038 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1044 /// A capture clause
1045 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1046 pub enum CaptureBy {
1051 pub type Mac = Spanned<Mac_>;
1053 /// Represents a macro invocation. The Path indicates which macro
1054 /// is being invoked, and the vector of token-trees contains the source
1055 /// of the macro invocation.
1057 /// NB: the additional ident for a macro_rules-style macro is actually
1058 /// stored in the enclosing item. Oog.
1059 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1062 pub tts: ThinTokenStream,
1066 pub fn stream(&self) -> TokenStream {
1067 self.tts.clone().into()
1071 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1072 pub struct MacroDef {
1073 pub tokens: ThinTokenStream,
1078 pub fn stream(&self) -> TokenStream {
1079 self.tokens.clone().into()
1083 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1085 /// A regular string, like `"foo"`
1087 /// A raw string, like `r##"foo"##`
1089 /// The uint is the number of `#` symbols used
1094 pub type Lit = Spanned<LitKind>;
1096 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1097 pub enum LitIntType {
1105 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1106 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1108 /// A string literal (`"foo"`)
1109 Str(Symbol, StrStyle),
1110 /// A byte string (`b"foo"`)
1111 ByteStr(Rc<Vec<u8>>),
1112 /// A byte char (`b'f'`)
1114 /// A character literal (`'a'`)
1116 /// An integer literal (`1`)
1117 Int(u128, LitIntType),
1118 /// A float literal (`1f64` or `1E10f64`)
1119 Float(Symbol, FloatTy),
1120 /// A float literal without a suffix (`1.0 or 1.0E10`)
1121 FloatUnsuffixed(Symbol),
1122 /// A boolean literal
1127 /// Returns true if this literal is a string and false otherwise.
1128 pub fn is_str(&self) -> bool {
1130 LitKind::Str(..) => true,
1135 /// Returns true if this literal has no suffix. Note: this will return true
1136 /// for literals with prefixes such as raw strings and byte strings.
1137 pub fn is_unsuffixed(&self) -> bool {
1139 // unsuffixed variants
1141 LitKind::ByteStr(..) |
1144 LitKind::Int(_, LitIntType::Unsuffixed) |
1145 LitKind::FloatUnsuffixed(..) |
1146 LitKind::Bool(..) => true,
1147 // suffixed variants
1148 LitKind::Int(_, LitIntType::Signed(..)) |
1149 LitKind::Int(_, LitIntType::Unsigned(..)) |
1150 LitKind::Float(..) => false,
1154 /// Returns true if this literal has a suffix.
1155 pub fn is_suffixed(&self) -> bool {
1156 !self.is_unsuffixed()
1160 // NB: If you change this, you'll probably want to change the corresponding
1161 // type structure in middle/ty.rs as well.
1162 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1165 pub mutbl: Mutability,
1168 /// Represents a method's signature in a trait declaration,
1169 /// or in an implementation.
1170 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1171 pub struct MethodSig {
1172 pub unsafety: Unsafety,
1173 pub constness: Spanned<Constness>,
1175 pub decl: P<FnDecl>,
1176 pub generics: Generics,
1179 /// Represents an item declaration within a trait declaration,
1180 /// possibly including a default implementation. A trait item is
1181 /// either required (meaning it doesn't have an implementation, just a
1182 /// signature) or provided (meaning it has a default implementation).
1183 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1184 pub struct TraitItem {
1187 pub attrs: Vec<Attribute>,
1188 pub node: TraitItemKind,
1190 /// See `Item::tokens` for what this is
1191 pub tokens: Option<TokenStream>,
1194 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1195 pub enum TraitItemKind {
1196 Const(P<Ty>, Option<P<Expr>>),
1197 Method(MethodSig, Option<P<Block>>),
1198 Type(TyParamBounds, Option<P<Ty>>),
1202 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1203 pub struct ImplItem {
1206 pub vis: Visibility,
1207 pub defaultness: Defaultness,
1208 pub attrs: Vec<Attribute>,
1209 pub node: ImplItemKind,
1211 /// See `Item::tokens` for what this is
1212 pub tokens: Option<TokenStream>,
1215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1216 pub enum ImplItemKind {
1217 Const(P<Ty>, P<Expr>),
1218 Method(MethodSig, P<Block>),
1223 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1233 impl fmt::Debug for IntTy {
1234 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1235 fmt::Display::fmt(self, f)
1239 impl fmt::Display for IntTy {
1240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1241 write!(f, "{}", self.ty_to_string())
1246 pub fn ty_to_string(&self) -> &'static str {
1248 IntTy::Is => "isize",
1250 IntTy::I16 => "i16",
1251 IntTy::I32 => "i32",
1252 IntTy::I64 => "i64",
1253 IntTy::I128 => "i128",
1257 pub fn val_to_string(&self, val: i128) -> String {
1258 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1259 // are parsed as u128, so we wouldn't want to print an extra negative
1261 format!("{}{}", val as u128, self.ty_to_string())
1264 pub fn bit_width(&self) -> Option<usize> {
1266 IntTy::Is => return None,
1276 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1287 pub fn ty_to_string(&self) -> &'static str {
1289 UintTy::Us => "usize",
1291 UintTy::U16 => "u16",
1292 UintTy::U32 => "u32",
1293 UintTy::U64 => "u64",
1294 UintTy::U128 => "u128",
1298 pub fn val_to_string(&self, val: u128) -> String {
1299 format!("{}{}", val, self.ty_to_string())
1302 pub fn bit_width(&self) -> Option<usize> {
1304 UintTy::Us => return None,
1309 UintTy::U128 => 128,
1314 impl fmt::Debug for UintTy {
1315 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1316 fmt::Display::fmt(self, f)
1320 impl fmt::Display for UintTy {
1321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1322 write!(f, "{}", self.ty_to_string())
1326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1332 impl fmt::Debug for FloatTy {
1333 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1334 fmt::Display::fmt(self, f)
1338 impl fmt::Display for FloatTy {
1339 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1340 write!(f, "{}", self.ty_to_string())
1345 pub fn ty_to_string(&self) -> &'static str {
1347 FloatTy::F32 => "f32",
1348 FloatTy::F64 => "f64",
1352 pub fn bit_width(&self) -> usize {
1360 // Bind a type to an associated type: `A=Foo`.
1361 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1362 pub struct TypeBinding {
1369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1376 impl fmt::Debug for Ty {
1377 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1378 write!(f, "type({})", pprust::ty_to_string(self))
1382 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1383 pub struct BareFnTy {
1384 pub unsafety: Unsafety,
1386 pub lifetimes: Vec<LifetimeDef>,
1390 /// The different kinds of types recognized by the compiler
1391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1393 /// A variable-length slice (`[T]`)
1395 /// A fixed length array (`[T; n]`)
1396 Array(P<Ty>, P<Expr>),
1397 /// A raw pointer (`*const T` or `*mut T`)
1399 /// A reference (`&'a T` or `&'a mut T`)
1400 Rptr(Option<Lifetime>, MutTy),
1401 /// A bare function (e.g. `fn(usize) -> bool`)
1402 BareFn(P<BareFnTy>),
1403 /// The never type (`!`)
1405 /// A tuple (`(A, B, C, D,...)`)
1407 /// A path (`module::module::...::Type`), optionally
1408 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1410 /// Type parameters are stored in the Path itself
1411 Path(Option<QSelf>, Path),
1412 /// A trait object type `Bound1 + Bound2 + Bound3`
1413 /// where `Bound` is a trait or a lifetime.
1414 TraitObject(TyParamBounds),
1415 /// An `impl Bound1 + Bound2 + Bound3` type
1416 /// where `Bound` is a trait or a lifetime.
1417 ImplTrait(TyParamBounds),
1418 /// No-op; kept solely so that we can pretty-print faithfully
1422 /// TyKind::Infer means the type should be inferred instead of it having been
1423 /// specified. This can appear anywhere in a type.
1425 /// Inferred type of a `self` or `&self` argument in a method.
1427 // A macro in the type position.
1429 /// Placeholder for a kind that has failed to be defined.
1433 /// Inline assembly dialect.
1435 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1436 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1437 pub enum AsmDialect {
1442 /// Inline assembly.
1444 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1445 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1446 pub struct InlineAsmOutput {
1447 pub constraint: Symbol,
1450 pub is_indirect: bool,
1453 /// Inline assembly.
1455 /// E.g. `asm!("NOP");`
1456 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1457 pub struct InlineAsm {
1459 pub asm_str_style: StrStyle,
1460 pub outputs: Vec<InlineAsmOutput>,
1461 pub inputs: Vec<(Symbol, P<Expr>)>,
1462 pub clobbers: Vec<Symbol>,
1464 pub alignstack: bool,
1465 pub dialect: AsmDialect,
1466 pub ctxt: SyntaxContext,
1469 /// An argument in a function header.
1471 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1472 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1479 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1481 /// E.g. `&mut self` as in `fn foo(&mut self)`
1482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1484 /// `self`, `mut self`
1486 /// `&'lt self`, `&'lt mut self`
1487 Region(Option<Lifetime>, Mutability),
1488 /// `self: TYPE`, `mut self: TYPE`
1489 Explicit(P<Ty>, Mutability),
1492 pub type ExplicitSelf = Spanned<SelfKind>;
1495 pub fn to_self(&self) -> Option<ExplicitSelf> {
1496 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1497 if ident.node.name == keywords::SelfValue.name() {
1498 return match self.ty.node {
1499 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1500 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1501 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1503 _ => Some(respan(self.pat.span.to(self.ty.span),
1504 SelfKind::Explicit(self.ty.clone(), mutbl))),
1511 pub fn is_self(&self) -> bool {
1512 if let PatKind::Ident(_, ident, _) = self.pat.node {
1513 ident.node.name == keywords::SelfValue.name()
1519 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1520 let span = eself.span.to(eself_ident.span);
1521 let infer_ty = P(Ty {
1523 node: TyKind::ImplicitSelf,
1526 let arg = |mutbl, ty| Arg {
1529 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1536 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1537 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1538 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1540 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1547 /// Header (not the body) of a function declaration.
1549 /// E.g. `fn foo(bar: baz)`
1550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1552 pub inputs: Vec<Arg>,
1553 pub output: FunctionRetTy,
1558 pub fn get_self(&self) -> Option<ExplicitSelf> {
1559 self.inputs.get(0).and_then(Arg::to_self)
1561 pub fn has_self(&self) -> bool {
1562 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1566 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1572 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1573 pub enum Constness {
1578 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1579 pub enum Defaultness {
1584 impl fmt::Display for Unsafety {
1585 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1586 fmt::Display::fmt(match *self {
1587 Unsafety::Normal => "normal",
1588 Unsafety::Unsafe => "unsafe",
1593 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1594 pub enum ImplPolarity {
1595 /// `impl Trait for Type`
1597 /// `impl !Trait for Type`
1601 impl fmt::Debug for ImplPolarity {
1602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1604 ImplPolarity::Positive => "positive".fmt(f),
1605 ImplPolarity::Negative => "negative".fmt(f),
1611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1612 pub enum FunctionRetTy {
1613 /// Return type is not specified.
1615 /// Functions default to `()` and
1616 /// closures default to inference. Span points to where return
1617 /// type would be inserted.
1623 impl FunctionRetTy {
1624 pub fn span(&self) -> Span {
1626 FunctionRetTy::Default(span) => span,
1627 FunctionRetTy::Ty(ref ty) => ty.span,
1632 /// Module declaration.
1634 /// E.g. `mod foo;` or `mod foo { .. }`
1635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1637 /// A span from the first token past `{` to the last token until `}`.
1638 /// For `mod foo;`, the inner span ranges from the first token
1639 /// to the last token in the external file.
1641 pub items: Vec<P<Item>>,
1644 /// Foreign module declaration.
1646 /// E.g. `extern { .. }` or `extern C { .. }`
1647 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1648 pub struct ForeignMod {
1650 pub items: Vec<ForeignItem>,
1653 /// Global inline assembly
1655 /// aka module-level assembly or file-scoped assembly
1656 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1657 pub struct GlobalAsm {
1659 pub ctxt: SyntaxContext,
1662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1663 pub struct EnumDef {
1664 pub variants: Vec<Variant>,
1667 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1668 pub struct Variant_ {
1670 pub attrs: Vec<Attribute>,
1671 pub data: VariantData,
1672 /// Explicit discriminant, e.g. `Foo = 1`
1673 pub disr_expr: Option<P<Expr>>,
1676 pub type Variant = Spanned<Variant_>;
1678 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1679 pub struct PathListItem_ {
1681 /// renamed in list, e.g. `use foo::{bar as baz};`
1682 pub rename: Option<Ident>,
1686 pub type PathListItem = Spanned<PathListItem_>;
1688 pub type ViewPath = Spanned<ViewPath_>;
1690 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1691 pub enum ViewPath_ {
1693 /// `foo::bar::baz as quux`
1697 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1698 ViewPathSimple(Ident, Path),
1703 /// `foo::bar::{a,b,c}`
1704 ViewPathList(Path, Vec<PathListItem>)
1708 pub fn path(&self) -> &Path {
1710 ViewPathSimple(_, ref path) |
1711 ViewPathGlob (ref path) |
1712 ViewPathList(ref path, _) => path
1718 /// Distinguishes between Attributes that decorate items and Attributes that
1719 /// are contained as statements within items. These two cases need to be
1720 /// distinguished for pretty-printing.
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1722 pub enum AttrStyle {
1727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1728 pub struct AttrId(pub usize);
1730 /// Meta-data associated with an item
1731 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1732 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1733 pub struct Attribute {
1735 pub style: AttrStyle,
1737 pub tokens: TokenStream,
1738 pub is_sugared_doc: bool,
1742 /// TraitRef's appear in impls.
1744 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1745 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1746 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1747 /// same as the impl's node id).
1748 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1749 pub struct TraitRef {
1754 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1755 pub struct PolyTraitRef {
1756 /// The `'a` in `<'a> Foo<&'a T>`
1757 pub bound_lifetimes: Vec<LifetimeDef>,
1759 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1760 pub trait_ref: TraitRef,
1766 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1768 bound_lifetimes: lifetimes,
1769 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1775 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1776 pub enum Visibility {
1779 Restricted { path: P<Path>, id: NodeId },
1783 /// Field of a struct.
1785 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1787 pub struct StructField {
1789 pub ident: Option<Ident>,
1790 pub vis: Visibility,
1793 pub attrs: Vec<Attribute>,
1796 /// Fields and Ids of enum variants and structs
1798 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1799 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1800 /// One shared Id can be successfully used for these two purposes.
1801 /// Id of the whole enum lives in `Item`.
1803 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1804 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1805 /// the variant itself" from enum variants.
1806 /// Id of the whole struct lives in `Item`.
1807 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1808 pub enum VariantData {
1811 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1812 Struct(Vec<StructField>, NodeId),
1815 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1816 Tuple(Vec<StructField>, NodeId),
1819 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1824 pub fn fields(&self) -> &[StructField] {
1826 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1830 pub fn id(&self) -> NodeId {
1832 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1835 pub fn is_struct(&self) -> bool {
1836 if let VariantData::Struct(..) = *self { true } else { false }
1838 pub fn is_tuple(&self) -> bool {
1839 if let VariantData::Tuple(..) = *self { true } else { false }
1841 pub fn is_unit(&self) -> bool {
1842 if let VariantData::Unit(..) = *self { true } else { false }
1848 /// The name might be a dummy name in case of anonymous items
1849 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1852 pub attrs: Vec<Attribute>,
1855 pub vis: Visibility,
1858 /// Original tokens this item was parsed from. This isn't necessarily
1859 /// available for all items, although over time more and more items should
1860 /// have this be `Some`. Right now this is primarily used for procedural
1861 /// macros, notably custom attributes.
1863 /// Note that the tokens here do not include the outer attributes, but will
1864 /// include inner attributes.
1865 pub tokens: Option<TokenStream>,
1868 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1870 /// An `extern crate` item, with optional original crate name.
1872 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1873 ExternCrate(Option<Name>),
1874 /// A use declaration (`use` or `pub use`) item.
1876 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1878 /// A static item (`static` or `pub static`).
1880 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1881 Static(P<Ty>, Mutability, P<Expr>),
1882 /// A constant item (`const` or `pub const`).
1884 /// E.g. `const FOO: i32 = 42;`
1885 Const(P<Ty>, P<Expr>),
1886 /// A function declaration (`fn` or `pub fn`).
1888 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1889 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1890 /// A module declaration (`mod` or `pub mod`).
1892 /// E.g. `mod foo;` or `mod foo { .. }`
1894 /// An external module (`extern` or `pub extern`).
1896 /// E.g. `extern {}` or `extern "C" {}`
1897 ForeignMod(ForeignMod),
1898 /// Module-level inline assembly (from `global_asm!()`)
1899 GlobalAsm(P<GlobalAsm>),
1900 /// A type alias (`type` or `pub type`).
1902 /// E.g. `type Foo = Bar<u8>;`
1903 Ty(P<Ty>, Generics),
1904 /// An enum definition (`enum` or `pub enum`).
1906 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1907 Enum(EnumDef, Generics),
1908 /// A struct definition (`struct` or `pub struct`).
1910 /// E.g. `struct Foo<A> { x: A }`
1911 Struct(VariantData, Generics),
1912 /// A union definition (`union` or `pub union`).
1914 /// E.g. `union Foo<A, B> { x: A, y: B }`
1915 Union(VariantData, Generics),
1916 /// A Trait declaration (`trait` or `pub trait`).
1918 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1919 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1920 // Default trait implementation.
1922 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1923 DefaultImpl(Unsafety, TraitRef),
1924 /// An implementation.
1926 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1931 Option<TraitRef>, // (optional) trait this impl implements
1934 /// A macro invocation.
1936 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1939 /// A macro definition.
1944 pub fn descriptive_variant(&self) -> &str {
1946 ItemKind::ExternCrate(..) => "extern crate",
1947 ItemKind::Use(..) => "use",
1948 ItemKind::Static(..) => "static item",
1949 ItemKind::Const(..) => "constant item",
1950 ItemKind::Fn(..) => "function",
1951 ItemKind::Mod(..) => "module",
1952 ItemKind::ForeignMod(..) => "foreign module",
1953 ItemKind::GlobalAsm(..) => "global asm",
1954 ItemKind::Ty(..) => "type alias",
1955 ItemKind::Enum(..) => "enum",
1956 ItemKind::Struct(..) => "struct",
1957 ItemKind::Union(..) => "union",
1958 ItemKind::Trait(..) => "trait",
1960 ItemKind::MacroDef(..) |
1961 ItemKind::Impl(..) |
1962 ItemKind::DefaultImpl(..) => "item"
1967 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1968 pub struct ForeignItem {
1970 pub attrs: Vec<Attribute>,
1971 pub node: ForeignItemKind,
1974 pub vis: Visibility,
1977 /// An item within an `extern` block
1978 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1979 pub enum ForeignItemKind {
1980 /// A foreign function
1981 Fn(P<FnDecl>, Generics),
1982 /// A foreign static item (`static ext: u8`), with optional mutability
1983 /// (the boolean is true when mutable)
1984 Static(P<Ty>, bool),
1987 impl ForeignItemKind {
1988 pub fn descriptive_variant(&self) -> &str {
1990 ForeignItemKind::Fn(..) => "foreign function",
1991 ForeignItemKind::Static(..) => "foreign static item"
2001 // are ASTs encodable?
2003 fn check_asts_encodable() {
2004 fn assert_encodable<T: serialize::Encodable>() {}
2005 assert_encodable::<Crate>();