]>
Commit | Line | Data |
---|---|---|
c34b1796 AL |
1 | // Copyright 2015 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 | // force-host | |
12 | ||
13 | #![feature(plugin_registrar)] | |
14 | #![feature(box_syntax)] | |
15 | #![feature(rustc_private)] | |
16 | ||
17 | extern crate syntax; | |
18 | extern crate rustc; | |
19 | ||
20 | use syntax::ast; | |
21 | use syntax::codemap::Span; | |
d9579d0f | 22 | use syntax::ext::base::{MultiDecorator, ExtCtxt, Annotatable}; |
c34b1796 AL |
23 | use syntax::ext::build::AstBuilder; |
24 | use syntax::ext::deriving::generic::{cs_fold, TraitDef, MethodDef, combine_substructure}; | |
25 | use syntax::ext::deriving::generic::ty::{Literal, LifetimeBounds, Path, borrowed_explicit_self}; | |
26 | use syntax::parse::token; | |
27 | use syntax::ptr::P; | |
28 | use rustc::plugin::Registry; | |
29 | ||
30 | #[plugin_registrar] | |
31 | pub fn plugin_registrar(reg: &mut Registry) { | |
32 | reg.register_syntax_extension( | |
33 | token::intern("derive_TotalSum"), | |
d9579d0f | 34 | MultiDecorator(box expand)); |
c34b1796 AL |
35 | } |
36 | ||
37 | fn expand(cx: &mut ExtCtxt, | |
38 | span: Span, | |
39 | mitem: &ast::MetaItem, | |
d9579d0f AL |
40 | item: Annotatable, |
41 | push: &mut FnMut(Annotatable)) { | |
c34b1796 AL |
42 | let trait_def = TraitDef { |
43 | span: span, | |
44 | attributes: vec![], | |
45 | path: Path::new(vec!["TotalSum"]), | |
46 | additional_bounds: vec![], | |
47 | generics: LifetimeBounds::empty(), | |
48 | associated_types: vec![], | |
49 | methods: vec![ | |
50 | MethodDef { | |
51 | name: "total_sum", | |
52 | generics: LifetimeBounds::empty(), | |
53 | explicit_self: borrowed_explicit_self(), | |
54 | args: vec![], | |
55 | ret_ty: Literal(Path::new_local("isize")), | |
56 | attributes: vec![], | |
57 | combine_substructure: combine_substructure(box |cx, span, substr| { | |
d9579d0f | 58 | let zero = cx.expr_isize(span, 0); |
c34b1796 AL |
59 | cs_fold(false, |
60 | |cx, span, subexpr, field, _| { | |
61 | cx.expr_binary(span, ast::BiAdd, subexpr, | |
62 | cx.expr_method_call(span, field, | |
63 | token::str_to_ident("total_sum"), vec![])) | |
64 | }, | |
65 | zero, | |
66 | box |cx, span, _, _| { cx.span_bug(span, "wtf??"); }, | |
67 | cx, span, substr) | |
68 | }), | |
69 | }, | |
70 | ], | |
71 | }; | |
72 | ||
d9579d0f | 73 | trait_def.expand(cx, mitem, &item, push) |
c34b1796 | 74 | } |