[antlr-interest] C preprocessor

maulattu maulattu at yahoo.it
Mon Nov 8 06:43:16 PST 2010


Hi all,
I've to add some parsing features to my grammar (it creates an AST, then with 
another grammar I walk the resulting tree).
The language is extremely simple, it's like C, i.e.:

    s_1 = 1;
    if (s_1)
    {
        s_2 = 1;
        s_3 = s_2 << 1;
    }
    else
        s_2 = 0;

what I'd like to to is to insert some "#define" optional directives as in C. If 
they are present, they must be only at the beginning of the file to be parsed:

   #define ignition s_1
    ... ... ...
    ignition = 1; /* was "s_1 = 1;" */
    ... // and the same as before

The main grammar (without the define feature) starts as

    script
      : statementList EOF
      ;
    statementList
      : statement+
      ;

    statement
      : compoundStatement
      | expressionStatement
      | selectionStatement
      ;

    compoundStatement
      : '{' statementList? '}'
      ;
....

I changed the grammar as following ("WS" is whitespace, \r,\n and similar):
    script
      : (defineStatement)* statementList EOF
      ;
  defineStatement
    : '#define' WS macroText = RAW_IDENTIFIER macroValue = RAW_IDENTIFIER
        -> (DEFINE $macroText $macroValue)
  ;

At this point I don't understand why the grammar is no more working.
It's expecting to have always a "#", not EOF or the other statements.
How can be written in order to have an optional "define list" only at the 
beginning on the text to be parsed by this grammar?
Even changing the "defineStatement" rule as
defineStatement
    : '#define' WS macroText = RAW_IDENTIFIER macroValue = RAW_IDENTIFIER
        -> (DEFINE $macroText $macroValue)
    |
  ;

nothing changes.

I take a look at
http://www.antlr.org/pipermail/antlr-interest/2004-July/008778.html
but it's a grammar related to a mandatory preprocessor directive list, not an 
optional one.

A lot of thanks in advance :)

Maurizio



      


More information about the antlr-interest mailing list