1

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;
Rakesh
  • 37
  • 7

1 Answers1

0

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;
}
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • Actually if I do what you suggested it's says that I am using both rewrite and oparator rules, but if I remove '!' then it's ok, but then RSQRBRACKET is also added to the tree, which I don't want. – Rakesh Aug 13 '14 at 09:19
  • Now for the other question I asked after some research I found I have to create separate grammar file for tree grammar, where I need to have "tree grammar [grammar file name]" at the top, then it autometicaly create a class file which extends TreeParser, or else it will create one which extends Parser. – Rakesh Aug 13 '14 at 09:21
  • About your 1st comment: then you're not doing what I suggested. The rule `expression` cannot give the error about using both rewrite and operator rules since there is no rewrite operator, `->`, anymore. There is in your rule, but not in mine. – Bart Kiers Aug 13 '14 at 09:43
  • About your 2nd comment: the first stage is to create a parser that generates an AST (this is what I thought you meant). It can be done as I answered. When the AST is created, you can create a tree-walker that traverses this AST and perform actions on the nodes of the AST. Such a tree-walker can be generated by a tree-grammar. Everything about trees in ANTLRv3 can be found here: https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Tree+construction – Bart Kiers Aug 13 '14 at 09:48