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 // FIXME (pending discussion of #1697, #2178...): local should really be
790 // a refinement on pat.
791 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
792 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
795 pub ty: Option<P<Ty>>,
796 /// Initializer expression to set the value, if any
797 pub init: Option<P<Expr>>,
800 pub attrs: ThinVec<Attribute>,
803 /// An arm of a 'match'.
805 /// E.g. `0...10 => { println!("match!") }` as in
809 /// 0...10 => { println!("match!") },
810 /// _ => { println!("no match!") },
813 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
815 pub attrs: Vec<Attribute>,
816 pub pats: Vec<P<Pat>>,
817 pub guard: Option<P<Expr>>,
819 pub beginning_vert: Option<Span>, // For RFC 1925 feature gate
822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
824 pub ident: SpannedIdent,
827 pub is_shorthand: bool,
828 pub attrs: ThinVec<Attribute>,
831 pub type SpannedIdent = Spanned<Ident>;
833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
834 pub enum BlockCheckMode {
836 Unsafe(UnsafeSource),
839 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
840 pub enum UnsafeSource {
846 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
851 pub attrs: ThinVec<Attribute>
855 /// Wether this expression would be valid somewhere that expects a value, for example, an `if`
857 pub fn returns(&self) -> bool {
858 if let ExprKind::Block(ref block) = self.node {
859 match block.stmts.last().map(|last_stmt| &last_stmt.node) {
861 Some(&StmtKind::Expr(_)) => true,
862 Some(&StmtKind::Semi(ref expr)) => {
863 if let ExprKind::Ret(_) = expr.node {
864 // last statement is explicit return
870 // This is a block that doesn't end in either an implicit or explicit return
874 // This is not a block, it is a value
880 impl fmt::Debug for Expr {
881 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
886 /// Limit types of a range (inclusive or exclusive)
887 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
888 pub enum RangeLimits {
889 /// Inclusive at the beginning, exclusive at the end
891 /// Inclusive at the beginning and end
895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
897 /// A `box x` expression.
899 /// First expr is the place; second expr is the value.
900 InPlace(P<Expr>, P<Expr>),
901 /// An array (`[a, b, c, d]`)
905 /// The first field resolves to the function itself,
906 /// and the second field is the list of arguments
907 Call(P<Expr>, Vec<P<Expr>>),
908 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
910 /// The `PathSegment` represents the method name and its generic arguments
911 /// (within the angle brackets).
912 /// The first element of the vector of `Expr`s is the expression that evaluates
913 /// to the object on which the method is being called on (the receiver),
914 /// and the remaining elements are the rest of the arguments.
915 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
916 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
917 MethodCall(PathSegment, Vec<P<Expr>>),
918 /// A tuple (`(a, b, c ,d)`)
920 /// A binary operation (For example: `a + b`, `a * b`)
921 Binary(BinOp, P<Expr>, P<Expr>),
922 /// A unary operation (For example: `!x`, `*x`)
923 Unary(UnOp, P<Expr>),
924 /// A literal (For example: `1`, `"foo"`)
926 /// A cast (`foo as f64`)
927 Cast(P<Expr>, P<Ty>),
928 Type(P<Expr>, P<Ty>),
929 /// An `if` block, with an optional else block
931 /// `if expr { block } else { expr }`
932 If(P<Expr>, P<Block>, Option<P<Expr>>),
933 /// An `if let` expression with an optional else block
935 /// `if let pat = expr { block } else { expr }`
937 /// This is desugared to a `match` expression.
938 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
939 /// A while loop, with an optional label
941 /// `'label: while expr { block }`
942 While(P<Expr>, P<Block>, Option<SpannedIdent>),
943 /// A while-let loop, with an optional label
945 /// `'label: while let pat = expr { block }`
947 /// This is desugared to a combination of `loop` and `match` expressions.
948 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
949 /// A for loop, with an optional label
951 /// `'label: for pat in expr { block }`
953 /// This is desugared to a combination of `loop` and `match` expressions.
954 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
955 /// Conditionless loop (can be exited with break, continue, or return)
957 /// `'label: loop { block }`
958 Loop(P<Block>, Option<SpannedIdent>),
960 Match(P<Expr>, Vec<Arm>),
961 /// A closure (for example, `move |a, b, c| a + b + c`)
963 /// The final span is the span of the argument block `|...|`
964 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
965 /// A block (`{ ... }`)
967 /// A catch block (`catch { ... }`)
970 /// An assignment (`a = foo()`)
971 Assign(P<Expr>, P<Expr>),
972 /// An assignment with an operator
974 /// For example, `a += 1`.
975 AssignOp(BinOp, P<Expr>, P<Expr>),
976 /// Access of a named struct field (`obj.foo`)
977 Field(P<Expr>, SpannedIdent),
978 /// Access of an unnamed field of a struct or tuple-struct
980 /// For example, `foo.0`.
981 TupField(P<Expr>, Spanned<usize>),
982 /// An indexing operation (`foo[2]`)
983 Index(P<Expr>, P<Expr>),
984 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
985 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
987 /// Variable reference, possibly containing `::` and/or type
988 /// parameters, e.g. foo::bar::<baz>.
990 /// Optionally "qualified",
991 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
992 Path(Option<QSelf>, Path),
994 /// A referencing operation (`&a` or `&mut a`)
995 AddrOf(Mutability, P<Expr>),
996 /// A `break`, with an optional label to break, and an optional expression
997 Break(Option<SpannedIdent>, Option<P<Expr>>),
998 /// A `continue`, with an optional label
999 Continue(Option<SpannedIdent>),
1000 /// A `return`, with an optional value to be returned
1001 Ret(Option<P<Expr>>),
1003 /// Output of the `asm!()` macro
1004 InlineAsm(P<InlineAsm>),
1006 /// A macro invocation; pre-expansion
1009 /// A struct literal expression.
1011 /// For example, `Foo {x: 1, y: 2}`, or
1012 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1013 Struct(Path, Vec<Field>, Option<P<Expr>>),
1015 /// An array literal constructed from one repeated element.
1017 /// For example, `[1; 5]`. The first expression is the element
1018 /// to be repeated; the second is the number of times to repeat it.
1019 Repeat(P<Expr>, P<Expr>),
1021 /// No-op: used solely so we can pretty-print faithfully
1027 /// A `yield`, with an optional value to be yielded
1028 Yield(Option<P<Expr>>),
1031 /// The explicit Self type in a "qualified path". The actual
1032 /// path, including the trait and the associated item, is stored
1033 /// separately. `position` represents the index of the associated
1034 /// item qualified with this Self type.
1036 /// ```ignore (only-for-syntax-highlight)
1037 /// <Vec<T> as a::b::Trait>::AssociatedItem
1038 /// ^~~~~ ~~~~~~~~~~~~~~^
1041 /// <Vec<T>>::AssociatedItem
1045 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1051 /// A capture clause
1052 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1053 pub enum CaptureBy {
1058 pub type Mac = Spanned<Mac_>;
1060 /// Represents a macro invocation. The Path indicates which macro
1061 /// is being invoked, and the vector of token-trees contains the source
1062 /// of the macro invocation.
1064 /// NB: the additional ident for a macro_rules-style macro is actually
1065 /// stored in the enclosing item. Oog.
1066 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1069 pub tts: ThinTokenStream,
1073 pub fn stream(&self) -> TokenStream {
1074 self.tts.clone().into()
1078 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1079 pub struct MacroDef {
1080 pub tokens: ThinTokenStream,
1085 pub fn stream(&self) -> TokenStream {
1086 self.tokens.clone().into()
1090 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1092 /// A regular string, like `"foo"`
1094 /// A raw string, like `r##"foo"##`
1096 /// The uint is the number of `#` symbols used
1101 pub type Lit = Spanned<LitKind>;
1103 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1104 pub enum LitIntType {
1112 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1113 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1115 /// A string literal (`"foo"`)
1116 Str(Symbol, StrStyle),
1117 /// A byte string (`b"foo"`)
1118 ByteStr(Rc<Vec<u8>>),
1119 /// A byte char (`b'f'`)
1121 /// A character literal (`'a'`)
1123 /// An integer literal (`1`)
1124 Int(u128, LitIntType),
1125 /// A float literal (`1f64` or `1E10f64`)
1126 Float(Symbol, FloatTy),
1127 /// A float literal without a suffix (`1.0 or 1.0E10`)
1128 FloatUnsuffixed(Symbol),
1129 /// A boolean literal
1134 /// Returns true if this literal is a string and false otherwise.
1135 pub fn is_str(&self) -> bool {
1137 LitKind::Str(..) => true,
1142 /// Returns true if this literal has no suffix. Note: this will return true
1143 /// for literals with prefixes such as raw strings and byte strings.
1144 pub fn is_unsuffixed(&self) -> bool {
1146 // unsuffixed variants
1148 LitKind::ByteStr(..) |
1151 LitKind::Int(_, LitIntType::Unsuffixed) |
1152 LitKind::FloatUnsuffixed(..) |
1153 LitKind::Bool(..) => true,
1154 // suffixed variants
1155 LitKind::Int(_, LitIntType::Signed(..)) |
1156 LitKind::Int(_, LitIntType::Unsigned(..)) |
1157 LitKind::Float(..) => false,
1161 /// Returns true if this literal has a suffix.
1162 pub fn is_suffixed(&self) -> bool {
1163 !self.is_unsuffixed()
1167 // NB: If you change this, you'll probably want to change the corresponding
1168 // type structure in middle/ty.rs as well.
1169 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1172 pub mutbl: Mutability,
1175 /// Represents a method's signature in a trait declaration,
1176 /// or in an implementation.
1177 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1178 pub struct MethodSig {
1179 pub unsafety: Unsafety,
1180 pub constness: Spanned<Constness>,
1182 pub decl: P<FnDecl>,
1183 pub generics: Generics,
1186 /// Represents an item declaration within a trait declaration,
1187 /// possibly including a default implementation. A trait item is
1188 /// either required (meaning it doesn't have an implementation, just a
1189 /// signature) or provided (meaning it has a default implementation).
1190 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1191 pub struct TraitItem {
1194 pub attrs: Vec<Attribute>,
1195 pub node: TraitItemKind,
1197 /// See `Item::tokens` for what this is
1198 pub tokens: Option<TokenStream>,
1201 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1202 pub enum TraitItemKind {
1203 Const(P<Ty>, Option<P<Expr>>),
1204 Method(MethodSig, Option<P<Block>>),
1205 Type(TyParamBounds, Option<P<Ty>>),
1209 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1210 pub struct ImplItem {
1213 pub vis: Visibility,
1214 pub defaultness: Defaultness,
1215 pub attrs: Vec<Attribute>,
1216 pub node: ImplItemKind,
1218 /// See `Item::tokens` for what this is
1219 pub tokens: Option<TokenStream>,
1222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1223 pub enum ImplItemKind {
1224 Const(P<Ty>, P<Expr>),
1225 Method(MethodSig, P<Block>),
1230 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1241 impl fmt::Debug for IntTy {
1242 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1243 fmt::Display::fmt(self, f)
1247 impl fmt::Display for IntTy {
1248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1249 write!(f, "{}", self.ty_to_string())
1254 pub fn ty_to_string(&self) -> &'static str {
1256 IntTy::Is => "isize",
1258 IntTy::I16 => "i16",
1259 IntTy::I32 => "i32",
1260 IntTy::I64 => "i64",
1261 IntTy::I128 => "i128",
1265 pub fn val_to_string(&self, val: i128) -> String {
1266 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1267 // are parsed as u128, so we wouldn't want to print an extra negative
1269 format!("{}{}", val as u128, self.ty_to_string())
1272 pub fn bit_width(&self) -> Option<usize> {
1274 IntTy::Is => return None,
1284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1296 pub fn ty_to_string(&self) -> &'static str {
1298 UintTy::Us => "usize",
1300 UintTy::U16 => "u16",
1301 UintTy::U32 => "u32",
1302 UintTy::U64 => "u64",
1303 UintTy::U128 => "u128",
1307 pub fn val_to_string(&self, val: u128) -> String {
1308 format!("{}{}", val, self.ty_to_string())
1311 pub fn bit_width(&self) -> Option<usize> {
1313 UintTy::Us => return None,
1318 UintTy::U128 => 128,
1323 impl fmt::Debug for UintTy {
1324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1325 fmt::Display::fmt(self, f)
1329 impl fmt::Display for UintTy {
1330 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1331 write!(f, "{}", self.ty_to_string())
1335 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
1342 impl fmt::Debug for FloatTy {
1343 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1344 fmt::Display::fmt(self, f)
1348 impl fmt::Display for FloatTy {
1349 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1350 write!(f, "{}", self.ty_to_string())
1355 pub fn ty_to_string(&self) -> &'static str {
1357 FloatTy::F32 => "f32",
1358 FloatTy::F64 => "f64",
1362 pub fn bit_width(&self) -> usize {
1370 // Bind a type to an associated type: `A=Foo`.
1371 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1372 pub struct TypeBinding {
1379 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1386 impl fmt::Debug for Ty {
1387 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1388 write!(f, "type({})", pprust::ty_to_string(self))
1392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1393 pub struct BareFnTy {
1394 pub unsafety: Unsafety,
1396 pub lifetimes: Vec<LifetimeDef>,
1400 /// The different kinds of types recognized by the compiler
1401 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1403 /// A variable-length slice (`[T]`)
1405 /// A fixed length array (`[T; n]`)
1406 Array(P<Ty>, P<Expr>),
1407 /// A raw pointer (`*const T` or `*mut T`)
1409 /// A reference (`&'a T` or `&'a mut T`)
1410 Rptr(Option<Lifetime>, MutTy),
1411 /// A bare function (e.g. `fn(usize) -> bool`)
1412 BareFn(P<BareFnTy>),
1413 /// The never type (`!`)
1415 /// A tuple (`(A, B, C, D,...)`)
1417 /// A path (`module::module::...::Type`), optionally
1418 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1420 /// Type parameters are stored in the Path itself
1421 Path(Option<QSelf>, Path),
1422 /// A trait object type `Bound1 + Bound2 + Bound3`
1423 /// where `Bound` is a trait or a lifetime.
1424 TraitObject(TyParamBounds),
1425 /// An `impl Bound1 + Bound2 + Bound3` type
1426 /// where `Bound` is a trait or a lifetime.
1427 ImplTrait(TyParamBounds),
1428 /// No-op; kept solely so that we can pretty-print faithfully
1432 /// TyKind::Infer means the type should be inferred instead of it having been
1433 /// specified. This can appear anywhere in a type.
1435 /// Inferred type of a `self` or `&self` argument in a method.
1437 // A macro in the type position.
1439 /// Placeholder for a kind that has failed to be defined.
1443 /// Inline assembly dialect.
1445 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1446 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1447 pub enum AsmDialect {
1452 /// Inline assembly.
1454 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1455 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1456 pub struct InlineAsmOutput {
1457 pub constraint: Symbol,
1460 pub is_indirect: bool,
1463 /// Inline assembly.
1465 /// E.g. `asm!("NOP");`
1466 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1467 pub struct InlineAsm {
1469 pub asm_str_style: StrStyle,
1470 pub outputs: Vec<InlineAsmOutput>,
1471 pub inputs: Vec<(Symbol, P<Expr>)>,
1472 pub clobbers: Vec<Symbol>,
1474 pub alignstack: bool,
1475 pub dialect: AsmDialect,
1476 pub ctxt: SyntaxContext,
1479 /// An argument in a function header.
1481 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1489 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1491 /// E.g. `&mut self` as in `fn foo(&mut self)`
1492 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1494 /// `self`, `mut self`
1496 /// `&'lt self`, `&'lt mut self`
1497 Region(Option<Lifetime>, Mutability),
1498 /// `self: TYPE`, `mut self: TYPE`
1499 Explicit(P<Ty>, Mutability),
1502 pub type ExplicitSelf = Spanned<SelfKind>;
1505 pub fn to_self(&self) -> Option<ExplicitSelf> {
1506 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1507 if ident.node.name == keywords::SelfValue.name() {
1508 return match self.ty.node {
1509 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1510 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1511 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1513 _ => Some(respan(self.pat.span.to(self.ty.span),
1514 SelfKind::Explicit(self.ty.clone(), mutbl))),
1521 pub fn is_self(&self) -> bool {
1522 if let PatKind::Ident(_, ident, _) = self.pat.node {
1523 ident.node.name == keywords::SelfValue.name()
1529 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1530 let span = eself.span.to(eself_ident.span);
1531 let infer_ty = P(Ty {
1533 node: TyKind::ImplicitSelf,
1536 let arg = |mutbl, ty| Arg {
1539 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1546 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1547 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1548 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1550 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1557 /// Header (not the body) of a function declaration.
1559 /// E.g. `fn foo(bar: baz)`
1560 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1562 pub inputs: Vec<Arg>,
1563 pub output: FunctionRetTy,
1568 pub fn get_self(&self) -> Option<ExplicitSelf> {
1569 self.inputs.get(0).and_then(Arg::to_self)
1571 pub fn has_self(&self) -> bool {
1572 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1576 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1582 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1583 pub enum Constness {
1588 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1589 pub enum Defaultness {
1594 impl fmt::Display for Unsafety {
1595 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1596 fmt::Display::fmt(match *self {
1597 Unsafety::Normal => "normal",
1598 Unsafety::Unsafe => "unsafe",
1603 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1604 pub enum ImplPolarity {
1605 /// `impl Trait for Type`
1607 /// `impl !Trait for Type`
1611 impl fmt::Debug for ImplPolarity {
1612 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1614 ImplPolarity::Positive => "positive".fmt(f),
1615 ImplPolarity::Negative => "negative".fmt(f),
1621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1622 pub enum FunctionRetTy {
1623 /// Return type is not specified.
1625 /// Functions default to `()` and
1626 /// closures default to inference. Span points to where return
1627 /// type would be inserted.
1633 impl FunctionRetTy {
1634 pub fn span(&self) -> Span {
1636 FunctionRetTy::Default(span) => span,
1637 FunctionRetTy::Ty(ref ty) => ty.span,
1642 /// Module declaration.
1644 /// E.g. `mod foo;` or `mod foo { .. }`
1645 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1647 /// A span from the first token past `{` to the last token until `}`.
1648 /// For `mod foo;`, the inner span ranges from the first token
1649 /// to the last token in the external file.
1651 pub items: Vec<P<Item>>,
1654 /// Foreign module declaration.
1656 /// E.g. `extern { .. }` or `extern C { .. }`
1657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1658 pub struct ForeignMod {
1660 pub items: Vec<ForeignItem>,
1663 /// Global inline assembly
1665 /// aka module-level assembly or file-scoped assembly
1666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1667 pub struct GlobalAsm {
1669 pub ctxt: SyntaxContext,
1672 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1673 pub struct EnumDef {
1674 pub variants: Vec<Variant>,
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 pub struct Variant_ {
1680 pub attrs: Vec<Attribute>,
1681 pub data: VariantData,
1682 /// Explicit discriminant, e.g. `Foo = 1`
1683 pub disr_expr: Option<P<Expr>>,
1686 pub type Variant = Spanned<Variant_>;
1688 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1689 pub struct PathListItem_ {
1691 /// renamed in list, e.g. `use foo::{bar as baz};`
1692 pub rename: Option<Ident>,
1696 pub type PathListItem = Spanned<PathListItem_>;
1698 pub type ViewPath = Spanned<ViewPath_>;
1700 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1701 pub enum ViewPath_ {
1703 /// `foo::bar::baz as quux`
1707 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1708 ViewPathSimple(Ident, Path),
1713 /// `foo::bar::{a,b,c}`
1714 ViewPathList(Path, Vec<PathListItem>)
1718 pub fn path(&self) -> &Path {
1720 ViewPathSimple(_, ref path) |
1721 ViewPathGlob (ref path) |
1722 ViewPathList(ref path, _) => path
1728 /// Distinguishes between Attributes that decorate items and Attributes that
1729 /// are contained as statements within items. These two cases need to be
1730 /// distinguished for pretty-printing.
1731 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1732 pub enum AttrStyle {
1737 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1738 pub struct AttrId(pub usize);
1740 /// Meta-data associated with an item
1741 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1743 pub struct Attribute {
1745 pub style: AttrStyle,
1747 pub tokens: TokenStream,
1748 pub is_sugared_doc: bool,
1752 /// TraitRef's appear in impls.
1754 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1755 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1756 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1757 /// same as the impl's node id).
1758 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1759 pub struct TraitRef {
1764 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1765 pub struct PolyTraitRef {
1766 /// The `'a` in `<'a> Foo<&'a T>`
1767 pub bound_lifetimes: Vec<LifetimeDef>,
1769 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1770 pub trait_ref: TraitRef,
1776 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1778 bound_lifetimes: lifetimes,
1779 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1786 pub enum Visibility {
1789 Restricted { path: P<Path>, id: NodeId },
1793 /// Field of a struct.
1795 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1796 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1797 pub struct StructField {
1799 pub ident: Option<Ident>,
1800 pub vis: Visibility,
1803 pub attrs: Vec<Attribute>,
1806 /// Fields and Ids of enum variants and structs
1808 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1809 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1810 /// One shared Id can be successfully used for these two purposes.
1811 /// Id of the whole enum lives in `Item`.
1813 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1814 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1815 /// the variant itself" from enum variants.
1816 /// Id of the whole struct lives in `Item`.
1817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1818 pub enum VariantData {
1821 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1822 Struct(Vec<StructField>, NodeId),
1825 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1826 Tuple(Vec<StructField>, NodeId),
1829 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1834 pub fn fields(&self) -> &[StructField] {
1836 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1840 pub fn id(&self) -> NodeId {
1842 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1845 pub fn is_struct(&self) -> bool {
1846 if let VariantData::Struct(..) = *self { true } else { false }
1848 pub fn is_tuple(&self) -> bool {
1849 if let VariantData::Tuple(..) = *self { true } else { false }
1851 pub fn is_unit(&self) -> bool {
1852 if let VariantData::Unit(..) = *self { true } else { false }
1858 /// The name might be a dummy name in case of anonymous items
1859 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1862 pub attrs: Vec<Attribute>,
1865 pub vis: Visibility,
1868 /// Original tokens this item was parsed from. This isn't necessarily
1869 /// available for all items, although over time more and more items should
1870 /// have this be `Some`. Right now this is primarily used for procedural
1871 /// macros, notably custom attributes.
1873 /// Note that the tokens here do not include the outer attributes, but will
1874 /// include inner attributes.
1875 pub tokens: Option<TokenStream>,
1878 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1880 /// An `extern crate` item, with optional original crate name.
1882 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1883 ExternCrate(Option<Name>),
1884 /// A use declaration (`use` or `pub use`) item.
1886 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1888 /// A static item (`static` or `pub static`).
1890 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1891 Static(P<Ty>, Mutability, P<Expr>),
1892 /// A constant item (`const` or `pub const`).
1894 /// E.g. `const FOO: i32 = 42;`
1895 Const(P<Ty>, P<Expr>),
1896 /// A function declaration (`fn` or `pub fn`).
1898 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1899 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1900 /// A module declaration (`mod` or `pub mod`).
1902 /// E.g. `mod foo;` or `mod foo { .. }`
1904 /// An external module (`extern` or `pub extern`).
1906 /// E.g. `extern {}` or `extern "C" {}`
1907 ForeignMod(ForeignMod),
1908 /// Module-level inline assembly (from `global_asm!()`)
1909 GlobalAsm(P<GlobalAsm>),
1910 /// A type alias (`type` or `pub type`).
1912 /// E.g. `type Foo = Bar<u8>;`
1913 Ty(P<Ty>, Generics),
1914 /// An enum definition (`enum` or `pub enum`).
1916 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1917 Enum(EnumDef, Generics),
1918 /// A struct definition (`struct` or `pub struct`).
1920 /// E.g. `struct Foo<A> { x: A }`
1921 Struct(VariantData, Generics),
1922 /// A union definition (`union` or `pub union`).
1924 /// E.g. `union Foo<A, B> { x: A, y: B }`
1925 Union(VariantData, Generics),
1926 /// A Trait declaration (`trait` or `pub trait`).
1928 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1929 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1930 // Default trait implementation.
1932 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1933 DefaultImpl(Unsafety, TraitRef),
1934 /// An implementation.
1936 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1941 Option<TraitRef>, // (optional) trait this impl implements
1944 /// A macro invocation.
1946 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1949 /// A macro definition.
1954 pub fn descriptive_variant(&self) -> &str {
1956 ItemKind::ExternCrate(..) => "extern crate",
1957 ItemKind::Use(..) => "use",
1958 ItemKind::Static(..) => "static item",
1959 ItemKind::Const(..) => "constant item",
1960 ItemKind::Fn(..) => "function",
1961 ItemKind::Mod(..) => "module",
1962 ItemKind::ForeignMod(..) => "foreign module",
1963 ItemKind::GlobalAsm(..) => "global asm",
1964 ItemKind::Ty(..) => "type alias",
1965 ItemKind::Enum(..) => "enum",
1966 ItemKind::Struct(..) => "struct",
1967 ItemKind::Union(..) => "union",
1968 ItemKind::Trait(..) => "trait",
1970 ItemKind::MacroDef(..) |
1971 ItemKind::Impl(..) |
1972 ItemKind::DefaultImpl(..) => "item"
1977 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1978 pub struct ForeignItem {
1980 pub attrs: Vec<Attribute>,
1981 pub node: ForeignItemKind,
1984 pub vis: Visibility,
1987 /// An item within an `extern` block
1988 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1989 pub enum ForeignItemKind {
1990 /// A foreign function
1991 Fn(P<FnDecl>, Generics),
1992 /// A foreign static item (`static ext: u8`), with optional mutability
1993 /// (the boolean is true when mutable)
1994 Static(P<Ty>, bool),
1997 impl ForeignItemKind {
1998 pub fn descriptive_variant(&self) -> &str {
2000 ForeignItemKind::Fn(..) => "foreign function",
2001 ForeignItemKind::Static(..) => "foreign static item"
2011 // are ASTs encodable?
2013 fn check_asts_encodable() {
2014 fn assert_encodable<T: serialize::Encodable>() {}
2015 assert_encodable::<Crate>();