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 symbol::{Symbol, keywords};
27 use tokenstream::{ThinTokenStream, TokenStream};
29 use std::collections::HashSet;
34 use serialize::{self, Encodable, Decodable, Encoder, Decoder};
36 /// An identifier contains a Name (index into the interner
37 /// table) and a SyntaxContext to track renaming and
38 /// macro expansion per Flatt et al., "Macros That Work Together"
39 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
42 pub ctxt: SyntaxContext
46 pub const fn with_empty_ctxt(name: Name) -> Ident {
47 Ident { name: name, ctxt: SyntaxContext::empty() }
50 /// Maps a string to an identifier with an empty syntax context.
51 pub fn from_str(s: &str) -> Ident {
52 Ident::with_empty_ctxt(Symbol::intern(s))
55 pub fn unhygienize(&self) -> Ident {
56 Ident { name: self.name, ctxt: SyntaxContext::empty() }
60 impl fmt::Debug for Ident {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 write!(f, "{}{:?}", self.name, self.ctxt)
66 impl fmt::Display for Ident {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 fmt::Display::fmt(&self.name, f)
72 impl Encodable for Ident {
73 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
78 impl Decodable for Ident {
79 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
80 Ok(Ident::with_empty_ctxt(Name::decode(d)?))
84 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
91 impl fmt::Debug for Lifetime {
92 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
97 /// A lifetime definition, e.g. `'a: 'b+'c+'d`
98 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
99 pub struct LifetimeDef {
100 pub attrs: ThinVec<Attribute>,
101 pub lifetime: Lifetime,
102 pub bounds: Vec<Lifetime>
105 /// A "Path" is essentially Rust's notion of a name.
107 /// It's represented as a sequence of identifiers,
108 /// along with a bunch of supporting information.
110 /// E.g. `std::cmp::PartialEq`
111 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
114 /// The segments in the path: the things separated by `::`.
115 /// Global paths begin with `keywords::CrateRoot`.
116 pub segments: Vec<PathSegment>,
119 impl<'a> PartialEq<&'a str> for Path {
120 fn eq(&self, string: &&'a str) -> bool {
121 self.segments.len() == 1 && self.segments[0].identifier.name == *string
125 impl fmt::Debug for Path {
126 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127 write!(f, "path({})", pprust::path_to_string(self))
131 impl fmt::Display for Path {
132 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133 write!(f, "{}", pprust::path_to_string(self))
138 // convert a span and an identifier to the corresponding
140 pub fn from_ident(s: Span, identifier: Ident) -> Path {
143 segments: vec![PathSegment::from_ident(identifier, s)],
147 pub fn default_to_global(mut self) -> Path {
148 let name = self.segments[0].identifier.name;
149 if !self.is_global() && name != "$crate" &&
150 name != keywords::SelfValue.name() && name != keywords::Super.name() {
151 self.segments.insert(0, PathSegment::crate_root());
156 pub fn is_global(&self) -> bool {
157 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
161 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
163 /// E.g. `std`, `String` or `Box<T>`
164 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
165 pub struct PathSegment {
166 /// The identifier portion of this path segment.
167 pub identifier: Ident,
168 /// Span of the segment identifier.
171 /// Type/lifetime parameters attached to this path. They come in
172 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
173 /// this is more than just simple syntactic sugar; the use of
174 /// parens affects the region binding rules, so we preserve the
176 /// The `Option<P<..>>` wrapper is purely a size optimization;
177 /// `None` is used to represent both `Path` and `Path<>`.
178 pub parameters: Option<P<PathParameters>>,
182 pub fn from_ident(ident: Ident, span: Span) -> Self {
183 PathSegment { identifier: ident, span: span, parameters: None }
185 pub fn crate_root() -> Self {
187 identifier: keywords::CrateRoot.ident(),
194 /// Parameters of a path segment.
196 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
197 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
198 pub enum PathParameters {
199 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
200 AngleBracketed(AngleBracketedParameterData),
201 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
202 Parenthesized(ParenthesizedParameterData),
205 /// A path like `Foo<'a, T>`
206 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
207 pub struct AngleBracketedParameterData {
208 /// The lifetime parameters for this path segment.
209 pub lifetimes: Vec<Lifetime>,
210 /// The type parameters for this path segment, if present.
211 pub types: Vec<P<Ty>>,
212 /// Bindings (equality constraints) on associated types, if present.
214 /// E.g., `Foo<A=Bar>`.
215 pub bindings: Vec<TypeBinding>,
218 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
219 fn into(self) -> Option<P<PathParameters>> {
220 let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
221 if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
225 /// A path like `Foo(A,B) -> C`
226 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
227 pub struct ParenthesizedParameterData {
232 pub inputs: Vec<P<Ty>>,
235 pub output: Option<P<Ty>>,
238 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
239 pub struct NodeId(u32);
242 pub fn new(x: usize) -> NodeId {
243 assert!(x < (u32::MAX as usize));
247 pub fn from_u32(x: u32) -> NodeId {
251 pub fn as_usize(&self) -> usize {
255 pub fn as_u32(&self) -> u32 {
260 impl fmt::Display for NodeId {
261 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
262 fmt::Display::fmt(&self.0, f)
266 impl serialize::UseSpecializedEncodable for NodeId {
267 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
272 impl serialize::UseSpecializedDecodable for NodeId {
273 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
274 d.read_u32().map(NodeId)
278 /// Node id used to represent the root of the crate.
279 pub const CRATE_NODE_ID: NodeId = NodeId(0);
281 /// When parsing and doing expansions, we initially give all AST nodes this AST
282 /// node value. Then later, in the renumber pass, we renumber them to have
283 /// small, positive ids.
284 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
286 /// The AST represents all type param bounds as types.
287 /// typeck::collect::compute_bounds matches these against
288 /// the "special" built-in traits (see middle::lang_items) and
289 /// detects Copy, Send and Sync.
290 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
291 pub enum TyParamBound {
292 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
293 RegionTyParamBound(Lifetime)
296 /// A modifier on a bound, currently this is only used for `?Sized`, where the
297 /// modifier is `Maybe`. Negative bounds should also be handled here.
298 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
299 pub enum TraitBoundModifier {
304 pub type TyParamBounds = Vec<TyParamBound>;
306 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
308 pub attrs: ThinVec<Attribute>,
311 pub bounds: TyParamBounds,
312 pub default: Option<P<Ty>>,
316 /// Represents lifetimes and type parameters attached to a declaration
317 /// of a function, enum, trait, etc.
318 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
319 pub struct Generics {
320 pub lifetimes: Vec<LifetimeDef>,
321 pub ty_params: Vec<TyParam>,
322 pub where_clause: WhereClause,
327 pub fn is_lt_parameterized(&self) -> bool {
328 !self.lifetimes.is_empty()
330 pub fn is_type_parameterized(&self) -> bool {
331 !self.ty_params.is_empty()
333 pub fn is_parameterized(&self) -> bool {
334 self.is_lt_parameterized() || self.is_type_parameterized()
336 pub fn span_for_name(&self, name: &str) -> Option<Span> {
337 for t in &self.ty_params {
338 if t.ident.name == name {
346 impl Default for Generics {
347 /// Creates an instance of `Generics`.
348 fn default() -> Generics {
350 lifetimes: Vec::new(),
351 ty_params: Vec::new(),
352 where_clause: WhereClause {
354 predicates: Vec::new(),
361 /// A `where` clause in a definition
362 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
363 pub struct WhereClause {
365 pub predicates: Vec<WherePredicate>,
368 /// A single predicate in a `where` clause
369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
370 pub enum WherePredicate {
371 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
372 BoundPredicate(WhereBoundPredicate),
373 /// A lifetime predicate, e.g. `'a: 'b+'c`
374 RegionPredicate(WhereRegionPredicate),
375 /// An equality predicate (unsupported)
376 EqPredicate(WhereEqPredicate),
381 /// E.g. `for<'c> Foo: Send+Clone+'c`
382 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
383 pub struct WhereBoundPredicate {
385 /// Any lifetimes from a `for` binding
386 pub bound_lifetimes: Vec<LifetimeDef>,
387 /// The type being bounded
388 pub bounded_ty: P<Ty>,
389 /// Trait and lifetime bounds (`Clone+Send+'static`)
390 pub bounds: TyParamBounds,
393 /// A lifetime predicate.
396 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
397 pub struct WhereRegionPredicate {
399 pub lifetime: Lifetime,
400 pub bounds: Vec<Lifetime>,
403 /// An equality predicate (unsupported).
406 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
407 pub struct WhereEqPredicate {
414 /// The set of MetaItems that define the compilation environment of the crate,
415 /// used to drive conditional compilation
416 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
418 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
421 pub attrs: Vec<Attribute>,
425 /// A spanned compile-time attribute list item.
426 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
428 /// Possible values inside of compile-time attribute lists.
430 /// E.g. the '..' in `#[name(..)]`.
431 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
432 pub enum NestedMetaItemKind {
433 /// A full MetaItem, for recursive meta items.
437 /// E.g. "foo", 64, true
441 /// A spanned compile-time attribute item.
443 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
445 pub struct MetaItem {
447 pub node: MetaItemKind,
451 /// A compile-time attribute item.
453 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
454 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
455 pub enum MetaItemKind {
458 /// E.g. `test` as in `#[test]`
462 /// E.g. `derive(..)` as in `#[derive(..)]`
463 List(Vec<NestedMetaItem>),
464 /// Name value meta item.
466 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
470 /// A Block (`{ .. }`).
472 /// E.g. `{ .. }` as in `fn foo() { .. }`
473 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
475 /// Statements in a block
476 pub stmts: Vec<Stmt>,
478 /// Distinguishes between `unsafe { ... }` and `{ ... }`
479 pub rules: BlockCheckMode,
483 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
490 impl fmt::Debug for Pat {
491 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
492 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
497 pub fn walk<F>(&self, it: &mut F) -> bool
498 where F: FnMut(&Pat) -> bool
505 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
506 PatKind::Struct(_, ref fields, _) => {
507 fields.iter().all(|field| field.node.pat.walk(it))
509 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
510 s.iter().all(|p| p.walk(it))
512 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
515 PatKind::Slice(ref before, ref slice, ref after) => {
516 before.iter().all(|p| p.walk(it)) &&
517 slice.iter().all(|p| p.walk(it)) &&
518 after.iter().all(|p| p.walk(it))
532 /// A single field in a struct pattern
534 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
535 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
536 /// except is_shorthand is true
537 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
538 pub struct FieldPat {
539 /// The identifier for the field
541 /// The pattern the field is destructured to
543 pub is_shorthand: bool,
544 pub attrs: ThinVec<Attribute>,
547 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
548 pub enum BindingMode {
553 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
559 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
561 /// Represents a wildcard pattern (`_`)
564 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
565 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
566 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
567 /// during name resolution.
568 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
570 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
571 /// The `bool` is `true` in the presence of a `..`.
572 Struct(Path, Vec<Spanned<FieldPat>>, bool),
574 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
575 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
576 /// 0 <= position <= subpats.len()
577 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
579 /// A possibly qualified path pattern.
580 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
581 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
582 /// only legally refer to associated constants.
583 Path(Option<QSelf>, Path),
585 /// A tuple pattern `(a, b)`.
586 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
587 /// 0 <= position <= subpats.len()
588 Tuple(Vec<P<Pat>>, Option<usize>),
591 /// A reference pattern, e.g. `&mut (a, b)`
592 Ref(P<Pat>, Mutability),
595 /// A range pattern, e.g. `1...2` or `1..2`
596 Range(P<Expr>, P<Expr>, RangeEnd),
597 /// `[a, b, ..i, y, z]` is represented as:
598 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
599 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
600 /// A macro pattern; pre-expansion
604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
605 pub enum Mutability {
610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
612 /// The `+` operator (addition)
614 /// The `-` operator (subtraction)
616 /// The `*` operator (multiplication)
618 /// The `/` operator (division)
620 /// The `%` operator (modulus)
622 /// The `&&` operator (logical and)
624 /// The `||` operator (logical or)
626 /// The `^` operator (bitwise xor)
628 /// The `&` operator (bitwise and)
630 /// The `|` operator (bitwise or)
632 /// The `<<` operator (shift left)
634 /// The `>>` operator (shift right)
636 /// The `==` operator (equality)
638 /// The `<` operator (less than)
640 /// The `<=` operator (less than or equal to)
642 /// The `!=` operator (not equal to)
644 /// The `>=` operator (greater than or equal to)
646 /// The `>` operator (greater than)
651 pub fn to_string(&self) -> &'static str {
652 use self::BinOpKind::*;
674 pub fn lazy(&self) -> bool {
676 BinOpKind::And | BinOpKind::Or => true,
681 pub fn is_shift(&self) -> bool {
683 BinOpKind::Shl | BinOpKind::Shr => true,
687 pub fn is_comparison(&self) -> bool {
688 use self::BinOpKind::*;
690 Eq | Lt | Le | Ne | Gt | Ge =>
692 And | Or | Add | Sub | Mul | Div | Rem |
693 BitXor | BitAnd | BitOr | Shl | Shr =>
697 /// Returns `true` if the binary operator takes its arguments by value
698 pub fn is_by_value(&self) -> bool {
699 !self.is_comparison()
703 pub type BinOp = Spanned<BinOpKind>;
705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
707 /// The `*` operator for dereferencing
709 /// The `!` operator for logical inversion
711 /// The `-` operator for negation
716 /// Returns `true` if the unary operator takes its argument by value
717 pub fn is_by_value(u: UnOp) -> bool {
719 UnOp::Neg | UnOp::Not => true,
724 pub fn to_string(op: UnOp) -> &'static str {
734 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
742 pub fn add_trailing_semicolon(mut self) -> Self {
743 self.node = match self.node {
744 StmtKind::Expr(expr) => StmtKind::Semi(expr),
745 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
746 (mac, MacStmtStyle::Semicolon, attrs)
754 impl fmt::Debug for Stmt {
755 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
756 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
761 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
763 /// A local (let) binding.
766 /// An item definition.
769 /// Expr without trailing semi-colon.
774 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
777 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
778 pub enum MacStmtStyle {
779 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
780 /// `foo!(...);`, `foo![...];`
782 /// The macro statement had braces; e.g. foo! { ... }
784 /// The macro statement had parentheses or brackets and no semicolon; e.g.
785 /// `foo!(...)`. All of these will end up being converted into macro
790 // FIXME (pending discussion of #1697, #2178...): local should really be
791 // a refinement on pat.
792 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
793 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
796 pub ty: Option<P<Ty>>,
797 /// Initializer expression to set the value, if any
798 pub init: Option<P<Expr>>,
801 pub attrs: ThinVec<Attribute>,
804 /// An arm of a 'match'.
806 /// E.g. `0...10 => { println!("match!") }` as in
810 /// 0...10 => { println!("match!") },
814 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
816 pub attrs: Vec<Attribute>,
817 pub pats: Vec<P<Pat>>,
818 pub guard: Option<P<Expr>>,
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>
854 impl fmt::Debug for Expr {
855 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
856 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
860 /// Limit types of a range (inclusive or exclusive)
861 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
862 pub enum RangeLimits {
863 /// Inclusive at the beginning, exclusive at the end
865 /// Inclusive at the beginning and end
869 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
871 /// A `box x` expression.
873 /// First expr is the place; second expr is the value.
874 InPlace(P<Expr>, P<Expr>),
875 /// An array (`[a, b, c, d]`)
879 /// The first field resolves to the function itself,
880 /// and the second field is the list of arguments
881 Call(P<Expr>, Vec<P<Expr>>),
882 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
884 /// The `SpannedIdent` is the identifier for the method name.
885 /// The vector of `Ty`s are the ascripted type parameters for the method
886 /// (within the angle brackets).
888 /// The first element of the vector of `Expr`s is the expression that evaluates
889 /// to the object on which the method is being called on (the receiver),
890 /// and the remaining elements are the rest of the arguments.
892 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
893 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
894 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
895 /// A tuple (`(a, b, c ,d)`)
897 /// A binary operation (For example: `a + b`, `a * b`)
898 Binary(BinOp, P<Expr>, P<Expr>),
899 /// A unary operation (For example: `!x`, `*x`)
900 Unary(UnOp, P<Expr>),
901 /// A literal (For example: `1`, `"foo"`)
903 /// A cast (`foo as f64`)
904 Cast(P<Expr>, P<Ty>),
905 Type(P<Expr>, P<Ty>),
906 /// An `if` block, with an optional else block
908 /// `if expr { block } else { expr }`
909 If(P<Expr>, P<Block>, Option<P<Expr>>),
910 /// An `if let` expression with an optional else block
912 /// `if let pat = expr { block } else { expr }`
914 /// This is desugared to a `match` expression.
915 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
916 /// A while loop, with an optional label
918 /// `'label: while expr { block }`
919 While(P<Expr>, P<Block>, Option<SpannedIdent>),
920 /// A while-let loop, with an optional label
922 /// `'label: while let pat = expr { block }`
924 /// This is desugared to a combination of `loop` and `match` expressions.
925 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
926 /// A for loop, with an optional label
928 /// `'label: for pat in expr { block }`
930 /// This is desugared to a combination of `loop` and `match` expressions.
931 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
932 /// Conditionless loop (can be exited with break, continue, or return)
934 /// `'label: loop { block }`
935 Loop(P<Block>, Option<SpannedIdent>),
937 Match(P<Expr>, Vec<Arm>),
938 /// A closure (for example, `move |a, b, c| a + b + c`)
940 /// The final span is the span of the argument block `|...|`
941 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
942 /// A block (`{ ... }`)
944 /// A catch block (`catch { ... }`)
947 /// An assignment (`a = foo()`)
948 Assign(P<Expr>, P<Expr>),
949 /// An assignment with an operator
951 /// For example, `a += 1`.
952 AssignOp(BinOp, P<Expr>, P<Expr>),
953 /// Access of a named struct field (`obj.foo`)
954 Field(P<Expr>, SpannedIdent),
955 /// Access of an unnamed field of a struct or tuple-struct
957 /// For example, `foo.0`.
958 TupField(P<Expr>, Spanned<usize>),
959 /// An indexing operation (`foo[2]`)
960 Index(P<Expr>, P<Expr>),
961 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
962 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
964 /// Variable reference, possibly containing `::` and/or type
965 /// parameters, e.g. foo::bar::<baz>.
967 /// Optionally "qualified",
968 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
969 Path(Option<QSelf>, Path),
971 /// A referencing operation (`&a` or `&mut a`)
972 AddrOf(Mutability, P<Expr>),
973 /// A `break`, with an optional label to break, and an optional expression
974 Break(Option<SpannedIdent>, Option<P<Expr>>),
975 /// A `continue`, with an optional label
976 Continue(Option<SpannedIdent>),
977 /// A `return`, with an optional value to be returned
978 Ret(Option<P<Expr>>),
980 /// Output of the `asm!()` macro
981 InlineAsm(P<InlineAsm>),
983 /// A macro invocation; pre-expansion
986 /// A struct literal expression.
988 /// For example, `Foo {x: 1, y: 2}`, or
989 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
990 Struct(Path, Vec<Field>, Option<P<Expr>>),
992 /// An array literal constructed from one repeated element.
994 /// For example, `[1; 5]`. The first expression is the element
995 /// to be repeated; the second is the number of times to repeat it.
996 Repeat(P<Expr>, P<Expr>),
998 /// No-op: used solely so we can pretty-print faithfully
1005 /// The explicit Self type in a "qualified path". The actual
1006 /// path, including the trait and the associated item, is stored
1007 /// separately. `position` represents the index of the associated
1008 /// item qualified with this Self type.
1011 /// <Vec<T> as a::b::Trait>::AssociatedItem
1012 /// ^~~~~ ~~~~~~~~~~~~~~^
1015 /// <Vec<T>>::AssociatedItem
1019 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1025 /// A capture clause
1026 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1027 pub enum CaptureBy {
1032 pub type Mac = Spanned<Mac_>;
1034 /// Represents a macro invocation. The Path indicates which macro
1035 /// is being invoked, and the vector of token-trees contains the source
1036 /// of the macro invocation.
1038 /// NB: the additional ident for a macro_rules-style macro is actually
1039 /// stored in the enclosing item. Oog.
1040 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1043 pub tts: ThinTokenStream,
1047 pub fn stream(&self) -> TokenStream {
1048 self.tts.clone().into()
1052 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1054 /// A regular string, like `"foo"`
1056 /// A raw string, like `r##"foo"##`
1058 /// The uint is the number of `#` symbols used
1063 pub type Lit = Spanned<LitKind>;
1065 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1066 pub enum LitIntType {
1074 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1075 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1077 /// A string literal (`"foo"`)
1078 Str(Symbol, StrStyle),
1079 /// A byte string (`b"foo"`)
1080 ByteStr(Rc<Vec<u8>>),
1081 /// A byte char (`b'f'`)
1083 /// A character literal (`'a'`)
1085 /// An integer literal (`1`)
1086 Int(u128, LitIntType),
1087 /// A float literal (`1f64` or `1E10f64`)
1088 Float(Symbol, FloatTy),
1089 /// A float literal without a suffix (`1.0 or 1.0E10`)
1090 FloatUnsuffixed(Symbol),
1091 /// A boolean literal
1096 /// Returns true if this literal is a string and false otherwise.
1097 pub fn is_str(&self) -> bool {
1099 LitKind::Str(..) => true,
1104 /// Returns true if this literal has no suffix. Note: this will return true
1105 /// for literals with prefixes such as raw strings and byte strings.
1106 pub fn is_unsuffixed(&self) -> bool {
1108 // unsuffixed variants
1109 LitKind::Str(..) => true,
1110 LitKind::ByteStr(..) => true,
1111 LitKind::Byte(..) => true,
1112 LitKind::Char(..) => true,
1113 LitKind::Int(_, LitIntType::Unsuffixed) => true,
1114 LitKind::FloatUnsuffixed(..) => true,
1115 LitKind::Bool(..) => true,
1116 // suffixed variants
1117 LitKind::Int(_, LitIntType::Signed(..)) => false,
1118 LitKind::Int(_, LitIntType::Unsigned(..)) => false,
1119 LitKind::Float(..) => false,
1123 /// Returns true if this literal has a suffix.
1124 pub fn is_suffixed(&self) -> bool {
1125 !self.is_unsuffixed()
1129 // NB: If you change this, you'll probably want to change the corresponding
1130 // type structure in middle/ty.rs as well.
1131 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1134 pub mutbl: Mutability,
1137 /// Represents a method's signature in a trait declaration,
1138 /// or in an implementation.
1139 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1140 pub struct MethodSig {
1141 pub unsafety: Unsafety,
1142 pub constness: Spanned<Constness>,
1144 pub decl: P<FnDecl>,
1145 pub generics: Generics,
1148 /// Represents an item declaration within a trait declaration,
1149 /// possibly including a default implementation. A trait item is
1150 /// either required (meaning it doesn't have an implementation, just a
1151 /// signature) or provided (meaning it has a default implementation).
1152 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1153 pub struct TraitItem {
1156 pub attrs: Vec<Attribute>,
1157 pub node: TraitItemKind,
1161 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1162 pub enum TraitItemKind {
1163 Const(P<Ty>, Option<P<Expr>>),
1164 Method(MethodSig, Option<P<Block>>),
1165 Type(TyParamBounds, Option<P<Ty>>),
1169 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1170 pub struct ImplItem {
1173 pub vis: Visibility,
1174 pub defaultness: Defaultness,
1175 pub attrs: Vec<Attribute>,
1176 pub node: ImplItemKind,
1180 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1181 pub enum ImplItemKind {
1182 Const(P<Ty>, P<Expr>),
1183 Method(MethodSig, P<Block>),
1188 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1198 impl fmt::Debug for IntTy {
1199 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1200 fmt::Display::fmt(self, f)
1204 impl fmt::Display for IntTy {
1205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1206 write!(f, "{}", self.ty_to_string())
1211 pub fn ty_to_string(&self) -> &'static str {
1213 IntTy::Is => "isize",
1215 IntTy::I16 => "i16",
1216 IntTy::I32 => "i32",
1217 IntTy::I64 => "i64",
1218 IntTy::I128 => "i128",
1222 pub fn val_to_string(&self, val: i128) -> String {
1223 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1224 // are parsed as u128, so we wouldn't want to print an extra negative
1226 format!("{}{}", val as u128, self.ty_to_string())
1229 pub fn bit_width(&self) -> Option<usize> {
1231 IntTy::Is => return None,
1241 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1252 pub fn ty_to_string(&self) -> &'static str {
1254 UintTy::Us => "usize",
1256 UintTy::U16 => "u16",
1257 UintTy::U32 => "u32",
1258 UintTy::U64 => "u64",
1259 UintTy::U128 => "u128",
1263 pub fn val_to_string(&self, val: u128) -> String {
1264 format!("{}{}", val, self.ty_to_string())
1267 pub fn bit_width(&self) -> Option<usize> {
1269 UintTy::Us => return None,
1274 UintTy::U128 => 128,
1279 impl fmt::Debug for UintTy {
1280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1281 fmt::Display::fmt(self, f)
1285 impl fmt::Display for UintTy {
1286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1287 write!(f, "{}", self.ty_to_string())
1291 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1297 impl fmt::Debug for FloatTy {
1298 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1299 fmt::Display::fmt(self, f)
1303 impl fmt::Display for FloatTy {
1304 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1305 write!(f, "{}", self.ty_to_string())
1310 pub fn ty_to_string(&self) -> &'static str {
1312 FloatTy::F32 => "f32",
1313 FloatTy::F64 => "f64",
1317 pub fn bit_width(&self) -> usize {
1325 // Bind a type to an associated type: `A=Foo`.
1326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1327 pub struct TypeBinding {
1334 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1341 impl fmt::Debug for Ty {
1342 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1343 write!(f, "type({})", pprust::ty_to_string(self))
1347 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1348 pub struct BareFnTy {
1349 pub unsafety: Unsafety,
1351 pub lifetimes: Vec<LifetimeDef>,
1355 /// The different kinds of types recognized by the compiler
1356 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1358 /// A variable-length slice (`[T]`)
1360 /// A fixed length array (`[T; n]`)
1361 Array(P<Ty>, P<Expr>),
1362 /// A raw pointer (`*const T` or `*mut T`)
1364 /// A reference (`&'a T` or `&'a mut T`)
1365 Rptr(Option<Lifetime>, MutTy),
1366 /// A bare function (e.g. `fn(usize) -> bool`)
1367 BareFn(P<BareFnTy>),
1368 /// The never type (`!`)
1370 /// A tuple (`(A, B, C, D,...)`)
1372 /// A path (`module::module::...::Type`), optionally
1373 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1375 /// Type parameters are stored in the Path itself
1376 Path(Option<QSelf>, Path),
1377 /// A trait object type `Bound1 + Bound2 + Bound3`
1378 /// where `Bound` is a trait or a lifetime.
1379 TraitObject(TyParamBounds),
1380 /// An `impl Bound1 + Bound2 + Bound3` type
1381 /// where `Bound` is a trait or a lifetime.
1382 ImplTrait(TyParamBounds),
1383 /// No-op; kept solely so that we can pretty-print faithfully
1387 /// TyKind::Infer means the type should be inferred instead of it having been
1388 /// specified. This can appear anywhere in a type.
1390 /// Inferred type of a `self` or `&self` argument in a method.
1392 // A macro in the type position.
1396 /// Inline assembly dialect.
1398 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1400 pub enum AsmDialect {
1405 /// Inline assembly.
1407 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1408 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1409 pub struct InlineAsmOutput {
1410 pub constraint: Symbol,
1413 pub is_indirect: bool,
1416 /// Inline assembly.
1418 /// E.g. `asm!("NOP");`
1419 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1420 pub struct InlineAsm {
1422 pub asm_str_style: StrStyle,
1423 pub outputs: Vec<InlineAsmOutput>,
1424 pub inputs: Vec<(Symbol, P<Expr>)>,
1425 pub clobbers: Vec<Symbol>,
1427 pub alignstack: bool,
1428 pub dialect: AsmDialect,
1429 pub expn_id: ExpnId,
1432 /// An argument in a function header.
1434 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1435 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1442 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1444 /// E.g. `&mut self` as in `fn foo(&mut self)`
1445 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1447 /// `self`, `mut self`
1449 /// `&'lt self`, `&'lt mut self`
1450 Region(Option<Lifetime>, Mutability),
1451 /// `self: TYPE`, `mut self: TYPE`
1452 Explicit(P<Ty>, Mutability),
1455 pub type ExplicitSelf = Spanned<SelfKind>;
1458 pub fn to_self(&self) -> Option<ExplicitSelf> {
1459 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1460 if ident.node.name == keywords::SelfValue.name() {
1461 return match self.ty.node {
1462 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1463 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1464 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1466 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1467 SelfKind::Explicit(self.ty.clone(), mutbl))),
1474 pub fn is_self(&self) -> bool {
1475 if let PatKind::Ident(_, ident, _) = self.pat.node {
1476 ident.node.name == keywords::SelfValue.name()
1482 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1483 let span = mk_sp(eself.span.lo, eself_ident.span.hi);
1484 let infer_ty = P(Ty {
1486 node: TyKind::ImplicitSelf,
1489 let arg = |mutbl, ty| Arg {
1492 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1499 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1500 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1501 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1503 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1510 /// Header (not the body) of a function declaration.
1512 /// E.g. `fn foo(bar: baz)`
1513 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1515 pub inputs: Vec<Arg>,
1516 pub output: FunctionRetTy,
1521 pub fn get_self(&self) -> Option<ExplicitSelf> {
1522 self.inputs.get(0).and_then(Arg::to_self)
1524 pub fn has_self(&self) -> bool {
1525 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1529 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1535 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub enum Constness {
1541 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1542 pub enum Defaultness {
1547 impl fmt::Display for Unsafety {
1548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1549 fmt::Display::fmt(match *self {
1550 Unsafety::Normal => "normal",
1551 Unsafety::Unsafe => "unsafe",
1556 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1557 pub enum ImplPolarity {
1558 /// `impl Trait for Type`
1560 /// `impl !Trait for Type`
1564 impl fmt::Debug for ImplPolarity {
1565 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1567 ImplPolarity::Positive => "positive".fmt(f),
1568 ImplPolarity::Negative => "negative".fmt(f),
1574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1575 pub enum FunctionRetTy {
1576 /// Return type is not specified.
1578 /// Functions default to `()` and
1579 /// closures default to inference. Span points to where return
1580 /// type would be inserted.
1586 impl FunctionRetTy {
1587 pub fn span(&self) -> Span {
1589 FunctionRetTy::Default(span) => span,
1590 FunctionRetTy::Ty(ref ty) => ty.span,
1595 /// Module declaration.
1597 /// E.g. `mod foo;` or `mod foo { .. }`
1598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1600 /// A span from the first token past `{` to the last token until `}`.
1601 /// For `mod foo;`, the inner span ranges from the first token
1602 /// to the last token in the external file.
1604 pub items: Vec<P<Item>>,
1607 /// Foreign module declaration.
1609 /// E.g. `extern { .. }` or `extern C { .. }`
1610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1611 pub struct ForeignMod {
1613 pub items: Vec<ForeignItem>,
1616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1617 pub struct EnumDef {
1618 pub variants: Vec<Variant>,
1621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1622 pub struct Variant_ {
1624 pub attrs: Vec<Attribute>,
1625 pub data: VariantData,
1626 /// Explicit discriminant, e.g. `Foo = 1`
1627 pub disr_expr: Option<P<Expr>>,
1630 pub type Variant = Spanned<Variant_>;
1632 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1633 pub struct PathListItem_ {
1635 /// renamed in list, e.g. `use foo::{bar as baz};`
1636 pub rename: Option<Ident>,
1640 pub type PathListItem = Spanned<PathListItem_>;
1642 pub type ViewPath = Spanned<ViewPath_>;
1644 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1645 pub enum ViewPath_ {
1647 /// `foo::bar::baz as quux`
1651 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1652 ViewPathSimple(Ident, Path),
1657 /// `foo::bar::{a,b,c}`
1658 ViewPathList(Path, Vec<PathListItem>)
1662 pub fn path(&self) -> &Path {
1664 ViewPathSimple(_, ref path) |
1665 ViewPathGlob (ref path) |
1666 ViewPathList(ref path, _) => path
1672 /// Distinguishes between Attributes that decorate items and Attributes that
1673 /// are contained as statements within items. These two cases need to be
1674 /// distinguished for pretty-printing.
1675 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1676 pub enum AttrStyle {
1681 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1682 pub struct AttrId(pub usize);
1684 /// Meta-data associated with an item
1685 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1686 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1687 pub struct Attribute {
1689 pub style: AttrStyle,
1691 pub tokens: TokenStream,
1692 pub is_sugared_doc: bool,
1696 /// TraitRef's appear in impls.
1698 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1699 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1700 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1701 /// same as the impl's node id).
1702 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1703 pub struct TraitRef {
1708 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1709 pub struct PolyTraitRef {
1710 /// The `'a` in `<'a> Foo<&'a T>`
1711 pub bound_lifetimes: Vec<LifetimeDef>,
1713 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1714 pub trait_ref: TraitRef,
1720 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, lo: BytePos, hi: BytePos) -> Self {
1722 bound_lifetimes: lifetimes,
1723 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1724 span: mk_sp(lo, hi),
1729 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1730 pub enum Visibility {
1733 Restricted { path: P<Path>, id: NodeId },
1737 /// Field of a struct.
1739 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1740 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1741 pub struct StructField {
1743 pub ident: Option<Ident>,
1744 pub vis: Visibility,
1747 pub attrs: Vec<Attribute>,
1750 /// Fields and Ids of enum variants and structs
1752 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1753 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1754 /// One shared Id can be successfully used for these two purposes.
1755 /// Id of the whole enum lives in `Item`.
1757 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1758 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1759 /// the variant itself" from enum variants.
1760 /// Id of the whole struct lives in `Item`.
1761 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1762 pub enum VariantData {
1765 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1766 Struct(Vec<StructField>, NodeId),
1769 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1770 Tuple(Vec<StructField>, NodeId),
1773 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1778 pub fn fields(&self) -> &[StructField] {
1780 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1784 pub fn id(&self) -> NodeId {
1786 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1789 pub fn is_struct(&self) -> bool {
1790 if let VariantData::Struct(..) = *self { true } else { false }
1792 pub fn is_tuple(&self) -> bool {
1793 if let VariantData::Tuple(..) = *self { true } else { false }
1795 pub fn is_unit(&self) -> bool {
1796 if let VariantData::Unit(..) = *self { true } else { false }
1802 /// The name might be a dummy name in case of anonymous items
1803 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1806 pub attrs: Vec<Attribute>,
1809 pub vis: Visibility,
1813 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1815 /// An`extern crate` item, with optional original crate name.
1817 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1818 ExternCrate(Option<Name>),
1819 /// A use declaration (`use` or `pub use`) item.
1821 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1823 /// A static item (`static` or `pub static`).
1825 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1826 Static(P<Ty>, Mutability, P<Expr>),
1827 /// A constant item (`const` or `pub const`).
1829 /// E.g. `const FOO: i32 = 42;`
1830 Const(P<Ty>, P<Expr>),
1831 /// A function declaration (`fn` or `pub fn`).
1833 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1834 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1835 /// A module declaration (`mod` or `pub mod`).
1837 /// E.g. `mod foo;` or `mod foo { .. }`
1839 /// An external module (`extern` or `pub extern`).
1841 /// E.g. `extern {}` or `extern "C" {}`
1842 ForeignMod(ForeignMod),
1843 /// A type alias (`type` or `pub type`).
1845 /// E.g. `type Foo = Bar<u8>;`
1846 Ty(P<Ty>, Generics),
1847 /// An enum definition (`enum` or `pub enum`).
1849 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1850 Enum(EnumDef, Generics),
1851 /// A struct definition (`struct` or `pub struct`).
1853 /// E.g. `struct Foo<A> { x: A }`
1854 Struct(VariantData, Generics),
1855 /// A union definition (`union` or `pub union`).
1857 /// E.g. `union Foo<A, B> { x: A, y: B }`
1858 Union(VariantData, Generics),
1859 /// A Trait declaration (`trait` or `pub trait`).
1861 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1862 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1863 // Default trait implementation.
1865 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1866 DefaultImpl(Unsafety, TraitRef),
1867 /// An implementation.
1869 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1873 Option<TraitRef>, // (optional) trait this impl implements
1876 /// A macro invocation.
1878 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1881 /// A macro definition.
1882 MacroDef(ThinTokenStream),
1886 pub fn descriptive_variant(&self) -> &str {
1888 ItemKind::ExternCrate(..) => "extern crate",
1889 ItemKind::Use(..) => "use",
1890 ItemKind::Static(..) => "static item",
1891 ItemKind::Const(..) => "constant item",
1892 ItemKind::Fn(..) => "function",
1893 ItemKind::Mod(..) => "module",
1894 ItemKind::ForeignMod(..) => "foreign module",
1895 ItemKind::Ty(..) => "type alias",
1896 ItemKind::Enum(..) => "enum",
1897 ItemKind::Struct(..) => "struct",
1898 ItemKind::Union(..) => "union",
1899 ItemKind::Trait(..) => "trait",
1901 ItemKind::MacroDef(..) |
1902 ItemKind::Impl(..) |
1903 ItemKind::DefaultImpl(..) => "item"
1908 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1909 pub struct ForeignItem {
1911 pub attrs: Vec<Attribute>,
1912 pub node: ForeignItemKind,
1915 pub vis: Visibility,
1918 /// An item within an `extern` block
1919 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1920 pub enum ForeignItemKind {
1921 /// A foreign function
1922 Fn(P<FnDecl>, Generics),
1923 /// A foreign static item (`static ext: u8`), with optional mutability
1924 /// (the boolean is true when mutable)
1925 Static(P<Ty>, bool),
1928 impl ForeignItemKind {
1929 pub fn descriptive_variant(&self) -> &str {
1931 ForeignItemKind::Fn(..) => "foreign function",
1932 ForeignItemKind::Static(..) => "foreign static item"
1942 // are ASTs encodable?
1944 fn check_asts_encodable() {
1945 fn assert_encodable<T: serialize::Encodable>() {}
1946 assert_encodable::<Crate>();