antlrcontext-free-grammarantlr2

ANTLR version2 grammar syntax?


My professor gave us an assignment about ANTLR,

but I found that the given grammar file does not work with current ANTLR versions.

Actually, it is an example code included in ANTLR v2, which there are few documents left I can find and has been stopped to be supported by any IDE tools such as Eclipse or ANTLRWorks.

Because of this, it took quite long time for me to find out that the grammar file is from the ancient.

I need to modify the given grammar file to find whlie loops that are immediately enclosed by else branch, but cannot understand some part of the grammar.

Somebody please teach me what does '=>' means in this example?


program
    :   ( declaration )* EOF
    ;

declaration
    :   (variable) => variable
    |   function
    ;

declarator
    :   id:ID
    |   STAR id2:ID
    ;

variable
    :   type declarator SEMI
    ;

function
    :   type id:ID LPAREN
        (formalParameter (COMMA formalParameter)*)?
        RPAREN
        block
    ;

statement
    :   (declaration) => declaration
    |   expr SEMI
    |   if_statement
    |   while_statement
    |   block
    ;

Solution

  • It is a look-ahead syntactic predicate as documented in the ANTLR 2 manual; these are used to disambiguate productions using lookahead.

    In this particular case, a declaration can be produced by a variable or a function. Because each of those can begin with a type production the predicate says to look ahead and prefer a declarator SEMI in preference to an id LPAREN.