[erlang-questions] Compilation question...

Ulf Wiger ulf@REDACTED
Tue Jan 30 15:30:06 CET 2007


Den 2007-01-30 15:05:01 skrev Emil Hellman <emil.hellman@REDACTED>:

> Hello!
>
> I have a small feature I want to several modules. My thought is to add
> this feature if I encounter a '-myfeature(Args)'  in the module.
>
> Example:
>
> -module(foo).
> -export([bar/0]).
> -myfeature(Args).
>
> Where args could be several different things.
>
> So essentially if I find this "tag" in the module I would like to
> append some code to the file (dependant on the args). And then compile
> the modified module. However, I don't want the generated code to be
> appended to the actual module, simply added temporarily during the
> compilation.

It sounds like you want a parse transform.

Look e.g. at some of the user contributions at trapexit.
My recommendation is to use syntax_tools, even though the
learning curve is somewhat steep.

You can recognize attributes during the parse transform
like so (example from erlhive.erl):

  recognize_form(E, O) ->
      case erl_syntax:type(E) of
        attribute ->
  	    AName = erl_syntax:attribute_name(E),
  	    rewrite_attribute(AName, E, O);
        ...
      end

A bit of warning, though: After doing a parse transform
with syntax_tools, you have to call erl_syntax:revert(Form)
to bring it back to the standard Erlang abstract format.
I've encountered some problems esp when reverting
rewritten attributes. I believe most of them have been
related to the handling of dotted module names, since they
are represented in the parse tree as record expressions.
My workaround has been to write a custom revert() which
converts the module names back to atoms again, and then
calls the standard revert.

(I've reported this to the OTP team - at least as regards
revert() of -import/2 attributes containing dotted module
names. A fix will come in some post-R11B-2 release.)

BR,
Ulf W
-- 
Ulf Wiger




More information about the erlang-questions mailing list