[erlang-questions] in-flight module transforms - request for comments

Ulf Wiger <>
Tue Oct 18 12:06:32 CEST 2011


From those of you who enjoy modifying existing code at run-time, I would like to ask for some input.

Inspired by Joe Norton's use of Meck to introduce support for asciiedoc syntax in EDoc [1], I started playing with Meck to do similar things with e.g. tweaking epp on the fly for alternative syntax support.

I found that Meck was a bit limited in this regard, and ultimately, it's a slight abuse of the tool anyway. Since I maintain the parse_trans application [2], I thought I'd continue my experimentation there (in the module-transforms branch).

First, I copied meck_mod.erl (into parse_trans_mod.erl) and made a slight addition to it: 

  parse_trans_mod:transform_module(Module, Transforms, Options) -> CompileAndLoadResult

which fetches the abstract code of a module, transforms it, then compiles and loads the result.

I then added two helper functions (replace_function/3 and export_function/3), for starters, to help make easy transforms. 

Here's an example [3]:

-module(test_transform_mod).
-export([ex1/0]).

-include("codegen.hrl").

ex1() ->
    parse_trans_mod:transform_module(
      ex1, [fun(Fs, _Os) ->
		    parse_trans:export_function(int, 0, Fs)
	    end,
	    fun transform_ex1/2], [{pt_pp_src,true}]).

transform_ex1(Forms, _Opts) ->
    NewF = codegen:gen_function(add, fun(A, B) ->
					     A - B
				     end),
    parse_trans:replace_function(add, 2, NewF, Forms).

A shell dialogue to illustrate:

Eshell V5.8.4  (abort with ^G)
1> ex1:add(5,3).
8
2> test_transform_mod:ex1().
Pretty-printed in "./ex1.xfm"
ok
3> ex1:add(5,3).
2

This changes the example module ex1 [4], by exporting a previously internal function, int/0, and changing the semantics of the add/2 function.

The idea is hardly new. Yariv Sadan did something similar with smerl. I wanted to add a few functions that would draw on the stuff already supported by parse_trans.

For those of you out there who have used similar things before, what kind of support would you like to see?

BR,
Ulf W

[1] https://github.com/norton/asciiedoc/blob/master/src/asciiedoc_lib.erl#L39

[2] http://github.com/esl/parse_trans

[3] https://github.com/esl/parse_trans/blob/module-transforms/examples/test_transform_mod.erl

[4] In ex1, add(X, Y) -> X+Y.
     After transformation, add(A, B) -> A - B.

Ulf Wiger, CTO, Erlang Solutions, Ltd.
http://erlang-solutions.com



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20111018/09139957/attachment.html>


More information about the erlang-questions mailing list