[erlang-questions] Function name macro (the counterpart of ?MODULE)

Zoltan Lajos Kis kiszl@REDACTED
Mon Dec 21 23:53:48 CET 2009

Hi Ciprian,

The ?MODULE, ?FILE and ?LINE macros can be handled by simple text 
processing, without touching any Erlang syntax. ?FUNCTION would not be 
that simple...
Anyway, as suggested, this can be done by using parse transforms. Below 
is a working version; others will hopefully fix my mistakes :) After 
compiling module z, you should get the expected results.


--------- zt.hrl ---------
-define(FUNCTION, '__function_macro__').
-define(ARITY, '__function_arity__').

--------- zt.erl ---------


parse_transform(AST, _Options) -> [parse(T) || T <- AST].

parse({function, _, FName, FArity, _} = T) -> erl_syntax_lib:map(fun(TE) 
-> parsemacro(FName, FArity, TE) end, T);
parse(T) -> T.

parsemacro(FName, FArity, T) ->
        case erl_syntax:type(T) of
            atom ->
                case erl_syntax:atom_value(T) of
                    ?FUNCTION -> erl_syntax:atom(FName);
                    ?ARITY -> erl_syntax:integer(FArity);
                    _ -> T
            _ ->

--------- z.erl ---------
-compile({parse_transform, zt}).

-export([a/0, b/1, c/2]).


c(_X, _Y) -> {?MODULE, ?FUNCTION, ?ARITY}.

Ciprian Dorin, Craciun wrote:
>     Hy all!
>     Maybe this question has been asked a thousand times, but please
> forgive and bare with me just one more time... :)
>     So as predefined macros we have ?MODULE, ?FILE, and ?LINE... But
> there is no ?FUNCTION (that should give me the current function name).
>     Now my question is: why isn't there any such macro? (I would guess
> that having such a macro is not so complicated...) And what can I do
> to obtain a similar functionality?
>     Thanks,
>     Ciprian.
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org

More information about the erlang-questions mailing list