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::{Mark, 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 {
260 pub fn placeholder_from_mark(mark: Mark) -> Self {
261 NodeId(mark.as_u32())
264 pub fn placeholder_to_mark(self) -> Mark {
265 Mark::from_u32(self.0)
269 impl fmt::Display for NodeId {
270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
271 fmt::Display::fmt(&self.0, f)
275 impl serialize::UseSpecializedEncodable for NodeId {
276 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
281 impl serialize::UseSpecializedDecodable for NodeId {
282 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
283 d.read_u32().map(NodeId)
287 impl indexed_vec::Idx for NodeId {
288 fn new(idx: usize) -> Self {
292 fn index(self) -> usize {
297 /// Node id used to represent the root of the crate.
298 pub const CRATE_NODE_ID: NodeId = NodeId(0);
300 /// When parsing and doing expansions, we initially give all AST nodes this AST
301 /// node value. Then later, in the renumber pass, we renumber them to have
302 /// small, positive ids.
303 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
305 /// The AST represents all type param bounds as types.
306 /// typeck::collect::compute_bounds matches these against
307 /// the "special" built-in traits (see middle::lang_items) and
308 /// detects Copy, Send and Sync.
309 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
310 pub enum TyParamBound {
311 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
312 RegionTyParamBound(Lifetime)
315 /// A modifier on a bound, currently this is only used for `?Sized`, where the
316 /// modifier is `Maybe`. Negative bounds should also be handled here.
317 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
318 pub enum TraitBoundModifier {
323 pub type TyParamBounds = Vec<TyParamBound>;
325 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
327 pub attrs: ThinVec<Attribute>,
330 pub bounds: TyParamBounds,
331 pub default: Option<P<Ty>>,
335 /// Represents lifetimes and type parameters attached to a declaration
336 /// of a function, enum, trait, etc.
337 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
338 pub struct Generics {
339 pub lifetimes: Vec<LifetimeDef>,
340 pub ty_params: Vec<TyParam>,
341 pub where_clause: WhereClause,
346 pub fn is_lt_parameterized(&self) -> bool {
347 !self.lifetimes.is_empty()
349 pub fn is_type_parameterized(&self) -> bool {
350 !self.ty_params.is_empty()
352 pub fn is_parameterized(&self) -> bool {
353 self.is_lt_parameterized() || self.is_type_parameterized()
355 pub fn span_for_name(&self, name: &str) -> Option<Span> {
356 for t in &self.ty_params {
357 if t.ident.name == name {
365 impl Default for Generics {
366 /// Creates an instance of `Generics`.
367 fn default() -> Generics {
369 lifetimes: Vec::new(),
370 ty_params: Vec::new(),
371 where_clause: WhereClause {
373 predicates: Vec::new(),
380 /// A `where` clause in a definition
381 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
382 pub struct WhereClause {
384 pub predicates: Vec<WherePredicate>,
387 /// A single predicate in a `where` clause
388 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
389 pub enum WherePredicate {
390 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
391 BoundPredicate(WhereBoundPredicate),
392 /// A lifetime predicate, e.g. `'a: 'b+'c`
393 RegionPredicate(WhereRegionPredicate),
394 /// An equality predicate (unsupported)
395 EqPredicate(WhereEqPredicate),
400 /// E.g. `for<'c> Foo: Send+Clone+'c`
401 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
402 pub struct WhereBoundPredicate {
404 /// Any lifetimes from a `for` binding
405 pub bound_lifetimes: Vec<LifetimeDef>,
406 /// The type being bounded
407 pub bounded_ty: P<Ty>,
408 /// Trait and lifetime bounds (`Clone+Send+'static`)
409 pub bounds: TyParamBounds,
412 /// A lifetime predicate.
415 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
416 pub struct WhereRegionPredicate {
418 pub lifetime: Lifetime,
419 pub bounds: Vec<Lifetime>,
422 /// An equality predicate (unsupported).
425 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
426 pub struct WhereEqPredicate {
433 /// The set of MetaItems that define the compilation environment of the crate,
434 /// used to drive conditional compilation
435 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
437 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
440 pub attrs: Vec<Attribute>,
444 /// A spanned compile-time attribute list item.
445 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
447 /// Possible values inside of compile-time attribute lists.
449 /// E.g. the '..' in `#[name(..)]`.
450 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
451 pub enum NestedMetaItemKind {
452 /// A full MetaItem, for recursive meta items.
456 /// E.g. "foo", 64, true
460 /// A spanned compile-time attribute item.
462 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
463 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
464 pub struct MetaItem {
466 pub node: MetaItemKind,
470 /// A compile-time attribute item.
472 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
473 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
474 pub enum MetaItemKind {
477 /// E.g. `test` as in `#[test]`
481 /// E.g. `derive(..)` as in `#[derive(..)]`
482 List(Vec<NestedMetaItem>),
483 /// Name value meta item.
485 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
489 /// A Block (`{ .. }`).
491 /// E.g. `{ .. }` as in `fn foo() { .. }`
492 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
494 /// Statements in a block
495 pub stmts: Vec<Stmt>,
497 /// Distinguishes between `unsafe { ... }` and `{ ... }`
498 pub rules: BlockCheckMode,
502 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
509 impl fmt::Debug for Pat {
510 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
511 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
516 pub fn walk<F>(&self, it: &mut F) -> bool
517 where F: FnMut(&Pat) -> bool
524 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
525 PatKind::Struct(_, ref fields, _) => {
526 fields.iter().all(|field| field.node.pat.walk(it))
528 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
529 s.iter().all(|p| p.walk(it))
531 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
534 PatKind::Slice(ref before, ref slice, ref after) => {
535 before.iter().all(|p| p.walk(it)) &&
536 slice.iter().all(|p| p.walk(it)) &&
537 after.iter().all(|p| p.walk(it))
551 /// A single field in a struct pattern
553 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
554 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
555 /// except is_shorthand is true
556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
557 pub struct FieldPat {
558 /// The identifier for the field
560 /// The pattern the field is destructured to
562 pub is_shorthand: bool,
563 pub attrs: ThinVec<Attribute>,
566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
567 pub enum BindingMode {
572 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
578 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
580 /// Represents a wildcard pattern (`_`)
583 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
584 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
585 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
586 /// during name resolution.
587 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
589 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
590 /// The `bool` is `true` in the presence of a `..`.
591 Struct(Path, Vec<Spanned<FieldPat>>, bool),
593 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
594 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
595 /// 0 <= position <= subpats.len()
596 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
598 /// A possibly qualified path pattern.
599 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
600 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
601 /// only legally refer to associated constants.
602 Path(Option<QSelf>, Path),
604 /// A tuple pattern `(a, b)`.
605 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
606 /// 0 <= position <= subpats.len()
607 Tuple(Vec<P<Pat>>, Option<usize>),
610 /// A reference pattern, e.g. `&mut (a, b)`
611 Ref(P<Pat>, Mutability),
614 /// A range pattern, e.g. `1...2` or `1..2`
615 Range(P<Expr>, P<Expr>, RangeEnd),
616 /// `[a, b, ..i, y, z]` is represented as:
617 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
618 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
619 /// A macro pattern; pre-expansion
623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
624 pub enum Mutability {
629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
631 /// The `+` operator (addition)
633 /// The `-` operator (subtraction)
635 /// The `*` operator (multiplication)
637 /// The `/` operator (division)
639 /// The `%` operator (modulus)
641 /// The `&&` operator (logical and)
643 /// The `||` operator (logical or)
645 /// The `^` operator (bitwise xor)
647 /// The `&` operator (bitwise and)
649 /// The `|` operator (bitwise or)
651 /// The `<<` operator (shift left)
653 /// The `>>` operator (shift right)
655 /// The `==` operator (equality)
657 /// The `<` operator (less than)
659 /// The `<=` operator (less than or equal to)
661 /// The `!=` operator (not equal to)
663 /// The `>=` operator (greater than or equal to)
665 /// The `>` operator (greater than)
670 pub fn to_string(&self) -> &'static str {
671 use self::BinOpKind::*;
693 pub fn lazy(&self) -> bool {
695 BinOpKind::And | BinOpKind::Or => true,
700 pub fn is_shift(&self) -> bool {
702 BinOpKind::Shl | BinOpKind::Shr => true,
706 pub fn is_comparison(&self) -> bool {
707 use self::BinOpKind::*;
709 Eq | Lt | Le | Ne | Gt | Ge =>
711 And | Or | Add | Sub | Mul | Div | Rem |
712 BitXor | BitAnd | BitOr | Shl | Shr =>
716 /// Returns `true` if the binary operator takes its arguments by value
717 pub fn is_by_value(&self) -> bool {
718 !self.is_comparison()
722 pub type BinOp = Spanned<BinOpKind>;
724 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
726 /// The `*` operator for dereferencing
728 /// The `!` operator for logical inversion
730 /// The `-` operator for negation
735 /// Returns `true` if the unary operator takes its argument by value
736 pub fn is_by_value(u: UnOp) -> bool {
738 UnOp::Neg | UnOp::Not => true,
743 pub fn to_string(op: UnOp) -> &'static str {
753 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
761 pub fn add_trailing_semicolon(mut self) -> Self {
762 self.node = match self.node {
763 StmtKind::Expr(expr) => StmtKind::Semi(expr),
764 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
765 (mac, MacStmtStyle::Semicolon, attrs)
773 impl fmt::Debug for Stmt {
774 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
775 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
780 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
782 /// A local (let) binding.
785 /// An item definition.
788 /// Expr without trailing semi-colon.
793 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
796 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
797 pub enum MacStmtStyle {
798 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
799 /// `foo!(...);`, `foo![...];`
801 /// The macro statement had braces; e.g. foo! { ... }
803 /// The macro statement had parentheses or brackets and no semicolon; e.g.
804 /// `foo!(...)`. All of these will end up being converted into macro
809 // FIXME (pending discussion of #1697, #2178...): local should really be
810 // a refinement on pat.
811 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
812 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
815 pub ty: Option<P<Ty>>,
816 /// Initializer expression to set the value, if any
817 pub init: Option<P<Expr>>,
820 pub attrs: ThinVec<Attribute>,
823 /// An arm of a 'match'.
825 /// E.g. `0...10 => { println!("match!") }` as in
829 /// 0...10 => { println!("match!") },
833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
835 pub attrs: Vec<Attribute>,
836 pub pats: Vec<P<Pat>>,
837 pub guard: Option<P<Expr>>,
841 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
843 pub ident: SpannedIdent,
846 pub is_shorthand: bool,
847 pub attrs: ThinVec<Attribute>,
850 pub type SpannedIdent = Spanned<Ident>;
852 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
853 pub enum BlockCheckMode {
855 Unsafe(UnsafeSource),
858 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
859 pub enum UnsafeSource {
865 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
870 pub attrs: ThinVec<Attribute>
873 impl fmt::Debug for Expr {
874 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
875 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
879 /// Limit types of a range (inclusive or exclusive)
880 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
881 pub enum RangeLimits {
882 /// Inclusive at the beginning, exclusive at the end
884 /// Inclusive at the beginning and end
888 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
890 /// A `box x` expression.
892 /// First expr is the place; second expr is the value.
893 InPlace(P<Expr>, P<Expr>),
894 /// An array (`[a, b, c, d]`)
898 /// The first field resolves to the function itself,
899 /// and the second field is the list of arguments
900 Call(P<Expr>, Vec<P<Expr>>),
901 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
903 /// The `SpannedIdent` is the identifier for the method name.
904 /// The vector of `Ty`s are the ascripted type parameters for the method
905 /// (within the angle brackets).
907 /// The first element of the vector of `Expr`s is the expression that evaluates
908 /// to the object on which the method is being called on (the receiver),
909 /// and the remaining elements are the rest of the arguments.
911 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
912 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
913 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
914 /// A tuple (`(a, b, c ,d)`)
916 /// A binary operation (For example: `a + b`, `a * b`)
917 Binary(BinOp, P<Expr>, P<Expr>),
918 /// A unary operation (For example: `!x`, `*x`)
919 Unary(UnOp, P<Expr>),
920 /// A literal (For example: `1`, `"foo"`)
922 /// A cast (`foo as f64`)
923 Cast(P<Expr>, P<Ty>),
924 Type(P<Expr>, P<Ty>),
925 /// An `if` block, with an optional else block
927 /// `if expr { block } else { expr }`
928 If(P<Expr>, P<Block>, Option<P<Expr>>),
929 /// An `if let` expression with an optional else block
931 /// `if let pat = expr { block } else { expr }`
933 /// This is desugared to a `match` expression.
934 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
935 /// A while loop, with an optional label
937 /// `'label: while expr { block }`
938 While(P<Expr>, P<Block>, Option<SpannedIdent>),
939 /// A while-let loop, with an optional label
941 /// `'label: while let pat = expr { block }`
943 /// This is desugared to a combination of `loop` and `match` expressions.
944 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
945 /// A for loop, with an optional label
947 /// `'label: for pat in expr { block }`
949 /// This is desugared to a combination of `loop` and `match` expressions.
950 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
951 /// Conditionless loop (can be exited with break, continue, or return)
953 /// `'label: loop { block }`
954 Loop(P<Block>, Option<SpannedIdent>),
956 Match(P<Expr>, Vec<Arm>),
957 /// A closure (for example, `move |a, b, c| a + b + c`)
959 /// The final span is the span of the argument block `|...|`
960 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
961 /// A block (`{ ... }`)
963 /// A catch block (`catch { ... }`)
966 /// An assignment (`a = foo()`)
967 Assign(P<Expr>, P<Expr>),
968 /// An assignment with an operator
970 /// For example, `a += 1`.
971 AssignOp(BinOp, P<Expr>, P<Expr>),
972 /// Access of a named struct field (`obj.foo`)
973 Field(P<Expr>, SpannedIdent),
974 /// Access of an unnamed field of a struct or tuple-struct
976 /// For example, `foo.0`.
977 TupField(P<Expr>, Spanned<usize>),
978 /// An indexing operation (`foo[2]`)
979 Index(P<Expr>, P<Expr>),
980 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
981 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
983 /// Variable reference, possibly containing `::` and/or type
984 /// parameters, e.g. foo::bar::<baz>.
986 /// Optionally "qualified",
987 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
988 Path(Option<QSelf>, Path),
990 /// A referencing operation (`&a` or `&mut a`)
991 AddrOf(Mutability, P<Expr>),
992 /// A `break`, with an optional label to break, and an optional expression
993 Break(Option<SpannedIdent>, Option<P<Expr>>),
994 /// A `continue`, with an optional label
995 Continue(Option<SpannedIdent>),
996 /// A `return`, with an optional value to be returned
997 Ret(Option<P<Expr>>),
999 /// Output of the `asm!()` macro
1000 InlineAsm(P<InlineAsm>),
1002 /// A macro invocation; pre-expansion
1005 /// A struct literal expression.
1007 /// For example, `Foo {x: 1, y: 2}`, or
1008 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1009 Struct(Path, Vec<Field>, Option<P<Expr>>),
1011 /// An array literal constructed from one repeated element.
1013 /// For example, `[1; 5]`. The first expression is the element
1014 /// to be repeated; the second is the number of times to repeat it.
1015 Repeat(P<Expr>, P<Expr>),
1017 /// No-op: used solely so we can pretty-print faithfully
1024 /// The explicit Self type in a "qualified path". The actual
1025 /// path, including the trait and the associated item, is stored
1026 /// separately. `position` represents the index of the associated
1027 /// item qualified with this Self type.
1030 /// <Vec<T> as a::b::Trait>::AssociatedItem
1031 /// ^~~~~ ~~~~~~~~~~~~~~^
1034 /// <Vec<T>>::AssociatedItem
1038 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1044 /// A capture clause
1045 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1046 pub enum CaptureBy {
1051 pub type Mac = Spanned<Mac_>;
1053 /// Represents a macro invocation. The Path indicates which macro
1054 /// is being invoked, and the vector of token-trees contains the source
1055 /// of the macro invocation.
1057 /// NB: the additional ident for a macro_rules-style macro is actually
1058 /// stored in the enclosing item. Oog.
1059 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1062 pub tts: ThinTokenStream,
1066 pub fn stream(&self) -> TokenStream {
1067 self.tts.clone().into()
1071 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1073 /// A regular string, like `"foo"`
1075 /// A raw string, like `r##"foo"##`
1077 /// The uint is the number of `#` symbols used
1082 pub type Lit = Spanned<LitKind>;
1084 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1085 pub enum LitIntType {
1093 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1094 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1096 /// A string literal (`"foo"`)
1097 Str(Symbol, StrStyle),
1098 /// A byte string (`b"foo"`)
1099 ByteStr(Rc<Vec<u8>>),
1100 /// A byte char (`b'f'`)
1102 /// A character literal (`'a'`)
1104 /// An integer literal (`1`)
1105 Int(u128, LitIntType),
1106 /// A float literal (`1f64` or `1E10f64`)
1107 Float(Symbol, FloatTy),
1108 /// A float literal without a suffix (`1.0 or 1.0E10`)
1109 FloatUnsuffixed(Symbol),
1110 /// A boolean literal
1115 /// Returns true if this literal is a string and false otherwise.
1116 pub fn is_str(&self) -> bool {
1118 LitKind::Str(..) => true,
1123 /// Returns true if this literal has no suffix. Note: this will return true
1124 /// for literals with prefixes such as raw strings and byte strings.
1125 pub fn is_unsuffixed(&self) -> bool {
1127 // unsuffixed variants
1128 LitKind::Str(..) => true,
1129 LitKind::ByteStr(..) => true,
1130 LitKind::Byte(..) => true,
1131 LitKind::Char(..) => true,
1132 LitKind::Int(_, LitIntType::Unsuffixed) => true,
1133 LitKind::FloatUnsuffixed(..) => true,
1134 LitKind::Bool(..) => true,
1135 // suffixed variants
1136 LitKind::Int(_, LitIntType::Signed(..)) => false,
1137 LitKind::Int(_, LitIntType::Unsigned(..)) => false,
1138 LitKind::Float(..) => false,
1142 /// Returns true if this literal has a suffix.
1143 pub fn is_suffixed(&self) -> bool {
1144 !self.is_unsuffixed()
1148 // NB: If you change this, you'll probably want to change the corresponding
1149 // type structure in middle/ty.rs as well.
1150 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1153 pub mutbl: Mutability,
1156 /// Represents a method's signature in a trait declaration,
1157 /// or in an implementation.
1158 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1159 pub struct MethodSig {
1160 pub unsafety: Unsafety,
1161 pub constness: Spanned<Constness>,
1163 pub decl: P<FnDecl>,
1164 pub generics: Generics,
1167 /// Represents an item declaration within a trait declaration,
1168 /// possibly including a default implementation. A trait item is
1169 /// either required (meaning it doesn't have an implementation, just a
1170 /// signature) or provided (meaning it has a default implementation).
1171 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1172 pub struct TraitItem {
1175 pub attrs: Vec<Attribute>,
1176 pub node: TraitItemKind,
1180 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1181 pub enum TraitItemKind {
1182 Const(P<Ty>, Option<P<Expr>>),
1183 Method(MethodSig, Option<P<Block>>),
1184 Type(TyParamBounds, Option<P<Ty>>),
1188 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1189 pub struct ImplItem {
1192 pub vis: Visibility,
1193 pub defaultness: Defaultness,
1194 pub attrs: Vec<Attribute>,
1195 pub node: ImplItemKind,
1199 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1200 pub enum ImplItemKind {
1201 Const(P<Ty>, P<Expr>),
1202 Method(MethodSig, P<Block>),
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1217 impl fmt::Debug for IntTy {
1218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1219 fmt::Display::fmt(self, f)
1223 impl fmt::Display for IntTy {
1224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1225 write!(f, "{}", self.ty_to_string())
1230 pub fn ty_to_string(&self) -> &'static str {
1232 IntTy::Is => "isize",
1234 IntTy::I16 => "i16",
1235 IntTy::I32 => "i32",
1236 IntTy::I64 => "i64",
1237 IntTy::I128 => "i128",
1241 pub fn val_to_string(&self, val: i128) -> String {
1242 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1243 // are parsed as u128, so we wouldn't want to print an extra negative
1245 format!("{}{}", val as u128, self.ty_to_string())
1248 pub fn bit_width(&self) -> Option<usize> {
1250 IntTy::Is => return None,
1260 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1271 pub fn ty_to_string(&self) -> &'static str {
1273 UintTy::Us => "usize",
1275 UintTy::U16 => "u16",
1276 UintTy::U32 => "u32",
1277 UintTy::U64 => "u64",
1278 UintTy::U128 => "u128",
1282 pub fn val_to_string(&self, val: u128) -> String {
1283 format!("{}{}", val, self.ty_to_string())
1286 pub fn bit_width(&self) -> Option<usize> {
1288 UintTy::Us => return None,
1293 UintTy::U128 => 128,
1298 impl fmt::Debug for UintTy {
1299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1300 fmt::Display::fmt(self, f)
1304 impl fmt::Display for UintTy {
1305 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1306 write!(f, "{}", self.ty_to_string())
1310 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1316 impl fmt::Debug for FloatTy {
1317 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1318 fmt::Display::fmt(self, f)
1322 impl fmt::Display for FloatTy {
1323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1324 write!(f, "{}", self.ty_to_string())
1329 pub fn ty_to_string(&self) -> &'static str {
1331 FloatTy::F32 => "f32",
1332 FloatTy::F64 => "f64",
1336 pub fn bit_width(&self) -> usize {
1344 // Bind a type to an associated type: `A=Foo`.
1345 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1346 pub struct TypeBinding {
1353 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1360 impl fmt::Debug for Ty {
1361 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1362 write!(f, "type({})", pprust::ty_to_string(self))
1366 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1367 pub struct BareFnTy {
1368 pub unsafety: Unsafety,
1370 pub lifetimes: Vec<LifetimeDef>,
1374 /// The different kinds of types recognized by the compiler
1375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1377 /// A variable-length slice (`[T]`)
1379 /// A fixed length array (`[T; n]`)
1380 Array(P<Ty>, P<Expr>),
1381 /// A raw pointer (`*const T` or `*mut T`)
1383 /// A reference (`&'a T` or `&'a mut T`)
1384 Rptr(Option<Lifetime>, MutTy),
1385 /// A bare function (e.g. `fn(usize) -> bool`)
1386 BareFn(P<BareFnTy>),
1387 /// The never type (`!`)
1389 /// A tuple (`(A, B, C, D,...)`)
1391 /// A path (`module::module::...::Type`), optionally
1392 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1394 /// Type parameters are stored in the Path itself
1395 Path(Option<QSelf>, Path),
1396 /// A trait object type `Bound1 + Bound2 + Bound3`
1397 /// where `Bound` is a trait or a lifetime.
1398 TraitObject(TyParamBounds),
1399 /// An `impl Bound1 + Bound2 + Bound3` type
1400 /// where `Bound` is a trait or a lifetime.
1401 ImplTrait(TyParamBounds),
1402 /// No-op; kept solely so that we can pretty-print faithfully
1406 /// TyKind::Infer means the type should be inferred instead of it having been
1407 /// specified. This can appear anywhere in a type.
1409 /// Inferred type of a `self` or `&self` argument in a method.
1411 // A macro in the type position.
1415 /// Inline assembly dialect.
1417 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1418 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1419 pub enum AsmDialect {
1424 /// Inline assembly.
1426 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1427 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1428 pub struct InlineAsmOutput {
1429 pub constraint: Symbol,
1432 pub is_indirect: bool,
1435 /// Inline assembly.
1437 /// E.g. `asm!("NOP");`
1438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1439 pub struct InlineAsm {
1441 pub asm_str_style: StrStyle,
1442 pub outputs: Vec<InlineAsmOutput>,
1443 pub inputs: Vec<(Symbol, P<Expr>)>,
1444 pub clobbers: Vec<Symbol>,
1446 pub alignstack: bool,
1447 pub dialect: AsmDialect,
1448 pub expn_id: ExpnId,
1451 /// An argument in a function header.
1453 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1454 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1461 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1463 /// E.g. `&mut self` as in `fn foo(&mut self)`
1464 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1466 /// `self`, `mut self`
1468 /// `&'lt self`, `&'lt mut self`
1469 Region(Option<Lifetime>, Mutability),
1470 /// `self: TYPE`, `mut self: TYPE`
1471 Explicit(P<Ty>, Mutability),
1474 pub type ExplicitSelf = Spanned<SelfKind>;
1477 pub fn to_self(&self) -> Option<ExplicitSelf> {
1478 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1479 if ident.node.name == keywords::SelfValue.name() {
1480 return match self.ty.node {
1481 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1482 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1483 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1485 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1486 SelfKind::Explicit(self.ty.clone(), mutbl))),
1493 pub fn is_self(&self) -> bool {
1494 if let PatKind::Ident(_, ident, _) = self.pat.node {
1495 ident.node.name == keywords::SelfValue.name()
1501 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1502 let span = mk_sp(eself.span.lo, eself_ident.span.hi);
1503 let infer_ty = P(Ty {
1505 node: TyKind::ImplicitSelf,
1508 let arg = |mutbl, ty| Arg {
1511 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1518 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1519 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1520 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1522 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1529 /// Header (not the body) of a function declaration.
1531 /// E.g. `fn foo(bar: baz)`
1532 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1534 pub inputs: Vec<Arg>,
1535 pub output: FunctionRetTy,
1540 pub fn get_self(&self) -> Option<ExplicitSelf> {
1541 self.inputs.get(0).and_then(Arg::to_self)
1543 pub fn has_self(&self) -> bool {
1544 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1548 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1554 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1555 pub enum Constness {
1560 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1561 pub enum Defaultness {
1566 impl fmt::Display for Unsafety {
1567 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1568 fmt::Display::fmt(match *self {
1569 Unsafety::Normal => "normal",
1570 Unsafety::Unsafe => "unsafe",
1575 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1576 pub enum ImplPolarity {
1577 /// `impl Trait for Type`
1579 /// `impl !Trait for Type`
1583 impl fmt::Debug for ImplPolarity {
1584 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1586 ImplPolarity::Positive => "positive".fmt(f),
1587 ImplPolarity::Negative => "negative".fmt(f),
1593 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1594 pub enum FunctionRetTy {
1595 /// Return type is not specified.
1597 /// Functions default to `()` and
1598 /// closures default to inference. Span points to where return
1599 /// type would be inserted.
1605 impl FunctionRetTy {
1606 pub fn span(&self) -> Span {
1608 FunctionRetTy::Default(span) => span,
1609 FunctionRetTy::Ty(ref ty) => ty.span,
1614 /// Module declaration.
1616 /// E.g. `mod foo;` or `mod foo { .. }`
1617 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1619 /// A span from the first token past `{` to the last token until `}`.
1620 /// For `mod foo;`, the inner span ranges from the first token
1621 /// to the last token in the external file.
1623 pub items: Vec<P<Item>>,
1626 /// Foreign module declaration.
1628 /// E.g. `extern { .. }` or `extern C { .. }`
1629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1630 pub struct ForeignMod {
1632 pub items: Vec<ForeignItem>,
1635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1636 pub struct EnumDef {
1637 pub variants: Vec<Variant>,
1640 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1641 pub struct Variant_ {
1643 pub attrs: Vec<Attribute>,
1644 pub data: VariantData,
1645 /// Explicit discriminant, e.g. `Foo = 1`
1646 pub disr_expr: Option<P<Expr>>,
1649 pub type Variant = Spanned<Variant_>;
1651 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1652 pub struct PathListItem_ {
1654 /// renamed in list, e.g. `use foo::{bar as baz};`
1655 pub rename: Option<Ident>,
1659 pub type PathListItem = Spanned<PathListItem_>;
1661 pub type ViewPath = Spanned<ViewPath_>;
1663 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1664 pub enum ViewPath_ {
1666 /// `foo::bar::baz as quux`
1670 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1671 ViewPathSimple(Ident, Path),
1676 /// `foo::bar::{a,b,c}`
1677 ViewPathList(Path, Vec<PathListItem>)
1681 pub fn path(&self) -> &Path {
1683 ViewPathSimple(_, ref path) |
1684 ViewPathGlob (ref path) |
1685 ViewPathList(ref path, _) => path
1691 /// Distinguishes between Attributes that decorate items and Attributes that
1692 /// are contained as statements within items. These two cases need to be
1693 /// distinguished for pretty-printing.
1694 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1695 pub enum AttrStyle {
1700 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1701 pub struct AttrId(pub usize);
1703 /// Meta-data associated with an item
1704 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1706 pub struct Attribute {
1708 pub style: AttrStyle,
1710 pub tokens: TokenStream,
1711 pub is_sugared_doc: bool,
1715 /// TraitRef's appear in impls.
1717 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1718 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1719 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1720 /// same as the impl's node id).
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1722 pub struct TraitRef {
1727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1728 pub struct PolyTraitRef {
1729 /// The `'a` in `<'a> Foo<&'a T>`
1730 pub bound_lifetimes: Vec<LifetimeDef>,
1732 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1733 pub trait_ref: TraitRef,
1739 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, lo: BytePos, hi: BytePos) -> Self {
1741 bound_lifetimes: lifetimes,
1742 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1743 span: mk_sp(lo, hi),
1748 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1749 pub enum Visibility {
1752 Restricted { path: P<Path>, id: NodeId },
1756 /// Field of a struct.
1758 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1759 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1760 pub struct StructField {
1762 pub ident: Option<Ident>,
1763 pub vis: Visibility,
1766 pub attrs: Vec<Attribute>,
1769 /// Fields and Ids of enum variants and structs
1771 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1772 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1773 /// One shared Id can be successfully used for these two purposes.
1774 /// Id of the whole enum lives in `Item`.
1776 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1777 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1778 /// the variant itself" from enum variants.
1779 /// Id of the whole struct lives in `Item`.
1780 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1781 pub enum VariantData {
1784 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1785 Struct(Vec<StructField>, NodeId),
1788 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1789 Tuple(Vec<StructField>, NodeId),
1792 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1797 pub fn fields(&self) -> &[StructField] {
1799 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1803 pub fn id(&self) -> NodeId {
1805 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1808 pub fn is_struct(&self) -> bool {
1809 if let VariantData::Struct(..) = *self { true } else { false }
1811 pub fn is_tuple(&self) -> bool {
1812 if let VariantData::Tuple(..) = *self { true } else { false }
1814 pub fn is_unit(&self) -> bool {
1815 if let VariantData::Unit(..) = *self { true } else { false }
1821 /// The name might be a dummy name in case of anonymous items
1822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1825 pub attrs: Vec<Attribute>,
1828 pub vis: Visibility,
1832 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1834 /// An`extern crate` item, with optional original crate name.
1836 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1837 ExternCrate(Option<Name>),
1838 /// A use declaration (`use` or `pub use`) item.
1840 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1842 /// A static item (`static` or `pub static`).
1844 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1845 Static(P<Ty>, Mutability, P<Expr>),
1846 /// A constant item (`const` or `pub const`).
1848 /// E.g. `const FOO: i32 = 42;`
1849 Const(P<Ty>, P<Expr>),
1850 /// A function declaration (`fn` or `pub fn`).
1852 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1853 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1854 /// A module declaration (`mod` or `pub mod`).
1856 /// E.g. `mod foo;` or `mod foo { .. }`
1858 /// An external module (`extern` or `pub extern`).
1860 /// E.g. `extern {}` or `extern "C" {}`
1861 ForeignMod(ForeignMod),
1862 /// A type alias (`type` or `pub type`).
1864 /// E.g. `type Foo = Bar<u8>;`
1865 Ty(P<Ty>, Generics),
1866 /// An enum definition (`enum` or `pub enum`).
1868 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1869 Enum(EnumDef, Generics),
1870 /// A struct definition (`struct` or `pub struct`).
1872 /// E.g. `struct Foo<A> { x: A }`
1873 Struct(VariantData, Generics),
1874 /// A union definition (`union` or `pub union`).
1876 /// E.g. `union Foo<A, B> { x: A, y: B }`
1877 Union(VariantData, Generics),
1878 /// A Trait declaration (`trait` or `pub trait`).
1880 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1881 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1882 // Default trait implementation.
1884 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1885 DefaultImpl(Unsafety, TraitRef),
1886 /// An implementation.
1888 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1892 Option<TraitRef>, // (optional) trait this impl implements
1895 /// A macro invocation.
1897 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1900 /// A macro definition.
1901 MacroDef(ThinTokenStream),
1905 pub fn descriptive_variant(&self) -> &str {
1907 ItemKind::ExternCrate(..) => "extern crate",
1908 ItemKind::Use(..) => "use",
1909 ItemKind::Static(..) => "static item",
1910 ItemKind::Const(..) => "constant item",
1911 ItemKind::Fn(..) => "function",
1912 ItemKind::Mod(..) => "module",
1913 ItemKind::ForeignMod(..) => "foreign module",
1914 ItemKind::Ty(..) => "type alias",
1915 ItemKind::Enum(..) => "enum",
1916 ItemKind::Struct(..) => "struct",
1917 ItemKind::Union(..) => "union",
1918 ItemKind::Trait(..) => "trait",
1920 ItemKind::MacroDef(..) |
1921 ItemKind::Impl(..) |
1922 ItemKind::DefaultImpl(..) => "item"
1927 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1928 pub struct ForeignItem {
1930 pub attrs: Vec<Attribute>,
1931 pub node: ForeignItemKind,
1934 pub vis: Visibility,
1937 /// An item within an `extern` block
1938 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1939 pub enum ForeignItemKind {
1940 /// A foreign function
1941 Fn(P<FnDecl>, Generics),
1942 /// A foreign static item (`static ext: u8`), with optional mutability
1943 /// (the boolean is true when mutable)
1944 Static(P<Ty>, bool),
1947 impl ForeignItemKind {
1948 pub fn descriptive_variant(&self) -> &str {
1950 ForeignItemKind::Fn(..) => "foreign function",
1951 ForeignItemKind::Static(..) => "foreign static item"
1961 // are ASTs encodable?
1963 fn check_asts_encodable() {
1964 fn assert_encodable<T: serialize::Encodable>() {}
1965 assert_encodable::<Crate>();