Tips about implementing parse_transform
- First write code to generate in a file, and compile it using
erlc -S
to check what the compiled forms look like - Use [https://github.com/esl/parse_trans]
Tips about implementing parse_transform
erlc -S
to check what the compiled forms look like$ erlc test_parse_trans.erl | |
$ erlc -pa . test.erl | |
[{attribute,1,file,{"test.erl",1}}, | |
{attribute,1,module,test}, | |
{attribute,2,export,[{start,0}]}, | |
{function,5,start,0,[{clause,5,[],[],[{call,6,{atom,6,new},[]}]}]}, | |
{eof,7}] | |
$ erl | |
Erlang R16B03-1 (erts-5.10.4) [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace] | |
Eshell V5.10.4 (abort with ^G) | |
1> test:start(). | |
test | |
2> |
-module(test). | |
-export([start/0]). | |
-compile({parse_transform, test_parse_trans}). | |
start() -> | |
new(). |
-module(test_parse_trans). | |
-export([parse_transform/2, format_error/1]). | |
parse_transform(Forms, _Options) -> | |
io:format("~p~n", [Forms]), | |
lists:append( | |
lists:map( | |
fun transform_form/1, | |
Forms | |
) | |
). | |
transform_form({eof, Line} = Form) -> | |
[ | |
%% Append function new/0 in the end of the module | |
{function,Line,new,0,[{clause,Line,[],[],[{atom,Line,test}]}]}, | |
Form | |
]; | |
transform_form(Form) -> | |
[Form]. | |
format_error(E) -> | |
case io_lib:deep_char_list(E) of | |
true -> | |
E; | |
_ -> | |
io_lib:write(E) | |
end. |