[erlang-questions] Extracting constants from a header file

Torben Hoffmann torben.lehoff@REDACTED
Thu Jul 9 15:18:15 CEST 2009

On Thu, Jul 9, 2009 at 13:46, Fabian Alenius <fabian.alenius@REDACTED>wrote:

> Torben Hoffmann wrote:
>> Hi,
>> I would like to get a hold of all the
>> -define(CONSTANT,42).
>> constant definitions so I can output them for use in an external tool.
>> I have played with epp_dodger, erl_syntax_lib et al, but I have not found
>> an
>> easy way of doing it.
>> Right now the following approach seems to be what I must do:
>>   1. Get the AST using epp:dodger:parse_file/1
>>   2. Filter all the elements from the AST where
>>   erl_syntax_lib:analyze_attribute/1 returns preprocessor
>>   3. Take the subtrees of the each element from the step above (using
>>   erl_syntaxt_lib:subtrees/1) and then use the fact that
>>   1. the first subtree is a list that contains {atom,_,define} and
>>      2.  the second subtree is a list consisting of {var,_,'PDU_TYPE'} and
>>      {integer,_,0} (i.e., the constant's name and type+value)
>> Is this the one and only way of doing it?
>> Not that I would mind terribly to code the above, but it seems like
>> something that ought to be easier and/or have been solved by someone else
>> before me.
>> Cheers,
>> Torben
> Is there any reason why you can't just use a simple reg-exp?
> E.g.
> {ok, Bin} = file:read_file("erl_bits.hrl"),
> re:run(Bin, ".*-define[(](?<NAME>.*),[ ]*(?<VALUE>.*)[)]",[global,
> {capture, ['NAME','VALUE'], list}]).
> {match,[["SYS_ENDIAN","big"],
>       ["SIZEOF_CHAR","1"],
>       ["SIZEOF_DOUBLE","8"],
>       ["SIZEOF_FLOAT","4"],
>       ["SIZEOF_INT","4"],
>       ["SIZEOF_LONG","4"],
>       ["SIZEOF_LONG_LONG","8"],
>       ["SIZEOF_SHORT","2"]]}
> / Fabian Alenius
Not really - just didn't think of it... which is why I ran the question by
the mailing list!

I will experiment with re and erl_syntaxt as Richard suggested and report
back on what is the easiest to work with.

Thanks to both of you for your hints.


More information about the erlang-questions mailing list