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.
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.
13 #![feature(plugin_registrar)]
14 #![feature(box_syntax)]
15 #![feature(rustc_private)]
19 extern crate rustc_plugin
;
22 use syntax
::attr
::AttrMetaMethods
;
23 use syntax
::codemap
::Span
;
24 use syntax
::ext
::base
::{MultiDecorator, ExtCtxt, Annotatable}
;
25 use syntax
::ext
::build
::AstBuilder
;
26 use syntax
::ext
::deriving
::generic
::{cs_fold, TraitDef, MethodDef, combine_substructure}
;
27 use syntax
::ext
::deriving
::generic
::{Substructure, Struct, EnumMatching}
;
28 use syntax
::ext
::deriving
::generic
::ty
::{Literal, LifetimeBounds, Path, borrowed_explicit_self}
;
29 use syntax
::parse
::token
;
31 use rustc_plugin
::Registry
;
34 pub fn plugin_registrar(reg
: &mut Registry
) {
35 reg
.register_syntax_extension(
36 token
::intern("derive_TotalSum"),
37 MultiDecorator(box expand
));
40 fn expand(cx
: &mut ExtCtxt
,
42 mitem
: &ast
::MetaItem
,
44 push
: &mut FnMut(Annotatable
)) {
45 let trait_def
= TraitDef
{
48 path
: Path
::new(vec
!["TotalSum"]),
49 additional_bounds
: vec
![],
50 generics
: LifetimeBounds
::empty(),
51 associated_types
: vec
![],
56 generics
: LifetimeBounds
::empty(),
57 explicit_self
: borrowed_explicit_self(),
59 ret_ty
: Literal(Path
::new_local("isize")),
62 combine_substructure
: combine_substructure(Box
::new(totalsum_substructure
)),
67 trait_def
.expand(cx
, mitem
, item
, push
)
70 // Mostly copied from syntax::ext::deriving::hash
71 /// Defines how the implementation for `trace()` is to be generated
72 fn totalsum_substructure(cx
: &mut ExtCtxt
, trait_span
: Span
,
73 substr
: &Substructure
) -> P
<ast
::Expr
> {
74 let fields
= match *substr
.fields
{
75 Struct(ref fs
) | EnumMatching(_
, _
, ref fs
) => fs
,
76 _
=> cx
.span_bug(trait_span
, "impossible substructure")
79 fields
.iter().fold(cx
.expr_isize(trait_span
, 0), |acc
, ref item
| {
80 if item
.attrs
.iter().find(|a
| a
.check_name("ignore")).is_some() {
83 cx
.expr_binary(item
.span
, ast
::BiAdd
, acc
,
84 cx
.expr_method_call(item
.span
,