Debian Codegraph @

src/horse_autoexport.erl

raw
1 %% Copyright (c) 2013, Loïc Hoguin <[email protected]>
2 %%
3 %% Permission to use, copy, modify, and/or distribute this software for any
4 %% purpose with or without fee is hereby granted, provided that the above
5 %% copyright notice and this permission notice appear in all copies.
6 %%
7 %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10 %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12 %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13 %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15 -module(horse_autoexport).
16
17 -export([parse_transform/2]).
18
19 parse_transform([File, Module|Forms], _) ->
20 Exports = [F || {attribute, _, export, [{F, 0}]} <- Forms],
21 AutoExports = [{attribute, 0, export, [{F, 0}]}
22 || {function, _, F, 0, _} <- Forms,
23 "horse_" =:= string:substr(atom_to_list(F), 1, 6),
24 false =:= lists:member(F, Exports)],
25 replace_calls([File, Module|AutoExports ++ Forms]).
26
27 replace_calls(Forms) ->
28 lists:flatten([replace_call(Form) || Form <- Forms]).
29
30 replace_call(
31 {function, Fu, Name, 0, [
32 {clause, Cl, [], [], [
33 {call, Ca, {remote, _, {atom, _, horse}, {atom, _, repeat}}, [
34 Repeat,
35 Expr
36 ]}
37 ]}
38 ]}
39 ) when Repeat > 0 ->
40 GenName = list_to_atom("generated_" ++ atom_to_list(Name)),
41 [
42 {function, Fu, Name, 0, [
43 {clause, Cl, [], [], [
44 {call, Ca, {atom, Ca, GenName}, [Repeat]}
45 ]}
46 ]},
47 {function, Ca, GenName, 1, [
48 {clause, Ca, [{integer, Ca, 0}], [], [
49 {atom, Ca, ok}
50 ]},
51 {clause, Ca, [{var, Ca, 'N'}], [], [
52 Expr,
53 {call, Ca, {atom, Ca, GenName}, [
54 {op, Ca, '-', {var, Ca, 'N'}, {integer, Ca, 1}}
55 ]}
56 ]}
57 ]}
58 ];
59 replace_call(Form) ->
60 Form.