Search code examples
javaantlr3antlr2

How to convert from antlr v2 to v3 grammar?


I have the below grammar in v2 of ANTLR, I need help to convert it to v3

expression
: ( simpleLookup
  | lookup
  )
  ( x:LSQRBRACKET^ {#x.setType(ATTRIBUTES);} attributesExpr RSQRBRACKET! )?
;enter code here

Actually I tried below but not sure if it will be same or not and also getting the below error while trying to build the parser

expression
: ( simpleLookup
  | lookup
  )
  (x=LSQRBRACKET b=attributesExpr RSQRBRACKET )?) -> ^(ATTRIBUTES[$x] $a $b)?
;

and getting below error

expecting SEMI, found '->'
unexpected token: $
unexpected token: $
unexpected token: )

How to convert "!" in v3 from v2?

Kindly help me with your expertise.....

One more question I have is how can I write tree parser in v3 at grammar level, like in v2 we used to write in the below format

class CustomTreeParser extends TreeParser;

Solution

  • Try something like this:

    grammar YourGrammarName;
    
    options {
      output=AST;
    }
    
    tokens {
      ATTRIBUTES;
    }
    
    // ...
    
    expression
     : ( simpleLookup
       | lookup
       )
       ( x=LSQRBRACKET^ {$x.setType(ATTRIBUTES);} attributesExpr RSQRBRACKET! )?
     ;
    
    // ...
    

    How to convert "!" in v3 from v2?

    The inline ! operator, which excludes certain rules/tokens from an AST, is unchanged in v3.

    One more question I have is how can I write tree parser in v3 at grammar level, like in v2 ...

    Like this:

    options {
      output=AST;
    }