]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/ast.rs
New upstream version 1.17.0+dfsg1
[rustc.git] / src / libsyntax / ast.rs
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.
4 //
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.
10
11 // The Rust abstract syntax tree.
12
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;
19
20 use syntax_pos::{mk_sp, Span, DUMMY_SP, ExpnId};
21 use codemap::{respan, Spanned};
22 use abi::Abi;
23 use ext::hygiene::SyntaxContext;
24 use print::pprust;
25 use ptr::P;
26 use symbol::{Symbol, keywords};
27 use tokenstream::{ThinTokenStream, TokenStream};
28
29 use std::collections::HashSet;
30 use std::fmt;
31 use std::rc::Rc;
32 use std::u32;
33
34 use serialize::{self, Encodable, Decodable, Encoder, Decoder};
35
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)]
40 pub struct Ident {
41 pub name: Symbol,
42 pub ctxt: SyntaxContext
43 }
44
45 impl Ident {
46 pub const fn with_empty_ctxt(name: Name) -> Ident {
47 Ident { name: name, ctxt: SyntaxContext::empty() }
48 }
49
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))
53 }
54
55 pub fn unhygienize(&self) -> Ident {
56 Ident { name: self.name, ctxt: SyntaxContext::empty() }
57 }
58 }
59
60 impl fmt::Debug for Ident {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 write!(f, "{}{:?}", self.name, self.ctxt)
63 }
64 }
65
66 impl fmt::Display for Ident {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 fmt::Display::fmt(&self.name, f)
69 }
70 }
71
72 impl Encodable for Ident {
73 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
74 self.name.encode(s)
75 }
76 }
77
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)?))
81 }
82 }
83
84 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
85 pub struct Lifetime {
86 pub id: NodeId,
87 pub span: Span,
88 pub name: Name
89 }
90
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))
94 }
95 }
96
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>
103 }
104
105 /// A "Path" is essentially Rust's notion of a name.
106 ///
107 /// It's represented as a sequence of identifiers,
108 /// along with a bunch of supporting information.
109 ///
110 /// E.g. `std::cmp::PartialEq`
111 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
112 pub struct Path {
113 pub span: Span,
114 /// The segments in the path: the things separated by `::`.
115 /// Global paths begin with `keywords::CrateRoot`.
116 pub segments: Vec<PathSegment>,
117 }
118
119 impl fmt::Debug for Path {
120 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121 write!(f, "path({})", pprust::path_to_string(self))
122 }
123 }
124
125 impl fmt::Display for Path {
126 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127 write!(f, "{}", pprust::path_to_string(self))
128 }
129 }
130
131 impl Path {
132 // convert a span and an identifier to the corresponding
133 // 1-segment path
134 pub fn from_ident(s: Span, identifier: Ident) -> Path {
135 Path {
136 span: s,
137 segments: vec![PathSegment::from_ident(identifier, s)],
138 }
139 }
140
141 pub fn default_to_global(mut self) -> Path {
142 let name = self.segments[0].identifier.name;
143 if !self.is_global() && name != "$crate" &&
144 name != keywords::SelfValue.name() && name != keywords::Super.name() {
145 self.segments.insert(0, PathSegment::crate_root());
146 }
147 self
148 }
149
150 pub fn is_global(&self) -> bool {
151 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
152 }
153 }
154
155 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
156 ///
157 /// E.g. `std`, `String` or `Box<T>`
158 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
159 pub struct PathSegment {
160 /// The identifier portion of this path segment.
161 pub identifier: Ident,
162 /// Span of the segment identifier.
163 pub span: Span,
164
165 /// Type/lifetime parameters attached to this path. They come in
166 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
167 /// this is more than just simple syntactic sugar; the use of
168 /// parens affects the region binding rules, so we preserve the
169 /// distinction.
170 /// The `Option<P<..>>` wrapper is purely a size optimization;
171 /// `None` is used to represent both `Path` and `Path<>`.
172 pub parameters: Option<P<PathParameters>>,
173 }
174
175 impl PathSegment {
176 pub fn from_ident(ident: Ident, span: Span) -> Self {
177 PathSegment { identifier: ident, span: span, parameters: None }
178 }
179 pub fn crate_root() -> Self {
180 PathSegment {
181 identifier: keywords::CrateRoot.ident(),
182 span: DUMMY_SP,
183 parameters: None,
184 }
185 }
186 }
187
188 /// Parameters of a path segment.
189 ///
190 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
192 pub enum PathParameters {
193 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
194 AngleBracketed(AngleBracketedParameterData),
195 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
196 Parenthesized(ParenthesizedParameterData),
197 }
198
199 /// A path like `Foo<'a, T>`
200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
201 pub struct AngleBracketedParameterData {
202 /// The lifetime parameters for this path segment.
203 pub lifetimes: Vec<Lifetime>,
204 /// The type parameters for this path segment, if present.
205 pub types: Vec<P<Ty>>,
206 /// Bindings (equality constraints) on associated types, if present.
207 ///
208 /// E.g., `Foo<A=Bar>`.
209 pub bindings: Vec<TypeBinding>,
210 }
211
212 impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
213 fn into(self) -> Option<P<PathParameters>> {
214 let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
215 if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
216 }
217 }
218
219 /// A path like `Foo(A,B) -> C`
220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
221 pub struct ParenthesizedParameterData {
222 /// Overall span
223 pub span: Span,
224
225 /// `(A,B)`
226 pub inputs: Vec<P<Ty>>,
227
228 /// `C`
229 pub output: Option<P<Ty>>,
230 }
231
232 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
233 pub struct NodeId(u32);
234
235 impl NodeId {
236 pub fn new(x: usize) -> NodeId {
237 assert!(x < (u32::MAX as usize));
238 NodeId(x as u32)
239 }
240
241 pub fn from_u32(x: u32) -> NodeId {
242 NodeId(x)
243 }
244
245 pub fn as_usize(&self) -> usize {
246 self.0 as usize
247 }
248
249 pub fn as_u32(&self) -> u32 {
250 self.0
251 }
252 }
253
254 impl fmt::Display for NodeId {
255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
256 fmt::Display::fmt(&self.0, f)
257 }
258 }
259
260 impl serialize::UseSpecializedEncodable for NodeId {
261 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
262 s.emit_u32(self.0)
263 }
264 }
265
266 impl serialize::UseSpecializedDecodable for NodeId {
267 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
268 d.read_u32().map(NodeId)
269 }
270 }
271
272 /// Node id used to represent the root of the crate.
273 pub const CRATE_NODE_ID: NodeId = NodeId(0);
274
275 /// When parsing and doing expansions, we initially give all AST nodes this AST
276 /// node value. Then later, in the renumber pass, we renumber them to have
277 /// small, positive ids.
278 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
279
280 /// The AST represents all type param bounds as types.
281 /// typeck::collect::compute_bounds matches these against
282 /// the "special" built-in traits (see middle::lang_items) and
283 /// detects Copy, Send and Sync.
284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
285 pub enum TyParamBound {
286 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
287 RegionTyParamBound(Lifetime)
288 }
289
290 /// A modifier on a bound, currently this is only used for `?Sized`, where the
291 /// modifier is `Maybe`. Negative bounds should also be handled here.
292 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
293 pub enum TraitBoundModifier {
294 None,
295 Maybe,
296 }
297
298 pub type TyParamBounds = Vec<TyParamBound>;
299
300 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
301 pub struct TyParam {
302 pub attrs: ThinVec<Attribute>,
303 pub ident: Ident,
304 pub id: NodeId,
305 pub bounds: TyParamBounds,
306 pub default: Option<P<Ty>>,
307 pub span: Span,
308 }
309
310 /// Represents lifetimes and type parameters attached to a declaration
311 /// of a function, enum, trait, etc.
312 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
313 pub struct Generics {
314 pub lifetimes: Vec<LifetimeDef>,
315 pub ty_params: Vec<TyParam>,
316 pub where_clause: WhereClause,
317 pub span: Span,
318 }
319
320 impl Generics {
321 pub fn is_lt_parameterized(&self) -> bool {
322 !self.lifetimes.is_empty()
323 }
324 pub fn is_type_parameterized(&self) -> bool {
325 !self.ty_params.is_empty()
326 }
327 pub fn is_parameterized(&self) -> bool {
328 self.is_lt_parameterized() || self.is_type_parameterized()
329 }
330 pub fn span_for_name(&self, name: &str) -> Option<Span> {
331 for t in &self.ty_params {
332 if t.ident.name == name {
333 return Some(t.span);
334 }
335 }
336 None
337 }
338 }
339
340 impl Default for Generics {
341 /// Creates an instance of `Generics`.
342 fn default() -> Generics {
343 Generics {
344 lifetimes: Vec::new(),
345 ty_params: Vec::new(),
346 where_clause: WhereClause {
347 id: DUMMY_NODE_ID,
348 predicates: Vec::new(),
349 },
350 span: DUMMY_SP,
351 }
352 }
353 }
354
355 /// A `where` clause in a definition
356 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
357 pub struct WhereClause {
358 pub id: NodeId,
359 pub predicates: Vec<WherePredicate>,
360 }
361
362 /// A single predicate in a `where` clause
363 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
364 pub enum WherePredicate {
365 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
366 BoundPredicate(WhereBoundPredicate),
367 /// A lifetime predicate, e.g. `'a: 'b+'c`
368 RegionPredicate(WhereRegionPredicate),
369 /// An equality predicate (unsupported)
370 EqPredicate(WhereEqPredicate),
371 }
372
373 /// A type bound.
374 ///
375 /// E.g. `for<'c> Foo: Send+Clone+'c`
376 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
377 pub struct WhereBoundPredicate {
378 pub span: Span,
379 /// Any lifetimes from a `for` binding
380 pub bound_lifetimes: Vec<LifetimeDef>,
381 /// The type being bounded
382 pub bounded_ty: P<Ty>,
383 /// Trait and lifetime bounds (`Clone+Send+'static`)
384 pub bounds: TyParamBounds,
385 }
386
387 /// A lifetime predicate.
388 ///
389 /// E.g. `'a: 'b+'c`
390 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
391 pub struct WhereRegionPredicate {
392 pub span: Span,
393 pub lifetime: Lifetime,
394 pub bounds: Vec<Lifetime>,
395 }
396
397 /// An equality predicate (unsupported).
398 ///
399 /// E.g. `T=int`
400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
401 pub struct WhereEqPredicate {
402 pub id: NodeId,
403 pub span: Span,
404 pub lhs_ty: P<Ty>,
405 pub rhs_ty: P<Ty>,
406 }
407
408 /// The set of MetaItems that define the compilation environment of the crate,
409 /// used to drive conditional compilation
410 pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
411
412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
413 pub struct Crate {
414 pub module: Mod,
415 pub attrs: Vec<Attribute>,
416 pub span: Span,
417 }
418
419 /// A spanned compile-time attribute list item.
420 pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
421
422 /// Possible values inside of compile-time attribute lists.
423 ///
424 /// E.g. the '..' in `#[name(..)]`.
425 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
426 pub enum NestedMetaItemKind {
427 /// A full MetaItem, for recursive meta items.
428 MetaItem(MetaItem),
429 /// A literal.
430 ///
431 /// E.g. "foo", 64, true
432 Literal(Lit),
433 }
434
435 /// A spanned compile-time attribute item.
436 ///
437 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub struct MetaItem {
440 pub name: Name,
441 pub node: MetaItemKind,
442 pub span: Span,
443 }
444
445 /// A compile-time attribute item.
446 ///
447 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
448 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
449 pub enum MetaItemKind {
450 /// Word meta item.
451 ///
452 /// E.g. `test` as in `#[test]`
453 Word,
454 /// List meta item.
455 ///
456 /// E.g. `derive(..)` as in `#[derive(..)]`
457 List(Vec<NestedMetaItem>),
458 /// Name value meta item.
459 ///
460 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
461 NameValue(Lit)
462 }
463
464 /// A Block (`{ .. }`).
465 ///
466 /// E.g. `{ .. }` as in `fn foo() { .. }`
467 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
468 pub struct Block {
469 /// Statements in a block
470 pub stmts: Vec<Stmt>,
471 pub id: NodeId,
472 /// Distinguishes between `unsafe { ... }` and `{ ... }`
473 pub rules: BlockCheckMode,
474 pub span: Span,
475 }
476
477 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
478 pub struct Pat {
479 pub id: NodeId,
480 pub node: PatKind,
481 pub span: Span,
482 }
483
484 impl fmt::Debug for Pat {
485 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
486 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
487 }
488 }
489
490 impl Pat {
491 pub fn walk<F>(&self, it: &mut F) -> bool
492 where F: FnMut(&Pat) -> bool
493 {
494 if !it(self) {
495 return false;
496 }
497
498 match self.node {
499 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
500 PatKind::Struct(_, ref fields, _) => {
501 fields.iter().all(|field| field.node.pat.walk(it))
502 }
503 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
504 s.iter().all(|p| p.walk(it))
505 }
506 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
507 s.walk(it)
508 }
509 PatKind::Slice(ref before, ref slice, ref after) => {
510 before.iter().all(|p| p.walk(it)) &&
511 slice.iter().all(|p| p.walk(it)) &&
512 after.iter().all(|p| p.walk(it))
513 }
514 PatKind::Wild |
515 PatKind::Lit(_) |
516 PatKind::Range(..) |
517 PatKind::Ident(..) |
518 PatKind::Path(..) |
519 PatKind::Mac(_) => {
520 true
521 }
522 }
523 }
524 }
525
526 /// A single field in a struct pattern
527 ///
528 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
529 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
530 /// except is_shorthand is true
531 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
532 pub struct FieldPat {
533 /// The identifier for the field
534 pub ident: Ident,
535 /// The pattern the field is destructured to
536 pub pat: P<Pat>,
537 pub is_shorthand: bool,
538 pub attrs: ThinVec<Attribute>,
539 }
540
541 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
542 pub enum BindingMode {
543 ByRef(Mutability),
544 ByValue(Mutability),
545 }
546
547 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
548 pub enum RangeEnd {
549 Included,
550 Excluded,
551 }
552
553 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
554 pub enum PatKind {
555 /// Represents a wildcard pattern (`_`)
556 Wild,
557
558 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
559 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
560 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
561 /// during name resolution.
562 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
563
564 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
565 /// The `bool` is `true` in the presence of a `..`.
566 Struct(Path, Vec<Spanned<FieldPat>>, bool),
567
568 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
569 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
570 /// 0 <= position <= subpats.len()
571 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
572
573 /// A possibly qualified path pattern.
574 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
575 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
576 /// only legally refer to associated constants.
577 Path(Option<QSelf>, Path),
578
579 /// A tuple pattern `(a, b)`.
580 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
581 /// 0 <= position <= subpats.len()
582 Tuple(Vec<P<Pat>>, Option<usize>),
583 /// A `box` pattern
584 Box(P<Pat>),
585 /// A reference pattern, e.g. `&mut (a, b)`
586 Ref(P<Pat>, Mutability),
587 /// A literal
588 Lit(P<Expr>),
589 /// A range pattern, e.g. `1...2` or `1..2`
590 Range(P<Expr>, P<Expr>, RangeEnd),
591 /// `[a, b, ..i, y, z]` is represented as:
592 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
593 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
594 /// A macro pattern; pre-expansion
595 Mac(Mac),
596 }
597
598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
599 pub enum Mutability {
600 Mutable,
601 Immutable,
602 }
603
604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
605 pub enum BinOpKind {
606 /// The `+` operator (addition)
607 Add,
608 /// The `-` operator (subtraction)
609 Sub,
610 /// The `*` operator (multiplication)
611 Mul,
612 /// The `/` operator (division)
613 Div,
614 /// The `%` operator (modulus)
615 Rem,
616 /// The `&&` operator (logical and)
617 And,
618 /// The `||` operator (logical or)
619 Or,
620 /// The `^` operator (bitwise xor)
621 BitXor,
622 /// The `&` operator (bitwise and)
623 BitAnd,
624 /// The `|` operator (bitwise or)
625 BitOr,
626 /// The `<<` operator (shift left)
627 Shl,
628 /// The `>>` operator (shift right)
629 Shr,
630 /// The `==` operator (equality)
631 Eq,
632 /// The `<` operator (less than)
633 Lt,
634 /// The `<=` operator (less than or equal to)
635 Le,
636 /// The `!=` operator (not equal to)
637 Ne,
638 /// The `>=` operator (greater than or equal to)
639 Ge,
640 /// The `>` operator (greater than)
641 Gt,
642 }
643
644 impl BinOpKind {
645 pub fn to_string(&self) -> &'static str {
646 use self::BinOpKind::*;
647 match *self {
648 Add => "+",
649 Sub => "-",
650 Mul => "*",
651 Div => "/",
652 Rem => "%",
653 And => "&&",
654 Or => "||",
655 BitXor => "^",
656 BitAnd => "&",
657 BitOr => "|",
658 Shl => "<<",
659 Shr => ">>",
660 Eq => "==",
661 Lt => "<",
662 Le => "<=",
663 Ne => "!=",
664 Ge => ">=",
665 Gt => ">",
666 }
667 }
668 pub fn lazy(&self) -> bool {
669 match *self {
670 BinOpKind::And | BinOpKind::Or => true,
671 _ => false
672 }
673 }
674
675 pub fn is_shift(&self) -> bool {
676 match *self {
677 BinOpKind::Shl | BinOpKind::Shr => true,
678 _ => false
679 }
680 }
681 pub fn is_comparison(&self) -> bool {
682 use self::BinOpKind::*;
683 match *self {
684 Eq | Lt | Le | Ne | Gt | Ge =>
685 true,
686 And | Or | Add | Sub | Mul | Div | Rem |
687 BitXor | BitAnd | BitOr | Shl | Shr =>
688 false,
689 }
690 }
691 /// Returns `true` if the binary operator takes its arguments by value
692 pub fn is_by_value(&self) -> bool {
693 !self.is_comparison()
694 }
695 }
696
697 pub type BinOp = Spanned<BinOpKind>;
698
699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
700 pub enum UnOp {
701 /// The `*` operator for dereferencing
702 Deref,
703 /// The `!` operator for logical inversion
704 Not,
705 /// The `-` operator for negation
706 Neg,
707 }
708
709 impl UnOp {
710 /// Returns `true` if the unary operator takes its argument by value
711 pub fn is_by_value(u: UnOp) -> bool {
712 match u {
713 UnOp::Neg | UnOp::Not => true,
714 _ => false,
715 }
716 }
717
718 pub fn to_string(op: UnOp) -> &'static str {
719 match op {
720 UnOp::Deref => "*",
721 UnOp::Not => "!",
722 UnOp::Neg => "-",
723 }
724 }
725 }
726
727 /// A statement
728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
729 pub struct Stmt {
730 pub id: NodeId,
731 pub node: StmtKind,
732 pub span: Span,
733 }
734
735 impl Stmt {
736 pub fn add_trailing_semicolon(mut self) -> Self {
737 self.node = match self.node {
738 StmtKind::Expr(expr) => StmtKind::Semi(expr),
739 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
740 (mac, MacStmtStyle::Semicolon, attrs)
741 })),
742 node @ _ => node,
743 };
744 self
745 }
746 }
747
748 impl fmt::Debug for Stmt {
749 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
750 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
751 }
752 }
753
754
755 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
756 pub enum StmtKind {
757 /// A local (let) binding.
758 Local(P<Local>),
759
760 /// An item definition.
761 Item(P<Item>),
762
763 /// Expr without trailing semi-colon.
764 Expr(P<Expr>),
765
766 Semi(P<Expr>),
767
768 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
769 }
770
771 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
772 pub enum MacStmtStyle {
773 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
774 /// `foo!(...);`, `foo![...];`
775 Semicolon,
776 /// The macro statement had braces; e.g. foo! { ... }
777 Braces,
778 /// The macro statement had parentheses or brackets and no semicolon; e.g.
779 /// `foo!(...)`. All of these will end up being converted into macro
780 /// expressions.
781 NoBraces,
782 }
783
784 // FIXME (pending discussion of #1697, #2178...): local should really be
785 // a refinement on pat.
786 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
787 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
788 pub struct Local {
789 pub pat: P<Pat>,
790 pub ty: Option<P<Ty>>,
791 /// Initializer expression to set the value, if any
792 pub init: Option<P<Expr>>,
793 pub id: NodeId,
794 pub span: Span,
795 pub attrs: ThinVec<Attribute>,
796 }
797
798 /// An arm of a 'match'.
799 ///
800 /// E.g. `0...10 => { println!("match!") }` as in
801 ///
802 /// ```rust,ignore
803 /// match n {
804 /// 0...10 => { println!("match!") },
805 /// // ..
806 /// }
807 /// ```
808 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
809 pub struct Arm {
810 pub attrs: Vec<Attribute>,
811 pub pats: Vec<P<Pat>>,
812 pub guard: Option<P<Expr>>,
813 pub body: P<Expr>,
814 }
815
816 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
817 pub struct Field {
818 pub ident: SpannedIdent,
819 pub expr: P<Expr>,
820 pub span: Span,
821 pub is_shorthand: bool,
822 pub attrs: ThinVec<Attribute>,
823 }
824
825 pub type SpannedIdent = Spanned<Ident>;
826
827 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
828 pub enum BlockCheckMode {
829 Default,
830 Unsafe(UnsafeSource),
831 }
832
833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
834 pub enum UnsafeSource {
835 CompilerGenerated,
836 UserProvided,
837 }
838
839 /// An expression
840 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
841 pub struct Expr {
842 pub id: NodeId,
843 pub node: ExprKind,
844 pub span: Span,
845 pub attrs: ThinVec<Attribute>
846 }
847
848 impl fmt::Debug for Expr {
849 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
850 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
851 }
852 }
853
854 /// Limit types of a range (inclusive or exclusive)
855 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
856 pub enum RangeLimits {
857 /// Inclusive at the beginning, exclusive at the end
858 HalfOpen,
859 /// Inclusive at the beginning and end
860 Closed,
861 }
862
863 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
864 pub enum ExprKind {
865 /// A `box x` expression.
866 Box(P<Expr>),
867 /// First expr is the place; second expr is the value.
868 InPlace(P<Expr>, P<Expr>),
869 /// An array (`[a, b, c, d]`)
870 Array(Vec<P<Expr>>),
871 /// A function call
872 ///
873 /// The first field resolves to the function itself,
874 /// and the second field is the list of arguments
875 Call(P<Expr>, Vec<P<Expr>>),
876 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
877 ///
878 /// The `SpannedIdent` is the identifier for the method name.
879 /// The vector of `Ty`s are the ascripted type parameters for the method
880 /// (within the angle brackets).
881 ///
882 /// The first element of the vector of `Expr`s is the expression that evaluates
883 /// to the object on which the method is being called on (the receiver),
884 /// and the remaining elements are the rest of the arguments.
885 ///
886 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
887 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
888 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
889 /// A tuple (`(a, b, c ,d)`)
890 Tup(Vec<P<Expr>>),
891 /// A binary operation (For example: `a + b`, `a * b`)
892 Binary(BinOp, P<Expr>, P<Expr>),
893 /// A unary operation (For example: `!x`, `*x`)
894 Unary(UnOp, P<Expr>),
895 /// A literal (For example: `1`, `"foo"`)
896 Lit(P<Lit>),
897 /// A cast (`foo as f64`)
898 Cast(P<Expr>, P<Ty>),
899 Type(P<Expr>, P<Ty>),
900 /// An `if` block, with an optional else block
901 ///
902 /// `if expr { block } else { expr }`
903 If(P<Expr>, P<Block>, Option<P<Expr>>),
904 /// An `if let` expression with an optional else block
905 ///
906 /// `if let pat = expr { block } else { expr }`
907 ///
908 /// This is desugared to a `match` expression.
909 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
910 /// A while loop, with an optional label
911 ///
912 /// `'label: while expr { block }`
913 While(P<Expr>, P<Block>, Option<SpannedIdent>),
914 /// A while-let loop, with an optional label
915 ///
916 /// `'label: while let pat = expr { block }`
917 ///
918 /// This is desugared to a combination of `loop` and `match` expressions.
919 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
920 /// A for loop, with an optional label
921 ///
922 /// `'label: for pat in expr { block }`
923 ///
924 /// This is desugared to a combination of `loop` and `match` expressions.
925 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
926 /// Conditionless loop (can be exited with break, continue, or return)
927 ///
928 /// `'label: loop { block }`
929 Loop(P<Block>, Option<SpannedIdent>),
930 /// A `match` block.
931 Match(P<Expr>, Vec<Arm>),
932 /// A closure (for example, `move |a, b, c| a + b + c`)
933 ///
934 /// The final span is the span of the argument block `|...|`
935 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
936 /// A block (`{ ... }`)
937 Block(P<Block>),
938
939 /// An assignment (`a = foo()`)
940 Assign(P<Expr>, P<Expr>),
941 /// An assignment with an operator
942 ///
943 /// For example, `a += 1`.
944 AssignOp(BinOp, P<Expr>, P<Expr>),
945 /// Access of a named struct field (`obj.foo`)
946 Field(P<Expr>, SpannedIdent),
947 /// Access of an unnamed field of a struct or tuple-struct
948 ///
949 /// For example, `foo.0`.
950 TupField(P<Expr>, Spanned<usize>),
951 /// An indexing operation (`foo[2]`)
952 Index(P<Expr>, P<Expr>),
953 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
954 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
955
956 /// Variable reference, possibly containing `::` and/or type
957 /// parameters, e.g. foo::bar::<baz>.
958 ///
959 /// Optionally "qualified",
960 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
961 Path(Option<QSelf>, Path),
962
963 /// A referencing operation (`&a` or `&mut a`)
964 AddrOf(Mutability, P<Expr>),
965 /// A `break`, with an optional label to break, and an optional expression
966 Break(Option<SpannedIdent>, Option<P<Expr>>),
967 /// A `continue`, with an optional label
968 Continue(Option<SpannedIdent>),
969 /// A `return`, with an optional value to be returned
970 Ret(Option<P<Expr>>),
971
972 /// Output of the `asm!()` macro
973 InlineAsm(P<InlineAsm>),
974
975 /// A macro invocation; pre-expansion
976 Mac(Mac),
977
978 /// A struct literal expression.
979 ///
980 /// For example, `Foo {x: 1, y: 2}`, or
981 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
982 Struct(Path, Vec<Field>, Option<P<Expr>>),
983
984 /// An array literal constructed from one repeated element.
985 ///
986 /// For example, `[1; 5]`. The first expression is the element
987 /// to be repeated; the second is the number of times to repeat it.
988 Repeat(P<Expr>, P<Expr>),
989
990 /// No-op: used solely so we can pretty-print faithfully
991 Paren(P<Expr>),
992
993 /// `expr?`
994 Try(P<Expr>),
995 }
996
997 /// The explicit Self type in a "qualified path". The actual
998 /// path, including the trait and the associated item, is stored
999 /// separately. `position` represents the index of the associated
1000 /// item qualified with this Self type.
1001 ///
1002 /// ```rust,ignore
1003 /// <Vec<T> as a::b::Trait>::AssociatedItem
1004 /// ^~~~~ ~~~~~~~~~~~~~~^
1005 /// ty position = 3
1006 ///
1007 /// <Vec<T>>::AssociatedItem
1008 /// ^~~~~ ^
1009 /// ty position = 0
1010 /// ```
1011 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1012 pub struct QSelf {
1013 pub ty: P<Ty>,
1014 pub position: usize
1015 }
1016
1017 /// A capture clause
1018 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1019 pub enum CaptureBy {
1020 Value,
1021 Ref,
1022 }
1023
1024 pub type Mac = Spanned<Mac_>;
1025
1026 /// Represents a macro invocation. The Path indicates which macro
1027 /// is being invoked, and the vector of token-trees contains the source
1028 /// of the macro invocation.
1029 ///
1030 /// NB: the additional ident for a macro_rules-style macro is actually
1031 /// stored in the enclosing item. Oog.
1032 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1033 pub struct Mac_ {
1034 pub path: Path,
1035 pub tts: ThinTokenStream,
1036 }
1037
1038 impl Mac_ {
1039 pub fn stream(&self) -> TokenStream {
1040 self.tts.clone().into()
1041 }
1042 }
1043
1044 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1045 pub enum StrStyle {
1046 /// A regular string, like `"foo"`
1047 Cooked,
1048 /// A raw string, like `r##"foo"##`
1049 ///
1050 /// The uint is the number of `#` symbols used
1051 Raw(usize)
1052 }
1053
1054 /// A literal
1055 pub type Lit = Spanned<LitKind>;
1056
1057 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1058 pub enum LitIntType {
1059 Signed(IntTy),
1060 Unsigned(UintTy),
1061 Unsuffixed,
1062 }
1063
1064 /// Literal kind.
1065 ///
1066 /// E.g. `"foo"`, `42`, `12.34` or `bool`
1067 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1068 pub enum LitKind {
1069 /// A string literal (`"foo"`)
1070 Str(Symbol, StrStyle),
1071 /// A byte string (`b"foo"`)
1072 ByteStr(Rc<Vec<u8>>),
1073 /// A byte char (`b'f'`)
1074 Byte(u8),
1075 /// A character literal (`'a'`)
1076 Char(char),
1077 /// An integer literal (`1`)
1078 Int(u128, LitIntType),
1079 /// A float literal (`1f64` or `1E10f64`)
1080 Float(Symbol, FloatTy),
1081 /// A float literal without a suffix (`1.0 or 1.0E10`)
1082 FloatUnsuffixed(Symbol),
1083 /// A boolean literal
1084 Bool(bool),
1085 }
1086
1087 impl LitKind {
1088 /// Returns true if this literal is a string and false otherwise.
1089 pub fn is_str(&self) -> bool {
1090 match *self {
1091 LitKind::Str(..) => true,
1092 _ => false,
1093 }
1094 }
1095
1096 /// Returns true if this literal has no suffix. Note: this will return true
1097 /// for literals with prefixes such as raw strings and byte strings.
1098 pub fn is_unsuffixed(&self) -> bool {
1099 match *self {
1100 // unsuffixed variants
1101 LitKind::Str(..) => true,
1102 LitKind::ByteStr(..) => true,
1103 LitKind::Byte(..) => true,
1104 LitKind::Char(..) => true,
1105 LitKind::Int(_, LitIntType::Unsuffixed) => true,
1106 LitKind::FloatUnsuffixed(..) => true,
1107 LitKind::Bool(..) => true,
1108 // suffixed variants
1109 LitKind::Int(_, LitIntType::Signed(..)) => false,
1110 LitKind::Int(_, LitIntType::Unsigned(..)) => false,
1111 LitKind::Float(..) => false,
1112 }
1113 }
1114
1115 /// Returns true if this literal has a suffix.
1116 pub fn is_suffixed(&self) -> bool {
1117 !self.is_unsuffixed()
1118 }
1119 }
1120
1121 // NB: If you change this, you'll probably want to change the corresponding
1122 // type structure in middle/ty.rs as well.
1123 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1124 pub struct MutTy {
1125 pub ty: P<Ty>,
1126 pub mutbl: Mutability,
1127 }
1128
1129 /// Represents a method's signature in a trait declaration,
1130 /// or in an implementation.
1131 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1132 pub struct MethodSig {
1133 pub unsafety: Unsafety,
1134 pub constness: Spanned<Constness>,
1135 pub abi: Abi,
1136 pub decl: P<FnDecl>,
1137 pub generics: Generics,
1138 }
1139
1140 /// Represents an item declaration within a trait declaration,
1141 /// possibly including a default implementation. A trait item is
1142 /// either required (meaning it doesn't have an implementation, just a
1143 /// signature) or provided (meaning it has a default implementation).
1144 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1145 pub struct TraitItem {
1146 pub id: NodeId,
1147 pub ident: Ident,
1148 pub attrs: Vec<Attribute>,
1149 pub node: TraitItemKind,
1150 pub span: Span,
1151 }
1152
1153 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1154 pub enum TraitItemKind {
1155 Const(P<Ty>, Option<P<Expr>>),
1156 Method(MethodSig, Option<P<Block>>),
1157 Type(TyParamBounds, Option<P<Ty>>),
1158 Macro(Mac),
1159 }
1160
1161 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1162 pub struct ImplItem {
1163 pub id: NodeId,
1164 pub ident: Ident,
1165 pub vis: Visibility,
1166 pub defaultness: Defaultness,
1167 pub attrs: Vec<Attribute>,
1168 pub node: ImplItemKind,
1169 pub span: Span,
1170 }
1171
1172 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1173 pub enum ImplItemKind {
1174 Const(P<Ty>, P<Expr>),
1175 Method(MethodSig, P<Block>),
1176 Type(P<Ty>),
1177 Macro(Mac),
1178 }
1179
1180 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1181 pub enum IntTy {
1182 Is,
1183 I8,
1184 I16,
1185 I32,
1186 I64,
1187 I128,
1188 }
1189
1190 impl fmt::Debug for IntTy {
1191 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1192 fmt::Display::fmt(self, f)
1193 }
1194 }
1195
1196 impl fmt::Display for IntTy {
1197 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1198 write!(f, "{}", self.ty_to_string())
1199 }
1200 }
1201
1202 impl IntTy {
1203 pub fn ty_to_string(&self) -> &'static str {
1204 match *self {
1205 IntTy::Is => "isize",
1206 IntTy::I8 => "i8",
1207 IntTy::I16 => "i16",
1208 IntTy::I32 => "i32",
1209 IntTy::I64 => "i64",
1210 IntTy::I128 => "i128",
1211 }
1212 }
1213
1214 pub fn val_to_string(&self, val: i128) -> String {
1215 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1216 // are parsed as u128, so we wouldn't want to print an extra negative
1217 // sign.
1218 format!("{}{}", val as u128, self.ty_to_string())
1219 }
1220
1221 pub fn bit_width(&self) -> Option<usize> {
1222 Some(match *self {
1223 IntTy::Is => return None,
1224 IntTy::I8 => 8,
1225 IntTy::I16 => 16,
1226 IntTy::I32 => 32,
1227 IntTy::I64 => 64,
1228 IntTy::I128 => 128,
1229 })
1230 }
1231 }
1232
1233 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1234 pub enum UintTy {
1235 Us,
1236 U8,
1237 U16,
1238 U32,
1239 U64,
1240 U128,
1241 }
1242
1243 impl UintTy {
1244 pub fn ty_to_string(&self) -> &'static str {
1245 match *self {
1246 UintTy::Us => "usize",
1247 UintTy::U8 => "u8",
1248 UintTy::U16 => "u16",
1249 UintTy::U32 => "u32",
1250 UintTy::U64 => "u64",
1251 UintTy::U128 => "u128",
1252 }
1253 }
1254
1255 pub fn val_to_string(&self, val: u128) -> String {
1256 format!("{}{}", val, self.ty_to_string())
1257 }
1258
1259 pub fn bit_width(&self) -> Option<usize> {
1260 Some(match *self {
1261 UintTy::Us => return None,
1262 UintTy::U8 => 8,
1263 UintTy::U16 => 16,
1264 UintTy::U32 => 32,
1265 UintTy::U64 => 64,
1266 UintTy::U128 => 128,
1267 })
1268 }
1269 }
1270
1271 impl fmt::Debug for UintTy {
1272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1273 fmt::Display::fmt(self, f)
1274 }
1275 }
1276
1277 impl fmt::Display for UintTy {
1278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1279 write!(f, "{}", self.ty_to_string())
1280 }
1281 }
1282
1283 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1284 pub enum FloatTy {
1285 F32,
1286 F64,
1287 }
1288
1289 impl fmt::Debug for FloatTy {
1290 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1291 fmt::Display::fmt(self, f)
1292 }
1293 }
1294
1295 impl fmt::Display for FloatTy {
1296 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1297 write!(f, "{}", self.ty_to_string())
1298 }
1299 }
1300
1301 impl FloatTy {
1302 pub fn ty_to_string(&self) -> &'static str {
1303 match *self {
1304 FloatTy::F32 => "f32",
1305 FloatTy::F64 => "f64",
1306 }
1307 }
1308
1309 pub fn bit_width(&self) -> usize {
1310 match *self {
1311 FloatTy::F32 => 32,
1312 FloatTy::F64 => 64,
1313 }
1314 }
1315 }
1316
1317 // Bind a type to an associated type: `A=Foo`.
1318 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1319 pub struct TypeBinding {
1320 pub id: NodeId,
1321 pub ident: Ident,
1322 pub ty: P<Ty>,
1323 pub span: Span,
1324 }
1325
1326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1327 pub struct Ty {
1328 pub id: NodeId,
1329 pub node: TyKind,
1330 pub span: Span,
1331 }
1332
1333 impl fmt::Debug for Ty {
1334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1335 write!(f, "type({})", pprust::ty_to_string(self))
1336 }
1337 }
1338
1339 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1340 pub struct BareFnTy {
1341 pub unsafety: Unsafety,
1342 pub abi: Abi,
1343 pub lifetimes: Vec<LifetimeDef>,
1344 pub decl: P<FnDecl>
1345 }
1346
1347 /// The different kinds of types recognized by the compiler
1348 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1349 pub enum TyKind {
1350 /// A variable-length slice (`[T]`)
1351 Slice(P<Ty>),
1352 /// A fixed length array (`[T; n]`)
1353 Array(P<Ty>, P<Expr>),
1354 /// A raw pointer (`*const T` or `*mut T`)
1355 Ptr(MutTy),
1356 /// A reference (`&'a T` or `&'a mut T`)
1357 Rptr(Option<Lifetime>, MutTy),
1358 /// A bare function (e.g. `fn(usize) -> bool`)
1359 BareFn(P<BareFnTy>),
1360 /// The never type (`!`)
1361 Never,
1362 /// A tuple (`(A, B, C, D,...)`)
1363 Tup(Vec<P<Ty>> ),
1364 /// A path (`module::module::...::Type`), optionally
1365 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1366 ///
1367 /// Type parameters are stored in the Path itself
1368 Path(Option<QSelf>, Path),
1369 /// A trait object type `Bound1 + Bound2 + Bound3`
1370 /// where `Bound` is a trait or a lifetime.
1371 TraitObject(TyParamBounds),
1372 /// An `impl Bound1 + Bound2 + Bound3` type
1373 /// where `Bound` is a trait or a lifetime.
1374 ImplTrait(TyParamBounds),
1375 /// No-op; kept solely so that we can pretty-print faithfully
1376 Paren(P<Ty>),
1377 /// Unused for now
1378 Typeof(P<Expr>),
1379 /// TyKind::Infer means the type should be inferred instead of it having been
1380 /// specified. This can appear anywhere in a type.
1381 Infer,
1382 /// Inferred type of a `self` or `&self` argument in a method.
1383 ImplicitSelf,
1384 // A macro in the type position.
1385 Mac(Mac),
1386 }
1387
1388 /// Inline assembly dialect.
1389 ///
1390 /// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1392 pub enum AsmDialect {
1393 Att,
1394 Intel,
1395 }
1396
1397 /// Inline assembly.
1398 ///
1399 /// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
1400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1401 pub struct InlineAsmOutput {
1402 pub constraint: Symbol,
1403 pub expr: P<Expr>,
1404 pub is_rw: bool,
1405 pub is_indirect: bool,
1406 }
1407
1408 /// Inline assembly.
1409 ///
1410 /// E.g. `asm!("NOP");`
1411 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1412 pub struct InlineAsm {
1413 pub asm: Symbol,
1414 pub asm_str_style: StrStyle,
1415 pub outputs: Vec<InlineAsmOutput>,
1416 pub inputs: Vec<(Symbol, P<Expr>)>,
1417 pub clobbers: Vec<Symbol>,
1418 pub volatile: bool,
1419 pub alignstack: bool,
1420 pub dialect: AsmDialect,
1421 pub expn_id: ExpnId,
1422 }
1423
1424 /// An argument in a function header.
1425 ///
1426 /// E.g. `bar: usize` as in `fn foo(bar: usize)`
1427 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1428 pub struct Arg {
1429 pub ty: P<Ty>,
1430 pub pat: P<Pat>,
1431 pub id: NodeId,
1432 }
1433
1434 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1435 ///
1436 /// E.g. `&mut self` as in `fn foo(&mut self)`
1437 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1438 pub enum SelfKind {
1439 /// `self`, `mut self`
1440 Value(Mutability),
1441 /// `&'lt self`, `&'lt mut self`
1442 Region(Option<Lifetime>, Mutability),
1443 /// `self: TYPE`, `mut self: TYPE`
1444 Explicit(P<Ty>, Mutability),
1445 }
1446
1447 pub type ExplicitSelf = Spanned<SelfKind>;
1448
1449 impl Arg {
1450 pub fn to_self(&self) -> Option<ExplicitSelf> {
1451 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1452 if ident.node.name == keywords::SelfValue.name() {
1453 return match self.ty.node {
1454 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1455 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1456 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1457 }
1458 _ => Some(respan(mk_sp(self.pat.span.lo, self.ty.span.hi),
1459 SelfKind::Explicit(self.ty.clone(), mutbl))),
1460 }
1461 }
1462 }
1463 None
1464 }
1465
1466 pub fn is_self(&self) -> bool {
1467 if let PatKind::Ident(_, ident, _) = self.pat.node {
1468 ident.node.name == keywords::SelfValue.name()
1469 } else {
1470 false
1471 }
1472 }
1473
1474 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
1475 let span = mk_sp(eself.span.lo, eself_ident.span.hi);
1476 let infer_ty = P(Ty {
1477 id: DUMMY_NODE_ID,
1478 node: TyKind::ImplicitSelf,
1479 span: span,
1480 });
1481 let arg = |mutbl, ty| Arg {
1482 pat: P(Pat {
1483 id: DUMMY_NODE_ID,
1484 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1485 span: span,
1486 }),
1487 ty: ty,
1488 id: DUMMY_NODE_ID,
1489 };
1490 match eself.node {
1491 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1492 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1493 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
1494 id: DUMMY_NODE_ID,
1495 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
1496 span: span,
1497 })),
1498 }
1499 }
1500 }
1501
1502 /// Header (not the body) of a function declaration.
1503 ///
1504 /// E.g. `fn foo(bar: baz)`
1505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1506 pub struct FnDecl {
1507 pub inputs: Vec<Arg>,
1508 pub output: FunctionRetTy,
1509 pub variadic: bool
1510 }
1511
1512 impl FnDecl {
1513 pub fn get_self(&self) -> Option<ExplicitSelf> {
1514 self.inputs.get(0).and_then(Arg::to_self)
1515 }
1516 pub fn has_self(&self) -> bool {
1517 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1518 }
1519 }
1520
1521 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1522 pub enum Unsafety {
1523 Unsafe,
1524 Normal,
1525 }
1526
1527 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1528 pub enum Constness {
1529 Const,
1530 NotConst,
1531 }
1532
1533 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1534 pub enum Defaultness {
1535 Default,
1536 Final,
1537 }
1538
1539 impl fmt::Display for Unsafety {
1540 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1541 fmt::Display::fmt(match *self {
1542 Unsafety::Normal => "normal",
1543 Unsafety::Unsafe => "unsafe",
1544 }, f)
1545 }
1546 }
1547
1548 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1549 pub enum ImplPolarity {
1550 /// `impl Trait for Type`
1551 Positive,
1552 /// `impl !Trait for Type`
1553 Negative,
1554 }
1555
1556 impl fmt::Debug for ImplPolarity {
1557 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1558 match *self {
1559 ImplPolarity::Positive => "positive".fmt(f),
1560 ImplPolarity::Negative => "negative".fmt(f),
1561 }
1562 }
1563 }
1564
1565
1566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1567 pub enum FunctionRetTy {
1568 /// Return type is not specified.
1569 ///
1570 /// Functions default to `()` and
1571 /// closures default to inference. Span points to where return
1572 /// type would be inserted.
1573 Default(Span),
1574 /// Everything else
1575 Ty(P<Ty>),
1576 }
1577
1578 impl FunctionRetTy {
1579 pub fn span(&self) -> Span {
1580 match *self {
1581 FunctionRetTy::Default(span) => span,
1582 FunctionRetTy::Ty(ref ty) => ty.span,
1583 }
1584 }
1585 }
1586
1587 /// Module declaration.
1588 ///
1589 /// E.g. `mod foo;` or `mod foo { .. }`
1590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1591 pub struct Mod {
1592 /// A span from the first token past `{` to the last token until `}`.
1593 /// For `mod foo;`, the inner span ranges from the first token
1594 /// to the last token in the external file.
1595 pub inner: Span,
1596 pub items: Vec<P<Item>>,
1597 }
1598
1599 /// Foreign module declaration.
1600 ///
1601 /// E.g. `extern { .. }` or `extern C { .. }`
1602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1603 pub struct ForeignMod {
1604 pub abi: Abi,
1605 pub items: Vec<ForeignItem>,
1606 }
1607
1608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1609 pub struct EnumDef {
1610 pub variants: Vec<Variant>,
1611 }
1612
1613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1614 pub struct Variant_ {
1615 pub name: Ident,
1616 pub attrs: Vec<Attribute>,
1617 pub data: VariantData,
1618 /// Explicit discriminant, e.g. `Foo = 1`
1619 pub disr_expr: Option<P<Expr>>,
1620 }
1621
1622 pub type Variant = Spanned<Variant_>;
1623
1624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1625 pub struct PathListItem_ {
1626 pub name: Ident,
1627 /// renamed in list, e.g. `use foo::{bar as baz};`
1628 pub rename: Option<Ident>,
1629 pub id: NodeId,
1630 }
1631
1632 pub type PathListItem = Spanned<PathListItem_>;
1633
1634 pub type ViewPath = Spanned<ViewPath_>;
1635
1636 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1637 pub enum ViewPath_ {
1638
1639 /// `foo::bar::baz as quux`
1640 ///
1641 /// or just
1642 ///
1643 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1644 ViewPathSimple(Ident, Path),
1645
1646 /// `foo::bar::*`
1647 ViewPathGlob(Path),
1648
1649 /// `foo::bar::{a,b,c}`
1650 ViewPathList(Path, Vec<PathListItem>)
1651 }
1652
1653 impl ViewPath_ {
1654 pub fn path(&self) -> &Path {
1655 match *self {
1656 ViewPathSimple(_, ref path) |
1657 ViewPathGlob (ref path) |
1658 ViewPathList(ref path, _) => path
1659 }
1660 }
1661 }
1662
1663
1664 /// Distinguishes between Attributes that decorate items and Attributes that
1665 /// are contained as statements within items. These two cases need to be
1666 /// distinguished for pretty-printing.
1667 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1668 pub enum AttrStyle {
1669 Outer,
1670 Inner,
1671 }
1672
1673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1674 pub struct AttrId(pub usize);
1675
1676 /// Meta-data associated with an item
1677 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1678 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1679 pub struct Attribute {
1680 pub id: AttrId,
1681 pub style: AttrStyle,
1682 pub value: MetaItem,
1683 pub is_sugared_doc: bool,
1684 pub span: Span,
1685 }
1686
1687 /// TraitRef's appear in impls.
1688 ///
1689 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1690 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1691 /// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1692 /// same as the impl's node id).
1693 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1694 pub struct TraitRef {
1695 pub path: Path,
1696 pub ref_id: NodeId,
1697 }
1698
1699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1700 pub struct PolyTraitRef {
1701 /// The `'a` in `<'a> Foo<&'a T>`
1702 pub bound_lifetimes: Vec<LifetimeDef>,
1703
1704 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1705 pub trait_ref: TraitRef,
1706
1707 pub span: Span,
1708 }
1709
1710 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1711 pub enum Visibility {
1712 Public,
1713 Crate(Span),
1714 Restricted { path: P<Path>, id: NodeId },
1715 Inherited,
1716 }
1717
1718 /// Field of a struct.
1719 ///
1720 /// E.g. `bar: usize` as in `struct Foo { bar: usize }`
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1722 pub struct StructField {
1723 pub span: Span,
1724 pub ident: Option<Ident>,
1725 pub vis: Visibility,
1726 pub id: NodeId,
1727 pub ty: P<Ty>,
1728 pub attrs: Vec<Attribute>,
1729 }
1730
1731 /// Fields and Ids of enum variants and structs
1732 ///
1733 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1734 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1735 /// One shared Id can be successfully used for these two purposes.
1736 /// Id of the whole enum lives in `Item`.
1737 ///
1738 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1739 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1740 /// the variant itself" from enum variants.
1741 /// Id of the whole struct lives in `Item`.
1742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1743 pub enum VariantData {
1744 /// Struct variant.
1745 ///
1746 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
1747 Struct(Vec<StructField>, NodeId),
1748 /// Tuple variant.
1749 ///
1750 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
1751 Tuple(Vec<StructField>, NodeId),
1752 /// Unit variant.
1753 ///
1754 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
1755 Unit(NodeId),
1756 }
1757
1758 impl VariantData {
1759 pub fn fields(&self) -> &[StructField] {
1760 match *self {
1761 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1762 _ => &[],
1763 }
1764 }
1765 pub fn id(&self) -> NodeId {
1766 match *self {
1767 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1768 }
1769 }
1770 pub fn is_struct(&self) -> bool {
1771 if let VariantData::Struct(..) = *self { true } else { false }
1772 }
1773 pub fn is_tuple(&self) -> bool {
1774 if let VariantData::Tuple(..) = *self { true } else { false }
1775 }
1776 pub fn is_unit(&self) -> bool {
1777 if let VariantData::Unit(..) = *self { true } else { false }
1778 }
1779 }
1780
1781 /// An item
1782 ///
1783 /// The name might be a dummy name in case of anonymous items
1784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1785 pub struct Item {
1786 pub ident: Ident,
1787 pub attrs: Vec<Attribute>,
1788 pub id: NodeId,
1789 pub node: ItemKind,
1790 pub vis: Visibility,
1791 pub span: Span,
1792 }
1793
1794 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1795 pub enum ItemKind {
1796 /// An`extern crate` item, with optional original crate name.
1797 ///
1798 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
1799 ExternCrate(Option<Name>),
1800 /// A use declaration (`use` or `pub use`) item.
1801 ///
1802 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
1803 Use(P<ViewPath>),
1804 /// A static item (`static` or `pub static`).
1805 ///
1806 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
1807 Static(P<Ty>, Mutability, P<Expr>),
1808 /// A constant item (`const` or `pub const`).
1809 ///
1810 /// E.g. `const FOO: i32 = 42;`
1811 Const(P<Ty>, P<Expr>),
1812 /// A function declaration (`fn` or `pub fn`).
1813 ///
1814 /// E.g. `fn foo(bar: usize) -> usize { .. }`
1815 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
1816 /// A module declaration (`mod` or `pub mod`).
1817 ///
1818 /// E.g. `mod foo;` or `mod foo { .. }`
1819 Mod(Mod),
1820 /// An external module (`extern` or `pub extern`).
1821 ///
1822 /// E.g. `extern {}` or `extern "C" {}`
1823 ForeignMod(ForeignMod),
1824 /// A type alias (`type` or `pub type`).
1825 ///
1826 /// E.g. `type Foo = Bar<u8>;`
1827 Ty(P<Ty>, Generics),
1828 /// An enum definition (`enum` or `pub enum`).
1829 ///
1830 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
1831 Enum(EnumDef, Generics),
1832 /// A struct definition (`struct` or `pub struct`).
1833 ///
1834 /// E.g. `struct Foo<A> { x: A }`
1835 Struct(VariantData, Generics),
1836 /// A union definition (`union` or `pub union`).
1837 ///
1838 /// E.g. `union Foo<A, B> { x: A, y: B }`
1839 Union(VariantData, Generics),
1840 /// A Trait declaration (`trait` or `pub trait`).
1841 ///
1842 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
1843 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
1844 // Default trait implementation.
1845 ///
1846 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
1847 DefaultImpl(Unsafety, TraitRef),
1848 /// An implementation.
1849 ///
1850 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
1851 Impl(Unsafety,
1852 ImplPolarity,
1853 Generics,
1854 Option<TraitRef>, // (optional) trait this impl implements
1855 P<Ty>, // self
1856 Vec<ImplItem>),
1857 /// A macro invocation.
1858 ///
1859 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
1860 Mac(Mac),
1861
1862 /// A macro definition.
1863 MacroDef(ThinTokenStream),
1864 }
1865
1866 impl ItemKind {
1867 pub fn descriptive_variant(&self) -> &str {
1868 match *self {
1869 ItemKind::ExternCrate(..) => "extern crate",
1870 ItemKind::Use(..) => "use",
1871 ItemKind::Static(..) => "static item",
1872 ItemKind::Const(..) => "constant item",
1873 ItemKind::Fn(..) => "function",
1874 ItemKind::Mod(..) => "module",
1875 ItemKind::ForeignMod(..) => "foreign module",
1876 ItemKind::Ty(..) => "type alias",
1877 ItemKind::Enum(..) => "enum",
1878 ItemKind::Struct(..) => "struct",
1879 ItemKind::Union(..) => "union",
1880 ItemKind::Trait(..) => "trait",
1881 ItemKind::Mac(..) |
1882 ItemKind::MacroDef(..) |
1883 ItemKind::Impl(..) |
1884 ItemKind::DefaultImpl(..) => "item"
1885 }
1886 }
1887 }
1888
1889 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1890 pub struct ForeignItem {
1891 pub ident: Ident,
1892 pub attrs: Vec<Attribute>,
1893 pub node: ForeignItemKind,
1894 pub id: NodeId,
1895 pub span: Span,
1896 pub vis: Visibility,
1897 }
1898
1899 /// An item within an `extern` block
1900 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1901 pub enum ForeignItemKind {
1902 /// A foreign function
1903 Fn(P<FnDecl>, Generics),
1904 /// A foreign static item (`static ext: u8`), with optional mutability
1905 /// (the boolean is true when mutable)
1906 Static(P<Ty>, bool),
1907 }
1908
1909 impl ForeignItemKind {
1910 pub fn descriptive_variant(&self) -> &str {
1911 match *self {
1912 ForeignItemKind::Fn(..) => "foreign function",
1913 ForeignItemKind::Static(..) => "foreign static item"
1914 }
1915 }
1916 }
1917
1918 #[cfg(test)]
1919 mod tests {
1920 use serialize;
1921 use super::*;
1922
1923 // are ASTs encodable?
1924 #[test]
1925 fn check_asts_encodable() {
1926 fn assert_encodable<T: serialize::Encodable>() {}
1927 assert_encodable::<Crate>();
1928 }
1929 }