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)]
541 Included(RangeSyntax),
545 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
546 pub enum RangeSyntax {
551 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
553 /// Represents a wildcard pattern (`_`)
556 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
557 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
558 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
559 /// during name resolution.
560 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
562 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
563 /// The `bool` is `true` in the presence of a `..`.
564 Struct(Path, Vec<Spanned<FieldPat>>, bool),
566 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
567 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
568 /// 0 <= position <= subpats.len()
569 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
571 /// A possibly qualified path pattern.
572 /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
573 /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
574 /// only legally refer to associated constants.
575 Path(Option<QSelf>, Path),
577 /// A tuple pattern `(a, b)`.
578 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
579 /// 0 <= position <= subpats.len()
580 Tuple(Vec<P<Pat>>, Option<usize>),
583 /// A reference pattern, e.g. `&mut (a, b)`
584 Ref(P<Pat>, Mutability),
587 /// A range pattern, e.g. `1...2`, `1..=2` or `1..2`
588 Range(P<Expr>, P<Expr>, RangeEnd),
589 /// `[a, b, ..i, y, z]` is represented as:
590 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
591 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
592 /// A macro pattern; pre-expansion
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
597 pub enum Mutability {
602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
604 /// The `+` operator (addition)
606 /// The `-` operator (subtraction)
608 /// The `*` operator (multiplication)
610 /// The `/` operator (division)
612 /// The `%` operator (modulus)
614 /// The `&&` operator (logical and)
616 /// The `||` operator (logical or)
618 /// The `^` operator (bitwise xor)
620 /// The `&` operator (bitwise and)
622 /// The `|` operator (bitwise or)
624 /// The `<<` operator (shift left)
626 /// The `>>` operator (shift right)
628 /// The `==` operator (equality)
630 /// The `<` operator (less than)
632 /// The `<=` operator (less than or equal to)
634 /// The `!=` operator (not equal to)
636 /// The `>=` operator (greater than or equal to)
638 /// The `>` operator (greater than)
643 pub fn to_string(&self) -> &'static str {
644 use self::BinOpKind::*;
666 pub fn lazy(&self) -> bool {
668 BinOpKind::And | BinOpKind::Or => true,
673 pub fn is_shift(&self) -> bool {
675 BinOpKind::Shl | BinOpKind::Shr => true,
679 pub fn is_comparison(&self) -> bool {
680 use self::BinOpKind::*;
682 Eq | Lt | Le | Ne | Gt | Ge =>
684 And | Or | Add | Sub | Mul | Div | Rem |
685 BitXor | BitAnd | BitOr | Shl | Shr =>
689 /// Returns `true` if the binary operator takes its arguments by value
690 pub fn is_by_value(&self) -> bool {
691 !self.is_comparison()
695 pub type BinOp = Spanned<BinOpKind>;
697 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
699 /// The `*` operator for dereferencing
701 /// The `!` operator for logical inversion
703 /// The `-` operator for negation
708 /// Returns `true` if the unary operator takes its argument by value
709 pub fn is_by_value(u: UnOp) -> bool {
711 UnOp::Neg | UnOp::Not => true,
716 pub fn to_string(op: UnOp) -> &'static str {
726 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
734 pub fn add_trailing_semicolon(mut self) -> Self {
735 self.node = match self.node {
736 StmtKind::Expr(expr) => StmtKind::Semi(expr),
737 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
738 (mac, MacStmtStyle::Semicolon, attrs)
745 pub fn is_item(&self) -> bool {
747 StmtKind::Local(_) => true,
753 impl fmt::Debug for Stmt {
754 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
755 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
760 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
762 /// A local (let) binding.
765 /// An item definition.
768 /// Expr without trailing semi-colon.
770 /// Expr with a trailing semi-colon.
773 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
776 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
777 pub enum MacStmtStyle {
778 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
779 /// `foo!(...);`, `foo![...];`
781 /// The macro statement had braces; e.g. foo! { ... }
783 /// The macro statement had parentheses or brackets and no semicolon; e.g.
784 /// `foo!(...)`. All of these will end up being converted into macro
789 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
790 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
793 pub ty: Option<P<Ty>>,
794 /// Initializer expression to set the value, if any
795 pub init: Option<P<Expr>>,
798 pub attrs: ThinVec<Attribute>,
801 /// An arm of a 'match'.
803 /// E.g. `0...10 => { println!("match!") }` as in
807 /// 0...10 => { println!("match!") },
808 /// _ => { println!("no match!") },
811 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
813 pub attrs: Vec<Attribute>,
814 pub pats: Vec<P<Pat>>,
815 pub guard: Option<P<Expr>>,
817 pub beginning_vert: Option<Span>, // For RFC 1925 feature gate
820 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
822 pub ident: SpannedIdent,
825 pub is_shorthand: bool,
826 pub attrs: ThinVec<Attribute>,
829 pub type SpannedIdent = Spanned<Ident>;
831 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
832 pub enum BlockCheckMode {
834 Unsafe(UnsafeSource),
837 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
838 pub enum UnsafeSource {
844 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
849 pub attrs: ThinVec<Attribute>
853 /// Wether this expression would be valid somewhere that expects a value, for example, an `if`
855 pub fn returns(&self) -> bool {
856 if let ExprKind::Block(ref block) = self.node {
857 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
859 Some(&StmtKind::Expr(_)) => true,
860 Some(&StmtKind::Semi(ref expr)) => {
861 if let ExprKind::Ret(_) = expr.node {
862 // last statement is explicit return
868 // This is a block that doesn't end in either an implicit or explicit return
872 // This is not a block, it is a value
878 impl fmt::Debug for Expr {
879 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
880 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
884 /// Limit types of a range (inclusive or exclusive)
885 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
886 pub enum RangeLimits {
887 /// Inclusive at the beginning, exclusive at the end
889 /// Inclusive at the beginning and end
893 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
895 /// A `box x` expression.
897 /// First expr is the place; second expr is the value.
898 InPlace(P<Expr>, P<Expr>),
899 /// An array (`[a, b, c, d]`)
903 /// The first field resolves to the function itself,
904 /// and the second field is the list of arguments
905 Call(P<Expr>, Vec<P<Expr>>),
906 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
908 /// The `PathSegment` represents the method name and its generic arguments
909 /// (within the angle brackets).
910 /// The first element of the vector of `Expr`s is the expression that evaluates
911 /// to the object on which the method is being called on (the receiver),
912 /// and the remaining elements are the rest of the arguments.
913 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
914 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
915 MethodCall(PathSegment, Vec<P<Expr>>),
916 /// A tuple (`(a, b, c ,d)`)
918 /// A binary operation (For example: `a + b`, `a * b`)
919 Binary(BinOp, P<Expr>, P<Expr>),
920 /// A unary operation (For example: `!x`, `*x`)
921 Unary(UnOp, P<Expr>),
922 /// A literal (For example: `1`, `"foo"`)
924 /// A cast (`foo as f64`)
925 Cast(P<Expr>, P<Ty>),
926 Type(P<Expr>, P<Ty>),
927 /// An `if` block, with an optional else block
929 /// `if expr { block } else { expr }`
930 If(P<Expr>, P<Block>, Option<P<Expr>>),
931 /// An `if let` expression with an optional else block
933 /// `if let pat = expr { block } else { expr }`
935 /// This is desugared to a `match` expression.
936 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
937 /// A while loop, with an optional label
939 /// `'label: while expr { block }`
940 While(P<Expr>, P<Block>, Option<SpannedIdent>),
941 /// A while-let loop, with an optional label
943 /// `'label: while let pat = expr { block }`
945 /// This is desugared to a combination of `loop` and `match` expressions.
946 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
947 /// A for loop, with an optional label
949 /// `'label: for pat in expr { block }`
951 /// This is desugared to a combination of `loop` and `match` expressions.
952 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
953 /// Conditionless loop (can be exited with break, continue, or return)
955 /// `'label: loop { block }`
956 Loop(P<Block>, Option<SpannedIdent>),
958 Match(P<Expr>, Vec<Arm>),
959 /// A closure (for example, `move |a, b, c| a + b + c`)
961 /// The final span is the span of the argument block `|...|`
962 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
963 /// A block (`{ ... }`)
965 /// A catch block (`catch { ... }`)
968 /// An assignment (`a = foo()`)
969 Assign(P<Expr>, P<Expr>),
970 /// An assignment with an operator
972 /// For example, `a += 1`.
973 AssignOp(BinOp, P<Expr>, P<Expr>),
974 /// Access of a named struct field (`obj.foo`)
975 Field(P<Expr>, SpannedIdent),
976 /// Access of an unnamed field of a struct or tuple-struct
978 /// For example, `foo.0`.
979 TupField(P<Expr>, Spanned<usize>),
980 /// An indexing operation (`foo[2]`)
981 Index(P<Expr>, P<Expr>),
982 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
983 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
985 /// Variable reference, possibly containing `::` and/or type
986 /// parameters, e.g. foo::bar::<baz>.
988 /// Optionally "qualified",
989 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
990 Path(Option<QSelf>, Path),
992 /// A referencing operation (`&a` or `&mut a`)
993 AddrOf(Mutability, P<Expr>),
994 /// A `break`, with an optional label to break, and an optional expression
995 Break(Option<SpannedIdent>, Option<P<Expr>>),
996 /// A `continue`, with an optional label
997 Continue(Option<SpannedIdent>),
998 /// A `return`, with an optional value to be returned
999 Ret(Option<P<Expr>>),
1001 /// Output of the `asm!()` macro
1002 InlineAsm(P<InlineAsm>),
1004 /// A macro invocation; pre-expansion
1007 /// A struct literal expression.
1009 /// For example, `Foo {x: 1, y: 2}`, or
1010 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1011 Struct(Path, Vec<Field>, Option<P<Expr>>),
1013 /// An array literal constructed from one repeated element.
1015 /// For example, `[1; 5]`. The first expression is the element
1016 /// to be repeated; the second is the number of times to repeat it.
1017 Repeat(P<Expr>, P<Expr>),
1019 /// No-op: used solely so we can pretty-print faithfully
1025 /// A `yield`, with an optional value to be yielded
1026 Yield(Option<P<Expr>>),
1029 /// The explicit Self type in a "qualified path". The actual
1030 /// path, including the trait and the associated item, is stored
1031 /// separately. `position` represents the index of the associated
1032 /// item qualified with this Self type.
1034 /// ```ignore (only-for-syntax-highlight)
1035 /// <Vec<T> as a::b::Trait>::AssociatedItem
1036 /// ^~~~~ ~~~~~~~~~~~~~~^
1039 /// <Vec<T>>::AssociatedItem
1043 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1049 /// A capture clause
1050 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1051 pub enum CaptureBy {
1056 pub type Mac = Spanned<Mac_>;
1058 /// Represents a macro invocation. The Path indicates which macro
1059 /// is being invoked, and the vector of token-trees contains the source
1060 /// of the macro invocation.
1062 /// NB: the additional ident for a macro_rules-style macro is actually
1063 /// stored in the enclosing item. Oog.
1064 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1067 pub tts: ThinTokenStream,
1071 pub fn stream(&self) -> TokenStream {
1072 self.tts.clone().into()
1076 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1077 pub struct MacroDef {
1078 pub tokens: ThinTokenStream,
1083 pub fn stream(&self) -> TokenStream {
1084 self.tokens.clone().into()
1088 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1090 /// A regular string, like `"foo"`
1092 /// A raw string, like `r##"foo"##`
1094 /// The uint is the number of `#` symbols used
1099 pub type Lit = Spanned<LitKind>;
1101 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1102 pub enum LitIntType {
1110 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1111 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1113 /// A string literal (`"foo"`)
1114 Str(Symbol, StrStyle),
1115 /// A byte string (`b"foo"`)
1116 ByteStr(Rc<Vec<u8>>),
1117 /// A byte char (`b'f'`)
1119 /// A character literal (`'a'`)
1121 /// An integer literal (`1`)
1122 Int(u128, LitIntType),
1123 /// A float literal (`1f64` or `1E10f64`)
1124 Float(Symbol, FloatTy),
1125 /// A float literal without a suffix (`1.0 or 1.0E10`)
1126 FloatUnsuffixed(Symbol),
1127 /// A boolean literal
1132 /// Returns true if this literal is a string and false otherwise.
1133 pub fn is_str(&self) -> bool {
1135 LitKind::Str(..) => true,
1140 /// Returns true if this literal has no suffix. Note: this will return true
1141 /// for literals with prefixes such as raw strings and byte strings.
1142 pub fn is_unsuffixed(&self) -> bool {
1144 // unsuffixed variants
1146 LitKind::ByteStr(..) |
1149 LitKind::Int(_, LitIntType::Unsuffixed) |
1150 LitKind::FloatUnsuffixed(..) |
1151 LitKind::Bool(..) => true,
1152 // suffixed variants
1153 LitKind::Int(_, LitIntType::Signed(..)) |
1154 LitKind::Int(_, LitIntType::Unsigned(..)) |
1155 LitKind::Float(..) => false,
1159 /// Returns true if this literal has a suffix.
1160 pub fn is_suffixed(&self) -> bool {
1161 !self.is_unsuffixed()
1165 // NB: If you change this, you'll probably want to change the corresponding
1166 // type structure in middle/ty.rs as well.
1167 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1170 pub mutbl: Mutability,
1173 /// Represents a method's signature in a trait declaration,
1174 /// or in an implementation.
1175 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1176 pub struct MethodSig {
1177 pub unsafety: Unsafety,
1178 pub constness: Spanned<Constness>,
1180 pub decl: P<FnDecl>,
1181 pub generics: Generics,
1184 /// Represents an item declaration within a trait declaration,
1185 /// possibly including a default implementation. A trait item is
1186 /// either required (meaning it doesn't have an implementation, just a
1187 /// signature) or provided (meaning it has a default implementation).
1188 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1189 pub struct TraitItem {
1192 pub attrs: Vec<Attribute>,
1193 pub node: TraitItemKind,
1195 /// See `Item::tokens` for what this is
1196 pub tokens: Option<TokenStream>,
1199 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1200 pub enum TraitItemKind {
1201 Const(P<Ty>, Option<P<Expr>>),
1202 Method(MethodSig, Option<P<Block>>),
1203 Type(TyParamBounds, Option<P<Ty>>),
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1208 pub struct ImplItem {
1211 pub vis: Visibility,
1212 pub defaultness: Defaultness,
1213 pub attrs: Vec<Attribute>,
1214 pub node: ImplItemKind,
1216 /// See `Item::tokens` for what this is
1217 pub tokens: Option<TokenStream>,
1220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1221 pub enum ImplItemKind {
1222 Const(P<Ty>, P<Expr>),
1223 Method(MethodSig, P<Block>),
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1239 impl fmt::Debug for IntTy {
1240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1241 fmt::Display::fmt(self, f)
1245 impl fmt::Display for IntTy {
1246 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1247 write!(f, "{}", self.ty_to_string())
1252 pub fn ty_to_string(&self) -> &'static str {
1254 IntTy::Is => "isize",
1256 IntTy::I16 => "i16",
1257 IntTy::I32 => "i32",
1258 IntTy::I64 => "i64",
1259 IntTy::I128 => "i128",
1263 pub fn val_to_string(&self, val: i128) -> String {
1264 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1265 // are parsed as u128, so we wouldn't want to print an extra negative
1267 format!("{}{}", val as u128, self.ty_to_string())
1270 pub fn bit_width(&self) -> Option<usize> {
1272 IntTy::Is => return None,
1282 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1294 pub fn ty_to_string(&self) -> &'static str {
1296 UintTy::Us => "usize",
1298 UintTy::U16 => "u16",
1299 UintTy::U32 => "u32",
1300 UintTy::U64 => "u64",
1301 UintTy::U128 => "u128",
1305 pub fn val_to_string(&self, val: u128) -> String {
1306 format!("{}{}", val, self.ty_to_string())
1309 pub fn bit_width(&self) -> Option<usize> {
1311 UintTy::Us => return None,
1316 UintTy::U128 => 128,
1321 impl fmt::Debug for UintTy {
1322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1323 fmt::Display::fmt(self, f)
1327 impl fmt::Display for UintTy {
1328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1329 write!(f, "{}", self.ty_to_string())
1333 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1340 impl fmt::Debug for FloatTy {
1341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1342 fmt::Display::fmt(self, f)
1346 impl fmt::Display for FloatTy {
1347 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1348 write!(f, "{}", self.ty_to_string())
1353 pub fn ty_to_string(&self) -> &'static str {
1355 FloatTy::F32 => "f32",
1356 FloatTy::F64 => "f64",
1360 pub fn bit_width(&self) -> usize {
1368 // Bind a type to an associated type: `A=Foo`.
1369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1370 pub struct TypeBinding {
1377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1384 impl fmt::Debug for Ty {
1385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1386 write!(f, "type({})", pprust::ty_to_string(self))
1390 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1391 pub struct BareFnTy {
1392 pub unsafety: Unsafety,
1394 pub lifetimes: Vec<LifetimeDef>,
1398 /// The different kinds of types recognized by the compiler
1399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1401 /// A variable-length slice (`[T]`)
1403 /// A fixed length array (`[T; n]`)
1404 Array(P<Ty>, P<Expr>),
1405 /// A raw pointer (`*const T` or `*mut T`)
1407 /// A reference (`&'a T` or `&'a mut T`)
1408 Rptr(Option<Lifetime>, MutTy),
1409 /// A bare function (e.g. `fn(usize) -> bool`)
1410 BareFn(P<BareFnTy>),
1411 /// The never type (`!`)
1413 /// A tuple (`(A, B, C, D,...)`)
1415 /// A path (`module::module::...::Type`), optionally
1416 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1418 /// Type parameters are stored in the Path itself
1419 Path(Option<QSelf>, Path),
1420 /// A trait object type `Bound1 + Bound2 + Bound3`
1421 /// where `Bound` is a trait or a lifetime.
1422 TraitObject(TyParamBounds, TraitObjectSyntax),
1423 /// An `impl Bound1 + Bound2 + Bound3` type
1424 /// where `Bound` is a trait or a lifetime.
1425 ImplTrait(TyParamBounds),
1426 /// No-op; kept solely so that we can pretty-print faithfully
1430 /// TyKind::Infer means the type should be inferred instead of it having been
1431 /// specified. This can appear anywhere in a type.
1433 /// Inferred type of a `self` or `&self` argument in a method.
1435 // A macro in the type position.
1437 /// Placeholder for a kind that has failed to be defined.
1441 /// Syntax used to declare a trait object.
1442 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1443 pub enum TraitObjectSyntax {
1448 /// Inline assembly dialect.
1450 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1451 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1452 pub enum AsmDialect {
1457 /// Inline assembly.
1459 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1460 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1461 pub struct InlineAsmOutput {
1462 pub constraint: Symbol,
1465 pub is_indirect: bool,
1468 /// Inline assembly.
1470 /// E.g. `asm!("NOP");`
1471 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1472 pub struct InlineAsm {
1474 pub asm_str_style: StrStyle,
1475 pub outputs: Vec<InlineAsmOutput>,
1476 pub inputs: Vec<(Symbol, P<Expr>)>,
1477 pub clobbers: Vec<Symbol>,
1479 pub alignstack: bool,
1480 pub dialect: AsmDialect,
1481 pub ctxt: SyntaxContext,
1484 /// An argument in a function header.
1486 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1487 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1494 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1496 /// E.g. `&mut self` as in `fn foo(&mut self)`
1497 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1499 /// `self`, `mut self`
1501 /// `&'lt self`, `&'lt mut self`
1502 Region(Option<Lifetime>, Mutability),
1503 /// `self: TYPE`, `mut self: TYPE`
1504 Explicit(P<Ty>, Mutability),
1507 pub type ExplicitSelf = Spanned<SelfKind>;
1510 pub fn to_self(&self) -> Option<ExplicitSelf> {
1511 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1512 if ident.node.name == keywords::SelfValue.name() {
1513 return match self.ty.node {
1514 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1515 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1516 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1518 _ => Some(respan(self.pat.span.to(self.ty.span),
1519 SelfKind::Explicit(self.ty.clone(), mutbl))),
1526 pub fn is_self(&self) -> bool {
1527 if let PatKind::Ident(_, ident, _) = self.pat.node {
1528 ident.node.name == keywords::SelfValue.name()
1534 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1535 let span = eself.span.to(eself_ident.span);
1536 let infer_ty = P(Ty {
1538 node: TyKind::ImplicitSelf,
1541 let arg = |mutbl, ty| Arg {
1544 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1551 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1552 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1553 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1555 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1562 /// Header (not the body) of a function declaration.
1564 /// E.g. `fn foo(bar: baz)`
1565 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1567 pub inputs: Vec<Arg>,
1568 pub output: FunctionRetTy,
1573 pub fn get_self(&self) -> Option<ExplicitSelf> {
1574 self.inputs.get(0).and_then(Arg::to_self)
1576 pub fn has_self(&self) -> bool {
1577 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1581 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1587 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1588 pub enum Constness {
1593 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1594 pub enum Defaultness {
1599 impl fmt::Display for Unsafety {
1600 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1601 fmt::Display::fmt(match *self {
1602 Unsafety::Normal => "normal",
1603 Unsafety::Unsafe => "unsafe",
1608 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1609 pub enum ImplPolarity {
1610 /// `impl Trait for Type`
1612 /// `impl !Trait for Type`
1616 impl fmt::Debug for ImplPolarity {
1617 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1619 ImplPolarity::Positive => "positive".fmt(f),
1620 ImplPolarity::Negative => "negative".fmt(f),
1626 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1627 pub enum FunctionRetTy {
1628 /// Return type is not specified.
1630 /// Functions default to `()` and
1631 /// closures default to inference. Span points to where return
1632 /// type would be inserted.
1638 impl FunctionRetTy {
1639 pub fn span(&self) -> Span {
1641 FunctionRetTy::Default(span) => span,
1642 FunctionRetTy::Ty(ref ty) => ty.span,
1647 /// Module declaration.
1649 /// E.g. `mod foo;` or `mod foo { .. }`
1650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1652 /// A span from the first token past `{` to the last token until `}`.
1653 /// For `mod foo;`, the inner span ranges from the first token
1654 /// to the last token in the external file.
1656 pub items: Vec<P<Item>>,
1659 /// Foreign module declaration.
1661 /// E.g. `extern { .. }` or `extern C { .. }`
1662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1663 pub struct ForeignMod {
1665 pub items: Vec<ForeignItem>,
1668 /// Global inline assembly
1670 /// aka module-level assembly or file-scoped assembly
1671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1672 pub struct GlobalAsm {
1674 pub ctxt: SyntaxContext,
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 pub struct EnumDef {
1679 pub variants: Vec<Variant>,
1682 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1683 pub struct Variant_ {
1685 pub attrs: Vec<Attribute>,
1686 pub data: VariantData,
1687 /// Explicit discriminant, e.g. `Foo = 1`
1688 pub disr_expr: Option<P<Expr>>,
1691 pub type Variant = Spanned<Variant_>;
1693 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1694 pub struct PathListItem_ {
1696 /// renamed in list, e.g. `use foo::{bar as baz};`
1697 pub rename: Option<Ident>,
1701 pub type PathListItem = Spanned<PathListItem_>;
1703 pub type ViewPath = Spanned<ViewPath_>;
1705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1706 pub enum ViewPath_ {
1708 /// `foo::bar::baz as quux`
1712 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1713 ViewPathSimple(Ident, Path),
1718 /// `foo::bar::{a,b,c}`
1719 ViewPathList(Path, Vec<PathListItem>)
1723 pub fn path(&self) -> &Path {
1725 ViewPathSimple(_, ref path) |
1726 ViewPathGlob (ref path) |
1727 ViewPathList(ref path, _) => path
1733 /// Distinguishes between Attributes that decorate items and Attributes that
1734 /// are contained as statements within items. These two cases need to be
1735 /// distinguished for pretty-printing.
1736 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1737 pub enum AttrStyle {
1742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1743 pub struct AttrId(pub usize);
1745 /// Meta-data associated with an item
1746 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1747 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1748 pub struct Attribute {
1750 pub style: AttrStyle,
1752 pub tokens: TokenStream,
1753 pub is_sugared_doc: bool,
1757 /// TraitRef's appear in impls.
1759 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1760 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1761 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1762 /// same as the impl's node id).
1763 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1764 pub struct TraitRef {
1769 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1770 pub struct PolyTraitRef {
1771 /// The `'a` in `<'a> Foo<&'a T>`
1772 pub bound_lifetimes: Vec<LifetimeDef>,
1774 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1775 pub trait_ref: TraitRef,
1781 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1783 bound_lifetimes: lifetimes,
1784 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1790 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1791 pub enum Visibility {
1794 Restricted { path: P<Path>, id: NodeId },
1798 /// Field of a struct.
1800 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1801 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1802 pub struct StructField {
1804 pub ident: Option<Ident>,
1805 pub vis: Visibility,
1808 pub attrs: Vec<Attribute>,
1811 /// Fields and Ids of enum variants and structs
1813 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1814 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1815 /// One shared Id can be successfully used for these two purposes.
1816 /// Id of the whole enum lives in `Item`.
1818 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1819 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1820 /// the variant itself" from enum variants.
1821 /// Id of the whole struct lives in `Item`.
1822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1823 pub enum VariantData {
1826 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1827 Struct(Vec<StructField>, NodeId),
1830 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1831 Tuple(Vec<StructField>, NodeId),
1834 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1839 pub fn fields(&self) -> &[StructField] {
1841 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1845 pub fn id(&self) -> NodeId {
1847 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1850 pub fn is_struct(&self) -> bool {
1851 if let VariantData::Struct(..) = *self { true } else { false }
1853 pub fn is_tuple(&self) -> bool {
1854 if let VariantData::Tuple(..) = *self { true } else { false }
1856 pub fn is_unit(&self) -> bool {
1857 if let VariantData::Unit(..) = *self { true } else { false }
1863 /// The name might be a dummy name in case of anonymous items
1864 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1867 pub attrs: Vec<Attribute>,
1870 pub vis: Visibility,
1873 /// Original tokens this item was parsed from. This isn't necessarily
1874 /// available for all items, although over time more and more items should
1875 /// have this be `Some`. Right now this is primarily used for procedural
1876 /// macros, notably custom attributes.
1878 /// Note that the tokens here do not include the outer attributes, but will
1879 /// include inner attributes.
1880 pub tokens: Option<TokenStream>,
1883 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1885 /// An `extern crate` item, with optional original crate name.
1887 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1888 ExternCrate(Option<Name>),
1889 /// A use declaration (`use` or `pub use`) item.
1891 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1893 /// A static item (`static` or `pub static`).
1895 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1896 Static(P<Ty>, Mutability, P<Expr>),
1897 /// A constant item (`const` or `pub const`).
1899 /// E.g. `const FOO: i32 = 42;`
1900 Const(P<Ty>, P<Expr>),
1901 /// A function declaration (`fn` or `pub fn`).
1903 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1904 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1905 /// A module declaration (`mod` or `pub mod`).
1907 /// E.g. `mod foo;` or `mod foo { .. }`
1909 /// An external module (`extern` or `pub extern`).
1911 /// E.g. `extern {}` or `extern "C" {}`
1912 ForeignMod(ForeignMod),
1913 /// Module-level inline assembly (from `global_asm!()`)
1914 GlobalAsm(P<GlobalAsm>),
1915 /// A type alias (`type` or `pub type`).
1917 /// E.g. `type Foo = Bar<u8>;`
1918 Ty(P<Ty>, Generics),
1919 /// An enum definition (`enum` or `pub enum`).
1921 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1922 Enum(EnumDef, Generics),
1923 /// A struct definition (`struct` or `pub struct`).
1925 /// E.g. `struct Foo<A> { x: A }`
1926 Struct(VariantData, Generics),
1927 /// A union definition (`union` or `pub union`).
1929 /// E.g. `union Foo<A, B> { x: A, y: B }`
1930 Union(VariantData, Generics),
1931 /// A Trait declaration (`trait` or `pub trait`).
1933 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1934 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1935 /// Auto trait implementation.
1937 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1938 DefaultImpl(Unsafety, TraitRef),
1939 /// An implementation.
1941 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1946 Option<TraitRef>, // (optional) trait this impl implements
1949 /// A macro invocation.
1951 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1954 /// A macro definition.
1959 pub fn descriptive_variant(&self) -> &str {
1961 ItemKind::ExternCrate(..) => "extern crate",
1962 ItemKind::Use(..) => "use",
1963 ItemKind::Static(..) => "static item",
1964 ItemKind::Const(..) => "constant item",
1965 ItemKind::Fn(..) => "function",
1966 ItemKind::Mod(..) => "module",
1967 ItemKind::ForeignMod(..) => "foreign module",
1968 ItemKind::GlobalAsm(..) => "global asm",
1969 ItemKind::Ty(..) => "type alias",
1970 ItemKind::Enum(..) => "enum",
1971 ItemKind::Struct(..) => "struct",
1972 ItemKind::Union(..) => "union",
1973 ItemKind::Trait(..) => "trait",
1975 ItemKind::MacroDef(..) |
1976 ItemKind::Impl(..) |
1977 ItemKind::DefaultImpl(..) => "item"
1982 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1983 pub struct ForeignItem {
1985 pub attrs: Vec<Attribute>,
1986 pub node: ForeignItemKind,
1989 pub vis: Visibility,
1992 /// An item within an `extern` block
1993 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1994 pub enum ForeignItemKind {
1995 /// A foreign function
1996 Fn(P<FnDecl>, Generics),
1997 /// A foreign static item (`static ext: u8`), with optional mutability
1998 /// (the boolean is true when mutable)
1999 Static(P<Ty>, bool),
2002 impl ForeignItemKind {
2003 pub fn descriptive_variant(&self) -> &str {
2005 ForeignItemKind::Fn(..) => "foreign function",
2006 ForeignItemKind::Static(..) => "foreign static item"
2016 // are ASTs encodable?
2018 fn check_asts_encodable() {
2019 fn assert_encodable<T: serialize::Encodable>() {}
2020 assert_encodable::<Crate>();