[erlang-questions] scanning a hrl file, for macros.

Richard Carlsson richardc@REDACTED
Fri Mar 6 00:08:53 CET 2009


fess wrote:
> I have an hrl file with a bunch of macro's in it that are just a bunch  
> of strings.  [...] So, I tried to erl_scan/erl_parse it.
> 
> erl_scan returns tokens which includes the defines. I could go on from  
> there and manually parse the defines. However, I thought that if I got  
> a parsed form it would be easier to pick out the macros.
> 
> so I moved on to erl_parse, however, I get errors with  
> erl_parse:parse_form and erl_parse:parse_exprs, [ {1,erl_parse,"bad  
> attribute"}, and {2,erl_parse,["syntax error before: ",["'-'"]]}   
> respectively ], the file when included compiles so I'm guessing it's  
> not an actual syntax problem.
> 
> My tokens look like this:
> 
> [{'-',1}, {atom,1,ifndef}, {'(',1},  ...
  >
> So, then I thought, ok,  maybe erl_parse needs this stuff to be pre  
> processed?  Next I tried out epp:parse_file/3 on it
> but that seemed to me to expect to apply macros,  not necessarily show  
> you that they were there.

Your basic analysis is correct: to run the parser requires that
there are no remains of preprocessor juju like -define(...), -ifdef,
or ?MACRO in the token sequence. (This is natural: since preprocessor
expansion can happen anywhere and result in arbitrary tokens being
inserted, the poor parser has  no chance of matching the unexpanded
sequence against the expected grammar. C works the same way.) But
getting rid of the macros means getting *rid* of the macros...

You should try the epp_dodger module in syntax tools, which can
read most "sane" preprocessor uses: the parse_file/2 function
ought to get you started; you may want to run erl_syntax:revert/1
on the result, depending on what you want to do with it. The
documentation for erl_syntax and erl_prettypr may be of help.

http://www.erlang.org/doc/apps/syntax_tools/index.html

     /Richard



More information about the erlang-questions mailing list