[erlang-questions] Extracting constants from a header file

Richard Carlsson richardc@REDACTED
Thu Jul 9 01:12:31 CEST 2009


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)

I'd call that pretty much an easy way of doing it. In step 3, you
might want to use the functions in erl_syntax all the way instead of
breaking the abstraction and matching directly on tuples, in particular
to decompose the attribute (rather than using subtrees/1).

> Is this the one and only way of doing it?

You could do your own parsing of the token stream and detect forms
that begin with '-','define','(', then extract the interesting tokens
and output them in whatever format you want. Might or might not be
easier for you.

     /Richard



More information about the erlang-questions mailing list