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::Symbol as Name;
18 pub use util::ThinVec;
20 use syntax_pos::{mk_sp, BytePos, Span, DUMMY_SP, ExpnId};
21 use codemap::{respan, Spanned};
23 use ext::hygiene::SyntaxContext;
26 use rustc_data_structures::indexed_vec;
27 use symbol::{Symbol, keywords};
28 use tokenstream::{ThinTokenStream, TokenStream};
30 use std::collections::HashSet;
35 use serialize::{self, Encodable, Decodable, Encoder, Decoder};
37 /// An identifier contains a Name (index into the interner
38 /// table) and a SyntaxContext to track renaming and
39 /// macro expansion per Flatt et al., "Macros That Work Together"
40 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
43 pub ctxt: SyntaxContext
47 pub const fn with_empty_ctxt(name: Name) -> Ident {
48 Ident { name: name, ctxt: SyntaxContext::empty() }
51 /// Maps a string to an identifier with an empty syntax context.
52 pub fn from_str(s: &str) -> Ident {
53 Ident::with_empty_ctxt(Symbol::intern(s))
56 pub fn unhygienize(&self) -> Ident {
57 Ident { name: self.name, ctxt: SyntaxContext::empty() }
61 impl fmt::Debug for Ident {
62 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 write!(f, "{}{:?}", self.name, self.ctxt)
67 impl fmt::Display for Ident {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 fmt::Display::fmt(&self.name, f)
73 impl Encodable for Ident {
74 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
79 impl Decodable for Ident {
80 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
81 Ok(Ident::with_empty_ctxt(Name::decode(d)?))
85 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
92 impl fmt::Debug for Lifetime {
93 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
98 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
99 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
100 pub struct LifetimeDef {
101 pub attrs: ThinVec<Attribute>,
102 pub lifetime: Lifetime,
103 pub bounds: Vec<Lifetime>
106 /// A "Path" is essentially Rust's notion of a name.
108 /// It's represented as a sequence of identifiers,
109 /// along with a bunch of supporting information.
111 /// E.g. `std::cmp::PartialEq`
112 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
115 /// The segments in the path: the things separated by `::`.
116 /// Global paths begin with `keywords::CrateRoot`.
117 pub segments: Vec<PathSegment>,
120 impl<'a> PartialEq<&'a str> for Path {
121 fn eq(&self, string: &&'a str) -> bool {
122 self.segments.len() == 1 && self.segments[0].identifier.name == *string
126 impl fmt::Debug for Path {
127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
128 write!(f, "path({})", pprust::path_to_string(self))
132 impl fmt::Display for Path {
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 write!(f, "{}", pprust::path_to_string(self))
139 // convert a span and an identifier to the corresponding
141 pub fn from_ident(s: Span, identifier: Ident) -> Path {
144 segments: vec![PathSegment::from_ident(identifier, s)],
148 pub fn default_to_global(mut self) -> Path {
149 let name = self.segments[0].identifier.name;
150 if !self.is_global() && name != "$crate" &&
151 name != keywords::SelfValue.name() && name != keywords::Super.name() {
152 self.segments.insert(0, PathSegment::crate_root());
157 pub fn is_global(&self) -> bool {
158 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
162 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
164 /// E.g. `std`, `String` or `Box<T>`
165 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
166 pub struct PathSegment {
167 /// The identifier portion of this path segment.
168 pub identifier: Ident,
169 /// Span of the segment identifier.
172 /// Type/lifetime parameters attached to this path. They come in
173 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
174 /// this is more than just simple syntactic sugar; the use of
175 /// parens affects the region binding rules, so we preserve the
177 /// The `Option<P<..>>` wrapper is purely a size optimization;
178 /// `None` is used to represent both `Path` and `Path<>`.
179 pub parameters: Option<P<PathParameters>>,
183 pub fn from_ident(ident: Ident, span: Span) -> Self {
184 PathSegment { identifier: ident, span: span, parameters: None }
186 pub fn crate_root() -> Self {
188 identifier: keywords::CrateRoot.ident(),
195 /// Parameters of a path segment.
197 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
198 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
199 pub enum PathParameters {
200 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
201 AngleBracketed(AngleBracketedParameterData),
202 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
203 Parenthesized(ParenthesizedParameterData),
206 /// A path like `Foo<'a, T>`
207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
208 pub struct AngleBracketedParameterData {
209 /// The lifetime parameters for this path segment.
210 pub lifetimes: Vec<Lifetime>,
211 /// The type parameters for this path segment, if present.
212 pub types: Vec<P<Ty>>,
213 /// Bindings (equality constraints) on associated types, if present.
215 /// E.g., `Foo<A=Bar>`.
216 pub bindings: Vec<TypeBinding>,
219 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
220 fn into(self) -> Option<P<PathParameters>> {
221 let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
222 if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
226 /// A path like `Foo(A,B) -> C`
227 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
228 pub struct ParenthesizedParameterData {
233 pub inputs: Vec<P<Ty>>,
236 pub output: Option<P<Ty>>,
239 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
240 pub struct NodeId(u32);
243 pub fn new(x: usize) -> NodeId {
244 assert!(x < (u32::MAX as usize));
248 pub fn from_u32(x: u32) -> NodeId {
252 pub fn as_usize(&self) -> usize {
256 pub fn as_u32(&self) -> u32 {
261 impl fmt::Display for NodeId {
262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
263 fmt::Display::fmt(&self.0, f)
267 impl serialize::UseSpecializedEncodable for NodeId {
268 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
273 impl serialize::UseSpecializedDecodable for NodeId {
274 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
275 d.read_u32().map(NodeId)
279 impl indexed_vec::Idx for NodeId {
280 fn new(idx: usize) -> Self {
284 fn index(self) -> usize {
289 /// Node id used to represent the root of the crate.
290 pub const CRATE_NODE_ID: NodeId = NodeId(0);
292 /// When parsing and doing expansions, we initially give all AST nodes this AST
293 /// node value. Then later, in the renumber pass, we renumber them to have
294 /// small, positive ids.
295 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
297 /// The AST represents all type param bounds as types.
298 /// typeck::collect::compute_bounds matches these against
299 /// the "special" built-in traits (see middle::lang_items) and
300 /// detects Copy, Send and Sync.
301 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
302 pub enum TyParamBound {
303 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
304 RegionTyParamBound(Lifetime)
307 /// A modifier on a bound, currently this is only used for `?Sized`, where the
308 /// modifier is `Maybe`. Negative bounds should also be handled here.
309 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
310 pub enum TraitBoundModifier {
315 pub type TyParamBounds = Vec<TyParamBound>;
317 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
319 pub attrs: ThinVec<Attribute>,
322 pub bounds: TyParamBounds,
323 pub default: Option<P<Ty>>,
327 /// Represents lifetimes and type parameters attached to a declaration
328 /// of a function, enum, trait, etc.
329 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
330 pub struct Generics {
331 pub lifetimes: Vec<LifetimeDef>,
332 pub ty_params: Vec<TyParam>,
333 pub where_clause: WhereClause,
338 pub fn is_lt_parameterized(&self) -> bool {
339 !self.lifetimes.is_empty()
341 pub fn is_type_parameterized(&self) -> bool {
342 !self.ty_params.is_empty()
344 pub fn is_parameterized(&self) -> bool {
345 self.is_lt_parameterized() || self.is_type_parameterized()
347 pub fn span_for_name(&self, name: &str) -> Option<Span> {
348 for t in &self.ty_params {
349 if t.ident.name == name {
357 impl Default for Generics {
358 /// Creates an instance of `Generics`.
359 fn default() -> Generics {
361 lifetimes: Vec::new(),
362 ty_params: Vec::new(),
363 where_clause: WhereClause {
365 predicates: Vec::new(),
372 /// A `where` clause in a definition
373 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
374 pub struct WhereClause {
376 pub predicates: Vec<WherePredicate>,
379 /// A single predicate in a `where` clause
380 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
381 pub enum WherePredicate {
382 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
383 BoundPredicate(WhereBoundPredicate),
384 /// A lifetime predicate, e.g. `'a: 'b+'c`
385 RegionPredicate(WhereRegionPredicate),
386 /// An equality predicate (unsupported)
387 EqPredicate(WhereEqPredicate),
392 /// E.g. `for<'c> Foo: Send+Clone+'c`
393 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
394 pub struct WhereBoundPredicate {
396 /// Any lifetimes from a `for` binding
397 pub bound_lifetimes: Vec<LifetimeDef>,
398 /// The type being bounded
399 pub bounded_ty: P<Ty>,
400 /// Trait and lifetime bounds (`Clone+Send+'static`)
401 pub bounds: TyParamBounds,
404 /// A lifetime predicate.
407 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
408 pub struct WhereRegionPredicate {
410 pub lifetime: Lifetime,
411 pub bounds: Vec<Lifetime>,
414 /// An equality predicate (unsupported).
417 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
418 pub struct WhereEqPredicate {
425 /// The set of MetaItems that define the compilation environment of the crate,
426 /// used to drive conditional compilation
427 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
429 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
432 pub attrs: Vec<Attribute>,
436 /// A spanned compile-time attribute list item.
437 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
439 /// Possible values inside of compile-time attribute lists.
441 /// E.g. the '..' in `#[name(..)]`.
442 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
443 pub enum NestedMetaItemKind {
444 /// A full MetaItem, for recursive meta items.
448 /// E.g. "foo", 64, true
452 /// A spanned compile-time attribute item.
454 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
455 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
456 pub struct MetaItem {
458 pub node: MetaItemKind,
462 /// A compile-time attribute item.
464 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
465 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
466 pub enum MetaItemKind {
469 /// E.g. `test` as in `#[test]`
473 /// E.g. `derive(..)` as in `#[derive(..)]`
474 List(Vec<NestedMetaItem>),
475 /// Name value meta item.
477 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
481 /// A Block (`{ .. }`).
483 /// E.g. `{ .. }` as in `fn foo() { .. }`
484 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
486 /// Statements in a block
487 pub stmts: Vec<Stmt>,
489 /// Distinguishes between `unsafe { ... }` and `{ ... }`
490 pub rules: BlockCheckMode,
494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
501 impl fmt::Debug for Pat {
502 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
503 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
508 pub fn walk<F>(&self, it: &mut F) -> bool
509 where F: FnMut(&Pat) -> bool
516 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
517 PatKind::Struct(_, ref fields, _) => {
518 fields.iter().all(|field| field.node.pat.walk(it))
520 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
521 s.iter().all(|p| p.walk(it))
523 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
526 PatKind::Slice(ref before, ref slice, ref after) => {
527 before.iter().all(|p| p.walk(it)) &&
528 slice.iter().all(|p| p.walk(it)) &&
529 after.iter().all(|p| p.walk(it))
543 /// A single field in a struct pattern
545 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
546 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
547 /// except is_shorthand is true
548 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
549 pub struct FieldPat {
550 /// The identifier for the field
552 /// The pattern the field is destructured to
554 pub is_shorthand: bool,
555 pub attrs: ThinVec<Attribute>,
558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
559 pub enum BindingMode {
564 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
572 /// Represents a wildcard pattern (`_`)
575 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
576 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
577 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
578 /// during name resolution.
579 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
581 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
582 /// The `bool` is `true` in the presence of a `..`.
583 Struct(Path, Vec<Spanned<FieldPat>>, bool),
585 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
586 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
587 /// 0 <= position <= subpats.len()
588 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
590 /// A possibly qualified path pattern.
591 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
592 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
593 /// only legally refer to associated constants.
594 Path(Option<QSelf>, Path),
596 /// A tuple pattern `(a, b)`.
597 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
598 /// 0 <= position <= subpats.len()
599 Tuple(Vec<P<Pat>>, Option<usize>),
602 /// A reference pattern, e.g. `&mut (a, b)`
603 Ref(P<Pat>, Mutability),
606 /// A range pattern, e.g. `1...2` or `1..2`
607 Range(P<Expr>, P<Expr>, RangeEnd),
608 /// `[a, b, ..i, y, z]` is represented as:
609 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
610 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
611 /// A macro pattern; pre-expansion
615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
616 pub enum Mutability {
621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
623 /// The `+` operator (addition)
625 /// The `-` operator (subtraction)
627 /// The `*` operator (multiplication)
629 /// The `/` operator (division)
631 /// The `%` operator (modulus)
633 /// The `&&` operator (logical and)
635 /// The `||` operator (logical or)
637 /// The `^` operator (bitwise xor)
639 /// The `&` operator (bitwise and)
641 /// The `|` operator (bitwise or)
643 /// The `<<` operator (shift left)
645 /// The `>>` operator (shift right)
647 /// The `==` operator (equality)
649 /// The `<` operator (less than)
651 /// The `<=` operator (less than or equal to)
653 /// The `!=` operator (not equal to)
655 /// The `>=` operator (greater than or equal to)
657 /// The `>` operator (greater than)
662 pub fn to_string(&self) -> &'static str {
663 use self::BinOpKind::*;
685 pub fn lazy(&self) -> bool {
687 BinOpKind::And | BinOpKind::Or => true,
692 pub fn is_shift(&self) -> bool {
694 BinOpKind::Shl | BinOpKind::Shr => true,
698 pub fn is_comparison(&self) -> bool {
699 use self::BinOpKind::*;
701 Eq | Lt | Le | Ne | Gt | Ge =>
703 And | Or | Add | Sub | Mul | Div | Rem |
704 BitXor | BitAnd | BitOr | Shl | Shr =>
708 /// Returns `true` if the binary operator takes its arguments by value
709 pub fn is_by_value(&self) -> bool {
710 !self.is_comparison()
714 pub type BinOp = Spanned<BinOpKind>;
716 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
718 /// The `*` operator for dereferencing
720 /// The `!` operator for logical inversion
722 /// The `-` operator for negation
727 /// Returns `true` if the unary operator takes its argument by value
728 pub fn is_by_value(u: UnOp) -> bool {
730 UnOp::Neg | UnOp::Not => true,
735 pub fn to_string(op: UnOp) -> &'static str {
745 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
753 pub fn add_trailing_semicolon(mut self) -> Self {
754 self.node = match self.node {
755 StmtKind::Expr(expr) => StmtKind::Semi(expr),
756 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
757 (mac, MacStmtStyle::Semicolon, attrs)
765 impl fmt::Debug for Stmt {
766 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
767 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
772 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
774 /// A local (let) binding.
777 /// An item definition.
780 /// Expr without trailing semi-colon.
785 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
788 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
789 pub enum MacStmtStyle {
790 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
791 /// `foo!(...);`, `foo![...];`
793 /// The macro statement had braces; e.g. foo! { ... }
795 /// The macro statement had parentheses or brackets and no semicolon; e.g.
796 /// `foo!(...)`. All of these will end up being converted into macro
801 // FIXME (pending discussion of #1697, #2178...): local should really be
802 // a refinement on pat.
803 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
804 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
807 pub ty: Option<P<Ty>>,
808 /// Initializer expression to set the value, if any
809 pub init: Option<P<Expr>>,
812 pub attrs: ThinVec<Attribute>,
815 /// An arm of a 'match'.
817 /// E.g. `0...10 => { println!("match!") }` as in
821 /// 0...10 => { println!("match!") },
825 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
827 pub attrs: Vec<Attribute>,
828 pub pats: Vec<P<Pat>>,
829 pub guard: Option<P<Expr>>,
833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
835 pub ident: SpannedIdent,
838 pub is_shorthand: bool,
839 pub attrs: ThinVec<Attribute>,
842 pub type SpannedIdent = Spanned<Ident>;
844 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
845 pub enum BlockCheckMode {
847 Unsafe(UnsafeSource),
850 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
851 pub enum UnsafeSource {
857 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
862 pub attrs: ThinVec<Attribute>
865 impl fmt::Debug for Expr {
866 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
867 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
871 /// Limit types of a range (inclusive or exclusive)
872 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
873 pub enum RangeLimits {
874 /// Inclusive at the beginning, exclusive at the end
876 /// Inclusive at the beginning and end
880 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
882 /// A `box x` expression.
884 /// First expr is the place; second expr is the value.
885 InPlace(P<Expr>, P<Expr>),
886 /// An array (`[a, b, c, d]`)
890 /// The first field resolves to the function itself,
891 /// and the second field is the list of arguments
892 Call(P<Expr>, Vec<P<Expr>>),
893 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
895 /// The `SpannedIdent` is the identifier for the method name.
896 /// The vector of `Ty`s are the ascripted type parameters for the method
897 /// (within the angle brackets).
899 /// The first element of the vector of `Expr`s is the expression that evaluates
900 /// to the object on which the method is being called on (the receiver),
901 /// and the remaining elements are the rest of the arguments.
903 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
904 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
905 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
906 /// A tuple (`(a, b, c ,d)`)
908 /// A binary operation (For example: `a + b`, `a * b`)
909 Binary(BinOp, P<Expr>, P<Expr>),
910 /// A unary operation (For example: `!x`, `*x`)
911 Unary(UnOp, P<Expr>),
912 /// A literal (For example: `1`, `"foo"`)
914 /// A cast (`foo as f64`)
915 Cast(P<Expr>, P<Ty>),
916 Type(P<Expr>, P<Ty>),
917 /// An `if` block, with an optional else block
919 /// `if expr { block } else { expr }`
920 If(P<Expr>, P<Block>, Option<P<Expr>>),
921 /// An `if let` expression with an optional else block
923 /// `if let pat = expr { block } else { expr }`
925 /// This is desugared to a `match` expression.
926 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
927 /// A while loop, with an optional label
929 /// `'label: while expr { block }`
930 While(P<Expr>, P<Block>, Option<SpannedIdent>),
931 /// A while-let loop, with an optional label
933 /// `'label: while let pat = expr { block }`
935 /// This is desugared to a combination of `loop` and `match` expressions.
936 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
937 /// A for loop, with an optional label
939 /// `'label: for pat in expr { block }`
941 /// This is desugared to a combination of `loop` and `match` expressions.
942 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
943 /// Conditionless loop (can be exited with break, continue, or return)
945 /// `'label: loop { block }`
946 Loop(P<Block>, Option<SpannedIdent>),
948 Match(P<Expr>, Vec<Arm>),
949 /// A closure (for example, `move |a, b, c| a + b + c`)
951 /// The final span is the span of the argument block `|...|`
952 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
953 /// A block (`{ ... }`)
955 /// A catch block (`catch { ... }`)
958 /// An assignment (`a = foo()`)
959 Assign(P<Expr>, P<Expr>),
960 /// An assignment with an operator
962 /// For example, `a += 1`.
963 AssignOp(BinOp, P<Expr>, P<Expr>),
964 /// Access of a named struct field (`obj.foo`)
965 Field(P<Expr>, SpannedIdent),
966 /// Access of an unnamed field of a struct or tuple-struct
968 /// For example, `foo.0`.
969 TupField(P<Expr>, Spanned<usize>),
970 /// An indexing operation (`foo[2]`)
971 Index(P<Expr>, P<Expr>),
972 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
973 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
975 /// Variable reference, possibly containing `::` and/or type
976 /// parameters, e.g. foo::bar::<baz>.
978 /// Optionally "qualified",
979 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
980 Path(Option<QSelf>, Path),
982 /// A referencing operation (`&a` or `&mut a`)
983 AddrOf(Mutability, P<Expr>),
984 /// A `break`, with an optional label to break, and an optional expression
985 Break(Option<SpannedIdent>, Option<P<Expr>>),
986 /// A `continue`, with an optional label
987 Continue(Option<SpannedIdent>),
988 /// A `return`, with an optional value to be returned
989 Ret(Option<P<Expr>>),
991 /// Output of the `asm!()` macro
992 InlineAsm(P<InlineAsm>),
994 /// A macro invocation; pre-expansion
997 /// A struct literal expression.
999 /// For example, `Foo {x: 1, y: 2}`, or
1000 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1001 Struct(Path, Vec<Field>, Option<P<Expr>>),
1003 /// An array literal constructed from one repeated element.
1005 /// For example, `[1; 5]`. The first expression is the element
1006 /// to be repeated; the second is the number of times to repeat it.
1007 Repeat(P<Expr>, P<Expr>),
1009 /// No-op: used solely so we can pretty-print faithfully
1016 /// The explicit Self type in a "qualified path". The actual
1017 /// path, including the trait and the associated item, is stored
1018 /// separately. `position` represents the index of the associated
1019 /// item qualified with this Self type.
1022 /// <Vec<T> as a::b::Trait>::AssociatedItem
1023 /// ^~~~~ ~~~~~~~~~~~~~~^
1026 /// <Vec<T>>::AssociatedItem
1030 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1036 /// A capture clause
1037 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1038 pub enum CaptureBy {
1043 pub type Mac = Spanned<Mac_>;
1045 /// Represents a macro invocation. The Path indicates which macro
1046 /// is being invoked, and the vector of token-trees contains the source
1047 /// of the macro invocation.
1049 /// NB: the additional ident for a macro_rules-style macro is actually
1050 /// stored in the enclosing item. Oog.
1051 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1054 pub tts: ThinTokenStream,
1058 pub fn stream(&self) -> TokenStream {
1059 self.tts.clone().into()
1063 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1065 /// A regular string, like `"foo"`
1067 /// A raw string, like `r##"foo"##`
1069 /// The uint is the number of `#` symbols used
1074 pub type Lit = Spanned<LitKind>;
1076 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1077 pub enum LitIntType {
1085 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1086 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1088 /// A string literal (`"foo"`)
1089 Str(Symbol, StrStyle),
1090 /// A byte string (`b"foo"`)
1091 ByteStr(Rc<Vec<u8>>),
1092 /// A byte char (`b'f'`)
1094 /// A character literal (`'a'`)
1096 /// An integer literal (`1`)
1097 Int(u128, LitIntType),
1098 /// A float literal (`1f64` or `1E10f64`)
1099 Float(Symbol, FloatTy),
1100 /// A float literal without a suffix (`1.0 or 1.0E10`)
1101 FloatUnsuffixed(Symbol),
1102 /// A boolean literal
1107 /// Returns true if this literal is a string and false otherwise.
1108 pub fn is_str(&self) -> bool {
1110 LitKind::Str(..) => true,
1115 /// Returns true if this literal has no suffix. Note: this will return true
1116 /// for literals with prefixes such as raw strings and byte strings.
1117 pub fn is_unsuffixed(&self) -> bool {
1119 // unsuffixed variants
1120 LitKind::Str(..) => true,
1121 LitKind::ByteStr(..) => true,
1122 LitKind::Byte(..) => true,
1123 LitKind::Char(..) => true,
1124 LitKind::Int(_, LitIntType::Unsuffixed) => true,
1125 LitKind::FloatUnsuffixed(..) => true,
1126 LitKind::Bool(..) => true,
1127 // suffixed variants
1128 LitKind::Int(_, LitIntType::Signed(..)) => false,
1129 LitKind::Int(_, LitIntType::Unsigned(..)) => false,
1130 LitKind::Float(..) => false,
1134 /// Returns true if this literal has a suffix.
1135 pub fn is_suffixed(&self) -> bool {
1136 !self.is_unsuffixed()
1140 // NB: If you change this, you'll probably want to change the corresponding
1141 // type structure in middle/ty.rs as well.
1142 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1145 pub mutbl: Mutability,
1148 /// Represents a method's signature in a trait declaration,
1149 /// or in an implementation.
1150 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1151 pub struct MethodSig {
1152 pub unsafety: Unsafety,
1153 pub constness: Spanned<Constness>,
1155 pub decl: P<FnDecl>,
1156 pub generics: Generics,
1159 /// Represents an item declaration within a trait declaration,
1160 /// possibly including a default implementation. A trait item is
1161 /// either required (meaning it doesn't have an implementation, just a
1162 /// signature) or provided (meaning it has a default implementation).
1163 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1164 pub struct TraitItem {
1167 pub attrs: Vec<Attribute>,
1168 pub node: TraitItemKind,
1172 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1173 pub enum TraitItemKind {
1174 Const(P<Ty>, Option<P<Expr>>),
1175 Method(MethodSig, Option<P<Block>>),
1176 Type(TyParamBounds, Option<P<Ty>>),
1180 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1181 pub struct ImplItem {
1184 pub vis: Visibility,
1185 pub defaultness: Defaultness,
1186 pub attrs: Vec<Attribute>,
1187 pub node: ImplItemKind,
1191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1192 pub enum ImplItemKind {
1193 Const(P<Ty>, P<Expr>),
1194 Method(MethodSig, P<Block>),
1199 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1209 impl fmt::Debug for IntTy {
1210 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1211 fmt::Display::fmt(self, f)
1215 impl fmt::Display for IntTy {
1216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1217 write!(f, "{}", self.ty_to_string())
1222 pub fn ty_to_string(&self) -> &'static str {
1224 IntTy::Is => "isize",
1226 IntTy::I16 => "i16",
1227 IntTy::I32 => "i32",
1228 IntTy::I64 => "i64",
1229 IntTy::I128 => "i128",
1233 pub fn val_to_string(&self, val: i128) -> String {
1234 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1235 // are parsed as u128, so we wouldn't want to print an extra negative
1237 format!("{}{}", val as u128, self.ty_to_string())
1240 pub fn bit_width(&self) -> Option<usize> {
1242 IntTy::Is => return None,
1252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1263 pub fn ty_to_string(&self) -> &'static str {
1265 UintTy::Us => "usize",
1267 UintTy::U16 => "u16",
1268 UintTy::U32 => "u32",
1269 UintTy::U64 => "u64",
1270 UintTy::U128 => "u128",
1274 pub fn val_to_string(&self, val: u128) -> String {
1275 format!("{}{}", val, self.ty_to_string())
1278 pub fn bit_width(&self) -> Option<usize> {
1280 UintTy::Us => return None,
1285 UintTy::U128 => 128,
1290 impl fmt::Debug for UintTy {
1291 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1292 fmt::Display::fmt(self, f)
1296 impl fmt::Display for UintTy {
1297 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1298 write!(f, "{}", self.ty_to_string())
1302 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1308 impl fmt::Debug for FloatTy {
1309 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1310 fmt::Display::fmt(self, f)
1314 impl fmt::Display for FloatTy {
1315 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1316 write!(f, "{}", self.ty_to_string())
1321 pub fn ty_to_string(&self) -> &'static str {
1323 FloatTy::F32 => "f32",
1324 FloatTy::F64 => "f64",
1328 pub fn bit_width(&self) -> usize {
1336 // Bind a type to an associated type: `A=Foo`.
1337 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1338 pub struct TypeBinding {
1345 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1352 impl fmt::Debug for Ty {
1353 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1354 write!(f, "type({})", pprust::ty_to_string(self))
1358 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1359 pub struct BareFnTy {
1360 pub unsafety: Unsafety,
1362 pub lifetimes: Vec<LifetimeDef>,
1366 /// The different kinds of types recognized by the compiler
1367 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1369 /// A variable-length slice (`[T]`)
1371 /// A fixed length array (`[T; n]`)
1372 Array(P<Ty>, P<Expr>),
1373 /// A raw pointer (`*const T` or `*mut T`)
1375 /// A reference (`&'a T` or `&'a mut T`)
1376 Rptr(Option<Lifetime>, MutTy),
1377 /// A bare function (e.g. `fn(usize) -> bool`)
1378 BareFn(P<BareFnTy>),
1379 /// The never type (`!`)
1381 /// A tuple (`(A, B, C, D,...)`)
1383 /// A path (`module::module::...::Type`), optionally
1384 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1386 /// Type parameters are stored in the Path itself
1387 Path(Option<QSelf>, Path),
1388 /// A trait object type `Bound1 + Bound2 + Bound3`
1389 /// where `Bound` is a trait or a lifetime.
1390 TraitObject(TyParamBounds),
1391 /// An `impl Bound1 + Bound2 + Bound3` type
1392 /// where `Bound` is a trait or a lifetime.
1393 ImplTrait(TyParamBounds),
1394 /// No-op; kept solely so that we can pretty-print faithfully
1398 /// TyKind::Infer means the type should be inferred instead of it having been
1399 /// specified. This can appear anywhere in a type.
1401 /// Inferred type of a `self` or `&self` argument in a method.
1403 // A macro in the type position.
1407 /// Inline assembly dialect.
1409 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1410 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1411 pub enum AsmDialect {
1416 /// Inline assembly.
1418 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1419 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1420 pub struct InlineAsmOutput {
1421 pub constraint: Symbol,
1424 pub is_indirect: bool,
1427 /// Inline assembly.
1429 /// E.g. `asm!("NOP");`
1430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1431 pub struct InlineAsm {
1433 pub asm_str_style: StrStyle,
1434 pub outputs: Vec<InlineAsmOutput>,
1435 pub inputs: Vec<(Symbol, P<Expr>)>,
1436 pub clobbers: Vec<Symbol>,
1438 pub alignstack: bool,
1439 pub dialect: AsmDialect,
1440 pub expn_id: ExpnId,
1443 /// An argument in a function header.
1445 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1446 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1453 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1455 /// E.g. `&mut self` as in `fn foo(&mut self)`
1456 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1458 /// `self`, `mut self`
1460 /// `&'lt self`, `&'lt mut self`
1461 Region(Option<Lifetime>, Mutability),
1462 /// `self: TYPE`, `mut self: TYPE`
1463 Explicit(P<Ty>, Mutability),
1466 pub type ExplicitSelf = Spanned<SelfKind>;
1469 pub fn to_self(&self) -> Option<ExplicitSelf> {
1470 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1471 if ident.node.name == keywords::SelfValue.name() {
1472 return match self.ty.node {
1473 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1474 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1475 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1477 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1478 SelfKind::Explicit(self.ty.clone(), mutbl))),
1485 pub fn is_self(&self) -> bool {
1486 if let PatKind::Ident(_, ident, _) = self.pat.node {
1487 ident.node.name == keywords::SelfValue.name()
1493 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1494 let span = mk_sp(eself.span.lo, eself_ident.span.hi);
1495 let infer_ty = P(Ty {
1497 node: TyKind::ImplicitSelf,
1500 let arg = |mutbl, ty| Arg {
1503 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1510 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1511 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1512 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1514 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1521 /// Header (not the body) of a function declaration.
1523 /// E.g. `fn foo(bar: baz)`
1524 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1526 pub inputs: Vec<Arg>,
1527 pub output: FunctionRetTy,
1532 pub fn get_self(&self) -> Option<ExplicitSelf> {
1533 self.inputs.get(0).and_then(Arg::to_self)
1535 pub fn has_self(&self) -> bool {
1536 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1540 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1546 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1547 pub enum Constness {
1552 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1553 pub enum Defaultness {
1558 impl fmt::Display for Unsafety {
1559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1560 fmt::Display::fmt(match *self {
1561 Unsafety::Normal => "normal",
1562 Unsafety::Unsafe => "unsafe",
1567 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1568 pub enum ImplPolarity {
1569 /// `impl Trait for Type`
1571 /// `impl !Trait for Type`
1575 impl fmt::Debug for ImplPolarity {
1576 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1578 ImplPolarity::Positive => "positive".fmt(f),
1579 ImplPolarity::Negative => "negative".fmt(f),
1585 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1586 pub enum FunctionRetTy {
1587 /// Return type is not specified.
1589 /// Functions default to `()` and
1590 /// closures default to inference. Span points to where return
1591 /// type would be inserted.
1597 impl FunctionRetTy {
1598 pub fn span(&self) -> Span {
1600 FunctionRetTy::Default(span) => span,
1601 FunctionRetTy::Ty(ref ty) => ty.span,
1606 /// Module declaration.
1608 /// E.g. `mod foo;` or `mod foo { .. }`
1609 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1611 /// A span from the first token past `{` to the last token until `}`.
1612 /// For `mod foo;`, the inner span ranges from the first token
1613 /// to the last token in the external file.
1615 pub items: Vec<P<Item>>,
1618 /// Foreign module declaration.
1620 /// E.g. `extern { .. }` or `extern C { .. }`
1621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1622 pub struct ForeignMod {
1624 pub items: Vec<ForeignItem>,
1627 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1628 pub struct EnumDef {
1629 pub variants: Vec<Variant>,
1632 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1633 pub struct Variant_ {
1635 pub attrs: Vec<Attribute>,
1636 pub data: VariantData,
1637 /// Explicit discriminant, e.g. `Foo = 1`
1638 pub disr_expr: Option<P<Expr>>,
1641 pub type Variant = Spanned<Variant_>;
1643 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1644 pub struct PathListItem_ {
1646 /// renamed in list, e.g. `use foo::{bar as baz};`
1647 pub rename: Option<Ident>,
1651 pub type PathListItem = Spanned<PathListItem_>;
1653 pub type ViewPath = Spanned<ViewPath_>;
1655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1656 pub enum ViewPath_ {
1658 /// `foo::bar::baz as quux`
1662 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1663 ViewPathSimple(Ident, Path),
1668 /// `foo::bar::{a,b,c}`
1669 ViewPathList(Path, Vec<PathListItem>)
1673 pub fn path(&self) -> &Path {
1675 ViewPathSimple(_, ref path) |
1676 ViewPathGlob (ref path) |
1677 ViewPathList(ref path, _) => path
1683 /// Distinguishes between Attributes that decorate items and Attributes that
1684 /// are contained as statements within items. These two cases need to be
1685 /// distinguished for pretty-printing.
1686 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1687 pub enum AttrStyle {
1692 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1693 pub struct AttrId(pub usize);
1695 /// Meta-data associated with an item
1696 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1697 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1698 pub struct Attribute {
1700 pub style: AttrStyle,
1702 pub tokens: TokenStream,
1703 pub is_sugared_doc: bool,
1707 /// TraitRef's appear in impls.
1709 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1710 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1711 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1712 /// same as the impl's node id).
1713 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1714 pub struct TraitRef {
1719 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1720 pub struct PolyTraitRef {
1721 /// The `'a` in `<'a> Foo<&'a T>`
1722 pub bound_lifetimes: Vec<LifetimeDef>,
1724 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1725 pub trait_ref: TraitRef,
1731 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, lo: BytePos, hi: BytePos) -> Self {
1733 bound_lifetimes: lifetimes,
1734 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1735 span: mk_sp(lo, hi),
1740 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1741 pub enum Visibility {
1744 Restricted { path: P<Path>, id: NodeId },
1748 /// Field of a struct.
1750 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1751 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1752 pub struct StructField {
1754 pub ident: Option<Ident>,
1755 pub vis: Visibility,
1758 pub attrs: Vec<Attribute>,
1761 /// Fields and Ids of enum variants and structs
1763 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1764 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1765 /// One shared Id can be successfully used for these two purposes.
1766 /// Id of the whole enum lives in `Item`.
1768 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1769 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1770 /// the variant itself" from enum variants.
1771 /// Id of the whole struct lives in `Item`.
1772 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1773 pub enum VariantData {
1776 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1777 Struct(Vec<StructField>, NodeId),
1780 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1781 Tuple(Vec<StructField>, NodeId),
1784 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1789 pub fn fields(&self) -> &[StructField] {
1791 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1795 pub fn id(&self) -> NodeId {
1797 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1800 pub fn is_struct(&self) -> bool {
1801 if let VariantData::Struct(..) = *self { true } else { false }
1803 pub fn is_tuple(&self) -> bool {
1804 if let VariantData::Tuple(..) = *self { true } else { false }
1806 pub fn is_unit(&self) -> bool {
1807 if let VariantData::Unit(..) = *self { true } else { false }
1813 /// The name might be a dummy name in case of anonymous items
1814 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1817 pub attrs: Vec<Attribute>,
1820 pub vis: Visibility,
1824 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1826 /// An`extern crate` item, with optional original crate name.
1828 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1829 ExternCrate(Option<Name>),
1830 /// A use declaration (`use` or `pub use`) item.
1832 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1834 /// A static item (`static` or `pub static`).
1836 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1837 Static(P<Ty>, Mutability, P<Expr>),
1838 /// A constant item (`const` or `pub const`).
1840 /// E.g. `const FOO: i32 = 42;`
1841 Const(P<Ty>, P<Expr>),
1842 /// A function declaration (`fn` or `pub fn`).
1844 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1845 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1846 /// A module declaration (`mod` or `pub mod`).
1848 /// E.g. `mod foo;` or `mod foo { .. }`
1850 /// An external module (`extern` or `pub extern`).
1852 /// E.g. `extern {}` or `extern "C" {}`
1853 ForeignMod(ForeignMod),
1854 /// A type alias (`type` or `pub type`).
1856 /// E.g. `type Foo = Bar<u8>;`
1857 Ty(P<Ty>, Generics),
1858 /// An enum definition (`enum` or `pub enum`).
1860 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1861 Enum(EnumDef, Generics),
1862 /// A struct definition (`struct` or `pub struct`).
1864 /// E.g. `struct Foo<A> { x: A }`
1865 Struct(VariantData, Generics),
1866 /// A union definition (`union` or `pub union`).
1868 /// E.g. `union Foo<A, B> { x: A, y: B }`
1869 Union(VariantData, Generics),
1870 /// A Trait declaration (`trait` or `pub trait`).
1872 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1873 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1874 // Default trait implementation.
1876 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1877 DefaultImpl(Unsafety, TraitRef),
1878 /// An implementation.
1880 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1884 Option<TraitRef>, // (optional) trait this impl implements
1887 /// A macro invocation.
1889 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1892 /// A macro definition.
1893 MacroDef(ThinTokenStream),
1897 pub fn descriptive_variant(&self) -> &str {
1899 ItemKind::ExternCrate(..) => "extern crate",
1900 ItemKind::Use(..) => "use",
1901 ItemKind::Static(..) => "static item",
1902 ItemKind::Const(..) => "constant item",
1903 ItemKind::Fn(..) => "function",
1904 ItemKind::Mod(..) => "module",
1905 ItemKind::ForeignMod(..) => "foreign module",
1906 ItemKind::Ty(..) => "type alias",
1907 ItemKind::Enum(..) => "enum",
1908 ItemKind::Struct(..) => "struct",
1909 ItemKind::Union(..) => "union",
1910 ItemKind::Trait(..) => "trait",
1912 ItemKind::MacroDef(..) |
1913 ItemKind::Impl(..) |
1914 ItemKind::DefaultImpl(..) => "item"
1919 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1920 pub struct ForeignItem {
1922 pub attrs: Vec<Attribute>,
1923 pub node: ForeignItemKind,
1926 pub vis: Visibility,
1929 /// An item within an `extern` block
1930 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1931 pub enum ForeignItemKind {
1932 /// A foreign function
1933 Fn(P<FnDecl>, Generics),
1934 /// A foreign static item (`static ext: u8`), with optional mutability
1935 /// (the boolean is true when mutable)
1936 Static(P<Ty>, bool),
1939 impl ForeignItemKind {
1940 pub fn descriptive_variant(&self) -> &str {
1942 ForeignItemKind::Fn(..) => "foreign function",
1943 ForeignItemKind::Static(..) => "foreign static item"
1953 // are ASTs encodable?
1955 fn check_asts_encodable() {
1956 fn assert_encodable<T: serialize::Encodable>() {}
1957 assert_encodable::<Crate>();