[antlr-interest] FW: MACROs in ANTLR

Dan Hazon dan.hazon at novafora.com
Thu Oct 25 15:58:59 PDT 2007


I pretty new ANTLR user. I have read the definitive reference and using
the C target language.
I have a section of code that repeats itself many times in different
rules with slight modification on the name of one variable. Instead of
manually instantiating the code and blowing up the size of the .g file
I'm interested to declare a macro that will reference some ANTLR
variables and let the code generator instantiate this in the same manner
C compiler does.
I think I can do it in C by "learning" the generated C code and defining
a C macro that would instantiate the expected code. However this is
almost as wrong as modifying the machine generated code manually.
Does ANTLR provide a way to define such macros?

Here is a simple example to demonstrate my need:

Section of the grammar:
exampleCFG
   :  ('exmpl1' { $eiddef = NULL; $eidref = NULL; }
      (eiddef=IDENTIFIER)? ('=' eidref=IDENTIFIER)? '{'
         { MY_DESIRED_MACRO(globalStructPtr, exmpl1Cfg) }
      cagCFG '}')?

      ('exmpl2' {$eiddef = NULL; $eidref = NULL; }
      (eiddef=IDENTIFIER)? ('=' eidref=IDENTIFIER)? '{'
         { MY_DESIRED_MACRO(globalStructPtr, exmpl2Cfg) }

      ...
   ;


definition of MY_DESIRED_MACRO:

#define MY_DESIRED_MACRO(pParent, name)\
if ($eiddef != NULL) {\
   pParent->DefHash_##name = index;\
   hashTbl->put(hashTbl, $eiddef.text->chars, index++, NULL);\
}\
if ($eidref != NULL) {\
   pParent->RefHash_##name = hashTbl->get(hashTbl,
(void*)$eidref.text->chars);\
}



the macro replaces every ##name with the actual string given in the name
place.

I hope I make some sense.
Appreciate your help,
Dan



More information about the antlr-interest mailing list